diff --git a/CHANGELOG.md b/CHANGELOG.md index 717b7bbc7..6f208b380 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,17 @@ All notable changes to @rpamis/comet will be documented in this file. +## What's Changed [0.4.0-beta.16] - 2026-08-05 + +### Fixed + +- **Classic/OpenSpec coexistence**: Classic now uses only the configured artifact root, so a standalone OpenSpec project can keep the other root at the same time; explicit root migration still refuses to overwrite a non-empty destination. +- **Codex Native Hook parsing**: Raw `apply_patch` input now attributes Add, Update, Delete, and standard `+++ b/...` file headers so Native phase protection is applied consistently. + +### Security + +- **Dependency security updates**: Updated PostCSS, Undici, and brace-expansion to patched releases to address reported dependency vulnerabilities. + ## What's Changed [0.4.0-beta.15] - 2026-08-05 ### Added diff --git a/app/commands/doctor.ts b/app/commands/doctor.ts index 58aace9c5..ea38165f3 100644 --- a/app/commands/doctor.ts +++ b/app/commands/doctor.ts @@ -309,11 +309,16 @@ async function checkClassicLayout(projectPath: string): Promise { }; } if (inspection.dualRoots) { + const configuredRoot = path + .relative(projectPath, inspection.paths.openSpecRoot) + .replaceAll('\\', '/'); + const alternateRoot = path + .relative(projectPath, inspection.alternateRoot) + .replaceAll('\\', '/'); return { check: 'Classic artifact layout', - status: 'fail', - message: - 'both openspec/ and docs/openspec/ exist; Classic writes are blocked until the conflict is resolved', + status: 'pass', + message: `${inspection.paths.artifactLayout}: configured ${configuredRoot}/ present; standalone OpenSpec root ${alternateRoot}/ also present and ignored by Comet`, }; } const configuredRoot = path diff --git a/assets/manifest.json b/assets/manifest.json index 51bfbdfd7..170a67b11 100644 --- a/assets/manifest.json +++ b/assets/manifest.json @@ -1,5 +1,5 @@ { - "version": "0.4.0-beta.15", + "version": "0.4.0-beta.16", "skills": [ "comet/SKILL.md", "comet-classic/SKILL.md", diff --git a/assets/skills/comet-native/scripts/comet-native-hook-guard.mjs b/assets/skills/comet-native/scripts/comet-native-hook-guard.mjs index 6b87115ef..d465f670e 100644 --- a/assets/skills/comet-native/scripts/comet-native-hook-guard.mjs +++ b/assets/skills/comet-native/scripts/comet-native-hook-guard.mjs @@ -1,31 +1,31 @@ #!/usr/bin/env node import { createRequire as __cometCreateRequire } from 'module'; const require = __cometCreateRequire(import.meta.url); -var Ql=Object.create;var Ga=Object.defineProperty;var Zl=Object.getOwnPropertyDescriptor;var eu=Object.getOwnPropertyNames;var tu=Object.getPrototypeOf,iu=Object.prototype.hasOwnProperty;var Qt=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,i)=>(typeof require<"u"?require:e)[i]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var w=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(i){throw e=0,i}};var nu=(t,e,i,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of eu(e))!iu.call(t,r)&&r!==i&&Ga(t,r,{get:()=>e[r],enumerable:!(n=Zl(e,r))||n.enumerable});return t};var On=(t,e,i)=>(i=t!=null?Ql(tu(t)):{},nu(e||!t||!t.__esModule?Ga(i,"default",{value:t,enumerable:!0}):i,t));var C=w(j=>{"use strict";var Hn=Symbol.for("yaml.alias"),io=Symbol.for("yaml.document"),Zt=Symbol.for("yaml.map"),no=Symbol.for("yaml.pair"),$n=Symbol.for("yaml.scalar"),ei=Symbol.for("yaml.seq"),ae=Symbol.for("yaml.node.type"),mu=t=>!!t&&typeof t=="object"&&t[ae]===Hn,vu=t=>!!t&&typeof t=="object"&&t[ae]===io,gu=t=>!!t&&typeof t=="object"&&t[ae]===Zt,wu=t=>!!t&&typeof t=="object"&&t[ae]===no,ro=t=>!!t&&typeof t=="object"&&t[ae]===$n,yu=t=>!!t&&typeof t=="object"&&t[ae]===ei;function ao(t){if(t&&typeof t=="object")switch(t[ae]){case Zt:case ei:return!0}return!1}function Nu(t){if(t&&typeof t=="object")switch(t[ae]){case Hn:case Zt:case $n:case ei:return!0}return!1}var bu=t=>(ro(t)||ao(t))&&!!t.anchor;j.ALIAS=Hn;j.DOC=io;j.MAP=Zt;j.NODE_TYPE=ae;j.PAIR=no;j.SCALAR=$n;j.SEQ=ei;j.hasAnchor=bu;j.isAlias=mu;j.isCollection=ao;j.isDocument=vu;j.isMap=gu;j.isNode=Nu;j.isPair=wu;j.isScalar=ro;j.isSeq=yu});var lt=w(Ln=>{"use strict";var O=C(),$=Symbol("break visit"),oo=Symbol("skip children"),Z=Symbol("remove node");function ti(t,e){let i=so(e);O.isDocument(t)?Ve(null,t.contents,i,Object.freeze([t]))===Z&&(t.contents=null):Ve(null,t,i,Object.freeze([]))}ti.BREAK=$;ti.SKIP=oo;ti.REMOVE=Z;function Ve(t,e,i,n){let r=co(t,e,i,n);if(O.isNode(r)||O.isPair(r))return lo(t,n,r),Ve(t,r,i,n);if(typeof r!="symbol"){if(O.isCollection(e)){n=Object.freeze(n.concat(e));for(let a=0;a{"use strict";var uo=C(),ku=lt(),Su={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Eu=t=>t.replace(/[!,[\]{}]/g,e=>Su[e]),ut=class t{constructor(e,i){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},t.defaultYaml,e),this.tags=Object.assign({},t.defaultTags,i)}clone(){let e=new t(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){let e=new t(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:t.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},t.defaultTags);break}return e}add(e,i){this.atNextDocument&&(this.yaml={explicit:t.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},t.defaultTags),this.atNextDocument=!1);let n=e.trim().split(/[ \t]+/),r=n.shift();switch(r){case"%TAG":{if(n.length!==2&&(i(0,"%TAG directive should contain exactly two parts"),n.length<2))return!1;let[a,o]=n;return this.tags[a]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,n.length!==1)return i(0,"%YAML directive should contain exactly one part"),!1;let[a]=n;if(a==="1.1"||a==="1.2")return this.yaml.version=a,!0;{let o=/^\d+\.\d+$/.test(a);return i(6,`Unsupported YAML version ${a}`,o),!1}}default:return i(0,`Unknown directive ${r}`,!0),!1}}tagName(e,i){if(e==="!")return"!";if(e[0]!=="!")return i(`Not a valid tag: ${e}`),null;if(e[1]==="<"){let o=e.slice(2,-1);return o==="!"||o==="!!"?(i(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&i("Verbatim tags must end with a >"),o)}let[,n,r]=e.match(/^(.*!)([^!]*)$/s);r||i(`The ${e} tag has no suffix`);let a=this.tags[n];if(a)try{return a+decodeURIComponent(r)}catch(o){return i(String(o)),null}return n==="!"?e:(i(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[i,n]of Object.entries(this.tags))if(e.startsWith(n))return i+Eu(e.substring(n.length));return e[0]==="!"?e:`!<${e}>`}toString(e){let i=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],n=Object.entries(this.tags),r;if(e&&n.length>0&&uo.isNode(e.contents)){let a={};ku.visit(e.contents,(o,s)=>{uo.isNode(s)&&s.tag&&(a[s.tag]=!0)}),r=Object.keys(a)}else r=[];for(let[a,o]of n)a==="!!"&&o==="tag:yaml.org,2002:"||(!e||r.some(s=>s.startsWith(o)))&&i.push(`%TAG ${a} ${o}`);return i.join(` -`)}};ut.defaultYaml={explicit:!1,version:"1.2"};ut.defaultTags={"!!":"tag:yaml.org,2002:"};fo.Directives=ut});var ni=w(ft=>{"use strict";var ho=C(),Cu=lt();function Ru(t){if(/[\x00-\x19\s,[\]{}]/.test(t)){let i=`Anchor must not contain whitespace or control characters: ${JSON.stringify(t)}`;throw new Error(i)}return!0}function po(t){let e=new Set;return Cu.visit(t,{Value(i,n){n.anchor&&e.add(n.anchor)}}),e}function mo(t,e){for(let i=1;;++i){let n=`${t}${i}`;if(!e.has(n))return n}}function Pu(t,e){let i=[],n=new Map,r=null;return{onAnchor:a=>{i.push(a),r??(r=po(t));let o=mo(e,r);return r.add(o),o},setAnchors:()=>{for(let a of i){let o=n.get(a);if(typeof o=="object"&&o.anchor&&(ho.isScalar(o.node)||ho.isCollection(o.node)))o.node.anchor=o.anchor;else{let s=new Error("Failed to resolve repeated object (this should not happen)");throw s.source=a,s}}},sourceObjects:n}}ft.anchorIsValid=Ru;ft.anchorNames=po;ft.createNodeAnchors=Pu;ft.findNewAnchor=mo});var Mn=w(vo=>{"use strict";function dt(t,e,i,n){if(n&&typeof n=="object")if(Array.isArray(n))for(let r=0,a=n.length;r{"use strict";var Au=C();function go(t,e,i){if(Array.isArray(t))return t.map((n,r)=>go(n,String(r),i));if(t&&typeof t.toJSON=="function"){if(!i||!Au.hasAnchor(t))return t.toJSON(e,i);let n={aliasCount:0,count:1,res:void 0};i.anchors.set(t,n),i.onCreate=a=>{n.res=a,delete i.onCreate};let r=t.toJSON(e,i);return i.onCreate&&i.onCreate(r),r}return typeof t=="bigint"&&!i?.keep?Number(t):t}wo.toJS=go});var ri=w(No=>{"use strict";var xu=Mn(),yo=C(),Tu=le(),Bn=class{constructor(e){Object.defineProperty(this,yo.NODE_TYPE,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:i,maxAliasCount:n,onAnchor:r,reviver:a}={}){if(!yo.isDocument(e))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:e,keep:!0,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},s=Tu.toJS(this,"",o);if(typeof r=="function")for(let{count:c,res:l}of o.anchors.values())r(l,c);return typeof a=="function"?xu.applyReviver(a,{"":s},"",s):s}};No.NodeBase=Bn});var ht=w(bo=>{"use strict";var Iu=ni(),_u=lt(),ze=C(),Ou=ri(),ju=le(),Dn=class extends Ou.NodeBase{constructor(e){super(ze.ALIAS),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,i){if(i?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let n;i?.aliasResolveCache?n=i.aliasResolveCache:(n=[],_u.visit(e,{Node:(a,o)=>{(ze.isAlias(o)||ze.hasAnchor(o))&&n.push(o)}}),i&&(i.aliasResolveCache=n));let r;for(let a of n){if(a===this)break;a.anchor===this.source&&(r=a)}return r}toJSON(e,i){if(!i)return{source:this.source};let{anchors:n,doc:r,maxAliasCount:a}=i,o=this.resolve(r,i);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let s=n.get(o);if(s||(ju.toJS(o,null,i),s=n.get(o)),s?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(a>=0&&(s.count+=1,s.aliasCount===0&&(s.aliasCount=ai(r,o,n)),s.count*s.aliasCount>a)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return s.res}toString(e,i,n){let r=`*${this.source}`;if(e){if(Iu.anchorIsValid(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let a=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(a)}if(e.implicitKey)return`${r} `}return r}};function ai(t,e,i){if(ze.isAlias(e)){let n=e.resolve(t),r=i&&n&&i.get(n);return r?r.count*r.aliasCount:0}else if(ze.isCollection(e)){let n=0;for(let r of e.items){let a=ai(t,r,i);a>n&&(n=a)}return n}else if(ze.isPair(e)){let n=ai(t,e.key,i),r=ai(t,e.value,i);return Math.max(n,r)}return 1}bo.Alias=Dn});var T=w(qn=>{"use strict";var Hu=C(),$u=ri(),Lu=le(),Fu=t=>!t||typeof t!="function"&&typeof t!="object",ue=class extends $u.NodeBase{constructor(e){super(Hu.SCALAR),this.value=e}toJSON(e,i){return i?.keep?this.value:Lu.toJS(this.value,e,i)}toString(){return String(this.value)}};ue.BLOCK_FOLDED="BLOCK_FOLDED";ue.BLOCK_LITERAL="BLOCK_LITERAL";ue.PLAIN="PLAIN";ue.QUOTE_DOUBLE="QUOTE_DOUBLE";ue.QUOTE_SINGLE="QUOTE_SINGLE";qn.Scalar=ue;qn.isScalarValue=Fu});var pt=w(So=>{"use strict";var Mu=ht(),Ce=C(),ko=T(),Bu="tag:yaml.org,2002:";function Du(t,e,i){if(e){let n=i.filter(a=>a.tag===e),r=n.find(a=>!a.format)??n[0];if(!r)throw new Error(`Tag ${e} not found`);return r}return i.find(n=>n.identify?.(t)&&!n.format)}function qu(t,e,i){if(Ce.isDocument(t)&&(t=t.contents),Ce.isNode(t))return t;if(Ce.isPair(t)){let u=i.schema[Ce.MAP].createNode?.(i.schema,null,i);return u.items.push(t),u}(t instanceof String||t instanceof Number||t instanceof Boolean||typeof BigInt<"u"&&t instanceof BigInt)&&(t=t.valueOf());let{aliasDuplicateObjects:n,onAnchor:r,onTagObj:a,schema:o,sourceObjects:s}=i,c;if(n&&t&&typeof t=="object"){if(c=s.get(t),c)return c.anchor??(c.anchor=r(t)),new Mu.Alias(c.anchor);c={anchor:null,node:null},s.set(t,c)}e?.startsWith("!!")&&(e=Bu+e.slice(2));let l=Du(t,e,o.tags);if(!l){if(t&&typeof t.toJSON=="function"&&(t=t.toJSON()),!t||typeof t!="object"){let u=new ko.Scalar(t);return c&&(c.node=u),u}l=t instanceof Map?o[Ce.MAP]:Symbol.iterator in Object(t)?o[Ce.SEQ]:o[Ce.MAP]}a&&(a(l),delete i.onTagObj);let d=l?.createNode?l.createNode(i.schema,t,i):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(i.schema,t,i):new ko.Scalar(t);return e?d.tag=e:l.default||(d.tag=l.tag),c&&(c.node=d),d}So.createNode=qu});var si=w(oi=>{"use strict";var Vu=pt(),ee=C(),Wu=ri();function Vn(t,e,i){let n=i;for(let r=e.length-1;r>=0;--r){let a=e[r];if(typeof a=="number"&&Number.isInteger(a)&&a>=0){let o=[];o[a]=n,n=o}else n=new Map([[a,n]])}return Vu.createNode(n,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:t,sourceObjects:new Map})}var Eo=t=>t==null||typeof t=="object"&&!!t[Symbol.iterator]().next().done,Wn=class extends Wu.NodeBase{constructor(e,i){super(e),Object.defineProperty(this,"schema",{value:i,configurable:!0,enumerable:!1,writable:!0})}clone(e){let i=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(i.schema=e),i.items=i.items.map(n=>ee.isNode(n)||ee.isPair(n)?n.clone(e):n),this.range&&(i.range=this.range.slice()),i}addIn(e,i){if(Eo(e))this.add(i);else{let[n,...r]=e,a=this.get(n,!0);if(ee.isCollection(a))a.addIn(r,i);else if(a===void 0&&this.schema)this.set(n,Vn(this.schema,r,i));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}}deleteIn(e){let[i,...n]=e;if(n.length===0)return this.delete(i);let r=this.get(i,!0);if(ee.isCollection(r))return r.deleteIn(n);throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}getIn(e,i){let[n,...r]=e,a=this.get(n,!0);return r.length===0?!i&&ee.isScalar(a)?a.value:a:ee.isCollection(a)?a.getIn(r,i):void 0}hasAllNullValues(e){return this.items.every(i=>{if(!ee.isPair(i))return!1;let n=i.value;return n==null||e&&ee.isScalar(n)&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn(e){let[i,...n]=e;if(n.length===0)return this.has(i);let r=this.get(i,!0);return ee.isCollection(r)?r.hasIn(n):!1}setIn(e,i){let[n,...r]=e;if(r.length===0)this.set(n,i);else{let a=this.get(n,!0);if(ee.isCollection(a))a.setIn(r,i);else if(a===void 0&&this.schema)this.set(n,Vn(this.schema,r,i));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}}};oi.Collection=Wn;oi.collectionFromPath=Vn;oi.isEmptyPath=Eo});var mt=w(ci=>{"use strict";var zu=t=>t.replace(/^(?!$)(?: $)?/gm,"#");function zn(t,e){return/^\n+$/.test(t)?t.substring(1):e?t.replace(/^(?! *$)/gm,e):t}var Ju=(t,e,i)=>t.endsWith(` -`)?zn(i,e):i.includes(` +var Ql=Object.create;var Ka=Object.defineProperty;var Zl=Object.getOwnPropertyDescriptor;var eu=Object.getOwnPropertyNames;var tu=Object.getPrototypeOf,iu=Object.prototype.hasOwnProperty;var Qt=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,i)=>(typeof require<"u"?require:e)[i]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var w=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(i){throw e=0,i}};var nu=(t,e,i,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of eu(e))!iu.call(t,r)&&r!==i&&Ka(t,r,{get:()=>e[r],enumerable:!(n=Zl(e,r))||n.enumerable});return t};var On=(t,e,i)=>(i=t!=null?Ql(tu(t)):{},nu(e||!t||!t.__esModule?Ka(i,"default",{value:t,enumerable:!0}):i,t));var C=w(j=>{"use strict";var $n=Symbol.for("yaml.alias"),io=Symbol.for("yaml.document"),Zt=Symbol.for("yaml.map"),no=Symbol.for("yaml.pair"),Ln=Symbol.for("yaml.scalar"),ei=Symbol.for("yaml.seq"),ae=Symbol.for("yaml.node.type"),mu=t=>!!t&&typeof t=="object"&&t[ae]===$n,vu=t=>!!t&&typeof t=="object"&&t[ae]===io,gu=t=>!!t&&typeof t=="object"&&t[ae]===Zt,wu=t=>!!t&&typeof t=="object"&&t[ae]===no,ro=t=>!!t&&typeof t=="object"&&t[ae]===Ln,yu=t=>!!t&&typeof t=="object"&&t[ae]===ei;function ao(t){if(t&&typeof t=="object")switch(t[ae]){case Zt:case ei:return!0}return!1}function Nu(t){if(t&&typeof t=="object")switch(t[ae]){case $n:case Zt:case Ln:case ei:return!0}return!1}var bu=t=>(ro(t)||ao(t))&&!!t.anchor;j.ALIAS=$n;j.DOC=io;j.MAP=Zt;j.NODE_TYPE=ae;j.PAIR=no;j.SCALAR=Ln;j.SEQ=ei;j.hasAnchor=bu;j.isAlias=mu;j.isCollection=ao;j.isDocument=vu;j.isMap=gu;j.isNode=Nu;j.isPair=wu;j.isScalar=ro;j.isSeq=yu});var lt=w(Fn=>{"use strict";var O=C(),$=Symbol("break visit"),oo=Symbol("skip children"),Z=Symbol("remove node");function ti(t,e){let i=so(e);O.isDocument(t)?Ve(null,t.contents,i,Object.freeze([t]))===Z&&(t.contents=null):Ve(null,t,i,Object.freeze([]))}ti.BREAK=$;ti.SKIP=oo;ti.REMOVE=Z;function Ve(t,e,i,n){let r=co(t,e,i,n);if(O.isNode(r)||O.isPair(r))return lo(t,n,r),Ve(t,r,i,n);if(typeof r!="symbol"){if(O.isCollection(e)){n=Object.freeze(n.concat(e));for(let a=0;a{"use strict";var uo=C(),ku=lt(),Su={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Eu=t=>t.replace(/[!,[\]{}]/g,e=>Su[e]),ut=class t{constructor(e,i){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},t.defaultYaml,e),this.tags=Object.assign({},t.defaultTags,i)}clone(){let e=new t(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){let e=new t(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:t.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},t.defaultTags);break}return e}add(e,i){this.atNextDocument&&(this.yaml={explicit:t.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},t.defaultTags),this.atNextDocument=!1);let n=e.trim().split(/[ \t]+/),r=n.shift();switch(r){case"%TAG":{if(n.length!==2&&(i(0,"%TAG directive should contain exactly two parts"),n.length<2))return!1;let[a,o]=n;return this.tags[a]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,n.length!==1)return i(0,"%YAML directive should contain exactly one part"),!1;let[a]=n;if(a==="1.1"||a==="1.2")return this.yaml.version=a,!0;{let o=/^\d+\.\d+$/.test(a);return i(6,`Unsupported YAML version ${a}`,o),!1}}default:return i(0,`Unknown directive ${r}`,!0),!1}}tagName(e,i){if(e==="!")return"!";if(e[0]!=="!")return i(`Not a valid tag: ${e}`),null;if(e[1]==="<"){let o=e.slice(2,-1);return o==="!"||o==="!!"?(i(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&i("Verbatim tags must end with a >"),o)}let[,n,r]=e.match(/^(.*!)([^!]*)$/s);r||i(`The ${e} tag has no suffix`);let a=this.tags[n];if(a)try{return a+decodeURIComponent(r)}catch(o){return i(String(o)),null}return n==="!"?e:(i(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[i,n]of Object.entries(this.tags))if(e.startsWith(n))return i+Eu(e.substring(n.length));return e[0]==="!"?e:`!<${e}>`}toString(e){let i=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],n=Object.entries(this.tags),r;if(e&&n.length>0&&uo.isNode(e.contents)){let a={};ku.visit(e.contents,(o,s)=>{uo.isNode(s)&&s.tag&&(a[s.tag]=!0)}),r=Object.keys(a)}else r=[];for(let[a,o]of n)a==="!!"&&o==="tag:yaml.org,2002:"||(!e||r.some(s=>s.startsWith(o)))&&i.push(`%TAG ${a} ${o}`);return i.join(` +`)}};ut.defaultYaml={explicit:!1,version:"1.2"};ut.defaultTags={"!!":"tag:yaml.org,2002:"};fo.Directives=ut});var ni=w(ft=>{"use strict";var ho=C(),Cu=lt();function Ru(t){if(/[\x00-\x19\s,[\]{}]/.test(t)){let i=`Anchor must not contain whitespace or control characters: ${JSON.stringify(t)}`;throw new Error(i)}return!0}function po(t){let e=new Set;return Cu.visit(t,{Value(i,n){n.anchor&&e.add(n.anchor)}}),e}function mo(t,e){for(let i=1;;++i){let n=`${t}${i}`;if(!e.has(n))return n}}function Pu(t,e){let i=[],n=new Map,r=null;return{onAnchor:a=>{i.push(a),r??(r=po(t));let o=mo(e,r);return r.add(o),o},setAnchors:()=>{for(let a of i){let o=n.get(a);if(typeof o=="object"&&o.anchor&&(ho.isScalar(o.node)||ho.isCollection(o.node)))o.node.anchor=o.anchor;else{let s=new Error("Failed to resolve repeated object (this should not happen)");throw s.source=a,s}}},sourceObjects:n}}ft.anchorIsValid=Ru;ft.anchorNames=po;ft.createNodeAnchors=Pu;ft.findNewAnchor=mo});var Bn=w(vo=>{"use strict";function dt(t,e,i,n){if(n&&typeof n=="object")if(Array.isArray(n))for(let r=0,a=n.length;r{"use strict";var Au=C();function go(t,e,i){if(Array.isArray(t))return t.map((n,r)=>go(n,String(r),i));if(t&&typeof t.toJSON=="function"){if(!i||!Au.hasAnchor(t))return t.toJSON(e,i);let n={aliasCount:0,count:1,res:void 0};i.anchors.set(t,n),i.onCreate=a=>{n.res=a,delete i.onCreate};let r=t.toJSON(e,i);return i.onCreate&&i.onCreate(r),r}return typeof t=="bigint"&&!i?.keep?Number(t):t}wo.toJS=go});var ri=w(No=>{"use strict";var xu=Bn(),yo=C(),Tu=le(),Dn=class{constructor(e){Object.defineProperty(this,yo.NODE_TYPE,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:i,maxAliasCount:n,onAnchor:r,reviver:a}={}){if(!yo.isDocument(e))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:e,keep:!0,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},s=Tu.toJS(this,"",o);if(typeof r=="function")for(let{count:c,res:l}of o.anchors.values())r(l,c);return typeof a=="function"?xu.applyReviver(a,{"":s},"",s):s}};No.NodeBase=Dn});var ht=w(bo=>{"use strict";var Iu=ni(),_u=lt(),ze=C(),Ou=ri(),ju=le(),qn=class extends Ou.NodeBase{constructor(e){super(ze.ALIAS),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,i){if(i?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let n;i?.aliasResolveCache?n=i.aliasResolveCache:(n=[],_u.visit(e,{Node:(a,o)=>{(ze.isAlias(o)||ze.hasAnchor(o))&&n.push(o)}}),i&&(i.aliasResolveCache=n));let r;for(let a of n){if(a===this)break;a.anchor===this.source&&(r=a)}return r}toJSON(e,i){if(!i)return{source:this.source};let{anchors:n,doc:r,maxAliasCount:a}=i,o=this.resolve(r,i);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let s=n.get(o);if(s||(ju.toJS(o,null,i),s=n.get(o)),s?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(a>=0&&(s.count+=1,s.aliasCount===0&&(s.aliasCount=ai(r,o,n)),s.count*s.aliasCount>a)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return s.res}toString(e,i,n){let r=`*${this.source}`;if(e){if(Iu.anchorIsValid(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let a=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(a)}if(e.implicitKey)return`${r} `}return r}};function ai(t,e,i){if(ze.isAlias(e)){let n=e.resolve(t),r=i&&n&&i.get(n);return r?r.count*r.aliasCount:0}else if(ze.isCollection(e)){let n=0;for(let r of e.items){let a=ai(t,r,i);a>n&&(n=a)}return n}else if(ze.isPair(e)){let n=ai(t,e.key,i),r=ai(t,e.value,i);return Math.max(n,r)}return 1}bo.Alias=qn});var T=w(Vn=>{"use strict";var Hu=C(),$u=ri(),Lu=le(),Fu=t=>!t||typeof t!="function"&&typeof t!="object",ue=class extends $u.NodeBase{constructor(e){super(Hu.SCALAR),this.value=e}toJSON(e,i){return i?.keep?this.value:Lu.toJS(this.value,e,i)}toString(){return String(this.value)}};ue.BLOCK_FOLDED="BLOCK_FOLDED";ue.BLOCK_LITERAL="BLOCK_LITERAL";ue.PLAIN="PLAIN";ue.QUOTE_DOUBLE="QUOTE_DOUBLE";ue.QUOTE_SINGLE="QUOTE_SINGLE";Vn.Scalar=ue;Vn.isScalarValue=Fu});var pt=w(So=>{"use strict";var Mu=ht(),Ce=C(),ko=T(),Bu="tag:yaml.org,2002:";function Du(t,e,i){if(e){let n=i.filter(a=>a.tag===e),r=n.find(a=>!a.format)??n[0];if(!r)throw new Error(`Tag ${e} not found`);return r}return i.find(n=>n.identify?.(t)&&!n.format)}function qu(t,e,i){if(Ce.isDocument(t)&&(t=t.contents),Ce.isNode(t))return t;if(Ce.isPair(t)){let u=i.schema[Ce.MAP].createNode?.(i.schema,null,i);return u.items.push(t),u}(t instanceof String||t instanceof Number||t instanceof Boolean||typeof BigInt<"u"&&t instanceof BigInt)&&(t=t.valueOf());let{aliasDuplicateObjects:n,onAnchor:r,onTagObj:a,schema:o,sourceObjects:s}=i,c;if(n&&t&&typeof t=="object"){if(c=s.get(t),c)return c.anchor??(c.anchor=r(t)),new Mu.Alias(c.anchor);c={anchor:null,node:null},s.set(t,c)}e?.startsWith("!!")&&(e=Bu+e.slice(2));let l=Du(t,e,o.tags);if(!l){if(t&&typeof t.toJSON=="function"&&(t=t.toJSON()),!t||typeof t!="object"){let u=new ko.Scalar(t);return c&&(c.node=u),u}l=t instanceof Map?o[Ce.MAP]:Symbol.iterator in Object(t)?o[Ce.SEQ]:o[Ce.MAP]}a&&(a(l),delete i.onTagObj);let d=l?.createNode?l.createNode(i.schema,t,i):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(i.schema,t,i):new ko.Scalar(t);return e?d.tag=e:l.default||(d.tag=l.tag),c&&(c.node=d),d}So.createNode=qu});var si=w(oi=>{"use strict";var Vu=pt(),ee=C(),Wu=ri();function Wn(t,e,i){let n=i;for(let r=e.length-1;r>=0;--r){let a=e[r];if(typeof a=="number"&&Number.isInteger(a)&&a>=0){let o=[];o[a]=n,n=o}else n=new Map([[a,n]])}return Vu.createNode(n,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:t,sourceObjects:new Map})}var Eo=t=>t==null||typeof t=="object"&&!!t[Symbol.iterator]().next().done,zn=class extends Wu.NodeBase{constructor(e,i){super(e),Object.defineProperty(this,"schema",{value:i,configurable:!0,enumerable:!1,writable:!0})}clone(e){let i=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(i.schema=e),i.items=i.items.map(n=>ee.isNode(n)||ee.isPair(n)?n.clone(e):n),this.range&&(i.range=this.range.slice()),i}addIn(e,i){if(Eo(e))this.add(i);else{let[n,...r]=e,a=this.get(n,!0);if(ee.isCollection(a))a.addIn(r,i);else if(a===void 0&&this.schema)this.set(n,Wn(this.schema,r,i));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}}deleteIn(e){let[i,...n]=e;if(n.length===0)return this.delete(i);let r=this.get(i,!0);if(ee.isCollection(r))return r.deleteIn(n);throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}getIn(e,i){let[n,...r]=e,a=this.get(n,!0);return r.length===0?!i&&ee.isScalar(a)?a.value:a:ee.isCollection(a)?a.getIn(r,i):void 0}hasAllNullValues(e){return this.items.every(i=>{if(!ee.isPair(i))return!1;let n=i.value;return n==null||e&&ee.isScalar(n)&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn(e){let[i,...n]=e;if(n.length===0)return this.has(i);let r=this.get(i,!0);return ee.isCollection(r)?r.hasIn(n):!1}setIn(e,i){let[n,...r]=e;if(r.length===0)this.set(n,i);else{let a=this.get(n,!0);if(ee.isCollection(a))a.setIn(r,i);else if(a===void 0&&this.schema)this.set(n,Wn(this.schema,r,i));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}}};oi.Collection=zn;oi.collectionFromPath=Wn;oi.isEmptyPath=Eo});var mt=w(ci=>{"use strict";var zu=t=>t.replace(/^(?!$)(?: $)?/gm,"#");function Jn(t,e){return/^\n+$/.test(t)?t.substring(1):e?t.replace(/^(?! *$)/gm,e):t}var Ju=(t,e,i)=>t.endsWith(` +`)?Jn(i,e):i.includes(` `)?` -`+zn(i,e):(t.endsWith(" ")?"":" ")+i;ci.indentComment=zn;ci.lineComment=Ju;ci.stringifyComment=zu});var Ro=w(vt=>{"use strict";var Gu="flow",Jn="block",li="quoted";function Ku(t,e,i="flow",{indentAtStart:n,lineWidth:r=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!r||r<0)return t;rr-Math.max(2,a)?l.push(0):u=r-n);let f,m,g=!1,h=-1,p=-1,y=-1;i===Jn&&(h=Co(t,h,e.length),h!==-1&&(u=h+c));for(let k;k=t[h+=1];){if(i===li&&k==="\\"){switch(p=h,t[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}y=h}if(k===` -`)i===Jn&&(h=Co(t,h,e.length)),u=h+e.length+c,f=void 0;else{if(k===" "&&m&&m!==" "&&m!==` +`+Jn(i,e):(t.endsWith(" ")?"":" ")+i;ci.indentComment=Jn;ci.lineComment=Ju;ci.stringifyComment=zu});var Ro=w(vt=>{"use strict";var Gu="flow",Gn="block",li="quoted";function Ku(t,e,i="flow",{indentAtStart:n,lineWidth:r=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!r||r<0)return t;rr-Math.max(2,a)?l.push(0):u=r-n);let f,m,g=!1,h=-1,p=-1,y=-1;i===Gn&&(h=Co(t,h,e.length),h!==-1&&(u=h+c));for(let k;k=t[h+=1];){if(i===li&&k==="\\"){switch(p=h,t[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}y=h}if(k===` +`)i===Gn&&(h=Co(t,h,e.length)),u=h+e.length+c,f=void 0;else{if(k===" "&&m&&m!==" "&&m!==` `&&m!==" "){let S=t[h+1];S&&S!==" "&&S!==` `&&S!==" "&&(f=h)}if(h>=u)if(f)l.push(f),u=f+c,f=void 0;else if(i===li){for(;m===" "||m===" ";)m=k,k=t[h+=1],g=!0;let S=h>y+1?h-2:p-1;if(d[S])return t;l.push(S),d[S]=!0,u=S+c,f=void 0}else g=!0}m=k}if(g&&s&&s(),l.length===0)return t;o&&o();let N=t.slice(0,l[0]);for(let k=0;k{"use strict";var W=T(),fe=Ro(),fi=(t,e)=>({indentAtStart:e?t.indent.length:t.indentAtStart,lineWidth:t.options.lineWidth,minContentWidth:t.options.minContentWidth}),di=t=>/^(%|---|\.\.\.)/m.test(t);function Uu(t,e,i){if(!e||e<0)return!1;let n=e-i,r=t.length;if(r<=n)return!1;for(let a=0,o=0;a{"use strict";var W=T(),fe=Ro(),fi=(t,e)=>({indentAtStart:e?t.indent.length:t.indentAtStart,lineWidth:t.options.lineWidth,minContentWidth:t.options.minContentWidth}),di=t=>/^(%|---|\.\.\.)/m.test(t);function Uu(t,e,i){if(!e||e<0)return!1;let n=e-i,r=t.length;if(r<=n)return!1;for(let a=0,o=0;an)return!0;if(o=a+1,r-o<=n)return!1}return!0}function gt(t,e){let i=JSON.stringify(t);if(e.options.doubleQuotedAsJSON)return i;let{implicitKey:n}=e,r=e.options.doubleQuotedMinMultiLineLength,a=e.indent||(di(t)?" ":""),o="",s=0;for(let c=0,l=i[c];l;l=i[++c])if(l===" "&&i[c+1]==="\\"&&i[c+2]==="n"&&(o+=i.slice(s,c)+"\\ ",c+=1,s=c,l="\\"),l==="\\")switch(i[c+1]){case"u":{o+=i.slice(s,c);let d=i.substr(c+2,4);switch(d){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:d.substr(0,2)==="00"?o+="\\x"+d.substr(2):o+=i.substr(c,6)}c+=5,s=c+1}break;case"n":if(n||i[c+2]==='"'||i.length `;let u,f;for(f=i.length;f>0;--f){let E=i[f-1];if(E!==` `&&E!==" "&&E!==" ")break}let m=i.substring(f),g=m.indexOf(` `);g===-1?u="-":i===m||g!==m.length-1?(u="+",a&&a()):u="",m&&(i=i.slice(0,-m.length),m[m.length-1]===` -`&&(m=m.slice(0,-1)),m=m.replace(Kn,`$&${l}`));let h=!1,p,y=-1;for(p=0;p{v=!0});let b=fe.foldFlowLines(`${N}${E}${m}`,l,fe.FOLD_BLOCK,R);if(!v)return`>${S} ${l}${b}`}return i=i.replace(/\n+/g,`$&${l}`),`|${S} @@ -33,8 +33,8 @@ ${l}${N}${i}${m}`}function Yu(t,e,i,n){let{type:r,value:a}=t,{actualString:o,imp `)||d&&/[[\]{},]/.test(a))return Je(a,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||d||!a.includes(` `)?Je(a,e):ui(t,e,i,n);if(!s&&!d&&r!==W.Scalar.PLAIN&&a.includes(` `))return ui(t,e,i,n);if(di(a)){if(c==="")return e.forceBlockIndent=!0,ui(t,e,i,n);if(s&&c===l)return Je(a,e)}let u=a.replace(/\n+/g,`$& -${c}`);if(o){let f=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(u),{compat:m,tags:g}=e.doc.schema;if(g.some(f)||m?.some(f))return Je(a,e)}return s?u:fe.foldFlowLines(u,c,fe.FOLD_FLOW,fi(e,!1))}function Xu(t,e,i,n){let{implicitKey:r,inFlow:a}=e,o=typeof t.value=="string"?t:Object.assign({},t,{value:String(t.value)}),{type:s}=t;s!==W.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=W.Scalar.QUOTE_DOUBLE);let c=d=>{switch(d){case W.Scalar.BLOCK_FOLDED:case W.Scalar.BLOCK_LITERAL:return r||a?Je(o.value,e):ui(o,e,i,n);case W.Scalar.QUOTE_DOUBLE:return gt(o.value,e);case W.Scalar.QUOTE_SINGLE:return Gn(o.value,e);case W.Scalar.PLAIN:return Yu(o,e,i,n);default:return null}},l=c(s);if(l===null){let{defaultKeyType:d,defaultStringType:u}=e.options,f=r&&d||u;if(l=c(f),l===null)throw new Error(`Unsupported default string type ${f}`)}return l}Po.stringifyString=Xu});var yt=w(Un=>{"use strict";var Qu=ni(),de=C(),Zu=mt(),ef=wt();function tf(t,e){let i=Object.assign({blockQuote:!0,commentString:Zu.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},t.schema.toStringOptions,e),n;switch(i.collectionStyle){case"block":n=!1;break;case"flow":n=!0;break;default:n=null}return{anchors:new Set,doc:t,flowCollectionPadding:i.flowCollectionPadding?" ":"",indent:"",indentStep:typeof i.indent=="number"?" ".repeat(i.indent):" ",inFlow:n,options:i}}function nf(t,e){if(e.tag){let r=t.filter(a=>a.tag===e.tag);if(r.length>0)return r.find(a=>a.format===e.format)??r[0]}let i,n;if(de.isScalar(e)){n=e.value;let r=t.filter(a=>a.identify?.(n));if(r.length>1){let a=r.filter(o=>o.test);a.length>0&&(r=a)}i=r.find(a=>a.format===e.format)??r.find(a=>!a.format)}else n=e,i=t.find(r=>r.nodeClass&&n instanceof r.nodeClass);if(!i){let r=n?.constructor?.name??(n===null?"null":typeof n);throw new Error(`Tag not resolved for ${r} value`)}return i}function rf(t,e,{anchors:i,doc:n}){if(!n.directives)return"";let r=[],a=(de.isScalar(t)||de.isCollection(t))&&t.anchor;a&&Qu.anchorIsValid(a)&&(i.add(a),r.push(`&${a}`));let o=t.tag??(e.default?null:e.tag);return o&&r.push(n.directives.tagString(o)),r.join(" ")}function af(t,e,i,n){if(de.isPair(t))return t.toString(e,i,n);if(de.isAlias(t)){if(e.doc.directives)return t.toString(e);if(e.resolvedAliases?.has(t))throw new TypeError("Cannot stringify circular structure without alias nodes");e.resolvedAliases?e.resolvedAliases.add(t):e.resolvedAliases=new Set([t]),t=t.resolve(e.doc)}let r,a=de.isNode(t)?t:e.doc.createNode(t,{onTagObj:c=>r=c});r??(r=nf(e.doc.schema.tags,a));let o=rf(a,r,e);o.length>0&&(e.indentAtStart=(e.indentAtStart??0)+o.length+1);let s=typeof r.stringify=="function"?r.stringify(a,e,i,n):de.isScalar(a)?ef.stringifyString(a,e,i,n):a.toString(e,i,n);return o?de.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o} -${e.indent}${s}`:s}Un.createStringifyContext=tf;Un.stringify=af});var Io=w(To=>{"use strict";var oe=C(),Ao=T(),xo=yt(),Nt=mt();function of({key:t,value:e},i,n,r){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:d,simpleKeys:u}}=i,f=oe.isNode(t)&&t.comment||null;if(u){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(oe.isCollection(t)||!oe.isNode(t)&&typeof t=="object"){let R="With simple keys, collection cannot be used as a key value";throw new Error(R)}}let m=!u&&(!t||f&&e==null&&!i.inFlow||oe.isCollection(t)||(oe.isScalar(t)?t.type===Ao.Scalar.BLOCK_FOLDED||t.type===Ao.Scalar.BLOCK_LITERAL:typeof t=="object"));i=Object.assign({},i,{allNullValues:!1,implicitKey:!m&&(u||!a),indent:s+c});let g=!1,h=!1,p=xo.stringify(t,i,()=>g=!0,()=>h=!0);if(!m&&!i.inFlow&&p.length>1024){if(u)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");m=!0}if(i.inFlow){if(a||e==null)return g&&n&&n(),p===""?"?":m?`? ${p}`:p}else if(a&&!u||e==null&&m)return p=`? ${p}`,f&&!g?p+=Nt.lineComment(p,i.indent,l(f)):h&&r&&r(),p;g&&(f=null),m?(f&&(p+=Nt.lineComment(p,i.indent,l(f))),p=`? ${p} +${c}`);if(o){let f=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(u),{compat:m,tags:g}=e.doc.schema;if(g.some(f)||m?.some(f))return Je(a,e)}return s?u:fe.foldFlowLines(u,c,fe.FOLD_FLOW,fi(e,!1))}function Xu(t,e,i,n){let{implicitKey:r,inFlow:a}=e,o=typeof t.value=="string"?t:Object.assign({},t,{value:String(t.value)}),{type:s}=t;s!==W.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=W.Scalar.QUOTE_DOUBLE);let c=d=>{switch(d){case W.Scalar.BLOCK_FOLDED:case W.Scalar.BLOCK_LITERAL:return r||a?Je(o.value,e):ui(o,e,i,n);case W.Scalar.QUOTE_DOUBLE:return gt(o.value,e);case W.Scalar.QUOTE_SINGLE:return Kn(o.value,e);case W.Scalar.PLAIN:return Yu(o,e,i,n);default:return null}},l=c(s);if(l===null){let{defaultKeyType:d,defaultStringType:u}=e.options,f=r&&d||u;if(l=c(f),l===null)throw new Error(`Unsupported default string type ${f}`)}return l}Po.stringifyString=Xu});var yt=w(Yn=>{"use strict";var Qu=ni(),de=C(),Zu=mt(),ef=wt();function tf(t,e){let i=Object.assign({blockQuote:!0,commentString:Zu.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},t.schema.toStringOptions,e),n;switch(i.collectionStyle){case"block":n=!1;break;case"flow":n=!0;break;default:n=null}return{anchors:new Set,doc:t,flowCollectionPadding:i.flowCollectionPadding?" ":"",indent:"",indentStep:typeof i.indent=="number"?" ".repeat(i.indent):" ",inFlow:n,options:i}}function nf(t,e){if(e.tag){let r=t.filter(a=>a.tag===e.tag);if(r.length>0)return r.find(a=>a.format===e.format)??r[0]}let i,n;if(de.isScalar(e)){n=e.value;let r=t.filter(a=>a.identify?.(n));if(r.length>1){let a=r.filter(o=>o.test);a.length>0&&(r=a)}i=r.find(a=>a.format===e.format)??r.find(a=>!a.format)}else n=e,i=t.find(r=>r.nodeClass&&n instanceof r.nodeClass);if(!i){let r=n?.constructor?.name??(n===null?"null":typeof n);throw new Error(`Tag not resolved for ${r} value`)}return i}function rf(t,e,{anchors:i,doc:n}){if(!n.directives)return"";let r=[],a=(de.isScalar(t)||de.isCollection(t))&&t.anchor;a&&Qu.anchorIsValid(a)&&(i.add(a),r.push(`&${a}`));let o=t.tag??(e.default?null:e.tag);return o&&r.push(n.directives.tagString(o)),r.join(" ")}function af(t,e,i,n){if(de.isPair(t))return t.toString(e,i,n);if(de.isAlias(t)){if(e.doc.directives)return t.toString(e);if(e.resolvedAliases?.has(t))throw new TypeError("Cannot stringify circular structure without alias nodes");e.resolvedAliases?e.resolvedAliases.add(t):e.resolvedAliases=new Set([t]),t=t.resolve(e.doc)}let r,a=de.isNode(t)?t:e.doc.createNode(t,{onTagObj:c=>r=c});r??(r=nf(e.doc.schema.tags,a));let o=rf(a,r,e);o.length>0&&(e.indentAtStart=(e.indentAtStart??0)+o.length+1);let s=typeof r.stringify=="function"?r.stringify(a,e,i,n):de.isScalar(a)?ef.stringifyString(a,e,i,n):a.toString(e,i,n);return o?de.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o} +${e.indent}${s}`:s}Yn.createStringifyContext=tf;Yn.stringify=af});var Io=w(To=>{"use strict";var oe=C(),Ao=T(),xo=yt(),Nt=mt();function of({key:t,value:e},i,n,r){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:d,simpleKeys:u}}=i,f=oe.isNode(t)&&t.comment||null;if(u){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(oe.isCollection(t)||!oe.isNode(t)&&typeof t=="object"){let R="With simple keys, collection cannot be used as a key value";throw new Error(R)}}let m=!u&&(!t||f&&e==null&&!i.inFlow||oe.isCollection(t)||(oe.isScalar(t)?t.type===Ao.Scalar.BLOCK_FOLDED||t.type===Ao.Scalar.BLOCK_LITERAL:typeof t=="object"));i=Object.assign({},i,{allNullValues:!1,implicitKey:!m&&(u||!a),indent:s+c});let g=!1,h=!1,p=xo.stringify(t,i,()=>g=!0,()=>h=!0);if(!m&&!i.inFlow&&p.length>1024){if(u)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");m=!0}if(i.inFlow){if(a||e==null)return g&&n&&n(),p===""?"?":m?`? ${p}`:p}else if(a&&!u||e==null&&m)return p=`? ${p}`,f&&!g?p+=Nt.lineComment(p,i.indent,l(f)):h&&r&&r(),p;g&&(f=null),m?(f&&(p+=Nt.lineComment(p,i.indent,l(f))),p=`? ${p} ${s}:`):(p=`${p}:`,f&&(p+=Nt.lineComment(p,i.indent,l(f))));let y,N,k;oe.isNode(e)?(y=!!e.spaceBefore,N=e.commentBefore,k=e.comment):(y=!1,N=null,k=null,e&&typeof e=="object"&&(e=o.createNode(e))),i.implicitKey=!1,!m&&!f&&oe.isScalar(e)&&(i.indentAtStart=p.length+1),h=!1,!d&&c.length>=2&&!i.inFlow&&!m&&oe.isSeq(e)&&!e.flow&&!e.tag&&!e.anchor&&(i.indent=i.indent.substring(2));let S=!1,E=xo.stringify(e,i,()=>S=!0,()=>h=!0),v=" ";if(f||y||N){if(v=y?` `:"",N){let R=l(N);v+=` ${Nt.indentComment(R,i.indent)}`}E===""&&!i.inFlow?v===` @@ -44,34 +44,34 @@ ${Nt.indentComment(R,i.indent)}`}E===""&&!i.inFlow?v===` ${i.indent}`}else if(!m&&oe.isCollection(e)){let R=E[0],b=E.indexOf(` `),x=b!==-1,F=i.inFlow??e.flow??e.items.length===0;if(x||!F){let qe=!1;if(x&&(R==="&"||R==="!")){let _=E.indexOf(" ");R==="&"&&_!==-1&&_{"use strict";var _o=Qt("process");function sf(t,...e){t==="debug"&&console.log(...e)}function cf(t,e){(t==="debug"||t==="warn")&&(typeof _o.emitWarning=="function"?_o.emitWarning(e):console.warn(e))}Yn.debug=sf;Yn.warn=cf});var gi=w(vi=>{"use strict";var mi=C(),Oo=T(),hi="<<",pi={identify:t=>t===hi||typeof t=="symbol"&&t.description===hi,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new Oo.Scalar(Symbol(hi)),{addToJSMap:jo}),stringify:()=>hi},lf=(t,e)=>(pi.identify(e)||mi.isScalar(e)&&(!e.type||e.type===Oo.Scalar.PLAIN)&&pi.identify(e.value))&&t?.doc.schema.tags.some(i=>i.tag===pi.tag&&i.default);function jo(t,e,i){let n=Ho(t,i);if(mi.isSeq(n))for(let r of n.items)Qn(t,e,r);else if(Array.isArray(n))for(let r of n)Qn(t,e,r);else Qn(t,e,n)}function Qn(t,e,i){let n=Ho(t,i);if(!mi.isMap(n))throw new Error("Merge sources must be maps or map aliases");let r=n.toJSON(null,t,Map);for(let[a,o]of r)e instanceof Map?e.has(a)||e.set(a,o):e instanceof Set?e.add(a):Object.prototype.hasOwnProperty.call(e,a)||Object.defineProperty(e,a,{value:o,writable:!0,enumerable:!0,configurable:!0});return e}function Ho(t,e){return t&&mi.isAlias(e)?e.resolve(t.doc,t):e}vi.addMergeToJSMap=jo;vi.isMergeKey=lf;vi.merge=pi});var er=w(Fo=>{"use strict";var uf=Xn(),$o=gi(),ff=yt(),Lo=C(),Zn=le();function df(t,e,{key:i,value:n}){if(Lo.isNode(i)&&i.addToJSMap)i.addToJSMap(t,e,n);else if($o.isMergeKey(t,i))$o.addMergeToJSMap(t,e,n);else{let r=Zn.toJS(i,"",t);if(e instanceof Map)e.set(r,Zn.toJS(n,r,t));else if(e instanceof Set)e.add(r);else{let a=hf(i,r,t),o=Zn.toJS(n,a,t);a in e?Object.defineProperty(e,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):e[a]=o}}return e}function hf(t,e,i){if(e===null)return"";if(typeof e!="object")return String(e);if(Lo.isNode(t)&&i?.doc){let n=ff.createStringifyContext(i.doc,{});n.anchors=new Set;for(let a of i.anchors.keys())n.anchors.add(a.anchor);n.inFlow=!0,n.inStringifyKey=!0;let r=t.toString(n);if(!i.mapKeyWarned){let a=JSON.stringify(r);a.length>40&&(a=a.substring(0,36)+'..."'),uf.warn(i.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${a}. Set mapAsMap: true to use object keys.`),i.mapKeyWarned=!0}return r}return JSON.stringify(e)}Fo.addPairToJSMap=df});var he=w(tr=>{"use strict";var Mo=pt(),pf=Io(),mf=er(),wi=C();function vf(t,e,i){let n=Mo.createNode(t,void 0,i),r=Mo.createNode(e,void 0,i);return new yi(n,r)}var yi=class t{constructor(e,i=null){Object.defineProperty(this,wi.NODE_TYPE,{value:wi.PAIR}),this.key=e,this.value=i}clone(e){let{key:i,value:n}=this;return wi.isNode(i)&&(i=i.clone(e)),wi.isNode(n)&&(n=n.clone(e)),new t(i,n)}toJSON(e,i){let n=i?.mapAsMap?new Map:{};return mf.addPairToJSMap(i,n,this)}toString(e,i,n){return e?.doc?pf.stringifyPair(this,e,i,n):JSON.stringify(this)}};tr.Pair=yi;tr.createPair=vf});var ir=w(Do=>{"use strict";var Re=C(),Bo=yt(),Ni=mt();function gf(t,e,i){return(e.inFlow??t.flow?yf:wf)(t,e,i)}function wf({comment:t,items:e},i,{blockItemPrefix:n,flowChars:r,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=i,d=Object.assign({},i,{indent:a,type:null}),u=!1,f=[];for(let g=0;gp=null,()=>u=!0);p&&(y+=Ni.lineComment(y,a,l(p))),u&&p&&(u=!1),f.push(n+y)}let m;if(f.length===0)m=r.start+r.end;else{m=f[0];for(let g=1;g{"use strict";var _o=Qt("process");function sf(t,...e){t==="debug"&&console.log(...e)}function cf(t,e){(t==="debug"||t==="warn")&&(typeof _o.emitWarning=="function"?_o.emitWarning(e):console.warn(e))}Xn.debug=sf;Xn.warn=cf});var gi=w(vi=>{"use strict";var mi=C(),Oo=T(),hi="<<",pi={identify:t=>t===hi||typeof t=="symbol"&&t.description===hi,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new Oo.Scalar(Symbol(hi)),{addToJSMap:jo}),stringify:()=>hi},lf=(t,e)=>(pi.identify(e)||mi.isScalar(e)&&(!e.type||e.type===Oo.Scalar.PLAIN)&&pi.identify(e.value))&&t?.doc.schema.tags.some(i=>i.tag===pi.tag&&i.default);function jo(t,e,i){let n=Ho(t,i);if(mi.isSeq(n))for(let r of n.items)Zn(t,e,r);else if(Array.isArray(n))for(let r of n)Zn(t,e,r);else Zn(t,e,n)}function Zn(t,e,i){let n=Ho(t,i);if(!mi.isMap(n))throw new Error("Merge sources must be maps or map aliases");let r=n.toJSON(null,t,Map);for(let[a,o]of r)e instanceof Map?e.has(a)||e.set(a,o):e instanceof Set?e.add(a):Object.prototype.hasOwnProperty.call(e,a)||Object.defineProperty(e,a,{value:o,writable:!0,enumerable:!0,configurable:!0});return e}function Ho(t,e){return t&&mi.isAlias(e)?e.resolve(t.doc,t):e}vi.addMergeToJSMap=jo;vi.isMergeKey=lf;vi.merge=pi});var tr=w(Fo=>{"use strict";var uf=Qn(),$o=gi(),ff=yt(),Lo=C(),er=le();function df(t,e,{key:i,value:n}){if(Lo.isNode(i)&&i.addToJSMap)i.addToJSMap(t,e,n);else if($o.isMergeKey(t,i))$o.addMergeToJSMap(t,e,n);else{let r=er.toJS(i,"",t);if(e instanceof Map)e.set(r,er.toJS(n,r,t));else if(e instanceof Set)e.add(r);else{let a=hf(i,r,t),o=er.toJS(n,a,t);a in e?Object.defineProperty(e,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):e[a]=o}}return e}function hf(t,e,i){if(e===null)return"";if(typeof e!="object")return String(e);if(Lo.isNode(t)&&i?.doc){let n=ff.createStringifyContext(i.doc,{});n.anchors=new Set;for(let a of i.anchors.keys())n.anchors.add(a.anchor);n.inFlow=!0,n.inStringifyKey=!0;let r=t.toString(n);if(!i.mapKeyWarned){let a=JSON.stringify(r);a.length>40&&(a=a.substring(0,36)+'..."'),uf.warn(i.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${a}. Set mapAsMap: true to use object keys.`),i.mapKeyWarned=!0}return r}return JSON.stringify(e)}Fo.addPairToJSMap=df});var he=w(ir=>{"use strict";var Mo=pt(),pf=Io(),mf=tr(),wi=C();function vf(t,e,i){let n=Mo.createNode(t,void 0,i),r=Mo.createNode(e,void 0,i);return new yi(n,r)}var yi=class t{constructor(e,i=null){Object.defineProperty(this,wi.NODE_TYPE,{value:wi.PAIR}),this.key=e,this.value=i}clone(e){let{key:i,value:n}=this;return wi.isNode(i)&&(i=i.clone(e)),wi.isNode(n)&&(n=n.clone(e)),new t(i,n)}toJSON(e,i){let n=i?.mapAsMap?new Map:{};return mf.addPairToJSMap(i,n,this)}toString(e,i,n){return e?.doc?pf.stringifyPair(this,e,i,n):JSON.stringify(this)}};ir.Pair=yi;ir.createPair=vf});var nr=w(Do=>{"use strict";var Re=C(),Bo=yt(),Ni=mt();function gf(t,e,i){return(e.inFlow??t.flow?yf:wf)(t,e,i)}function wf({comment:t,items:e},i,{blockItemPrefix:n,flowChars:r,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=i,d=Object.assign({},i,{indent:a,type:null}),u=!1,f=[];for(let g=0;gp=null,()=>u=!0);p&&(y+=Ni.lineComment(y,a,l(p))),u&&p&&(u=!1),f.push(n+y)}let m;if(f.length===0)m=r.start+r.end;else{m=f[0];for(let g=1;gp=null);l||(l=u.length>d||y.includes(` `)),g0&&(l||(l=u.reduce((N,k)=>N+k.length+2,2)+(y.length+2)>e.options.lineWidth)),l&&(y+=",")),p&&(y+=Ni.lineComment(y,n,s(p))),u.push(y),d=u.length}let{start:f,end:m}=i;if(u.length===0)return f+m;if(!l){let g=u.reduce((h,p)=>h+p.length+2,2);l=e.options.lineWidth>0&&g>e.options.lineWidth}if(l){let g=f;for(let h of u)g+=h?` ${a}${r}${h}`:` `;return`${g} -${r}${m}`}else return`${f}${o}${u.join(" ")}${o}${m}`}function bi({indent:t,options:{commentString:e}},i,n,r){if(n&&r&&(n=n.replace(/^\n+/,"")),n){let a=Ni.indentComment(e(n),t);i.push(a.trimStart())}}Do.stringifyCollection=gf});var me=w(rr=>{"use strict";var Nf=ir(),bf=er(),kf=si(),pe=C(),ki=he(),Sf=T();function bt(t,e){let i=pe.isScalar(e)?e.value:e;for(let n of t)if(pe.isPair(n)&&(n.key===e||n.key===i||pe.isScalar(n.key)&&n.key.value===i))return n}var nr=class extends kf.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(pe.MAP,e),this.items=[]}static from(e,i,n){let{keepUndefined:r,replacer:a}=n,o=new this(e),s=(c,l)=>{if(typeof a=="function")l=a.call(i,c,l);else if(Array.isArray(a)&&!a.includes(c))return;(l!==void 0||r)&&o.items.push(ki.createPair(c,l,n))};if(i instanceof Map)for(let[c,l]of i)s(c,l);else if(i&&typeof i=="object")for(let c of Object.keys(i))s(c,i[c]);return typeof e.sortMapEntries=="function"&&o.items.sort(e.sortMapEntries),o}add(e,i){let n;pe.isPair(e)?n=e:!e||typeof e!="object"||!("key"in e)?n=new ki.Pair(e,e?.value):n=new ki.Pair(e.key,e.value);let r=bt(this.items,n.key),a=this.schema?.sortMapEntries;if(r){if(!i)throw new Error(`Key ${n.key} already set`);pe.isScalar(r.value)&&Sf.isScalarValue(n.value)?r.value.value=n.value:r.value=n.value}else if(a){let o=this.items.findIndex(s=>a(n,s)<0);o===-1?this.items.push(n):this.items.splice(o,0,n)}else this.items.push(n)}delete(e){let i=bt(this.items,e);return i?this.items.splice(this.items.indexOf(i),1).length>0:!1}get(e,i){let r=bt(this.items,e)?.value;return(!i&&pe.isScalar(r)?r.value:r)??void 0}has(e){return!!bt(this.items,e)}set(e,i){this.add(new ki.Pair(e,i),!0)}toJSON(e,i,n){let r=n?new n:i?.mapAsMap?new Map:{};i?.onCreate&&i.onCreate(r);for(let a of this.items)bf.addPairToJSMap(i,r,a);return r}toString(e,i,n){if(!e)return JSON.stringify(this);for(let r of this.items)if(!pe.isPair(r))throw new Error(`Map items must all be pairs; found ${JSON.stringify(r)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),Nf.stringifyCollection(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:n,onComment:i})}};rr.YAMLMap=nr;rr.findPair=bt});var Ge=w(Vo=>{"use strict";var Ef=C(),qo=me(),Cf={collection:"map",default:!0,nodeClass:qo.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(t,e){return Ef.isMap(t)||e("Expected a mapping for this tag"),t},createNode:(t,e,i)=>qo.YAMLMap.from(t,e,i)};Vo.map=Cf});var ve=w(Wo=>{"use strict";var Rf=pt(),Pf=ir(),Af=si(),Ei=C(),xf=T(),Tf=le(),ar=class extends Af.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(Ei.SEQ,e),this.items=[]}add(e){this.items.push(e)}delete(e){let i=Si(e);return typeof i!="number"?!1:this.items.splice(i,1).length>0}get(e,i){let n=Si(e);if(typeof n!="number")return;let r=this.items[n];return!i&&Ei.isScalar(r)?r.value:r}has(e){let i=Si(e);return typeof i=="number"&&i=0?e:null}Wo.YAMLSeq=ar});var Ke=w(Jo=>{"use strict";var If=C(),zo=ve(),_f={collection:"seq",default:!0,nodeClass:zo.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(t,e){return If.isSeq(t)||e("Expected a sequence for this tag"),t},createNode:(t,e,i)=>zo.YAMLSeq.from(t,e,i)};Jo.seq=_f});var kt=w(Go=>{"use strict";var Of=wt(),jf={identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify(t,e,i,n){return e=Object.assign({actualString:!0},e),Of.stringifyString(t,e,i,n)}};Go.string=jf});var Ci=w(Yo=>{"use strict";var Ko=T(),Uo={identify:t=>t==null,createNode:()=>new Ko.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Ko.Scalar(null),stringify:({source:t},e)=>typeof t=="string"&&Uo.test.test(t)?t:e.options.nullStr};Yo.nullTag=Uo});var or=w(Qo=>{"use strict";var Hf=T(),Xo={identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:t=>new Hf.Scalar(t[0]==="t"||t[0]==="T"),stringify({source:t,value:e},i){if(t&&Xo.test.test(t)){let n=t[0]==="t"||t[0]==="T";if(e===n)return t}return e?i.options.trueStr:i.options.falseStr}};Qo.boolTag=Xo});var Ue=w(Zo=>{"use strict";function $f({format:t,minFractionDigits:e,tag:i,value:n}){if(typeof n=="bigint")return String(n);let r=typeof n=="number"?n:Number(n);if(!isFinite(r))return isNaN(r)?".nan":r<0?"-.inf":".inf";let a=Object.is(n,-0)?"-0":JSON.stringify(n);if(!t&&e&&(!i||i==="tag:yaml.org,2002:float")&&/^-?\d/.test(a)&&!a.includes("e")){let o=a.indexOf(".");o<0&&(o=a.length,a+=".");let s=e-(a.length-o-1);for(;s-- >0;)a+="0"}return a}Zo.stringifyNumber=$f});var cr=w(Ri=>{"use strict";var Lf=T(),sr=Ue(),Ff={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:t=>t.slice(-3).toLowerCase()==="nan"?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:sr.stringifyNumber},Mf={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t),stringify(t){let e=Number(t.value);return isFinite(e)?e.toExponential():sr.stringifyNumber(t)}},Bf={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(t){let e=new Lf.Scalar(parseFloat(t)),i=t.indexOf(".");return i!==-1&&t[t.length-1]==="0"&&(e.minFractionDigits=t.length-i-1),e},stringify:sr.stringifyNumber};Ri.float=Bf;Ri.floatExp=Mf;Ri.floatNaN=Ff});var ur=w(Ai=>{"use strict";var es=Ue(),Pi=t=>typeof t=="bigint"||Number.isInteger(t),lr=(t,e,i,{intAsBigInt:n})=>n?BigInt(t):parseInt(t.substring(e),i);function ts(t,e,i){let{value:n}=t;return Pi(n)&&n>=0?i+n.toString(e):es.stringifyNumber(t)}var Df={identify:t=>Pi(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(t,e,i)=>lr(t,2,8,i),stringify:t=>ts(t,8,"0o")},qf={identify:Pi,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(t,e,i)=>lr(t,0,10,i),stringify:es.stringifyNumber},Vf={identify:t=>Pi(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(t,e,i)=>lr(t,2,16,i),stringify:t=>ts(t,16,"0x")};Ai.int=qf;Ai.intHex=Vf;Ai.intOct=Df});var ns=w(is=>{"use strict";var Wf=Ge(),zf=Ci(),Jf=Ke(),Gf=kt(),Kf=or(),fr=cr(),dr=ur(),Uf=[Wf.map,Jf.seq,Gf.string,zf.nullTag,Kf.boolTag,dr.intOct,dr.int,dr.intHex,fr.floatNaN,fr.floatExp,fr.float];is.schema=Uf});var os=w(as=>{"use strict";var Yf=T(),Xf=Ge(),Qf=Ke();function rs(t){return typeof t=="bigint"||Number.isInteger(t)}var xi=({value:t})=>JSON.stringify(t),Zf=[{identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify:xi},{identify:t=>t==null,createNode:()=>new Yf.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:xi},{identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:t=>t==="true",stringify:xi},{identify:rs,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(t,e,{intAsBigInt:i})=>i?BigInt(t):parseInt(t,10),stringify:({value:t})=>rs(t)?t.toString():JSON.stringify(t)},{identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:t=>parseFloat(t),stringify:xi}],ed={default:!0,tag:"",test:/^/,resolve(t,e){return e(`Unresolved plain scalar ${JSON.stringify(t)}`),t}},td=[Xf.map,Qf.seq].concat(Zf,ed);as.schema=td});var pr=w(ss=>{"use strict";var St=Qt("buffer"),hr=T(),id=wt(),nd={identify:t=>t instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(t,e){if(typeof St.Buffer=="function")return St.Buffer.from(t,"base64");if(typeof atob=="function"){let i=atob(t.replace(/[\n\r]/g,"")),n=new Uint8Array(i.length);for(let r=0;r{"use strict";var Ti=C(),mr=he(),rd=T(),ad=ve();function cs(t,e){if(Ti.isSeq(t))for(let i=0;i1&&e("Each pair must have its own sequence indicator");let r=n.items[0]||new mr.Pair(new rd.Scalar(null));if(n.commentBefore&&(r.key.commentBefore=r.key.commentBefore?`${n.commentBefore} +${r}${m}`}else return`${f}${o}${u.join(" ")}${o}${m}`}function bi({indent:t,options:{commentString:e}},i,n,r){if(n&&r&&(n=n.replace(/^\n+/,"")),n){let a=Ni.indentComment(e(n),t);i.push(a.trimStart())}}Do.stringifyCollection=gf});var me=w(ar=>{"use strict";var Nf=nr(),bf=tr(),kf=si(),pe=C(),ki=he(),Sf=T();function bt(t,e){let i=pe.isScalar(e)?e.value:e;for(let n of t)if(pe.isPair(n)&&(n.key===e||n.key===i||pe.isScalar(n.key)&&n.key.value===i))return n}var rr=class extends kf.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(pe.MAP,e),this.items=[]}static from(e,i,n){let{keepUndefined:r,replacer:a}=n,o=new this(e),s=(c,l)=>{if(typeof a=="function")l=a.call(i,c,l);else if(Array.isArray(a)&&!a.includes(c))return;(l!==void 0||r)&&o.items.push(ki.createPair(c,l,n))};if(i instanceof Map)for(let[c,l]of i)s(c,l);else if(i&&typeof i=="object")for(let c of Object.keys(i))s(c,i[c]);return typeof e.sortMapEntries=="function"&&o.items.sort(e.sortMapEntries),o}add(e,i){let n;pe.isPair(e)?n=e:!e||typeof e!="object"||!("key"in e)?n=new ki.Pair(e,e?.value):n=new ki.Pair(e.key,e.value);let r=bt(this.items,n.key),a=this.schema?.sortMapEntries;if(r){if(!i)throw new Error(`Key ${n.key} already set`);pe.isScalar(r.value)&&Sf.isScalarValue(n.value)?r.value.value=n.value:r.value=n.value}else if(a){let o=this.items.findIndex(s=>a(n,s)<0);o===-1?this.items.push(n):this.items.splice(o,0,n)}else this.items.push(n)}delete(e){let i=bt(this.items,e);return i?this.items.splice(this.items.indexOf(i),1).length>0:!1}get(e,i){let r=bt(this.items,e)?.value;return(!i&&pe.isScalar(r)?r.value:r)??void 0}has(e){return!!bt(this.items,e)}set(e,i){this.add(new ki.Pair(e,i),!0)}toJSON(e,i,n){let r=n?new n:i?.mapAsMap?new Map:{};i?.onCreate&&i.onCreate(r);for(let a of this.items)bf.addPairToJSMap(i,r,a);return r}toString(e,i,n){if(!e)return JSON.stringify(this);for(let r of this.items)if(!pe.isPair(r))throw new Error(`Map items must all be pairs; found ${JSON.stringify(r)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),Nf.stringifyCollection(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:n,onComment:i})}};ar.YAMLMap=rr;ar.findPair=bt});var Ge=w(Vo=>{"use strict";var Ef=C(),qo=me(),Cf={collection:"map",default:!0,nodeClass:qo.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(t,e){return Ef.isMap(t)||e("Expected a mapping for this tag"),t},createNode:(t,e,i)=>qo.YAMLMap.from(t,e,i)};Vo.map=Cf});var ve=w(Wo=>{"use strict";var Rf=pt(),Pf=nr(),Af=si(),Ei=C(),xf=T(),Tf=le(),or=class extends Af.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(Ei.SEQ,e),this.items=[]}add(e){this.items.push(e)}delete(e){let i=Si(e);return typeof i!="number"?!1:this.items.splice(i,1).length>0}get(e,i){let n=Si(e);if(typeof n!="number")return;let r=this.items[n];return!i&&Ei.isScalar(r)?r.value:r}has(e){let i=Si(e);return typeof i=="number"&&i=0?e:null}Wo.YAMLSeq=or});var Ke=w(Jo=>{"use strict";var If=C(),zo=ve(),_f={collection:"seq",default:!0,nodeClass:zo.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(t,e){return If.isSeq(t)||e("Expected a sequence for this tag"),t},createNode:(t,e,i)=>zo.YAMLSeq.from(t,e,i)};Jo.seq=_f});var kt=w(Go=>{"use strict";var Of=wt(),jf={identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify(t,e,i,n){return e=Object.assign({actualString:!0},e),Of.stringifyString(t,e,i,n)}};Go.string=jf});var Ci=w(Yo=>{"use strict";var Ko=T(),Uo={identify:t=>t==null,createNode:()=>new Ko.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Ko.Scalar(null),stringify:({source:t},e)=>typeof t=="string"&&Uo.test.test(t)?t:e.options.nullStr};Yo.nullTag=Uo});var sr=w(Qo=>{"use strict";var Hf=T(),Xo={identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:t=>new Hf.Scalar(t[0]==="t"||t[0]==="T"),stringify({source:t,value:e},i){if(t&&Xo.test.test(t)){let n=t[0]==="t"||t[0]==="T";if(e===n)return t}return e?i.options.trueStr:i.options.falseStr}};Qo.boolTag=Xo});var Ue=w(Zo=>{"use strict";function $f({format:t,minFractionDigits:e,tag:i,value:n}){if(typeof n=="bigint")return String(n);let r=typeof n=="number"?n:Number(n);if(!isFinite(r))return isNaN(r)?".nan":r<0?"-.inf":".inf";let a=Object.is(n,-0)?"-0":JSON.stringify(n);if(!t&&e&&(!i||i==="tag:yaml.org,2002:float")&&/^-?\d/.test(a)&&!a.includes("e")){let o=a.indexOf(".");o<0&&(o=a.length,a+=".");let s=e-(a.length-o-1);for(;s-- >0;)a+="0"}return a}Zo.stringifyNumber=$f});var lr=w(Ri=>{"use strict";var Lf=T(),cr=Ue(),Ff={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:t=>t.slice(-3).toLowerCase()==="nan"?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:cr.stringifyNumber},Mf={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t),stringify(t){let e=Number(t.value);return isFinite(e)?e.toExponential():cr.stringifyNumber(t)}},Bf={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(t){let e=new Lf.Scalar(parseFloat(t)),i=t.indexOf(".");return i!==-1&&t[t.length-1]==="0"&&(e.minFractionDigits=t.length-i-1),e},stringify:cr.stringifyNumber};Ri.float=Bf;Ri.floatExp=Mf;Ri.floatNaN=Ff});var fr=w(Ai=>{"use strict";var es=Ue(),Pi=t=>typeof t=="bigint"||Number.isInteger(t),ur=(t,e,i,{intAsBigInt:n})=>n?BigInt(t):parseInt(t.substring(e),i);function ts(t,e,i){let{value:n}=t;return Pi(n)&&n>=0?i+n.toString(e):es.stringifyNumber(t)}var Df={identify:t=>Pi(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(t,e,i)=>ur(t,2,8,i),stringify:t=>ts(t,8,"0o")},qf={identify:Pi,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(t,e,i)=>ur(t,0,10,i),stringify:es.stringifyNumber},Vf={identify:t=>Pi(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(t,e,i)=>ur(t,2,16,i),stringify:t=>ts(t,16,"0x")};Ai.int=qf;Ai.intHex=Vf;Ai.intOct=Df});var ns=w(is=>{"use strict";var Wf=Ge(),zf=Ci(),Jf=Ke(),Gf=kt(),Kf=sr(),dr=lr(),hr=fr(),Uf=[Wf.map,Jf.seq,Gf.string,zf.nullTag,Kf.boolTag,hr.intOct,hr.int,hr.intHex,dr.floatNaN,dr.floatExp,dr.float];is.schema=Uf});var os=w(as=>{"use strict";var Yf=T(),Xf=Ge(),Qf=Ke();function rs(t){return typeof t=="bigint"||Number.isInteger(t)}var xi=({value:t})=>JSON.stringify(t),Zf=[{identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify:xi},{identify:t=>t==null,createNode:()=>new Yf.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:xi},{identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:t=>t==="true",stringify:xi},{identify:rs,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(t,e,{intAsBigInt:i})=>i?BigInt(t):parseInt(t,10),stringify:({value:t})=>rs(t)?t.toString():JSON.stringify(t)},{identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:t=>parseFloat(t),stringify:xi}],ed={default:!0,tag:"",test:/^/,resolve(t,e){return e(`Unresolved plain scalar ${JSON.stringify(t)}`),t}},td=[Xf.map,Qf.seq].concat(Zf,ed);as.schema=td});var mr=w(ss=>{"use strict";var St=Qt("buffer"),pr=T(),id=wt(),nd={identify:t=>t instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(t,e){if(typeof St.Buffer=="function")return St.Buffer.from(t,"base64");if(typeof atob=="function"){let i=atob(t.replace(/[\n\r]/g,"")),n=new Uint8Array(i.length);for(let r=0;r{"use strict";var Ti=C(),vr=he(),rd=T(),ad=ve();function cs(t,e){if(Ti.isSeq(t))for(let i=0;i1&&e("Each pair must have its own sequence indicator");let r=n.items[0]||new vr.Pair(new rd.Scalar(null));if(n.commentBefore&&(r.key.commentBefore=r.key.commentBefore?`${n.commentBefore} ${r.key.commentBefore}`:n.commentBefore),n.comment){let a=r.value??r.key;a.comment=a.comment?`${n.comment} -${a.comment}`:n.comment}n=r}t.items[i]=Ti.isPair(n)?n:new mr.Pair(n)}}else e("Expected a sequence for this tag");return t}function ls(t,e,i){let{replacer:n}=i,r=new ad.YAMLSeq(t);r.tag="tag:yaml.org,2002:pairs";let a=0;if(e&&Symbol.iterator in Object(e))for(let o of e){typeof n=="function"&&(o=n.call(e,String(a++),o));let s,c;if(Array.isArray(o))if(o.length===2)s=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)s=l[0],c=o[s];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else s=o;r.items.push(mr.createPair(s,c,i))}return r}var od={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:cs,createNode:ls};Ii.createPairs=ls;Ii.pairs=od;Ii.resolvePairs=cs});var wr=w(gr=>{"use strict";var us=C(),vr=le(),Et=me(),sd=ve(),fs=_i(),Pe=class t extends sd.YAMLSeq{constructor(){super(),this.add=Et.YAMLMap.prototype.add.bind(this),this.delete=Et.YAMLMap.prototype.delete.bind(this),this.get=Et.YAMLMap.prototype.get.bind(this),this.has=Et.YAMLMap.prototype.has.bind(this),this.set=Et.YAMLMap.prototype.set.bind(this),this.tag=t.tag}toJSON(e,i){if(!i)return super.toJSON(e);let n=new Map;i?.onCreate&&i.onCreate(n);for(let r of this.items){let a,o;if(us.isPair(r)?(a=vr.toJS(r.key,"",i),o=vr.toJS(r.value,a,i)):a=vr.toJS(r,"",i),n.has(a))throw new Error("Ordered maps must not include duplicate keys");n.set(a,o)}return n}static from(e,i,n){let r=fs.createPairs(e,i,n),a=new this;return a.items=r.items,a}};Pe.tag="tag:yaml.org,2002:omap";var cd={collection:"seq",identify:t=>t instanceof Map,nodeClass:Pe,default:!1,tag:"tag:yaml.org,2002:omap",resolve(t,e){let i=fs.resolvePairs(t,e),n=[];for(let{key:r}of i.items)us.isScalar(r)&&(n.includes(r.value)?e(`Ordered maps must not include duplicate keys: ${r.value}`):n.push(r.value));return Object.assign(new Pe,i)},createNode:(t,e,i)=>Pe.from(t,e,i)};gr.YAMLOMap=Pe;gr.omap=cd});var vs=w(yr=>{"use strict";var ds=T();function hs({value:t,source:e},i){return e&&(t?ps:ms).test.test(e)?e:t?i.options.trueStr:i.options.falseStr}var ps={identify:t=>t===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new ds.Scalar(!0),stringify:hs},ms={identify:t=>t===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new ds.Scalar(!1),stringify:hs};yr.falseTag=ms;yr.trueTag=ps});var gs=w(Oi=>{"use strict";var ld=T(),Nr=Ue(),ud={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:t=>t.slice(-3).toLowerCase()==="nan"?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Nr.stringifyNumber},fd={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t.replace(/_/g,"")),stringify(t){let e=Number(t.value);return isFinite(e)?e.toExponential():Nr.stringifyNumber(t)}},dd={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(t){let e=new ld.Scalar(parseFloat(t.replace(/_/g,""))),i=t.indexOf(".");if(i!==-1){let n=t.substring(i+1).replace(/_/g,"");n[n.length-1]==="0"&&(e.minFractionDigits=n.length)}return e},stringify:Nr.stringifyNumber};Oi.float=dd;Oi.floatExp=fd;Oi.floatNaN=ud});var ys=w(Rt=>{"use strict";var ws=Ue(),Ct=t=>typeof t=="bigint"||Number.isInteger(t);function ji(t,e,i,{intAsBigInt:n}){let r=t[0];if((r==="-"||r==="+")&&(e+=1),t=t.substring(e).replace(/_/g,""),n){switch(i){case 2:t=`0b${t}`;break;case 8:t=`0o${t}`;break;case 16:t=`0x${t}`;break}let o=BigInt(t);return r==="-"?BigInt(-1)*o:o}let a=parseInt(t,i);return r==="-"?-1*a:a}function br(t,e,i){let{value:n}=t;if(Ct(n)){let r=n.toString(e);return n<0?"-"+i+r.substr(1):i+r}return ws.stringifyNumber(t)}var hd={identify:Ct,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(t,e,i)=>ji(t,2,2,i),stringify:t=>br(t,2,"0b")},pd={identify:Ct,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(t,e,i)=>ji(t,1,8,i),stringify:t=>br(t,8,"0")},md={identify:Ct,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(t,e,i)=>ji(t,0,10,i),stringify:ws.stringifyNumber},vd={identify:Ct,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(t,e,i)=>ji(t,2,16,i),stringify:t=>br(t,16,"0x")};Rt.int=md;Rt.intBin=hd;Rt.intHex=vd;Rt.intOct=pd});var Sr=w(kr=>{"use strict";var Li=C(),Hi=he(),$i=me(),Ae=class t extends $i.YAMLMap{constructor(e){super(e),this.tag=t.tag}add(e){let i;Li.isPair(e)?i=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?i=new Hi.Pair(e.key,null):i=new Hi.Pair(e,null),$i.findPair(this.items,i.key)||this.items.push(i)}get(e,i){let n=$i.findPair(this.items,e);return!i&&Li.isPair(n)?Li.isScalar(n.key)?n.key.value:n.key:n}set(e,i){if(typeof i!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof i}`);let n=$i.findPair(this.items,e);n&&!i?this.items.splice(this.items.indexOf(n),1):!n&&i&&this.items.push(new Hi.Pair(e))}toJSON(e,i){return super.toJSON(e,i,Set)}toString(e,i,n){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),i,n);throw new Error("Set items must all have null values")}static from(e,i,n){let{replacer:r}=n,a=new this(e);if(i&&Symbol.iterator in Object(i))for(let o of i)typeof r=="function"&&(o=r.call(i,o,o)),a.items.push(Hi.createPair(o,null,n));return a}};Ae.tag="tag:yaml.org,2002:set";var gd={collection:"map",identify:t=>t instanceof Set,nodeClass:Ae,default:!1,tag:"tag:yaml.org,2002:set",createNode:(t,e,i)=>Ae.from(t,e,i),resolve(t,e){if(Li.isMap(t)){if(t.hasAllNullValues(!0))return Object.assign(new Ae,t);e("Set items must all have null values")}else e("Expected a mapping for this tag");return t}};kr.YAMLSet=Ae;kr.set=gd});var Cr=w(Fi=>{"use strict";var wd=Ue();function Er(t,e){let i=t[0],n=i==="-"||i==="+"?t.substring(1):t,r=o=>e?BigInt(o):Number(o),a=n.replace(/_/g,"").split(":").reduce((o,s)=>o*r(60)+r(s),r(0));return i==="-"?r(-1)*a:a}function Ns(t){let{value:e}=t,i=o=>o;if(typeof e=="bigint")i=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return wd.stringifyNumber(t);let n="";e<0&&(n="-",e*=i(-1));let r=i(60),a=[e%r];return e<60?a.unshift(0):(e=(e-a[0])/r,a.unshift(e%r),e>=60&&(e=(e-a[0])/r,a.unshift(e))),n+a.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var yd={identify:t=>typeof t=="bigint"||Number.isInteger(t),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(t,e,{intAsBigInt:i})=>Er(t,i),stringify:Ns},Nd={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:t=>Er(t,!1),stringify:Ns},bs={identify:t=>t instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(t){let e=t.match(bs.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,i,n,r,a,o,s]=e.map(Number),c=e[7]?Number((e[7]+"00").substr(1,3)):0,l=Date.UTC(i,n-1,r,a||0,o||0,s||0,c),d=e[8];if(d&&d!=="Z"){let u=Er(d,!1);Math.abs(u)<30&&(u*=60),l-=6e4*u}return new Date(l)},stringify:({value:t})=>t?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};Fi.floatTime=Nd;Fi.intTime=yd;Fi.timestamp=bs});var Es=w(Ss=>{"use strict";var bd=Ge(),kd=Ci(),Sd=Ke(),Ed=kt(),Cd=pr(),ks=vs(),Rr=gs(),Mi=ys(),Rd=gi(),Pd=wr(),Ad=_i(),xd=Sr(),Pr=Cr(),Td=[bd.map,Sd.seq,Ed.string,kd.nullTag,ks.trueTag,ks.falseTag,Mi.intBin,Mi.intOct,Mi.int,Mi.intHex,Rr.floatNaN,Rr.floatExp,Rr.float,Cd.binary,Rd.merge,Pd.omap,Ad.pairs,xd.set,Pr.intTime,Pr.floatTime,Pr.timestamp];Ss.schema=Td});var js=w(Tr=>{"use strict";var As=Ge(),Id=Ci(),xs=Ke(),_d=kt(),Od=or(),Ar=cr(),xr=ur(),jd=ns(),Hd=os(),Ts=pr(),Pt=gi(),Is=wr(),_s=_i(),Cs=Es(),Os=Sr(),Bi=Cr(),Rs=new Map([["core",jd.schema],["failsafe",[As.map,xs.seq,_d.string]],["json",Hd.schema],["yaml11",Cs.schema],["yaml-1.1",Cs.schema]]),Ps={binary:Ts.binary,bool:Od.boolTag,float:Ar.float,floatExp:Ar.floatExp,floatNaN:Ar.floatNaN,floatTime:Bi.floatTime,int:xr.int,intHex:xr.intHex,intOct:xr.intOct,intTime:Bi.intTime,map:As.map,merge:Pt.merge,null:Id.nullTag,omap:Is.omap,pairs:_s.pairs,seq:xs.seq,set:Os.set,timestamp:Bi.timestamp},$d={"tag:yaml.org,2002:binary":Ts.binary,"tag:yaml.org,2002:merge":Pt.merge,"tag:yaml.org,2002:omap":Is.omap,"tag:yaml.org,2002:pairs":_s.pairs,"tag:yaml.org,2002:set":Os.set,"tag:yaml.org,2002:timestamp":Bi.timestamp};function Ld(t,e,i){let n=Rs.get(e);if(n&&!t)return i&&!n.includes(Pt.merge)?n.concat(Pt.merge):n.slice();let r=n;if(!r)if(Array.isArray(t))r=[];else{let a=Array.from(Rs.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${e}"; use one of ${a} or define customTags array`)}if(Array.isArray(t))for(let a of t)r=r.concat(a);else typeof t=="function"&&(r=t(r.slice()));return i&&(r=r.concat(Pt.merge)),r.reduce((a,o)=>{let s=typeof o=="string"?Ps[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(Ps).map(d=>JSON.stringify(d)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return a.includes(s)||a.push(s),a},[])}Tr.coreKnownTags=$d;Tr.getTags=Ld});var Or=w(Hs=>{"use strict";var Ir=C(),Fd=Ge(),Md=Ke(),Bd=kt(),Di=js(),Dd=(t,e)=>t.keye.key?1:0,_r=class t{constructor({compat:e,customTags:i,merge:n,resolveKnownTags:r,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(e)?Di.getTags(e,"compat"):e?Di.getTags(null,e):null,this.name=typeof a=="string"&&a||"core",this.knownTags=r?Di.coreKnownTags:{},this.tags=Di.getTags(i,this.name,n),this.toStringOptions=s??null,Object.defineProperty(this,Ir.MAP,{value:Fd.map}),Object.defineProperty(this,Ir.SCALAR,{value:Bd.string}),Object.defineProperty(this,Ir.SEQ,{value:Md.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?Dd:null}clone(){let e=Object.create(t.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};Hs.Schema=_r});var Ls=w($s=>{"use strict";var qd=C(),jr=yt(),At=mt();function Vd(t,e){let i=[],n=e.directives===!0;if(e.directives!==!1&&t.directives){let c=t.directives.toString(t);c?(i.push(c),n=!0):t.directives.docStart&&(n=!0)}n&&i.push("---");let r=jr.createStringifyContext(t,e),{commentString:a}=r.options;if(t.commentBefore){i.length!==1&&i.unshift("");let c=a(t.commentBefore);i.unshift(At.indentComment(c,""))}let o=!1,s=null;if(t.contents){if(qd.isNode(t.contents)){if(t.contents.spaceBefore&&n&&i.push(""),t.contents.commentBefore){let d=a(t.contents.commentBefore);i.push(At.indentComment(d,""))}r.forceBlockIndent=!!t.comment,s=t.contents.comment}let c=s?void 0:()=>o=!0,l=jr.stringify(t.contents,r,()=>s=null,c);s&&(l+=At.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&i[i.length-1]==="---"?i[i.length-1]=`--- ${l}`:i.push(l)}else i.push(jr.stringify(t.contents,r));if(t.directives?.docEnd)if(t.comment){let c=a(t.comment);c.includes(` +${a.comment}`:n.comment}n=r}t.items[i]=Ti.isPair(n)?n:new vr.Pair(n)}}else e("Expected a sequence for this tag");return t}function ls(t,e,i){let{replacer:n}=i,r=new ad.YAMLSeq(t);r.tag="tag:yaml.org,2002:pairs";let a=0;if(e&&Symbol.iterator in Object(e))for(let o of e){typeof n=="function"&&(o=n.call(e,String(a++),o));let s,c;if(Array.isArray(o))if(o.length===2)s=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)s=l[0],c=o[s];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else s=o;r.items.push(vr.createPair(s,c,i))}return r}var od={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:cs,createNode:ls};Ii.createPairs=ls;Ii.pairs=od;Ii.resolvePairs=cs});var yr=w(wr=>{"use strict";var us=C(),gr=le(),Et=me(),sd=ve(),fs=_i(),Pe=class t extends sd.YAMLSeq{constructor(){super(),this.add=Et.YAMLMap.prototype.add.bind(this),this.delete=Et.YAMLMap.prototype.delete.bind(this),this.get=Et.YAMLMap.prototype.get.bind(this),this.has=Et.YAMLMap.prototype.has.bind(this),this.set=Et.YAMLMap.prototype.set.bind(this),this.tag=t.tag}toJSON(e,i){if(!i)return super.toJSON(e);let n=new Map;i?.onCreate&&i.onCreate(n);for(let r of this.items){let a,o;if(us.isPair(r)?(a=gr.toJS(r.key,"",i),o=gr.toJS(r.value,a,i)):a=gr.toJS(r,"",i),n.has(a))throw new Error("Ordered maps must not include duplicate keys");n.set(a,o)}return n}static from(e,i,n){let r=fs.createPairs(e,i,n),a=new this;return a.items=r.items,a}};Pe.tag="tag:yaml.org,2002:omap";var cd={collection:"seq",identify:t=>t instanceof Map,nodeClass:Pe,default:!1,tag:"tag:yaml.org,2002:omap",resolve(t,e){let i=fs.resolvePairs(t,e),n=[];for(let{key:r}of i.items)us.isScalar(r)&&(n.includes(r.value)?e(`Ordered maps must not include duplicate keys: ${r.value}`):n.push(r.value));return Object.assign(new Pe,i)},createNode:(t,e,i)=>Pe.from(t,e,i)};wr.YAMLOMap=Pe;wr.omap=cd});var vs=w(Nr=>{"use strict";var ds=T();function hs({value:t,source:e},i){return e&&(t?ps:ms).test.test(e)?e:t?i.options.trueStr:i.options.falseStr}var ps={identify:t=>t===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new ds.Scalar(!0),stringify:hs},ms={identify:t=>t===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new ds.Scalar(!1),stringify:hs};Nr.falseTag=ms;Nr.trueTag=ps});var gs=w(Oi=>{"use strict";var ld=T(),br=Ue(),ud={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:t=>t.slice(-3).toLowerCase()==="nan"?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:br.stringifyNumber},fd={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t.replace(/_/g,"")),stringify(t){let e=Number(t.value);return isFinite(e)?e.toExponential():br.stringifyNumber(t)}},dd={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(t){let e=new ld.Scalar(parseFloat(t.replace(/_/g,""))),i=t.indexOf(".");if(i!==-1){let n=t.substring(i+1).replace(/_/g,"");n[n.length-1]==="0"&&(e.minFractionDigits=n.length)}return e},stringify:br.stringifyNumber};Oi.float=dd;Oi.floatExp=fd;Oi.floatNaN=ud});var ys=w(Rt=>{"use strict";var ws=Ue(),Ct=t=>typeof t=="bigint"||Number.isInteger(t);function ji(t,e,i,{intAsBigInt:n}){let r=t[0];if((r==="-"||r==="+")&&(e+=1),t=t.substring(e).replace(/_/g,""),n){switch(i){case 2:t=`0b${t}`;break;case 8:t=`0o${t}`;break;case 16:t=`0x${t}`;break}let o=BigInt(t);return r==="-"?BigInt(-1)*o:o}let a=parseInt(t,i);return r==="-"?-1*a:a}function kr(t,e,i){let{value:n}=t;if(Ct(n)){let r=n.toString(e);return n<0?"-"+i+r.substr(1):i+r}return ws.stringifyNumber(t)}var hd={identify:Ct,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(t,e,i)=>ji(t,2,2,i),stringify:t=>kr(t,2,"0b")},pd={identify:Ct,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(t,e,i)=>ji(t,1,8,i),stringify:t=>kr(t,8,"0")},md={identify:Ct,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(t,e,i)=>ji(t,0,10,i),stringify:ws.stringifyNumber},vd={identify:Ct,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(t,e,i)=>ji(t,2,16,i),stringify:t=>kr(t,16,"0x")};Rt.int=md;Rt.intBin=hd;Rt.intHex=vd;Rt.intOct=pd});var Er=w(Sr=>{"use strict";var Li=C(),Hi=he(),$i=me(),Ae=class t extends $i.YAMLMap{constructor(e){super(e),this.tag=t.tag}add(e){let i;Li.isPair(e)?i=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?i=new Hi.Pair(e.key,null):i=new Hi.Pair(e,null),$i.findPair(this.items,i.key)||this.items.push(i)}get(e,i){let n=$i.findPair(this.items,e);return!i&&Li.isPair(n)?Li.isScalar(n.key)?n.key.value:n.key:n}set(e,i){if(typeof i!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof i}`);let n=$i.findPair(this.items,e);n&&!i?this.items.splice(this.items.indexOf(n),1):!n&&i&&this.items.push(new Hi.Pair(e))}toJSON(e,i){return super.toJSON(e,i,Set)}toString(e,i,n){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),i,n);throw new Error("Set items must all have null values")}static from(e,i,n){let{replacer:r}=n,a=new this(e);if(i&&Symbol.iterator in Object(i))for(let o of i)typeof r=="function"&&(o=r.call(i,o,o)),a.items.push(Hi.createPair(o,null,n));return a}};Ae.tag="tag:yaml.org,2002:set";var gd={collection:"map",identify:t=>t instanceof Set,nodeClass:Ae,default:!1,tag:"tag:yaml.org,2002:set",createNode:(t,e,i)=>Ae.from(t,e,i),resolve(t,e){if(Li.isMap(t)){if(t.hasAllNullValues(!0))return Object.assign(new Ae,t);e("Set items must all have null values")}else e("Expected a mapping for this tag");return t}};Sr.YAMLSet=Ae;Sr.set=gd});var Rr=w(Fi=>{"use strict";var wd=Ue();function Cr(t,e){let i=t[0],n=i==="-"||i==="+"?t.substring(1):t,r=o=>e?BigInt(o):Number(o),a=n.replace(/_/g,"").split(":").reduce((o,s)=>o*r(60)+r(s),r(0));return i==="-"?r(-1)*a:a}function Ns(t){let{value:e}=t,i=o=>o;if(typeof e=="bigint")i=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return wd.stringifyNumber(t);let n="";e<0&&(n="-",e*=i(-1));let r=i(60),a=[e%r];return e<60?a.unshift(0):(e=(e-a[0])/r,a.unshift(e%r),e>=60&&(e=(e-a[0])/r,a.unshift(e))),n+a.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var yd={identify:t=>typeof t=="bigint"||Number.isInteger(t),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(t,e,{intAsBigInt:i})=>Cr(t,i),stringify:Ns},Nd={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:t=>Cr(t,!1),stringify:Ns},bs={identify:t=>t instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(t){let e=t.match(bs.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,i,n,r,a,o,s]=e.map(Number),c=e[7]?Number((e[7]+"00").substr(1,3)):0,l=Date.UTC(i,n-1,r,a||0,o||0,s||0,c),d=e[8];if(d&&d!=="Z"){let u=Cr(d,!1);Math.abs(u)<30&&(u*=60),l-=6e4*u}return new Date(l)},stringify:({value:t})=>t?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};Fi.floatTime=Nd;Fi.intTime=yd;Fi.timestamp=bs});var Es=w(Ss=>{"use strict";var bd=Ge(),kd=Ci(),Sd=Ke(),Ed=kt(),Cd=mr(),ks=vs(),Pr=gs(),Mi=ys(),Rd=gi(),Pd=yr(),Ad=_i(),xd=Er(),Ar=Rr(),Td=[bd.map,Sd.seq,Ed.string,kd.nullTag,ks.trueTag,ks.falseTag,Mi.intBin,Mi.intOct,Mi.int,Mi.intHex,Pr.floatNaN,Pr.floatExp,Pr.float,Cd.binary,Rd.merge,Pd.omap,Ad.pairs,xd.set,Ar.intTime,Ar.floatTime,Ar.timestamp];Ss.schema=Td});var js=w(Ir=>{"use strict";var As=Ge(),Id=Ci(),xs=Ke(),_d=kt(),Od=sr(),xr=lr(),Tr=fr(),jd=ns(),Hd=os(),Ts=mr(),Pt=gi(),Is=yr(),_s=_i(),Cs=Es(),Os=Er(),Bi=Rr(),Rs=new Map([["core",jd.schema],["failsafe",[As.map,xs.seq,_d.string]],["json",Hd.schema],["yaml11",Cs.schema],["yaml-1.1",Cs.schema]]),Ps={binary:Ts.binary,bool:Od.boolTag,float:xr.float,floatExp:xr.floatExp,floatNaN:xr.floatNaN,floatTime:Bi.floatTime,int:Tr.int,intHex:Tr.intHex,intOct:Tr.intOct,intTime:Bi.intTime,map:As.map,merge:Pt.merge,null:Id.nullTag,omap:Is.omap,pairs:_s.pairs,seq:xs.seq,set:Os.set,timestamp:Bi.timestamp},$d={"tag:yaml.org,2002:binary":Ts.binary,"tag:yaml.org,2002:merge":Pt.merge,"tag:yaml.org,2002:omap":Is.omap,"tag:yaml.org,2002:pairs":_s.pairs,"tag:yaml.org,2002:set":Os.set,"tag:yaml.org,2002:timestamp":Bi.timestamp};function Ld(t,e,i){let n=Rs.get(e);if(n&&!t)return i&&!n.includes(Pt.merge)?n.concat(Pt.merge):n.slice();let r=n;if(!r)if(Array.isArray(t))r=[];else{let a=Array.from(Rs.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${e}"; use one of ${a} or define customTags array`)}if(Array.isArray(t))for(let a of t)r=r.concat(a);else typeof t=="function"&&(r=t(r.slice()));return i&&(r=r.concat(Pt.merge)),r.reduce((a,o)=>{let s=typeof o=="string"?Ps[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(Ps).map(d=>JSON.stringify(d)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return a.includes(s)||a.push(s),a},[])}Ir.coreKnownTags=$d;Ir.getTags=Ld});var jr=w(Hs=>{"use strict";var _r=C(),Fd=Ge(),Md=Ke(),Bd=kt(),Di=js(),Dd=(t,e)=>t.keye.key?1:0,Or=class t{constructor({compat:e,customTags:i,merge:n,resolveKnownTags:r,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(e)?Di.getTags(e,"compat"):e?Di.getTags(null,e):null,this.name=typeof a=="string"&&a||"core",this.knownTags=r?Di.coreKnownTags:{},this.tags=Di.getTags(i,this.name,n),this.toStringOptions=s??null,Object.defineProperty(this,_r.MAP,{value:Fd.map}),Object.defineProperty(this,_r.SCALAR,{value:Bd.string}),Object.defineProperty(this,_r.SEQ,{value:Md.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?Dd:null}clone(){let e=Object.create(t.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};Hs.Schema=Or});var Ls=w($s=>{"use strict";var qd=C(),Hr=yt(),At=mt();function Vd(t,e){let i=[],n=e.directives===!0;if(e.directives!==!1&&t.directives){let c=t.directives.toString(t);c?(i.push(c),n=!0):t.directives.docStart&&(n=!0)}n&&i.push("---");let r=Hr.createStringifyContext(t,e),{commentString:a}=r.options;if(t.commentBefore){i.length!==1&&i.unshift("");let c=a(t.commentBefore);i.unshift(At.indentComment(c,""))}let o=!1,s=null;if(t.contents){if(qd.isNode(t.contents)){if(t.contents.spaceBefore&&n&&i.push(""),t.contents.commentBefore){let d=a(t.contents.commentBefore);i.push(At.indentComment(d,""))}r.forceBlockIndent=!!t.comment,s=t.contents.comment}let c=s?void 0:()=>o=!0,l=Hr.stringify(t.contents,r,()=>s=null,c);s&&(l+=At.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&i[i.length-1]==="---"?i[i.length-1]=`--- ${l}`:i.push(l)}else i.push(Hr.stringify(t.contents,r));if(t.directives?.docEnd)if(t.comment){let c=a(t.comment);c.includes(` `)?(i.push("..."),i.push(At.indentComment(c,""))):i.push(`... ${c}`)}else i.push("...");else{let c=t.comment;c&&o&&(c=c.replace(/^\n+/,"")),c&&((!o||s)&&i[i.length-1]!==""&&i.push(""),i.push(At.indentComment(a(c),"")))}return i.join(` `)+` -`}$s.stringifyDocument=Vd});var xt=w(Fs=>{"use strict";var Wd=ht(),Ye=si(),M=C(),zd=he(),Jd=le(),Gd=Or(),Kd=Ls(),Hr=ni(),Ud=Mn(),Yd=pt(),$r=Fn(),Lr=class t{constructor(e,i,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,M.NODE_TYPE,{value:M.DOC});let r=null;typeof i=="function"||Array.isArray(i)?r=i:n===void 0&&i&&(n=i,i=void 0);let a=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},n);this.options=a;let{version:o}=a;n?._directives?(this.directives=n._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new $r.Directives({version:o}),this.setSchema(o,n),this.contents=e===void 0?null:this.createNode(e,r,n)}clone(){let e=Object.create(t.prototype,{[M.NODE_TYPE]:{value:M.DOC}});return e.commentBefore=this.commentBefore,e.comment=this.comment,e.errors=this.errors.slice(),e.warnings=this.warnings.slice(),e.options=Object.assign({},this.options),this.directives&&(e.directives=this.directives.clone()),e.schema=this.schema.clone(),e.contents=M.isNode(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){Xe(this.contents)&&this.contents.add(e)}addIn(e,i){Xe(this.contents)&&this.contents.addIn(e,i)}createAlias(e,i){if(!e.anchor){let n=Hr.anchorNames(this);e.anchor=!i||n.has(i)?Hr.findNewAnchor(i||"a",n):i}return new Wd.Alias(e.anchor)}createNode(e,i,n){let r;if(typeof i=="function")e=i.call({"":e},"",e),r=i;else if(Array.isArray(i)){let p=N=>typeof N=="number"||N instanceof String||N instanceof Number,y=i.filter(p).map(String);y.length>0&&(i=i.concat(y)),r=i}else n===void 0&&i&&(n=i,i=void 0);let{aliasDuplicateObjects:a,anchorPrefix:o,flow:s,keepUndefined:c,onTagObj:l,tag:d}=n??{},{onAnchor:u,setAnchors:f,sourceObjects:m}=Hr.createNodeAnchors(this,o||"a"),g={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:u,onTagObj:l,replacer:r,schema:this.schema,sourceObjects:m},h=Yd.createNode(e,d,g);return s&&M.isCollection(h)&&(h.flow=!0),f(),h}createPair(e,i,n={}){let r=this.createNode(e,null,n),a=this.createNode(i,null,n);return new zd.Pair(r,a)}delete(e){return Xe(this.contents)?this.contents.delete(e):!1}deleteIn(e){return Ye.isEmptyPath(e)?this.contents==null?!1:(this.contents=null,!0):Xe(this.contents)?this.contents.deleteIn(e):!1}get(e,i){return M.isCollection(this.contents)?this.contents.get(e,i):void 0}getIn(e,i){return Ye.isEmptyPath(e)?!i&&M.isScalar(this.contents)?this.contents.value:this.contents:M.isCollection(this.contents)?this.contents.getIn(e,i):void 0}has(e){return M.isCollection(this.contents)?this.contents.has(e):!1}hasIn(e){return Ye.isEmptyPath(e)?this.contents!==void 0:M.isCollection(this.contents)?this.contents.hasIn(e):!1}set(e,i){this.contents==null?this.contents=Ye.collectionFromPath(this.schema,[e],i):Xe(this.contents)&&this.contents.set(e,i)}setIn(e,i){Ye.isEmptyPath(e)?this.contents=i:this.contents==null?this.contents=Ye.collectionFromPath(this.schema,Array.from(e),i):Xe(this.contents)&&this.contents.setIn(e,i)}setSchema(e,i={}){typeof e=="number"&&(e=String(e));let n;switch(e){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new $r.Directives({version:"1.1"}),n={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=e:this.directives=new $r.Directives({version:e}),n={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,n=null;break;default:{let r=JSON.stringify(e);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${r}`)}}if(i.schema instanceof Object)this.schema=i.schema;else if(n)this.schema=new Gd.Schema(Object.assign(n,i));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:e,jsonArg:i,mapAsMap:n,maxAliasCount:r,onAnchor:a,reviver:o}={}){let s={anchors:new Map,doc:this,keep:!e,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},c=Jd.toJS(this.contents,i??"",s);if(typeof a=="function")for(let{count:l,res:d}of s.anchors.values())a(d,l);return typeof o=="function"?Ud.applyReviver(o,{"":c},"",c):c}toJSON(e,i){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:i})}toString(e={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let i=JSON.stringify(e.indent);throw new Error(`"indent" option must be a positive integer, not ${i}`)}return Kd.stringifyDocument(this,e)}};function Xe(t){if(M.isCollection(t))return!0;throw new Error("Expected a YAML collection as document contents")}Fs.Document=Lr});var _t=w(It=>{"use strict";var Tt=class extends Error{constructor(e,i,n,r){super(),this.name=e,this.code=n,this.message=r,this.pos=i}},Fr=class extends Tt{constructor(e,i,n){super("YAMLParseError",e,i,n)}},Mr=class extends Tt{constructor(e,i,n){super("YAMLWarning",e,i,n)}},Xd=(t,e)=>i=>{if(i.pos[0]===-1)return;i.linePos=i.pos.map(s=>e.linePos(s));let{line:n,col:r}=i.linePos[0];i.message+=` at line ${n}, column ${r}`;let a=r-1,o=t.substring(e.lineStarts[n-1],e.lineStarts[n]).replace(/[\n\r]+$/,"");if(a>=60&&o.length>80){let s=Math.min(a-39,o.length-79);o="…"+o.substring(s),a-=s-1}if(o.length>80&&(o=o.substring(0,79)+"…"),n>1&&/^ *$/.test(o.substring(0,a))){let s=t.substring(e.lineStarts[n-2],e.lineStarts[n-1]);s.length>80&&(s=s.substring(0,79)+`… +`}$s.stringifyDocument=Vd});var xt=w(Fs=>{"use strict";var Wd=ht(),Ye=si(),M=C(),zd=he(),Jd=le(),Gd=jr(),Kd=Ls(),$r=ni(),Ud=Bn(),Yd=pt(),Lr=Mn(),Fr=class t{constructor(e,i,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,M.NODE_TYPE,{value:M.DOC});let r=null;typeof i=="function"||Array.isArray(i)?r=i:n===void 0&&i&&(n=i,i=void 0);let a=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},n);this.options=a;let{version:o}=a;n?._directives?(this.directives=n._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new Lr.Directives({version:o}),this.setSchema(o,n),this.contents=e===void 0?null:this.createNode(e,r,n)}clone(){let e=Object.create(t.prototype,{[M.NODE_TYPE]:{value:M.DOC}});return e.commentBefore=this.commentBefore,e.comment=this.comment,e.errors=this.errors.slice(),e.warnings=this.warnings.slice(),e.options=Object.assign({},this.options),this.directives&&(e.directives=this.directives.clone()),e.schema=this.schema.clone(),e.contents=M.isNode(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){Xe(this.contents)&&this.contents.add(e)}addIn(e,i){Xe(this.contents)&&this.contents.addIn(e,i)}createAlias(e,i){if(!e.anchor){let n=$r.anchorNames(this);e.anchor=!i||n.has(i)?$r.findNewAnchor(i||"a",n):i}return new Wd.Alias(e.anchor)}createNode(e,i,n){let r;if(typeof i=="function")e=i.call({"":e},"",e),r=i;else if(Array.isArray(i)){let p=N=>typeof N=="number"||N instanceof String||N instanceof Number,y=i.filter(p).map(String);y.length>0&&(i=i.concat(y)),r=i}else n===void 0&&i&&(n=i,i=void 0);let{aliasDuplicateObjects:a,anchorPrefix:o,flow:s,keepUndefined:c,onTagObj:l,tag:d}=n??{},{onAnchor:u,setAnchors:f,sourceObjects:m}=$r.createNodeAnchors(this,o||"a"),g={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:u,onTagObj:l,replacer:r,schema:this.schema,sourceObjects:m},h=Yd.createNode(e,d,g);return s&&M.isCollection(h)&&(h.flow=!0),f(),h}createPair(e,i,n={}){let r=this.createNode(e,null,n),a=this.createNode(i,null,n);return new zd.Pair(r,a)}delete(e){return Xe(this.contents)?this.contents.delete(e):!1}deleteIn(e){return Ye.isEmptyPath(e)?this.contents==null?!1:(this.contents=null,!0):Xe(this.contents)?this.contents.deleteIn(e):!1}get(e,i){return M.isCollection(this.contents)?this.contents.get(e,i):void 0}getIn(e,i){return Ye.isEmptyPath(e)?!i&&M.isScalar(this.contents)?this.contents.value:this.contents:M.isCollection(this.contents)?this.contents.getIn(e,i):void 0}has(e){return M.isCollection(this.contents)?this.contents.has(e):!1}hasIn(e){return Ye.isEmptyPath(e)?this.contents!==void 0:M.isCollection(this.contents)?this.contents.hasIn(e):!1}set(e,i){this.contents==null?this.contents=Ye.collectionFromPath(this.schema,[e],i):Xe(this.contents)&&this.contents.set(e,i)}setIn(e,i){Ye.isEmptyPath(e)?this.contents=i:this.contents==null?this.contents=Ye.collectionFromPath(this.schema,Array.from(e),i):Xe(this.contents)&&this.contents.setIn(e,i)}setSchema(e,i={}){typeof e=="number"&&(e=String(e));let n;switch(e){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new Lr.Directives({version:"1.1"}),n={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=e:this.directives=new Lr.Directives({version:e}),n={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,n=null;break;default:{let r=JSON.stringify(e);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${r}`)}}if(i.schema instanceof Object)this.schema=i.schema;else if(n)this.schema=new Gd.Schema(Object.assign(n,i));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:e,jsonArg:i,mapAsMap:n,maxAliasCount:r,onAnchor:a,reviver:o}={}){let s={anchors:new Map,doc:this,keep:!e,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},c=Jd.toJS(this.contents,i??"",s);if(typeof a=="function")for(let{count:l,res:d}of s.anchors.values())a(d,l);return typeof o=="function"?Ud.applyReviver(o,{"":c},"",c):c}toJSON(e,i){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:i})}toString(e={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let i=JSON.stringify(e.indent);throw new Error(`"indent" option must be a positive integer, not ${i}`)}return Kd.stringifyDocument(this,e)}};function Xe(t){if(M.isCollection(t))return!0;throw new Error("Expected a YAML collection as document contents")}Fs.Document=Fr});var _t=w(It=>{"use strict";var Tt=class extends Error{constructor(e,i,n,r){super(),this.name=e,this.code=n,this.message=r,this.pos=i}},Mr=class extends Tt{constructor(e,i,n){super("YAMLParseError",e,i,n)}},Br=class extends Tt{constructor(e,i,n){super("YAMLWarning",e,i,n)}},Xd=(t,e)=>i=>{if(i.pos[0]===-1)return;i.linePos=i.pos.map(s=>e.linePos(s));let{line:n,col:r}=i.linePos[0];i.message+=` at line ${n}, column ${r}`;let a=r-1,o=t.substring(e.lineStarts[n-1],e.lineStarts[n]).replace(/[\n\r]+$/,"");if(a>=60&&o.length>80){let s=Math.min(a-39,o.length-79);o="…"+o.substring(s),a-=s-1}if(o.length>80&&(o=o.substring(0,79)+"…"),n>1&&/^ *$/.test(o.substring(0,a))){let s=t.substring(e.lineStarts[n-2],e.lineStarts[n-1]);s.length>80&&(s=s.substring(0,79)+`… `),o=s+o}if(/[^ ]/.test(o)){let s=1,c=i.linePos[1];c?.line===n&&c.col>r&&(s=Math.max(1,Math.min(c.col-r,80-a)));let l=" ".repeat(a)+"^".repeat(s);i.message+=`: ${o} ${l} -`}};It.YAMLError=Tt;It.YAMLParseError=Fr;It.YAMLWarning=Mr;It.prettifyError=Xd});var Ot=w(Ms=>{"use strict";function Qd(t,{flow:e,indicator:i,next:n,offset:r,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,d=s,u="",f="",m=!1,g=!1,h=null,p=null,y=null,N=null,k=null,S=null,E=null;for(let b of t)switch(g&&(b.type!=="space"&&b.type!=="newline"&&b.type!=="comma"&&a(b.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),g=!1),h&&(l&&b.type!=="comment"&&b.type!=="newline"&&a(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),h=null),b.type){case"space":!e&&(i!=="doc-start"||n?.type!=="flow-collection")&&b.source.includes(" ")&&(h=b),d=!0;break;case"comment":{d||a(b,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let x=b.source.substring(1)||" ";u?u+=f+x:u=x,f="",l=!1;break}case"newline":l?u?u+=b.source:(!S||i!=="seq-item-ind")&&(c=!0):f+=b.source,l=!0,m=!0,(p||y)&&(N=b),d=!0;break;case"anchor":p&&a(b,"MULTIPLE_ANCHORS","A node can have at most one anchor"),b.source.endsWith(":")&&a(b.offset+b.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),p=b,E??(E=b.offset),l=!1,d=!1,g=!0;break;case"tag":{y&&a(b,"MULTIPLE_TAGS","A node can have at most one tag"),y=b,E??(E=b.offset),l=!1,d=!1,g=!0;break}case i:(p||y)&&a(b,"BAD_PROP_ORDER",`Anchors and tags must be after the ${b.source} indicator`),S&&a(b,"UNEXPECTED_TOKEN",`Unexpected ${b.source} in ${e??"collection"}`),S=b,l=i==="seq-item-ind"||i==="explicit-key-ind",d=!1;break;case"comma":if(e){k&&a(b,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),k=b,l=!1,d=!1;break}default:a(b,"UNEXPECTED_TOKEN",`Unexpected ${b.type} token`),l=!1,d=!1}let v=t[t.length-1],R=v?v.offset+v.source.length:r;return g&&n&&n.type!=="space"&&n.type!=="newline"&&n.type!=="comma"&&(n.type!=="scalar"||n.source!=="")&&a(n.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),h&&(l&&h.indent<=o||n?.type==="block-map"||n?.type==="block-seq")&&a(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:k,found:S,spaceBefore:c,comment:u,hasNewline:m,anchor:p,tag:y,newlineAfterProp:N,end:R,start:E??R}}Ms.resolveProps=Qd});var qi=w(Bs=>{"use strict";function Br(t){if(!t)return null;switch(t.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(t.source.includes(` -`))return!0;if(t.end){for(let e of t.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(let e of t.items){for(let i of e.start)if(i.type==="newline")return!0;if(e.sep){for(let i of e.sep)if(i.type==="newline")return!0}if(Br(e.key)||Br(e.value))return!0}return!1;default:return!0}}Bs.containsNewline=Br});var Dr=w(Ds=>{"use strict";var Zd=qi();function eh(t,e,i){if(e?.type==="flow-collection"){let n=e.end[0];n.indent===t&&(n.source==="]"||n.source==="}")&&Zd.containsNewline(e)&&i(n,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Ds.flowIndentCheck=eh});var qr=w(Vs=>{"use strict";var qs=C();function th(t,e,i){let{uniqueKeys:n}=t.options;if(n===!1)return!1;let r=typeof n=="function"?n:(a,o)=>a===o||qs.isScalar(a)&&qs.isScalar(o)&&a.value===o.value;return e.some(a=>r(a.key,i))}Vs.mapIncludes=th});var Us=w(Ks=>{"use strict";var Ws=he(),ih=me(),zs=Ot(),nh=qi(),Js=Dr(),rh=qr(),Gs="All mapping items must start at the same column";function ah({composeNode:t,composeEmptyNode:e},i,n,r,a){let o=a?.nodeClass??ih.YAMLMap,s=new o(i.schema);i.atRoot&&(i.atRoot=!1);let c=n.offset,l=null;for(let d of n.items){let{start:u,key:f,sep:m,value:g}=d,h=zs.resolveProps(u,{indicator:"explicit-key-ind",next:f??m?.[0],offset:c,onError:r,parentIndent:n.indent,startOnNewline:!0}),p=!h.found;if(p){if(f&&(f.type==="block-seq"?r(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in f&&f.indent!==n.indent&&r(c,"BAD_INDENT",Gs)),!h.anchor&&!h.tag&&!m){l=h.end,h.comment&&(s.comment?s.comment+=` +`}};It.YAMLError=Tt;It.YAMLParseError=Mr;It.YAMLWarning=Br;It.prettifyError=Xd});var Ot=w(Ms=>{"use strict";function Qd(t,{flow:e,indicator:i,next:n,offset:r,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,d=s,u="",f="",m=!1,g=!1,h=null,p=null,y=null,N=null,k=null,S=null,E=null;for(let b of t)switch(g&&(b.type!=="space"&&b.type!=="newline"&&b.type!=="comma"&&a(b.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),g=!1),h&&(l&&b.type!=="comment"&&b.type!=="newline"&&a(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),h=null),b.type){case"space":!e&&(i!=="doc-start"||n?.type!=="flow-collection")&&b.source.includes(" ")&&(h=b),d=!0;break;case"comment":{d||a(b,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let x=b.source.substring(1)||" ";u?u+=f+x:u=x,f="",l=!1;break}case"newline":l?u?u+=b.source:(!S||i!=="seq-item-ind")&&(c=!0):f+=b.source,l=!0,m=!0,(p||y)&&(N=b),d=!0;break;case"anchor":p&&a(b,"MULTIPLE_ANCHORS","A node can have at most one anchor"),b.source.endsWith(":")&&a(b.offset+b.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),p=b,E??(E=b.offset),l=!1,d=!1,g=!0;break;case"tag":{y&&a(b,"MULTIPLE_TAGS","A node can have at most one tag"),y=b,E??(E=b.offset),l=!1,d=!1,g=!0;break}case i:(p||y)&&a(b,"BAD_PROP_ORDER",`Anchors and tags must be after the ${b.source} indicator`),S&&a(b,"UNEXPECTED_TOKEN",`Unexpected ${b.source} in ${e??"collection"}`),S=b,l=i==="seq-item-ind"||i==="explicit-key-ind",d=!1;break;case"comma":if(e){k&&a(b,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),k=b,l=!1,d=!1;break}default:a(b,"UNEXPECTED_TOKEN",`Unexpected ${b.type} token`),l=!1,d=!1}let v=t[t.length-1],R=v?v.offset+v.source.length:r;return g&&n&&n.type!=="space"&&n.type!=="newline"&&n.type!=="comma"&&(n.type!=="scalar"||n.source!=="")&&a(n.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),h&&(l&&h.indent<=o||n?.type==="block-map"||n?.type==="block-seq")&&a(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:k,found:S,spaceBefore:c,comment:u,hasNewline:m,anchor:p,tag:y,newlineAfterProp:N,end:R,start:E??R}}Ms.resolveProps=Qd});var qi=w(Bs=>{"use strict";function Dr(t){if(!t)return null;switch(t.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(t.source.includes(` +`))return!0;if(t.end){for(let e of t.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(let e of t.items){for(let i of e.start)if(i.type==="newline")return!0;if(e.sep){for(let i of e.sep)if(i.type==="newline")return!0}if(Dr(e.key)||Dr(e.value))return!0}return!1;default:return!0}}Bs.containsNewline=Dr});var qr=w(Ds=>{"use strict";var Zd=qi();function eh(t,e,i){if(e?.type==="flow-collection"){let n=e.end[0];n.indent===t&&(n.source==="]"||n.source==="}")&&Zd.containsNewline(e)&&i(n,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Ds.flowIndentCheck=eh});var Vr=w(Vs=>{"use strict";var qs=C();function th(t,e,i){let{uniqueKeys:n}=t.options;if(n===!1)return!1;let r=typeof n=="function"?n:(a,o)=>a===o||qs.isScalar(a)&&qs.isScalar(o)&&a.value===o.value;return e.some(a=>r(a.key,i))}Vs.mapIncludes=th});var Us=w(Ks=>{"use strict";var Ws=he(),ih=me(),zs=Ot(),nh=qi(),Js=qr(),rh=Vr(),Gs="All mapping items must start at the same column";function ah({composeNode:t,composeEmptyNode:e},i,n,r,a){let o=a?.nodeClass??ih.YAMLMap,s=new o(i.schema);i.atRoot&&(i.atRoot=!1);let c=n.offset,l=null;for(let d of n.items){let{start:u,key:f,sep:m,value:g}=d,h=zs.resolveProps(u,{indicator:"explicit-key-ind",next:f??m?.[0],offset:c,onError:r,parentIndent:n.indent,startOnNewline:!0}),p=!h.found;if(p){if(f&&(f.type==="block-seq"?r(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in f&&f.indent!==n.indent&&r(c,"BAD_INDENT",Gs)),!h.anchor&&!h.tag&&!m){l=h.end,h.comment&&(s.comment?s.comment+=` `+h.comment:s.comment=h.comment);continue}(h.newlineAfterProp||nh.containsNewline(f))&&r(f??u[u.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else h.found?.indent!==n.indent&&r(c,"BAD_INDENT",Gs);i.atKey=!0;let y=h.end,N=f?t(i,f,h,r):e(i,y,u,null,h,r);i.schema.compat&&Js.flowIndentCheck(n.indent,f,r),i.atKey=!1,rh.mapIncludes(i,s.items,N)&&r(y,"DUPLICATE_KEY","Map keys must be unique");let k=zs.resolveProps(m??[],{indicator:"map-value-ind",next:g,offset:N.range[2],onError:r,parentIndent:n.indent,startOnNewline:!f||f.type==="block-scalar"});if(c=k.end,k.found){p&&(g?.type==="block-map"&&!k.hasNewline&&r(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),i.options.strict&&h.start{"use strict";var oh=ve(),sh=Ot(),ch=Dr();function lh({composeNode:t,composeEmptyNode:e},i,n,r,a){let o=a?.nodeClass??oh.YAMLSeq,s=new o(i.schema);i.atRoot&&(i.atRoot=!1),i.atKey&&(i.atKey=!1);let c=n.offset,l=null;for(let{start:d,value:u}of n.items){let f=sh.resolveProps(d,{indicator:"seq-item-ind",next:u,offset:c,onError:r,parentIndent:n.indent,startOnNewline:!0});if(!f.found)if(f.anchor||f.tag||u)u?.type==="block-seq"?r(f.end,"BAD_INDENT","All sequence items must start at the same column"):r(c,"MISSING_CHAR","Sequence item without - indicator");else{l=f.end,f.comment&&(s.comment=f.comment);continue}let m=u?t(i,u,f,r):e(i,f.end,d,null,f,r);i.schema.compat&&ch.flowIndentCheck(n.indent,u,r),c=m.range[2],s.items.push(m)}return s.range=[n.offset,c,l??c],s}Ys.resolveBlockSeq=lh});var Qe=w(Qs=>{"use strict";function uh(t,e,i,n){let r="";if(t){let a=!1,o="";for(let s of t){let{source:c,type:l}=s;switch(l){case"space":a=!0;break;case"comment":{i&&!a&&n(s,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let d=c.substring(1)||" ";r?r+=o+d:r=d,o="";break}case"newline":r&&(o+=c),a=!0;break;default:n(s,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}e+=c.length}}return{comment:r,offset:e}}Qs.resolveEnd=uh});var ic=w(tc=>{"use strict";var fh=C(),dh=he(),Zs=me(),hh=ve(),ph=Qe(),ec=Ot(),mh=qi(),vh=qr(),Vr="Block collections are not allowed within flow collections",Wr=t=>t&&(t.type==="block-map"||t.type==="block-seq");function gh({composeNode:t,composeEmptyNode:e},i,n,r,a){let o=n.start.source==="{",s=o?"flow map":"flow sequence",c=a?.nodeClass??(o?Zs.YAMLMap:hh.YAMLSeq),l=new c(i.schema);l.flow=!0;let d=i.atRoot;d&&(i.atRoot=!1),i.atKey&&(i.atKey=!1);let u=n.offset+n.start.source.length;for(let p=0;p{"use strict";var oh=ve(),sh=Ot(),ch=qr();function lh({composeNode:t,composeEmptyNode:e},i,n,r,a){let o=a?.nodeClass??oh.YAMLSeq,s=new o(i.schema);i.atRoot&&(i.atRoot=!1),i.atKey&&(i.atKey=!1);let c=n.offset,l=null;for(let{start:d,value:u}of n.items){let f=sh.resolveProps(d,{indicator:"seq-item-ind",next:u,offset:c,onError:r,parentIndent:n.indent,startOnNewline:!0});if(!f.found)if(f.anchor||f.tag||u)u?.type==="block-seq"?r(f.end,"BAD_INDENT","All sequence items must start at the same column"):r(c,"MISSING_CHAR","Sequence item without - indicator");else{l=f.end,f.comment&&(s.comment=f.comment);continue}let m=u?t(i,u,f,r):e(i,f.end,d,null,f,r);i.schema.compat&&ch.flowIndentCheck(n.indent,u,r),c=m.range[2],s.items.push(m)}return s.range=[n.offset,c,l??c],s}Ys.resolveBlockSeq=lh});var Qe=w(Qs=>{"use strict";function uh(t,e,i,n){let r="";if(t){let a=!1,o="";for(let s of t){let{source:c,type:l}=s;switch(l){case"space":a=!0;break;case"comment":{i&&!a&&n(s,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let d=c.substring(1)||" ";r?r+=o+d:r=d,o="";break}case"newline":r&&(o+=c),a=!0;break;default:n(s,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}e+=c.length}}return{comment:r,offset:e}}Qs.resolveEnd=uh});var ic=w(tc=>{"use strict";var fh=C(),dh=he(),Zs=me(),hh=ve(),ph=Qe(),ec=Ot(),mh=qi(),vh=Vr(),Wr="Block collections are not allowed within flow collections",zr=t=>t&&(t.type==="block-map"||t.type==="block-seq");function gh({composeNode:t,composeEmptyNode:e},i,n,r,a){let o=n.start.source==="{",s=o?"flow map":"flow sequence",c=a?.nodeClass??(o?Zs.YAMLMap:hh.YAMLSeq),l=new c(i.schema);l.flow=!0;let d=i.atRoot;d&&(i.atRoot=!1),i.atKey&&(i.atKey=!1);let u=n.offset+n.start.source.length;for(let p=0;p0){let p=ph.resolveEnd(g,h,i.options.strict,r);p.comment&&(l.comment?l.comment+=` -`+p.comment:l.comment=p.comment),l.range=[n.offset,h,p.offset]}else l.range=[n.offset,h,h];return l}tc.resolveFlowCollection=gh});var rc=w(nc=>{"use strict";var wh=C(),yh=T(),Nh=me(),bh=ve(),kh=Us(),Sh=Xs(),Eh=ic();function zr(t,e,i,n,r,a){let o=i.type==="block-map"?kh.resolveBlockMap(t,e,i,n,a):i.type==="block-seq"?Sh.resolveBlockSeq(t,e,i,n,a):Eh.resolveFlowCollection(t,e,i,n,a),s=o.constructor;return r==="!"||r===s.tagName?(o.tag=s.tagName,o):(r&&(o.tag=r),o)}function Ch(t,e,i,n,r){let a=n.tag,o=a?e.directives.tagName(a.source,f=>r(a,"TAG_RESOLVE_FAILED",f)):null;if(i.type==="block-seq"){let{anchor:f,newlineAfterProp:m}=n,g=f&&a?f.offset>a.offset?f:a:f??a;g&&(!m||m.offsetf.tag===o&&f.collection===s);if(!c){let f=e.schema.knownTags[o];if(f?.collection===s)e.schema.tags.push(Object.assign({},f,{default:!1})),c=f;else return f?r(a,"BAD_COLLECTION_TYPE",`${f.tag} used for ${s} collection, but expects ${f.collection??"scalar"}`,!0):r(a,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),zr(t,e,i,r,o)}let l=zr(t,e,i,r,o,c),d=c.resolve?.(l,f=>r(a,"TAG_RESOLVE_FAILED",f),e.options)??l,u=wh.isNode(d)?d:new yh.Scalar(d);return u.range=l.range,u.tag=o,c?.format&&(u.format=c.format),u}nc.composeCollection=Ch});var Gr=w(ac=>{"use strict";var Jr=T();function Rh(t,e,i){let n=e.offset,r=Ph(e,t.options.strict,i);if(!r)return{value:"",type:null,comment:"",range:[n,n,n]};let a=r.mode===">"?Jr.Scalar.BLOCK_FOLDED:Jr.Scalar.BLOCK_LITERAL,o=e.source?Ah(e.source):[],s=o.length;for(let h=o.length-1;h>=0;--h){let p=o[h][1];if(p===""||p==="\r")s=h;else break}if(s===0){let h=r.chomp==="+"&&o.length>0?` +`+R:b.comment=R,v.comment=v.comment.substring(R.length+1)}}if(!o&&!S&&!v.found){let R=E?t(i,E,v,r):e(i,v.end,S,null,v,r);l.items.push(R),u=R.range[2],zr(E)&&r(R.range,"BLOCK_IN_FLOW",Wr)}else{i.atKey=!0;let R=v.end,b=k?t(i,k,v,r):e(i,R,N,null,v,r);zr(k)&&r(b.range,"BLOCK_IN_FLOW",Wr),i.atKey=!1;let x=ec.resolveProps(S??[],{flow:s,indicator:"map-value-ind",next:E,offset:b.range[2],onError:r,parentIndent:n.indent,startOnNewline:!1});if(x.found){if(!o&&!v.found&&i.options.strict){if(S)for(let _ of S){if(_===x.found)break;if(_.type==="newline"){r(_,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}v.start0){let p=ph.resolveEnd(g,h,i.options.strict,r);p.comment&&(l.comment?l.comment+=` +`+p.comment:l.comment=p.comment),l.range=[n.offset,h,p.offset]}else l.range=[n.offset,h,h];return l}tc.resolveFlowCollection=gh});var rc=w(nc=>{"use strict";var wh=C(),yh=T(),Nh=me(),bh=ve(),kh=Us(),Sh=Xs(),Eh=ic();function Jr(t,e,i,n,r,a){let o=i.type==="block-map"?kh.resolveBlockMap(t,e,i,n,a):i.type==="block-seq"?Sh.resolveBlockSeq(t,e,i,n,a):Eh.resolveFlowCollection(t,e,i,n,a),s=o.constructor;return r==="!"||r===s.tagName?(o.tag=s.tagName,o):(r&&(o.tag=r),o)}function Ch(t,e,i,n,r){let a=n.tag,o=a?e.directives.tagName(a.source,f=>r(a,"TAG_RESOLVE_FAILED",f)):null;if(i.type==="block-seq"){let{anchor:f,newlineAfterProp:m}=n,g=f&&a?f.offset>a.offset?f:a:f??a;g&&(!m||m.offsetf.tag===o&&f.collection===s);if(!c){let f=e.schema.knownTags[o];if(f?.collection===s)e.schema.tags.push(Object.assign({},f,{default:!1})),c=f;else return f?r(a,"BAD_COLLECTION_TYPE",`${f.tag} used for ${s} collection, but expects ${f.collection??"scalar"}`,!0):r(a,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),Jr(t,e,i,r,o)}let l=Jr(t,e,i,r,o,c),d=c.resolve?.(l,f=>r(a,"TAG_RESOLVE_FAILED",f),e.options)??l,u=wh.isNode(d)?d:new yh.Scalar(d);return u.range=l.range,u.tag=o,c?.format&&(u.format=c.format),u}nc.composeCollection=Ch});var Kr=w(ac=>{"use strict";var Gr=T();function Rh(t,e,i){let n=e.offset,r=Ph(e,t.options.strict,i);if(!r)return{value:"",type:null,comment:"",range:[n,n,n]};let a=r.mode===">"?Gr.Scalar.BLOCK_FOLDED:Gr.Scalar.BLOCK_LITERAL,o=e.source?Ah(e.source):[],s=o.length;for(let h=o.length-1;h>=0;--h){let p=o[h][1];if(p===""||p==="\r")s=h;else break}if(s===0){let h=r.chomp==="+"&&o.length>0?` `.repeat(Math.max(1,o.length-1)):"",p=n+r.length;return e.source&&(p+=e.source.length),{value:h,type:a,comment:r.comment,range:[n,p,p]}}let c=e.indent+r.indent,l=e.offset+r.length,d=0;for(let h=0;hc&&(c=p.length);else{p.length=s;--h)o[h][0].length>c&&(s=h+1);let u="",f="",m=!1;for(let h=0;hc||y[0]===" "?(f===" "?f=` `:!m&&f===` `&&(f=` @@ -84,7 +84,7 @@ ${l} `+o[h][0].slice(c);u[u.length-1]!==` `&&(u+=` `);break;default:u+=` -`}let g=n+r.length+e.source.length;return{value:u,type:a,comment:r.comment,range:[n,g,g]}}function Ph({offset:t,props:e},i,n){if(e[0].type!=="block-scalar-header")return n(e[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:r}=e[0],a=r[0],o=0,s="",c=-1;for(let f=1;f{"use strict";var Kr=T(),xh=Qe();function Th(t,e,i){let{offset:n,type:r,source:a,end:o}=t,s,c,l=(f,m,g)=>i(n+f,m,g);switch(r){case"scalar":s=Kr.Scalar.PLAIN,c=Ih(a,l);break;case"single-quoted-scalar":s=Kr.Scalar.QUOTE_SINGLE,c=_h(a,l);break;case"double-quoted-scalar":s=Kr.Scalar.QUOTE_DOUBLE,c=Oh(a,l);break;default:return i(t,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${r}`),{value:"",type:null,comment:"",range:[n,n+a.length,n+a.length]}}let d=n+a.length,u=xh.resolveEnd(o,d,e,i);return{value:c,type:s,comment:u.comment,range:[n,d,u.offset]}}function Ih(t,e){let i="";switch(t[0]){case" ":i="a tab character";break;case",":i="flow indicator character ,";break;case"%":i="directive indicator character %";break;case"|":case">":{i=`block scalar indicator ${t[0]}`;break}case"@":case"`":{i=`reserved character ${t[0]}`;break}}return i&&e(0,"BAD_SCALAR_START",`Plain value cannot start with ${i}`),oc(t)}function _h(t,e){return(t[t.length-1]!=="'"||t.length===1)&&e(t.length,"MISSING_CHAR","Missing closing 'quote"),oc(t.slice(1,-1)).replace(/''/g,"'")}function oc(t){let e,i;try{e=new RegExp(`(.*?)(?{"use strict";var Ur=T(),xh=Qe();function Th(t,e,i){let{offset:n,type:r,source:a,end:o}=t,s,c,l=(f,m,g)=>i(n+f,m,g);switch(r){case"scalar":s=Ur.Scalar.PLAIN,c=Ih(a,l);break;case"single-quoted-scalar":s=Ur.Scalar.QUOTE_SINGLE,c=_h(a,l);break;case"double-quoted-scalar":s=Ur.Scalar.QUOTE_DOUBLE,c=Oh(a,l);break;default:return i(t,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${r}`),{value:"",type:null,comment:"",range:[n,n+a.length,n+a.length]}}let d=n+a.length,u=xh.resolveEnd(o,d,e,i);return{value:c,type:s,comment:u.comment,range:[n,d,u.offset]}}function Ih(t,e){let i="";switch(t[0]){case" ":i="a tab character";break;case",":i="flow indicator character ,";break;case"%":i="directive indicator character %";break;case"|":case">":{i=`block scalar indicator ${t[0]}`;break}case"@":case"`":{i=`reserved character ${t[0]}`;break}}return i&&e(0,"BAD_SCALAR_START",`Plain value cannot start with ${i}`),oc(t)}function _h(t,e){return(t[t.length-1]!=="'"||t.length===1)&&e(t.length,"MISSING_CHAR","Missing closing 'quote"),oc(t.slice(1,-1)).replace(/''/g,"'")}function oc(t){let e,i;try{e=new RegExp(`(.*?)(?{"use strict";var xe=C(),cc=T(),Lh=Gr(),Fh=Ur();function Mh(t,e,i,n){let{value:r,type:a,comment:o,range:s}=e.type==="block-scalar"?Lh.resolveBlockScalar(t,e,n):Fh.resolveFlowScalar(e,t.options.strict,n),c=i?t.directives.tagName(i.source,u=>n(i,"TAG_RESOLVE_FAILED",u)):null,l;t.options.stringKeys&&t.atKey?l=t.schema[xe.SCALAR]:c?l=Bh(t.schema,r,c,i,n):e.type==="scalar"?l=Dh(t,r,e,n):l=t.schema[xe.SCALAR];let d;try{let u=l.resolve(r,f=>n(i??e,"TAG_RESOLVE_FAILED",f),t.options);d=xe.isScalar(u)?u:new cc.Scalar(u)}catch(u){let f=u instanceof Error?u.message:String(u);n(i??e,"TAG_RESOLVE_FAILED",f),d=new cc.Scalar(r)}return d.range=s,d.source=r,a&&(d.type=a),c&&(d.tag=c),l.format&&(d.format=l.format),o&&(d.comment=o),d}function Bh(t,e,i,n,r){if(i==="!")return t[xe.SCALAR];let a=[];for(let s of t.tags)if(!s.collection&&s.tag===i)if(s.default&&s.test)a.push(s);else return s;for(let s of a)if(s.test?.test(e))return s;let o=t.knownTags[i];return o&&!o.collection?(t.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(r(n,"TAG_RESOLVE_FAILED",`Unresolved tag: ${i}`,i!=="tag:yaml.org,2002:str"),t[xe.SCALAR])}function Dh({atKey:t,directives:e,schema:i},n,r,a){let o=i.tags.find(s=>(s.default===!0||t&&s.default==="key")&&s.test?.test(n))||i[xe.SCALAR];if(i.compat){let s=i.compat.find(c=>c.default&&c.test?.test(n))??i[xe.SCALAR];if(o.tag!==s.tag){let c=e.tagString(o.tag),l=e.tagString(s.tag),d=`Value may be parsed as either ${c} or ${l}`;a(r,"TAG_RESOLVE_FAILED",d,!0)}}return o}lc.composeScalar=Mh});var dc=w(fc=>{"use strict";function qh(t,e,i){if(e){i??(i=e.length);for(let n=i-1;n>=0;--n){let r=e[n];switch(r.type){case"space":case"comment":case"newline":t-=r.source.length;continue}for(r=e[++n];r?.type==="space";)t+=r.source.length,r=e[++n];break}}return t}fc.emptyScalarPosition=qh});var mc=w(Xr=>{"use strict";var Vh=ht(),Wh=C(),zh=rc(),hc=uc(),Jh=Qe(),Gh=dc(),Kh={composeNode:pc,composeEmptyNode:Yr};function pc(t,e,i,n){let r=t.atKey,{spaceBefore:a,comment:o,anchor:s,tag:c}=i,l,d=!0;switch(e.type){case"alias":l=Uh(t,e,n),(s||c)&&n(e,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=hc.composeScalar(t,e,c,n),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=zh.composeCollection(Kh,t,e,i,n),s&&(l.anchor=s.source.substring(1))}catch(u){let f=u instanceof Error?u.message:String(u);n(e,"RESOURCE_EXHAUSTION",f)}break;default:{let u=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;n(e,"UNEXPECTED_TOKEN",u),d=!1}}return l??(l=Yr(t,e.offset,void 0,null,i,n)),s&&l.anchor===""&&n(s,"BAD_ALIAS","Anchor cannot be an empty string"),r&&t.options.stringKeys&&(!Wh.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&n(c??e,"NON_STRING_KEY","With stringKeys, all keys must be strings"),a&&(l.spaceBefore=!0),o&&(e.type==="scalar"&&e.source===""?l.comment=o:l.commentBefore=o),t.options.keepSourceTokens&&d&&(l.srcToken=e),l}function Yr(t,e,i,n,{spaceBefore:r,comment:a,anchor:o,tag:s,end:c},l){let d={type:"scalar",offset:Gh.emptyScalarPosition(e,i,n),indent:-1,source:""},u=hc.composeScalar(t,d,s,l);return o&&(u.anchor=o.source.substring(1),u.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),r&&(u.spaceBefore=!0),a&&(u.comment=a,u.range[2]=c),u}function Uh({options:t},{offset:e,source:i,end:n},r){let a=new Vh.Alias(i.substring(1));a.source===""&&r(e,"BAD_ALIAS","Alias cannot be an empty string"),a.source.endsWith(":")&&r(e+i.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=e+i.length,s=Jh.resolveEnd(n,o,t.strict,r);return a.range=[e,o,s.offset],s.comment&&(a.comment=s.comment),a}Xr.composeEmptyNode=Yr;Xr.composeNode=pc});var wc=w(gc=>{"use strict";var Yh=xt(),vc=mc(),Xh=Qe(),Qh=Ot();function Zh(t,e,{offset:i,start:n,value:r,end:a},o){let s=Object.assign({_directives:e},t),c=new Yh.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},d=Qh.resolveProps(n,{indicator:"doc-start",next:r??a?.[0],offset:i,onError:o,parentIndent:0,startOnNewline:!0});d.found&&(c.directives.docStart=!0,r&&(r.type==="block-map"||r.type==="block-seq")&&!d.hasNewline&&o(d.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=r?vc.composeNode(l,r,d,o):vc.composeEmptyNode(l,d.end,n,null,d,o);let u=c.contents.range[2],f=Xh.resolveEnd(a,u,!1,o);return f.comment&&(c.comment=f.comment),c.range=[i,u,f.offset],c}gc.composeDoc=Zh});var Zr=w(bc=>{"use strict";var ep=Qt("process"),tp=Fn(),ip=xt(),jt=_t(),yc=C(),np=wc(),rp=Qe();function Ht(t){if(typeof t=="number")return[t,t+1];if(Array.isArray(t))return t.length===2?t:[t[0],t[1]];let{offset:e,source:i}=t;return[e,e+(typeof i=="string"?i.length:1)]}function Nc(t){let e="",i=!1,n=!1;for(let r=0;r{"use strict";var xe=C(),cc=T(),Lh=Kr(),Fh=Yr();function Mh(t,e,i,n){let{value:r,type:a,comment:o,range:s}=e.type==="block-scalar"?Lh.resolveBlockScalar(t,e,n):Fh.resolveFlowScalar(e,t.options.strict,n),c=i?t.directives.tagName(i.source,u=>n(i,"TAG_RESOLVE_FAILED",u)):null,l;t.options.stringKeys&&t.atKey?l=t.schema[xe.SCALAR]:c?l=Bh(t.schema,r,c,i,n):e.type==="scalar"?l=Dh(t,r,e,n):l=t.schema[xe.SCALAR];let d;try{let u=l.resolve(r,f=>n(i??e,"TAG_RESOLVE_FAILED",f),t.options);d=xe.isScalar(u)?u:new cc.Scalar(u)}catch(u){let f=u instanceof Error?u.message:String(u);n(i??e,"TAG_RESOLVE_FAILED",f),d=new cc.Scalar(r)}return d.range=s,d.source=r,a&&(d.type=a),c&&(d.tag=c),l.format&&(d.format=l.format),o&&(d.comment=o),d}function Bh(t,e,i,n,r){if(i==="!")return t[xe.SCALAR];let a=[];for(let s of t.tags)if(!s.collection&&s.tag===i)if(s.default&&s.test)a.push(s);else return s;for(let s of a)if(s.test?.test(e))return s;let o=t.knownTags[i];return o&&!o.collection?(t.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(r(n,"TAG_RESOLVE_FAILED",`Unresolved tag: ${i}`,i!=="tag:yaml.org,2002:str"),t[xe.SCALAR])}function Dh({atKey:t,directives:e,schema:i},n,r,a){let o=i.tags.find(s=>(s.default===!0||t&&s.default==="key")&&s.test?.test(n))||i[xe.SCALAR];if(i.compat){let s=i.compat.find(c=>c.default&&c.test?.test(n))??i[xe.SCALAR];if(o.tag!==s.tag){let c=e.tagString(o.tag),l=e.tagString(s.tag),d=`Value may be parsed as either ${c} or ${l}`;a(r,"TAG_RESOLVE_FAILED",d,!0)}}return o}lc.composeScalar=Mh});var dc=w(fc=>{"use strict";function qh(t,e,i){if(e){i??(i=e.length);for(let n=i-1;n>=0;--n){let r=e[n];switch(r.type){case"space":case"comment":case"newline":t-=r.source.length;continue}for(r=e[++n];r?.type==="space";)t+=r.source.length,r=e[++n];break}}return t}fc.emptyScalarPosition=qh});var mc=w(Qr=>{"use strict";var Vh=ht(),Wh=C(),zh=rc(),hc=uc(),Jh=Qe(),Gh=dc(),Kh={composeNode:pc,composeEmptyNode:Xr};function pc(t,e,i,n){let r=t.atKey,{spaceBefore:a,comment:o,anchor:s,tag:c}=i,l,d=!0;switch(e.type){case"alias":l=Uh(t,e,n),(s||c)&&n(e,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=hc.composeScalar(t,e,c,n),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=zh.composeCollection(Kh,t,e,i,n),s&&(l.anchor=s.source.substring(1))}catch(u){let f=u instanceof Error?u.message:String(u);n(e,"RESOURCE_EXHAUSTION",f)}break;default:{let u=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;n(e,"UNEXPECTED_TOKEN",u),d=!1}}return l??(l=Xr(t,e.offset,void 0,null,i,n)),s&&l.anchor===""&&n(s,"BAD_ALIAS","Anchor cannot be an empty string"),r&&t.options.stringKeys&&(!Wh.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&n(c??e,"NON_STRING_KEY","With stringKeys, all keys must be strings"),a&&(l.spaceBefore=!0),o&&(e.type==="scalar"&&e.source===""?l.comment=o:l.commentBefore=o),t.options.keepSourceTokens&&d&&(l.srcToken=e),l}function Xr(t,e,i,n,{spaceBefore:r,comment:a,anchor:o,tag:s,end:c},l){let d={type:"scalar",offset:Gh.emptyScalarPosition(e,i,n),indent:-1,source:""},u=hc.composeScalar(t,d,s,l);return o&&(u.anchor=o.source.substring(1),u.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),r&&(u.spaceBefore=!0),a&&(u.comment=a,u.range[2]=c),u}function Uh({options:t},{offset:e,source:i,end:n},r){let a=new Vh.Alias(i.substring(1));a.source===""&&r(e,"BAD_ALIAS","Alias cannot be an empty string"),a.source.endsWith(":")&&r(e+i.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=e+i.length,s=Jh.resolveEnd(n,o,t.strict,r);return a.range=[e,o,s.offset],s.comment&&(a.comment=s.comment),a}Qr.composeEmptyNode=Xr;Qr.composeNode=pc});var wc=w(gc=>{"use strict";var Yh=xt(),vc=mc(),Xh=Qe(),Qh=Ot();function Zh(t,e,{offset:i,start:n,value:r,end:a},o){let s=Object.assign({_directives:e},t),c=new Yh.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},d=Qh.resolveProps(n,{indicator:"doc-start",next:r??a?.[0],offset:i,onError:o,parentIndent:0,startOnNewline:!0});d.found&&(c.directives.docStart=!0,r&&(r.type==="block-map"||r.type==="block-seq")&&!d.hasNewline&&o(d.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=r?vc.composeNode(l,r,d,o):vc.composeEmptyNode(l,d.end,n,null,d,o);let u=c.contents.range[2],f=Xh.resolveEnd(a,u,!1,o);return f.comment&&(c.comment=f.comment),c.range=[i,u,f.offset],c}gc.composeDoc=Zh});var ea=w(bc=>{"use strict";var ep=Qt("process"),tp=Mn(),ip=xt(),jt=_t(),yc=C(),np=wc(),rp=Qe();function Ht(t){if(typeof t=="number")return[t,t+1];if(Array.isArray(t))return t.length===2?t:[t[0],t[1]];let{offset:e,source:i}=t;return[e,e+(typeof i=="string"?i.length:1)]}function Nc(t){let e="",i=!1,n=!1;for(let r=0;r{let o=Ht(i);a?this.warnings.push(new jt.YAMLWarning(o,n,r)):this.errors.push(new jt.YAMLParseError(o,n,r))},this.directives=new tp.Directives({version:e.version||"1.2"}),this.options=e}decorate(e,i){let{comment:n,afterEmptyLine:r}=Nc(this.prelude);if(n){let a=e.contents;if(i)e.comment=e.comment?`${e.comment} +`)+(a.substring(1)||" "),i=!0,n=!1;break;case"%":t[r+1]?.[0]!=="#"&&(r+=1),i=!1;break;default:i||(n=!0),i=!1}}return{comment:e,afterEmptyLine:n}}var Zr=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(i,n,r,a)=>{let o=Ht(i);a?this.warnings.push(new jt.YAMLWarning(o,n,r)):this.errors.push(new jt.YAMLParseError(o,n,r))},this.directives=new tp.Directives({version:e.version||"1.2"}),this.options=e}decorate(e,i){let{comment:n,afterEmptyLine:r}=Nc(this.prelude);if(n){let a=e.contents;if(i)e.comment=e.comment?`${e.comment} ${n}`:n;else if(r||e.directives.docStart||!a)e.commentBefore=n;else if(yc.isCollection(a)&&!a.flow&&a.items.length>0){let o=a.items[0];yc.isPair(o)&&(o=o.key);let s=o.commentBefore;o.commentBefore=s?`${n} ${s}`:n}else{let o=a.commentBefore;a.commentBefore=o?`${n} ${o}`:n}}if(i){for(let a=0;a{let a=Ht(e);a[0]+=i,this.onError(a,"BAD_DIRECTIVE",n,r)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let i=np.composeDoc(this.options,this.directives,e,this.onError);this.atDirectives&&!i.directives.docStart&&this.onError(e,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(i,!1),this.doc&&(yield this.doc),this.doc=i,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(e.source);break;case"error":{let i=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,n=new jt.YAMLParseError(Ht(e),"UNEXPECTED_TOKEN",i);this.atDirectives||!this.doc?this.errors.push(n):this.doc.errors.push(n);break}case"doc-end":{if(!this.doc){let n="Unexpected doc-end without preceding document";this.errors.push(new jt.YAMLParseError(Ht(e),"UNEXPECTED_TOKEN",n));break}this.doc.directives.docEnd=!0;let i=rp.resolveEnd(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),i.comment){let n=this.doc.comment;this.doc.comment=n?`${n} -${i.comment}`:i.comment}this.doc.range[2]=i.offset;break}default:this.errors.push(new jt.YAMLParseError(Ht(e),"UNEXPECTED_TOKEN",`Unsupported token ${e.type}`))}}*end(e=!1,i=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let n=Object.assign({_directives:this.directives},this.options),r=new ip.Document(void 0,n);this.atDirectives&&this.onError(i,"MISSING_CHAR","Missing directives-end indicator line"),r.range=[0,i,i],this.decorate(r,!1),yield r}}};bc.Composer=Qr});var Ec=w(Vi=>{"use strict";var ap=Gr(),op=Ur(),sp=_t(),kc=wt();function cp(t,e=!0,i){if(t){let n=(r,a,o)=>{let s=typeof r=="number"?r:Array.isArray(r)?r[0]:r.offset;if(i)i(s,a,o);else throw new sp.YAMLParseError([s,s+1],a,o)};switch(t.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return op.resolveFlowScalar(t,e,n);case"block-scalar":return ap.resolveBlockScalar({options:{strict:e}},t,n)}}return null}function lp(t,e){let{implicitKey:i=!1,indent:n,inFlow:r=!1,offset:a=-1,type:o="PLAIN"}=e,s=kc.stringifyString({type:o,value:t},{implicitKey:i,indent:n>0?" ".repeat(n):"",inFlow:r,options:{blockQuote:!0,lineWidth:-1}}),c=e.end??[{type:"newline",offset:-1,indent:n,source:` +${i.comment}`:i.comment}this.doc.range[2]=i.offset;break}default:this.errors.push(new jt.YAMLParseError(Ht(e),"UNEXPECTED_TOKEN",`Unsupported token ${e.type}`))}}*end(e=!1,i=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let n=Object.assign({_directives:this.directives},this.options),r=new ip.Document(void 0,n);this.atDirectives&&this.onError(i,"MISSING_CHAR","Missing directives-end indicator line"),r.range=[0,i,i],this.decorate(r,!1),yield r}}};bc.Composer=Zr});var Ec=w(Vi=>{"use strict";var ap=Kr(),op=Yr(),sp=_t(),kc=wt();function cp(t,e=!0,i){if(t){let n=(r,a,o)=>{let s=typeof r=="number"?r:Array.isArray(r)?r[0]:r.offset;if(i)i(s,a,o);else throw new sp.YAMLParseError([s,s+1],a,o)};switch(t.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return op.resolveFlowScalar(t,e,n);case"block-scalar":return ap.resolveBlockScalar({options:{strict:e}},t,n)}}return null}function lp(t,e){let{implicitKey:i=!1,indent:n,inFlow:r=!1,offset:a=-1,type:o="PLAIN"}=e,s=kc.stringifyString({type:o,value:t},{implicitKey:i,indent:n>0?" ".repeat(n):"",inFlow:r,options:{blockQuote:!0,lineWidth:-1}}),c=e.end??[{type:"newline",offset:-1,indent:n,source:` `}];switch(s[0]){case"|":case">":{let l=s.indexOf(` `),d=s.substring(0,l),u=s.substring(l+1)+` `,f=[{type:"block-scalar-header",offset:a,indent:n,source:d}];return Sc(f,c)||f.push({type:"newline",offset:-1,indent:n,source:` -`}),{type:"block-scalar",offset:a,indent:n,props:f,source:u}}case'"':return{type:"double-quoted-scalar",offset:a,indent:n,source:s,end:c};case"'":return{type:"single-quoted-scalar",offset:a,indent:n,source:s,end:c};default:return{type:"scalar",offset:a,indent:n,source:s,end:c}}}function up(t,e,i={}){let{afterKey:n=!1,implicitKey:r=!1,inFlow:a=!1,type:o}=i,s="indent"in t?t.indent:null;if(n&&typeof s=="number"&&(s+=2),!o)switch(t.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let l=t.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let c=kc.stringifyString({type:o,value:e},{implicitKey:r||s===null,indent:s!==null&&s>0?" ".repeat(s):"",inFlow:a,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":fp(t,c);break;case'"':ea(t,c,"double-quoted-scalar");break;case"'":ea(t,c,"single-quoted-scalar");break;default:ea(t,c,"scalar")}}function fp(t,e){let i=e.indexOf(` +`}),{type:"block-scalar",offset:a,indent:n,props:f,source:u}}case'"':return{type:"double-quoted-scalar",offset:a,indent:n,source:s,end:c};case"'":return{type:"single-quoted-scalar",offset:a,indent:n,source:s,end:c};default:return{type:"scalar",offset:a,indent:n,source:s,end:c}}}function up(t,e,i={}){let{afterKey:n=!1,implicitKey:r=!1,inFlow:a=!1,type:o}=i,s="indent"in t?t.indent:null;if(n&&typeof s=="number"&&(s+=2),!o)switch(t.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let l=t.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let c=kc.stringifyString({type:o,value:e},{implicitKey:r||s===null,indent:s!==null&&s>0?" ".repeat(s):"",inFlow:a,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":fp(t,c);break;case'"':ta(t,c,"double-quoted-scalar");break;case"'":ta(t,c,"single-quoted-scalar");break;default:ta(t,c,"scalar")}}function fp(t,e){let i=e.indexOf(` `),n=e.substring(0,i),r=e.substring(i+1)+` `;if(t.type==="block-scalar"){let a=t.props[0];if(a.type!=="block-scalar-header")throw new Error("Invalid block scalar header");a.source=n,t.source=r}else{let{offset:a}=t,o="indent"in t?t.indent:-1,s=[{type:"block-scalar-header",offset:a,indent:o,source:n}];Sc(s,"end"in t?t.end:void 0)||s.push({type:"newline",offset:-1,indent:o,source:` -`});for(let c of Object.keys(t))c!=="type"&&c!=="offset"&&delete t[c];Object.assign(t,{type:"block-scalar",indent:o,props:s,source:r})}}function Sc(t,e){if(e)for(let i of e)switch(i.type){case"space":case"comment":t.push(i);break;case"newline":return t.push(i),!0}return!1}function ea(t,e,i){switch(t.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":t.type=i,t.source=e;break;case"block-scalar":{let n=t.props.slice(1),r=e.length;t.props[0].type==="block-scalar-header"&&(r-=t.props[0].source.length);for(let a of n)a.offset+=r;delete t.props,Object.assign(t,{type:i,source:e,end:n});break}case"block-map":case"block-seq":{let r={type:"newline",offset:t.offset+e.length,indent:t.indent,source:` -`};delete t.items,Object.assign(t,{type:i,source:e,end:[r]});break}default:{let n="indent"in t?t.indent:-1,r="end"in t&&Array.isArray(t.end)?t.end.filter(a=>a.type==="space"||a.type==="comment"||a.type==="newline"):[];for(let a of Object.keys(t))a!=="type"&&a!=="offset"&&delete t[a];Object.assign(t,{type:i,indent:n,source:e,end:r})}}}Vi.createScalarToken=lp;Vi.resolveAsScalar=cp;Vi.setScalarValue=up});var Rc=w(Cc=>{"use strict";var dp=t=>"type"in t?zi(t):Wi(t);function zi(t){switch(t.type){case"block-scalar":{let e="";for(let i of t.props)e+=zi(i);return e+t.source}case"block-map":case"block-seq":{let e="";for(let i of t.items)e+=Wi(i);return e}case"flow-collection":{let e=t.start.source;for(let i of t.items)e+=Wi(i);for(let i of t.end)e+=i.source;return e}case"document":{let e=Wi(t);if(t.end)for(let i of t.end)e+=i.source;return e}default:{let e=t.source;if("end"in t&&t.end)for(let i of t.end)e+=i.source;return e}}}function Wi({start:t,key:e,sep:i,value:n}){let r="";for(let a of t)r+=a.source;if(e&&(r+=zi(e)),i)for(let a of i)r+=a.source;return n&&(r+=zi(n)),r}Cc.stringify=dp});var Tc=w(xc=>{"use strict";var ta=Symbol("break visit"),hp=Symbol("skip children"),Pc=Symbol("remove item");function Te(t,e){"type"in t&&t.type==="document"&&(t={start:t.start,value:t.value}),Ac(Object.freeze([]),t,e)}Te.BREAK=ta;Te.SKIP=hp;Te.REMOVE=Pc;Te.itemAtPath=(t,e)=>{let i=t;for(let[n,r]of e){let a=i?.[n];if(a&&"items"in a)i=a.items[r];else return}return i};Te.parentCollection=(t,e)=>{let i=Te.itemAtPath(t,e.slice(0,-1)),n=e[e.length-1][0],r=i?.[n];if(r&&"items"in r)return r;throw new Error("Parent collection not found")};function Ac(t,e,i){let n=i(e,t);if(typeof n=="symbol")return n;for(let r of["key","value"]){let a=e[r];if(a&&"items"in a){for(let o=0;o{"use strict";var ia=Ec(),pp=Rc(),mp=Tc(),na="\uFEFF",ra="",aa="",oa="",vp=t=>!!t&&"items"in t,gp=t=>!!t&&(t.type==="scalar"||t.type==="single-quoted-scalar"||t.type==="double-quoted-scalar"||t.type==="block-scalar");function wp(t){switch(t){case na:return"";case ra:return"";case aa:return"";case oa:return"";default:return JSON.stringify(t)}}function yp(t){switch(t){case na:return"byte-order-mark";case ra:return"doc-mode";case aa:return"flow-error-end";case oa:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case` +`});for(let c of Object.keys(t))c!=="type"&&c!=="offset"&&delete t[c];Object.assign(t,{type:"block-scalar",indent:o,props:s,source:r})}}function Sc(t,e){if(e)for(let i of e)switch(i.type){case"space":case"comment":t.push(i);break;case"newline":return t.push(i),!0}return!1}function ta(t,e,i){switch(t.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":t.type=i,t.source=e;break;case"block-scalar":{let n=t.props.slice(1),r=e.length;t.props[0].type==="block-scalar-header"&&(r-=t.props[0].source.length);for(let a of n)a.offset+=r;delete t.props,Object.assign(t,{type:i,source:e,end:n});break}case"block-map":case"block-seq":{let r={type:"newline",offset:t.offset+e.length,indent:t.indent,source:` +`};delete t.items,Object.assign(t,{type:i,source:e,end:[r]});break}default:{let n="indent"in t?t.indent:-1,r="end"in t&&Array.isArray(t.end)?t.end.filter(a=>a.type==="space"||a.type==="comment"||a.type==="newline"):[];for(let a of Object.keys(t))a!=="type"&&a!=="offset"&&delete t[a];Object.assign(t,{type:i,indent:n,source:e,end:r})}}}Vi.createScalarToken=lp;Vi.resolveAsScalar=cp;Vi.setScalarValue=up});var Rc=w(Cc=>{"use strict";var dp=t=>"type"in t?zi(t):Wi(t);function zi(t){switch(t.type){case"block-scalar":{let e="";for(let i of t.props)e+=zi(i);return e+t.source}case"block-map":case"block-seq":{let e="";for(let i of t.items)e+=Wi(i);return e}case"flow-collection":{let e=t.start.source;for(let i of t.items)e+=Wi(i);for(let i of t.end)e+=i.source;return e}case"document":{let e=Wi(t);if(t.end)for(let i of t.end)e+=i.source;return e}default:{let e=t.source;if("end"in t&&t.end)for(let i of t.end)e+=i.source;return e}}}function Wi({start:t,key:e,sep:i,value:n}){let r="";for(let a of t)r+=a.source;if(e&&(r+=zi(e)),i)for(let a of i)r+=a.source;return n&&(r+=zi(n)),r}Cc.stringify=dp});var Tc=w(xc=>{"use strict";var ia=Symbol("break visit"),hp=Symbol("skip children"),Pc=Symbol("remove item");function Te(t,e){"type"in t&&t.type==="document"&&(t={start:t.start,value:t.value}),Ac(Object.freeze([]),t,e)}Te.BREAK=ia;Te.SKIP=hp;Te.REMOVE=Pc;Te.itemAtPath=(t,e)=>{let i=t;for(let[n,r]of e){let a=i?.[n];if(a&&"items"in a)i=a.items[r];else return}return i};Te.parentCollection=(t,e)=>{let i=Te.itemAtPath(t,e.slice(0,-1)),n=e[e.length-1][0],r=i?.[n];if(r&&"items"in r)return r;throw new Error("Parent collection not found")};function Ac(t,e,i){let n=i(e,t);if(typeof n=="symbol")return n;for(let r of["key","value"]){let a=e[r];if(a&&"items"in a){for(let o=0;o{"use strict";var na=Ec(),pp=Rc(),mp=Tc(),ra="\uFEFF",aa="",oa="",sa="",vp=t=>!!t&&"items"in t,gp=t=>!!t&&(t.type==="scalar"||t.type==="single-quoted-scalar"||t.type==="double-quoted-scalar"||t.type==="block-scalar");function wp(t){switch(t){case ra:return"";case aa:return"";case oa:return"";case sa:return"";default:return JSON.stringify(t)}}function yp(t){switch(t){case ra:return"byte-order-mark";case aa:return"doc-mode";case oa:return"flow-error-end";case sa:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case` `:case`\r -`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(t[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}L.createScalarToken=ia.createScalarToken;L.resolveAsScalar=ia.resolveAsScalar;L.setScalarValue=ia.setScalarValue;L.stringify=pp.stringify;L.visit=mp.visit;L.BOM=na;L.DOCUMENT=ra;L.FLOW_END=aa;L.SCALAR=oa;L.isCollection=vp;L.isScalar=gp;L.prettyToken=wp;L.tokenType=yp});var la=w(_c=>{"use strict";var $t=Ji();function z(t){switch(t){case void 0:case" ":case` +`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(t[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}L.createScalarToken=na.createScalarToken;L.resolveAsScalar=na.resolveAsScalar;L.setScalarValue=na.setScalarValue;L.stringify=pp.stringify;L.visit=mp.visit;L.BOM=ra;L.DOCUMENT=aa;L.FLOW_END=oa;L.SCALAR=sa;L.isCollection=vp;L.isScalar=gp;L.prettyToken=wp;L.tokenType=yp});var ua=w(_c=>{"use strict";var $t=Ji();function z(t){switch(t){case void 0:case" ":case` `:case"\r":case" ":return!0;default:return!1}}var Ic=new Set("0123456789ABCDEFabcdef"),Np=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Gi=new Set(",[]{}"),bp=new Set(` ,[]{} -\r `),sa=t=>!t||bp.has(t),ca=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,i=!1){if(e){if(typeof e!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!i;let n=this.next??"stream";for(;n&&(i||this.hasChars(1));)n=yield*this.parseNext(n)}atLineEnd(){let e=this.pos,i=this.buffer[e];for(;i===" "||i===" ";)i=this.buffer[++e];return!i||i==="#"||i===` +\r `),ca=t=>!t||bp.has(t),la=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,i=!1){if(e){if(typeof e!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!i;let n=this.next??"stream";for(;n&&(i||this.hasChars(1));)n=yield*this.parseNext(n)}atLineEnd(){let e=this.pos,i=this.buffer[e];for(;i===" "||i===" ";)i=this.buffer[++e];return!i||i==="#"||i===` `?!0:i==="\r"?this.buffer[e+1]===` `:!1}charAt(e){return this.buffer[this.pos+e]}continueScalar(e){let i=this.buffer[e];if(this.indentNext>0){let n=0;for(;i===" ";)i=this.buffer[++n+e];if(i==="\r"){let r=this.buffer[n+e+1];if(r===` `||!r&&!this.atEnd)return e+n+1}return i===` `||n>=this.indentNext||!i&&!this.atEnd?e+n:-1}if(i==="-"||i==="."){let n=this.buffer.substr(e,3);if((n==="---"||n==="...")&&z(this.buffer[e+3]))return-1}return e}getLine(){let e=this.lineEndPos;return(typeof e!="number"||e!==-1&&ethis.indentValue&&!z(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[e,i]=this.peek(2);if(!i&&!this.atEnd)return this.setNext("block-start");if((e==="-"||e==="?"||e===":")&&z(i)){let n=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=n,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let e=this.getLine();if(e===null)return this.setNext("doc");let i=yield*this.pushIndicators();switch(e[i]){case"#":yield*this.pushCount(e.length-i);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(sa),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return i+=yield*this.parseBlockScalarHeader(),i+=yield*this.pushSpaces(!0),yield*this.pushCount(e.length-i),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,i,n=-1;do e=yield*this.pushNewline(),e>0?(i=yield*this.pushSpaces(!1),this.indentValue=n=i):i=0,i+=yield*this.pushSpaces(!0);while(e+i>0);let r=this.getLine();if(r===null)return this.setNext("flow");if((n!==-1&&nthis.indentValue&&!z(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[e,i]=this.peek(2);if(!i&&!this.atEnd)return this.setNext("block-start");if((e==="-"||e==="?"||e===":")&&z(i)){let n=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=n,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let e=this.getLine();if(e===null)return this.setNext("doc");let i=yield*this.pushIndicators();switch(e[i]){case"#":yield*this.pushCount(e.length-i);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(ca),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return i+=yield*this.parseBlockScalarHeader(),i+=yield*this.pushSpaces(!0),yield*this.pushCount(e.length-i),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,i,n=-1;do e=yield*this.pushNewline(),e>0?(i=yield*this.pushSpaces(!1),this.indentValue=n=i):i=0,i+=yield*this.pushSpaces(!0);while(e+i>0);let r=this.getLine();if(r===null)return this.setNext("flow");if((n!==-1&&n"0"&&i<="9")this.blockScalarIndent=Number(i)-1;else if(i!=="-")break}return yield*this.pushUntil(i=>z(i)||i==="#")}*parseBlockScalar(){let e=this.pos-1,i=0,n;e:for(let a=this.pos;n=this.buffer[a];++a)switch(n){case" ":i+=1;break;case` `:e=a,i=0;break;case"\r":{let o=this.buffer[a+1];if(!o&&!this.atEnd)return this.setNext("block-scalar");if(o===` @@ -133,23 +133,23 @@ ${i.comment}`:i.comment}this.doc.range[2]=i.offset;break}default:this.errors.pus `&&a>=this.pos&&a+1+i>s)e=a;else break}while(!0);return yield $t.SCALAR,yield*this.pushToIndex(e+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let e=this.flowLevel>0,i=this.pos-1,n=this.pos-1,r;for(;r=this.buffer[++n];)if(r===":"){let a=this.buffer[n+1];if(z(a)||e&&Gi.has(a))break;i=n}else if(z(r)){let a=this.buffer[n+1];if(r==="\r"&&(a===` `?(n+=1,r=` `,a=this.buffer[n+1]):i=n),a==="#"||e&&Gi.has(a))break;if(r===` -`){let o=this.continueScalar(n+1);if(o===-1)break;n=Math.max(n,o-2)}}else{if(e&&Gi.has(r))break;i=n}return!r&&!this.atEnd?this.setNext("plain-scalar"):(yield $t.SCALAR,yield*this.pushToIndex(i+1,!0),e?"flow":"doc")}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,i){let n=this.buffer.slice(this.pos,e);return n?(yield n,this.pos+=n.length,n.length):(i&&(yield""),0)}*pushIndicators(){let e=0;e:for(;;){switch(this.charAt(0)){case"!":e+=yield*this.pushTag(),e+=yield*this.pushSpaces(!0);continue e;case"&":e+=yield*this.pushUntil(sa),e+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let i=this.flowLevel>0,n=this.charAt(1);if(z(n)||i&&Gi.has(n)){i?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,e+=yield*this.pushCount(1),e+=yield*this.pushSpaces(!0);continue e}}}break e}return e}*pushTag(){if(this.charAt(1)==="<"){let e=this.pos+2,i=this.buffer[e];for(;!z(i)&&i!==">";)i=this.buffer[++e];return yield*this.pushToIndex(i===">"?e+1:e,!1)}else{let e=this.pos+1,i=this.buffer[e];for(;i;)if(Np.has(i))i=this.buffer[++e];else if(i==="%"&&Ic.has(this.buffer[e+1])&&Ic.has(this.buffer[e+2]))i=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];return e===` +`){let o=this.continueScalar(n+1);if(o===-1)break;n=Math.max(n,o-2)}}else{if(e&&Gi.has(r))break;i=n}return!r&&!this.atEnd?this.setNext("plain-scalar"):(yield $t.SCALAR,yield*this.pushToIndex(i+1,!0),e?"flow":"doc")}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,i){let n=this.buffer.slice(this.pos,e);return n?(yield n,this.pos+=n.length,n.length):(i&&(yield""),0)}*pushIndicators(){let e=0;e:for(;;){switch(this.charAt(0)){case"!":e+=yield*this.pushTag(),e+=yield*this.pushSpaces(!0);continue e;case"&":e+=yield*this.pushUntil(ca),e+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let i=this.flowLevel>0,n=this.charAt(1);if(z(n)||i&&Gi.has(n)){i?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,e+=yield*this.pushCount(1),e+=yield*this.pushSpaces(!0);continue e}}}break e}return e}*pushTag(){if(this.charAt(1)==="<"){let e=this.pos+2,i=this.buffer[e];for(;!z(i)&&i!==">";)i=this.buffer[++e];return yield*this.pushToIndex(i===">"?e+1:e,!1)}else{let e=this.pos+1,i=this.buffer[e];for(;i;)if(Np.has(i))i=this.buffer[++e];else if(i==="%"&&Ic.has(this.buffer[e+1])&&Ic.has(this.buffer[e+2]))i=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];return e===` `?yield*this.pushCount(1):e==="\r"&&this.charAt(1)===` -`?yield*this.pushCount(2):0}*pushSpaces(e){let i=this.pos-1,n;do n=this.buffer[++i];while(n===" "||e&&n===" ");let r=i-this.pos;return r>0&&(yield this.buffer.substr(this.pos,r),this.pos=i),r}*pushUntil(e){let i=this.pos,n=this.buffer[i];for(;!e(n);)n=this.buffer[++i];return yield*this.pushToIndex(i,!1)}};_c.Lexer=ca});var fa=w(Oc=>{"use strict";var ua=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let i=0,n=this.lineStarts.length;for(;i>1;this.lineStarts[a]{"use strict";var kp=Qt("process"),jc=Ji(),Sp=la();function ge(t,e){for(let i=0;i=0;)switch(t[e].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;t[++e]?.type==="space";);return t.splice(e,t.length)}function Ui(t,e){if(e.length<1e5)Array.prototype.push.apply(t,e);else for(let i=0;i0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let e=this.peek(1);if(this.type==="doc-end"&&e?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!e)return yield*this.stream();switch(e.type){case"document":return yield*this.document(e);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(e);case"block-scalar":return yield*this.blockScalar(e);case"block-map":return yield*this.blockMap(e);case"block-seq":return yield*this.blockSequence(e);case"flow-collection":return yield*this.flowCollection(e);case"doc-end":return yield*this.documentEnd(e)}yield*this.pop()}peek(e){return this.stack[this.stack.length-e]}*pop(e){let i=e??this.stack.pop();if(!i)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield i;else{let n=this.peek(1);switch(i.type==="block-scalar"?i.indent="indent"in n?n.indent:0:i.type==="flow-collection"&&n.type==="document"&&(i.indent=0),i.type==="flow-collection"&&$c(i),n.type){case"document":n.value=i;break;case"block-scalar":n.props.push(i);break;case"block-map":{let r=n.items[n.items.length-1];if(r.value){n.items.push({start:[],key:i,sep:[]}),this.onKeyLine=!0;return}else if(r.sep)r.value=i;else{Object.assign(r,{key:i,sep:[]}),this.onKeyLine=!r.explicitKey;return}break}case"block-seq":{let r=n.items[n.items.length-1];r.value?n.items.push({start:[],value:i}):r.value=i;break}case"flow-collection":{let r=n.items[n.items.length-1];!r||r.value?n.items.push({start:[],key:i,sep:[]}):r.sep?r.value=i:Object.assign(r,{key:i,sep:[]});return}default:yield*this.pop(),yield*this.pop(i)}if((n.type==="document"||n.type==="block-map"||n.type==="block-seq")&&(i.type==="block-map"||i.type==="block-seq")){let r=i.items[i.items.length-1];r&&!r.sep&&!r.value&&r.start.length>0&&Hc(r.start)===-1&&(i.indent===0||r.start.every(a=>a.type!=="comment"||a.indent0&&(yield this.buffer.substr(this.pos,r),this.pos=i),r}*pushUntil(e){let i=this.pos,n=this.buffer[i];for(;!e(n);)n=this.buffer[++i];return yield*this.pushToIndex(i,!1)}};_c.Lexer=la});var da=w(Oc=>{"use strict";var fa=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let i=0,n=this.lineStarts.length;for(;i>1;this.lineStarts[a]{"use strict";var kp=Qt("process"),jc=Ji(),Sp=ua();function ge(t,e){for(let i=0;i=0;)switch(t[e].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;t[++e]?.type==="space";);return t.splice(e,t.length)}function Ui(t,e){if(e.length<1e5)Array.prototype.push.apply(t,e);else for(let i=0;i0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let e=this.peek(1);if(this.type==="doc-end"&&e?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!e)return yield*this.stream();switch(e.type){case"document":return yield*this.document(e);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(e);case"block-scalar":return yield*this.blockScalar(e);case"block-map":return yield*this.blockMap(e);case"block-seq":return yield*this.blockSequence(e);case"flow-collection":return yield*this.flowCollection(e);case"doc-end":return yield*this.documentEnd(e)}yield*this.pop()}peek(e){return this.stack[this.stack.length-e]}*pop(e){let i=e??this.stack.pop();if(!i)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield i;else{let n=this.peek(1);switch(i.type==="block-scalar"?i.indent="indent"in n?n.indent:0:i.type==="flow-collection"&&n.type==="document"&&(i.indent=0),i.type==="flow-collection"&&$c(i),n.type){case"document":n.value=i;break;case"block-scalar":n.props.push(i);break;case"block-map":{let r=n.items[n.items.length-1];if(r.value){n.items.push({start:[],key:i,sep:[]}),this.onKeyLine=!0;return}else if(r.sep)r.value=i;else{Object.assign(r,{key:i,sep:[]}),this.onKeyLine=!r.explicitKey;return}break}case"block-seq":{let r=n.items[n.items.length-1];r.value?n.items.push({start:[],value:i}):r.value=i;break}case"flow-collection":{let r=n.items[n.items.length-1];!r||r.value?n.items.push({start:[],key:i,sep:[]}):r.sep?r.value=i:Object.assign(r,{key:i,sep:[]});return}default:yield*this.pop(),yield*this.pop(i)}if((n.type==="document"||n.type==="block-map"||n.type==="block-seq")&&(i.type==="block-map"||i.type==="block-seq")){let r=i.items[i.items.length-1];r&&!r.sep&&!r.value&&r.start.length>0&&Hc(r.start)===-1&&(i.indent===0||r.start.every(a=>a.type!=="comment"||a.indent=e.indent){let n=!this.onKeyLine&&this.indent===e.indent,r=n&&(i.sep||i.explicitKey)&&this.type!=="seq-item-ind",a=[];if(r&&i.sep&&!i.value){let o=[];for(let s=0;se.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(a=i.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":r||i.value?(a.push(this.sourceToken),e.items.push({start:a}),this.onKeyLine=!0):i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"explicit-key-ind":!i.sep&&!i.explicitKey?(i.start.push(this.sourceToken),i.explicitKey=!0):r||i.value?(a.push(this.sourceToken),e.items.push({start:a,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(i.explicitKey)if(i.sep)if(i.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(ge(i.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:a,key:null,sep:[this.sourceToken]}]});else if(Lc(i.key)&&!ge(i.sep,"newline")){let o=Ze(i.start),s=i.key,c=i.sep;c.push(this.sourceToken),delete i.key,delete i.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:s,sep:c}]})}else a.length>0?i.sep=i.sep.concat(a,this.sourceToken):i.sep.push(this.sourceToken);else if(ge(i.start,"newline"))Object.assign(i,{key:null,sep:[this.sourceToken]});else{let o=Ze(i.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else i.sep?i.value||r?e.items.push({start:a,key:null,sep:[this.sourceToken]}):ge(i.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):i.sep.push(this.sourceToken):Object.assign(i,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);r||i.value?(e.items.push({start:a,key:o,sep:[]}),this.onKeyLine=!0):i.sep?this.stack.push(o):(Object.assign(i,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(e);if(o){if(o.type==="block-seq"){if(!i.explicitKey&&i.sep&&!ge(i.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else n&&e.items.push({start:a});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let i=e.items[e.items.length-1];switch(this.type){case"newline":if(i.value){let n="end"in i.value?i.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else i.start.push(this.sourceToken);return;case"space":case"comment":if(i.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(i.start,e.indent)){let r=e.items[e.items.length-2]?.value?.end;if(Array.isArray(r)){Ui(r,i.start),r.push(this.sourceToken),e.items.pop();return}}i.start.push(this.sourceToken)}return;case"anchor":case"tag":if(i.value||this.indent<=e.indent)break;i.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;i.value||ge(i.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):i.start.push(this.sourceToken);return}if(this.indent>e.indent){let n=this.startBlockValue(e);if(n){this.stack.push(n);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let i=e.items[e.items.length-1];if(this.type==="flow-error-end"){let n;do yield*this.pop(),n=this.peek(1);while(n?.type==="flow-collection")}else if(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!i||i.sep?e.items.push({start:[this.sourceToken]}):i.start.push(this.sourceToken);return;case"map-value-ind":!i||i.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):i.sep?i.sep.push(this.sourceToken):Object.assign(i,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!i||i.value?e.items.push({start:[this.sourceToken]}):i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let r=this.flowScalar(this.type);!i||i.value?e.items.push({start:[],key:r,sep:[]}):i.sep?this.stack.push(r):Object.assign(i,{key:r,sep:[]});return}case"flow-map-end":case"flow-seq-end":e.end.push(this.sourceToken);return}let n=this.startBlockValue(e);n?this.stack.push(n):(yield*this.pop(),yield*this.step())}else{let n=this.peek(2);if(n.type==="block-map"&&(this.type==="map-value-ind"&&n.indent===e.indent||this.type==="newline"&&!n.items[n.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&n.type!=="flow-collection"){let r=Ki(n),a=Ze(r);$c(e);let o=e.end.splice(1,e.end.length);o.push(this.sourceToken);let s={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:a,key:e,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let i=this.source.indexOf(` `)+1;for(;i!==0;)this.onNewLine(this.offset+i),i=this.source.indexOf(` -`,i)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let i=Ki(e),n=Ze(i);return n.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let i=Ki(e),n=Ze(i);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,i){return this.type!=="comment"||this.indent<=i?!1:e.every(n=>n.type==="newline"||n.type==="space")}*documentEnd(e){this.type!=="doc-mode"&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};Fc.Parser=da});var Vc=w(Ft=>{"use strict";var Mc=Zr(),Ep=xt(),Lt=_t(),Cp=Xn(),Rp=C(),Pp=fa(),Bc=ha();function Dc(t){let e=t.prettyErrors!==!1;return{lineCounter:t.lineCounter||e&&new Pp.LineCounter||null,prettyErrors:e}}function Ap(t,e={}){let{lineCounter:i,prettyErrors:n}=Dc(e),r=new Bc.Parser(i?.addNewLine),a=new Mc.Composer(e),o=Array.from(a.compose(r.parse(t)));if(n&&i)for(let s of o)s.errors.forEach(Lt.prettifyError(t,i)),s.warnings.forEach(Lt.prettifyError(t,i));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function qc(t,e={}){let{lineCounter:i,prettyErrors:n}=Dc(e),r=new Bc.Parser(i?.addNewLine),a=new Mc.Composer(e),o=null;for(let s of a.compose(r.parse(t),!0,t.length))if(!o)o=s;else if(o.options.logLevel!=="silent"){o.errors.push(new Lt.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&i&&(o.errors.forEach(Lt.prettifyError(t,i)),o.warnings.forEach(Lt.prettifyError(t,i))),o}function xp(t,e,i){let n;typeof e=="function"?n=e:i===void 0&&e&&typeof e=="object"&&(i=e);let r=qc(t,i);if(!r)return null;if(r.warnings.forEach(a=>Cp.warn(r.options.logLevel,a)),r.errors.length>0){if(r.options.logLevel!=="silent")throw r.errors[0];r.errors=[]}return r.toJS(Object.assign({reviver:n},i))}function Tp(t,e,i){let n=null;if(typeof e=="function"||Array.isArray(e)?n=e:i===void 0&&e&&(i=e),typeof i=="string"&&(i=i.length),typeof i=="number"){let r=Math.round(i);i=r<1?void 0:r>8?{indent:8}:{indent:r}}if(t===void 0){let{keepUndefined:r}=i??e??{};if(!r)return}return Rp.isDocument(t)&&!n?t.toString(i):new Ep.Document(t,n,i).toString(i)}Ft.parse=xp;Ft.parseAllDocuments=Ap;Ft.parseDocument=qc;Ft.stringify=Tp});var Xi=w(P=>{"use strict";var Ip=Zr(),_p=xt(),Op=Or(),pa=_t(),jp=ht(),we=C(),Hp=he(),$p=T(),Lp=me(),Fp=ve(),Mp=Ji(),Bp=la(),Dp=fa(),qp=ha(),Yi=Vc(),Wc=lt();P.Composer=Ip.Composer;P.Document=_p.Document;P.Schema=Op.Schema;P.YAMLError=pa.YAMLError;P.YAMLParseError=pa.YAMLParseError;P.YAMLWarning=pa.YAMLWarning;P.Alias=jp.Alias;P.isAlias=we.isAlias;P.isCollection=we.isCollection;P.isDocument=we.isDocument;P.isMap=we.isMap;P.isNode=we.isNode;P.isPair=we.isPair;P.isScalar=we.isScalar;P.isSeq=we.isSeq;P.Pair=Hp.Pair;P.Scalar=$p.Scalar;P.YAMLMap=Lp.YAMLMap;P.YAMLSeq=Fp.YAMLSeq;P.CST=Mp;P.Lexer=Bp.Lexer;P.LineCounter=Dp.LineCounter;P.Parser=qp.Parser;P.parse=Yi.parse;P.parseAllDocuments=Yi.parseAllDocuments;P.parseDocument=Yi.parseDocument;P.stringify=Yi.stringify;P.visit=Wc.visit;P.visitAsync=Wc.visitAsync});import{promises as Gv}from"fs";import st from"path";var ru=null;function au(t,e){let i=t;for(let n of e)i+="\0"+(typeof n=="string"?n:JSON.stringify(n));return i}function Ka(t,e){return(...i)=>{let n=ru;if(n===null)return e(...i);let r=au(`async:${t}`,i),a=n.entries.get(r);if(a)return a.value;let o=e(...i).catch(s=>{throw n.entries.delete(r),s});return n.entries.set(r,{value:o}),o}}import{readFileSync as ou}from"fs";import Ua from"path";var su=new Set(["applypatch","create","createfile","deletefile","edit","editfile","patch","strreplaceeditor","write","writefile","writefiletool"]),cu=new Set(["glob","grep","listfiles","read","readfile","search","view"]),Qa=["file_path","filePath","path","target_file","targetFile"],Za=["file_paths","filePaths","paths","files","targets"],eo=["operations","edits"],lu=["patch","diff","patchText","patch_text","changes"];function jn(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function Ya(t){return t.toLowerCase().replace(/[^a-z0-9]+/gu,"")}function uu(t){for(let e of["tool_name","toolName","tool","name"]){let i=t[e];if(typeof i=="string"&&i.trim())return i.trim()}return null}function fu(t){for(let e of["cwd","working_directory","workspaceRoot"]){let i=t[e];if(!(typeof i!="string"||!i.trim()||!Ua.isAbsolute(i.trim())))return Ua.resolve(i.trim())}}function du(t){if(typeof t!="string")return t;let e=t.trim();if(!e.startsWith("{")&&!e.startsWith("["))return t;try{return JSON.parse(e)}catch{return t}}function hu(t){for(let e of["tool_input","toolInput","toolArgs","tool_args","arguments"])if(t[e]!==void 0)return du(t[e]);return t}function Xa(t){let e=[],i=[/^\*\*\* (?:Add|Update|Delete) File:\s+(.+?)\s*$/gmu,/^\+\+\+\s+(?:b\/)?(.+?)\s*$/gmu];for(let n of i)for(let r of t.matchAll(n)){let a=r[1]?.trim();a&&a!=="/dev/null"&&e.push(a)}return e}function Ee(t,e){if(typeof e=="string"){let i=e.trim();i&&t.push(i);return}if(Array.isArray(e)){for(let i of e)Ee(t,i);return}if(jn(e)){for(let i of Qa)Ee(t,e[i]);for(let i of Za)Ee(t,e[i]);for(let i of eo)Ee(t,e[i])}}function pu(t,e){let i=[],n=[e,t].filter(jn);for(let r of n){for(let a of Qa)Ee(i,r[a]);for(let a of Za)Ee(i,r[a]);for(let a of eo)Ee(i,r[a]);for(let a of lu){let o=r[a];typeof o=="string"&&i.push(...Xa(o))}}return typeof e=="string"&&i.push(...Xa(e)),[...new Set(i)]}function ct(t,e){if(e?.trim())return{intent:"write",targets:[e.trim()],toolName:null};if(!t.trim())return{intent:"unknown",targets:[],toolName:null};let i;try{i=JSON.parse(t)}catch{return{intent:"unknown",targets:[],toolName:null}}if(!jn(i))return{intent:"unknown",targets:[],toolName:null};let n=uu(i),r=pu(i,hu(i)),a=fu(i);return n&&su.has(Ya(n))?{intent:r.length>0?"write":"unknown",targets:r,toolName:n,...a?{cwd:a}:{}}:n&&cu.has(Ya(n))?{intent:"non-write",targets:[],toolName:n,...a?{cwd:a}:{}}:n?{intent:"unknown",targets:r,toolName:n,...a?{cwd:a}:{}}:{intent:r.length>0?"write":"unknown",targets:r,toolName:null,...a?{cwd:a}:{}}}function to(){let t=process.env.FILE_PATH;if(t?.trim()||process.stdin.isTTY)return ct("",t);try{return ct(ou(0,"utf8"),t)}catch{return ct("",t)}}var La=On(Xi(),1);import{promises as Ev}from"fs";import Me from"path";import{createHash as Jp}from"node:crypto";import{promises as G}from"node:fs";import B from"node:path";import{TextDecoder as Gp}from"node:util";var Vp=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),Wp=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function zp(t){return t.toLowerCase().startsWith(".env")}function Mt(t){let i=t.replaceAll("\\","/").split("/").filter(Boolean).map(n=>n.toLowerCase());return i.some(n=>zp(n))?"environment-file":i.some(n=>Wp.has(n))?"credential-config":i.includes(".git")?"git-metadata":i.some(n=>Vp.has(n))?"dependency-or-cache":i.join("/")===".comet/config.yaml"?"comet-config":i.join("/")===".comet/current-change.json"?"comet-selection":null}function ye(t){return t!==0&&t!==0n&&t!=="0"}function J(t,e){return ye(t.dev)&&ye(e.dev)&&ye(t.ino)&&ye(e.ino)}function I(t,e){let i=ye(t.dev)&&ye(e.dev);if(i&&t.dev!==e.dev)return!1;let n=ye(t.ino)&&ye(e.ino);return n&&t.ino!==e.ino?!1:i&&n?!0:t.birthtime===e.birthtime}var Zi=1024*1024;function ma(t,e){let i=B.relative(t,e);return i===""||!B.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${B.sep}`)}function Kp(t){let e=B.posix.normalize(t);if(t.length===0||t!==t.trim()||t.includes("\\")||Array.from(t).some(r=>{let a=r.codePointAt(0)??0;return a<=31||a===127})||B.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes("..")||e!==t||e==="."||t.endsWith("/"))throw new Error(`Native artifact ref must be normalized and relative: ${t}`);let i=t.toLowerCase(),n=Mt(t);if(n||i==="runtime"||i.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${n??"native-runtime"}): ${t}`);return t}function Up(t){if(!Number.isSafeInteger(t)||t<1)throw new Error("Native artifact byte limit must be a positive integer");return t}function Yp(t,e){return I({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function Qi(t,e){let i={...t,birthtime:t.birthtimeMs},n={...e,birthtime:e.birthtimeMs};return J(i,n)?I(i,n):I(i,n)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.size===e.size}async function zc(t){let e=await G.lstat(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${t}`);return{path:t,realPath:await G.realpath(t),dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}async function Xp(t,e){let i=B.resolve(t),n=B.resolve(e);if(!ma(i,n))throw new Error("Native artifact path is outside its root");let r=[await zc(i)],a=i;for(let o of B.relative(i,n).split(B.sep).filter(Boolean)){a=B.join(a,o);let s=await zc(a);if(!ma(r[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);r.push(s)}return r}async function Jc(t){for(let e of t){let i=await G.lstat(e.path);if(!i.isDirectory()||i.isSymbolicLink()||!Yp(e,i)||await G.realpath(e.path)!==e.realPath)throw new Error(`Native artifact parent changed while reading: ${e.path}`)}}async function Ne(t){let e=Kp(t.ref),i=Up(t.maxBytes??Zi),n=B.resolve(t.root,...e.split("/")),r=await Xp(t.root,B.dirname(n));await t.hooks?.afterParentChainCaptured?.();let a=await G.lstat(n);if(!a.isFile()||a.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${e}`);if(a.size>i)throw new Error(`Native artifact exceeds ${i} bytes: ${e}`);let o=await G.realpath(n);if(!ma(r[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${e}`);let s=await G.open(n,"r");try{let[c,l,d]=await Promise.all([s.stat(),G.lstat(n),G.realpath(n)]);if(await Jc(r),!c.isFile()||!l.isFile()||l.isSymbolicLink()||d!==o||!Qi(a,c)||!Qi(c,l))throw new Error(`Native artifact changed while opening: ${e}`);await t.hooks?.afterOpen?.();let u=[],f=0,m=Buffer.allocUnsafe(Math.min(64*1024,i+1));for(;;){let k=i+1-f,S=await s.read(m,0,Math.min(m.length,k),null);if(S.bytesRead===0)break;if(f+=S.bytesRead,f>i)throw new Error(`Native artifact exceeds ${i} bytes: ${e}`);u.push(Buffer.from(m.subarray(0,S.bytesRead)))}await t.hooks?.beforeFinalCheck?.();let[g,h,p]=await Promise.all([s.stat(),G.lstat(n),G.realpath(n)]);if(await Jc(r),!h.isFile()||h.isSymbolicLink()||p!==o||!Qi(c,g)||!Qi(c,h))throw new Error(`Native artifact changed while reading: ${e}`);let y=Buffer.concat(u,f),N;try{N=new Gp("utf-8",{fatal:!0}).decode(y)}catch(k){throw new Error(`Native artifact is not valid UTF-8: ${e}`,{cause:k})}return{ref:e,size:f,hash:Jp("sha256").update(y).digest("hex"),text:N}}finally{await s.close()}}var ga=On(Xi(),1);import en from"path";var Dt=64*1024,tn=1024,nn=64,Kc=5,Qp=[".agents/skills/**",".amazonq/skills/**",".augment/skills/**",".bob/skills/**",".claude/skills/**",".cline/skills/**",".codebuddy/skills/**",".continue/skills/**",".cospec/skills/**",".crush/skills/**",".cursor/skills/**",".factory/skills/**",".forge/skills/**",".gemini/skills/**",".github/skills/**",".iflow/skills/**",".junie/skills/**",".kilocode/skills/**",".kimi-code/skills/**",".kiro/skills/**",".lingma/skills/**",".mimocode/skills/**",".opencode/skills/**",".pi/skills/**",".qoder/skills/**",".qwen/skills/**",".roo/skills/**",".trae-cn/skills/**",".trae/skills/**",".windsurf/skills/**",".zcode/skills/**"],te={include:["**/*"],exclude:[...Qp],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4};function Zp(t,e){if(typeof t!="string")throw new Error(`${e} must be a string`);let i=t.trim();if(i.length===0||en.posix.isAbsolute(i)||en.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${e} must be a project-relative path`);if(i===".")return[];let n=i.replaceAll("\\","/").split("/");if(n.some(r=>r===".."))throw new Error(`${e} must stay inside the project root`);if(n.some(r=>r===""||r==="."))throw new Error(`${e} must not contain empty or dot path segments`);return n}function et(t){let e=Zp(t,"native.artifact_root");return e.length===0?".":e.join("/")}function Uc(t,e="docs"){let i=t??e;if(i!=="legacy"&&i!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return i}function wa(t,e,i=!1){if(typeof t!="string")throw new Error(`${e} must be a string`);let n=t.trim().replaceAll("\\","/");if(n.length===0||en.posix.isAbsolute(n)||en.win32.isAbsolute(n)||/^(?:~|[\\/])/u.test(n))throw new Error(`${e} must be relative to its declared path base`);let r=n.split("/");if(r.some(a=>a===".."))throw new Error(`${e} must stay inside its declared path base`);if(r.some(a=>a===""||a==="."))throw new Error(`${e} must not contain empty or dot path segments`);if(!i&&/[*?]/u.test(n))throw new Error(`${e} cannot contain wildcards`);return r.join("/")}function Bt(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function Yc(t,e,i){let n=t??e;if(n!=="en"&&n!=="zh-CN")throw new Error(`${i} must be en or zh-CN`);return n}function rn(t,e){if(typeof t!="string"||t.length===0||t.includes("\\")||t.includes("\0")||t.startsWith("/")||t.split("/").includes(".."))throw new Error(`${e} contains an unsafe pattern`);if(t.length>tn)throw new Error(`${e} exceeds ${tn} characters`);let i=0;for(let n=0;nnn)throw new Error(`${e} contains more than ${nn} wildcard tokens`);return t}function Gc(t,e,i){if(t===void 0)return[...i];if(!Array.isArray(t))throw new Error(`${e} contains an unsafe pattern`);return[...new Set(t.map(n=>rn(n,e)))].sort((n,r)=>n.localeCompare(r,"en"))}function va(t,e,i){let n=t??e;if(!Number.isSafeInteger(n)||n<1)throw new Error(`${i} must be a positive integer`);return n}function em(t){if(t===void 0)return{...te,include:[...te.include],exclude:[...te.exclude]};let e=Bt(t,"native.snapshot");return{include:Gc(e.include,"native.snapshot.include",te.include),exclude:Gc(e.exclude,"native.snapshot.exclude",te.exclude),max_files:va(e.max_files,te.max_files,"native.snapshot.max_files"),max_total_bytes:va(e.max_total_bytes,te.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:va(e.max_duration_ms,te.max_duration_ms,"native.snapshot.max_duration_ms")}}function tm(t){if(t===void 0)return;let e=Bt(t,"native.pending_root_move"),i=e.id,n=e.from_artifact_root,r=e.to_artifact_root,a=e.stage;if(typeof i!="string"||!/^[a-f0-9-]{8,}$/u.test(i))throw new Error("native.pending_root_move.id is invalid");if(typeof n!="string"||typeof r!="string")throw new Error("native.pending_root_move roots must be strings");if(a!=="copying"&&a!=="ready"&&a!=="switched")throw new Error("native.pending_root_move.stage is invalid");let o;if(e.cleanup!==void 0){let s=Bt(e.cleanup,"native.pending_root_move.cleanup"),c=s.kind,l=s.state,d=s.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof d!="string"||!/^[a-f0-9]{64}$/u.test(d))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:d}}return{id:i,fromArtifactRoot:et(n),toArtifactRoot:et(r),stage:a,...o?{cleanup:o}:{}}}function im(t,e={}){let i=Bt(t,"native"),n=i.artifact_root??(e.allowMissingArtifactRoot?"docs":void 0);if(typeof n!="string")throw new Error("native.artifact_root must be a string");let r=i.clarification_mode??"sequential";if(r!=="sequential"&&r!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let a=i.archive_confirmation??"automatic";if(a!=="automatic"&&a!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=i.max_verify_failures??Kc;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=tm(i.pending_root_move);return{artifact_root:et(n),language:Yc(i.language,"en","native.language"),clarification_mode:r,archive_confirmation:a,max_verify_failures:o,snapshot:em(i.snapshot),...s?{pending_root_move:s}:{}}}function nm(t){let e=Bt(t,"classic"),i=e.context_compression??"off";if(i!=="off"&&i!=="beta")throw new Error("classic.context_compression must be off or beta");let n=e.review_mode??"standard";if(n!=="off"&&n!=="standard"&&n!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let r=e.auto_transition??!0;if(typeof r!="boolean")throw new Error("classic.auto_transition must be true or false");return{artifact_layout:Uc(e.artifact_layout),language:Yc(e.language,"zh-CN","classic.language"),context_compression:i,review_mode:n,auto_transition:r}}function rm(t){let e=t??!0;if(typeof e!="boolean")throw new Error("ambient_resume must be true or false");return e}function am(t,e,i,n,r){let a=t.schema!==void 0;if(!(a||t.default_workflow!==void 0||t.workflows!==void 0||!r.allowPartialProject&&t.native!==void 0)||r.allowPartialProject&&!a)return null;if(t.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(t.default_workflow!=="native"&&t.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let s=t.workflows??[t.default_workflow];if(!Array.isArray(s)||s.length===0||s.some(l=>l!=="native"&&l!=="classic"))throw new Error("workflows must contain native and/or classic");let c=[...new Set(s)];if(!c.includes(t.default_workflow))throw new Error("workflows must include default_workflow");if(c.includes("native")&&!e)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:t.default_workflow,workflows:c,ambient_resume:n,...e?{native:e}:{},...i?{classic:i}:{}}}function qt(t,e={}){let i=(0,ga.parseDocument)(t,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${i.errors[0].message}`);let n=i.toJS();if(n==null)return{value:{},config:null,ambient_resume:!0};if(typeof n!="object"||Array.isArray(n))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let r=n,a=rm(r.ambient_resume),o=r.native===void 0?void 0:im(r.native,{allowMissingArtifactRoot:e.allowMissingNativeFields}),s=r.classic===void 0?void 0:nm(r.classic),c=am(r,o,s,a,{allowPartialProject:e.allowPartialProject??!1});return{value:r,config:c,ambient_resume:a,...o?{native:o}:{},...s?{classic:s}:{}}}import{createHash as sm}from"crypto";import{promises as sn}from"fs";import be from"path";import{constants as an,promises as Ie}from"fs";var ie=class extends Error{reason;constructor(e,i,n){super(i,n),this.name="RaceSafeReadError",this.reason=e}};function ya(t){return"birthtimeNs"in t&&typeof t.birthtimeNs=="bigint"?t.birthtimeNs:t.birthtimeMs}function Xc(t){return"ctimeNs"in t&&typeof t.ctimeNs=="bigint"?t.ctimeNs:t.ctimeMs}function Vt(t){return{dev:t.dev,ino:t.ino,birthtime:ya(t)}}function on(t,e){let i=Vt(t),n=Vt(e);return J(i,n)?I(i,n):I(i,n)&&ya(t)===ya(e)&&Xc(t)===Xc(e)&&t.size===e.size}async function tt(t,e,i={}){if(!Number.isSafeInteger(e)||e<1)throw new Error("race-safe read byte limit must be a positive integer");let n=i.label??"file",r=i.bigint===!0,a=await Ie.lstat(t,{bigint:r});if(!a.isFile()||a.isSymbolicLink())throw new ie("not-regular-file",`${n} must be a regular file`);if(BigInt(a.size)>BigInt(e))throw new ie("too-large",`${n} exceeds ${e} bytes`);let o=await Ie.realpath(t);await i.verify?.("pre-open",{realPath:o,identity:Vt(a)});let s=process.platform==="win32"?an.O_RDONLY:an.O_RDONLY|an.O_NOFOLLOW|an.O_NONBLOCK,c;try{c=await Ie.open(t,s)}catch(l){throw l.code==="ELOOP"?new ie("not-regular-file",`${n} must be a regular file`,{cause:l}):l}try{let[l,d,u]=await Promise.all([c.stat({bigint:r}),Ie.lstat(t,{bigint:r}),Ie.realpath(t)]);if(!l.isFile()||!d.isFile()||d.isSymbolicLink()||u!==o||!on(a,l)||!on(a,d))throw new ie("changed",`${n} changed while opening`);await i.verify?.("post-open",{realPath:u,identity:Vt(l)}),await i.hooks?.afterOpen?.();let f=[],m=0,g=Buffer.allocUnsafe(Math.min(64*1024,e+1));for(;;){let N=e+1-m,{bytesRead:k}=await c.read(g,0,Math.min(g.length,N),null);if(k===0)break;if(m+=k,m>e)throw new ie("too-large",`${n} exceeds ${e} bytes`);f.push(Buffer.from(g.subarray(0,k)))}await i.hooks?.beforeFinalCheck?.();let[h,p,y]=await Promise.all([c.stat({bigint:r}),Ie.lstat(t,{bigint:r}),Ie.realpath(t)]);if(!p.isFile()||p.isSymbolicLink()||y!==o||!on(a,h)||!on(a,p))throw new ie("changed",`${n} changed while reading`);return await i.verify?.("post-read",{realPath:y,identity:Vt(h)}),{bytes:Buffer.concat(f,m),stat:h,realPath:y}}finally{await c.close()}}function om(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}function Na(t,e){let i=be.relative(t,e);return i===""||!be.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${be.sep}`)}async function Qc(t,e){let i=be.resolve(t),n=await sn.lstat(i);if(!n.isDirectory()||n.isSymbolicLink())throw new Error(`${e} project root must be a real directory`);return sn.realpath(i)}async function Zc(t,e,i,n){let r=t;for(let a=0;a{if(!Na(a,s.realPath))throw new Error(`${n.label} resolves outside the project root`);await Zc(r.projectRoot,a,r.relative.split("/"),{label:n.label,expected:"file"})}})}var zt=".comet/config.yaml";function cm(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function ba(t,e={}){return(await cn(t,e)).document}async function lm(t){try{return(await _e(t,zt,Dt,{label:zt})).bytes}catch(e){if(cm(e))return null;throw e}}function um(t){return t?{exists:!0,sha256:sm("sha256").update(t).digest("hex")}:{exists:!1,sha256:null}}async function cn(t,e={}){let i=await lm(t);return{document:i?qt(i.toString("utf8"),e):null,identity:um(i)}}var Hy=16*1024;import{promises as it}from"fs";import A from"path";import mm from"os";var Ca=".comet/config.yaml";async function Ea(t){try{return await it.lstat(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function vm(t){try{let e=await it.readFile(t,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(e)}catch(e){if(e.code==="ENOENT")return!1;throw e}}function Jt(t,e){let i=A.relative(t,e);return i===""||!A.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${A.sep}`)}async function Gt(t){let e=[],i=t;for(;!await Ea(i);){let r=A.dirname(i);if(r===i)break;e.push(A.basename(i)),i=r}let n=await it.realpath(i);return A.resolve(n,...e.reverse())}async function tl(t){try{return(await it.lstat(t)).isSymbolicLink()}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function Ra(t){let e=A.resolve(t);try{(await it.stat(e)).isDirectory()||(e=A.dirname(e))}catch(r){if(r.code!=="ENOENT")throw r}let i=e,n=A.resolve(mm.homedir());for(;;){if(!(e===n&&i!==n)){let o=A.join(e,...Ca.split("/")),s=e===i||await vm(o);if(await Ea(o)&&s)return e}if(await Ea(A.join(e,".git")))return e;let a=A.dirname(e);if(a===e)return i;e=a}}function Pa(t){return et(t)}async function gm(t,e){let i=Pa(e),n=A.resolve(t,...i.split("/")),r=await it.realpath(t),a=await Gt(n);if(!Jt(r,a))throw new Error("native.artifact_root resolves outside the project root");return n}async function un(t,e){let i=Pa(e),n=await gm(t,i),r=A.join(n,"comet");if(await tl(r))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([Gt(n),Gt(r)]);if(!Jt(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");return{projectRoot:A.resolve(t),configFile:A.join(t,...Ca.split("/")),artifactRoot:n,artifactRootRef:i,nativeRoot:r,specsDir:A.join(r,"specs"),changesDir:A.join(r,"changes"),archiveDir:A.join(r,"archive"),runtimeDir:A.join(r,"runtime"),locksDir:A.join(r,"runtime","locks"),transactionsDir:A.join(r,"runtime","transactions")}}function ne(t,e){return Jt(A.resolve(t),A.resolve(e))}async function H(t,e){let i=A.resolve(t),n=A.resolve(e);if(!Jt(i,n))throw new Error(`Path is outside the Native root: ${e}`);if(await tl(i))throw new Error(`Native root must not be a symbolic link: ${t}`);let[r,a]=await Promise.all([Gt(i),Gt(n)]);if(!Jt(r,a))throw new Error(`Path resolves outside the Native root: ${e}`);return n}var fn=rn;async function nt(t){let e=(await ba(t))?.config??null;return e?.native?e:null}import{AsyncLocalStorage as ym}from"async_hooks";var aN=16*1024;var oN=new ym;import{TextDecoder as Am}from"util";import{createHash as Nm}from"node:crypto";import{constants as dn,promises as K}from"node:fs";import U from"node:path";import{TextDecoder as bm}from"node:util";function pn(t,e){let i=U.relative(t,e);return i===""||!U.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${U.sep}`)}function km(t){if(!Number.isSafeInteger(t)||t<1)throw new Error("Native protected file byte limit must be a positive integer");return t}function Sm(t,e){return I({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function Em(t){return{dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs,ctimeMs:t.ctimeMs,mtimeMs:t.mtimeMs,size:t.size}}function hn(t,e){return I({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.mtimeMs===e.mtimeMs&&t.size===e.size}async function xa(t,e){let i=await K.lstat(t);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${e} parent must be a real directory: ${t}`);return{path:t,realPath:await K.realpath(t),dev:i.dev,ino:i.ino,birthtimeMs:i.birthtimeMs}}async function Cm(t,e,i){let n=U.resolve(t),r=U.resolve(e);if(!pn(n,r))throw new Error(`${i} is outside its managed root`);let a=[await xa(n,i)],o=n;for(let s of U.relative(n,r).split(U.sep).filter(Boolean)){await Oe(a,i),o=U.join(o,s);let c=await xa(o,i);if(!pn(a[0].realPath,c.realPath))throw new Error(`${i} parent resolves outside its managed root: ${o}`);a.push(c)}return await Oe(a,i),a}async function Oe(t,e){for(let i of t){let n=await K.lstat(i.path);if(!n.isDirectory()||n.isSymbolicLink()||!Sm(i,n)||await K.realpath(i.path)!==i.realPath)throw new Error(`${e} parent changed during I/O: ${i.path}`)}}async function Rm(t,e,i){let n=[],r=0,a=Buffer.allocUnsafe(Math.min(64*1024,e+1));for(;;){let o=e+1-r,{bytesRead:s}=await t.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(r+=s,r>e)throw new Error(`${i} exceeds ${e} bytes`);n.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(n,r)}async function rt(t){let e=km(t.maxBytes),i=U.resolve(t.file),n=await Cm(t.root,U.dirname(i),t.label),r=await Promise.all((t.forbiddenRoots??[]).map(d=>xa(U.resolve(d),t.label)));await t.hooks?.afterParentChainCaptured?.(),await Oe(n,t.label);let a=await K.lstat(i);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${t.label} must be a regular file`);if(a.size>e)throw new Error(`${t.label} exceeds ${e} bytes`);let o=Em(a),s=await K.realpath(i);if(!pn(n[0].realPath,s))throw new Error(`${t.label} resolves outside its managed root`);if(r.some(d=>pn(d.realPath,s)))throw new Error(`${t.label} resolves inside an excluded root`);let c=process.platform==="win32"?dn.O_RDONLY:dn.O_RDONLY|dn.O_NOFOLLOW|dn.O_NONBLOCK,l=await K.open(i,c);try{let d=await l.stat();await t.hooks?.afterOpen?.();let[u,f]=await Promise.all([K.lstat(i),K.realpath(i)]);if(await Oe(n,t.label),await Oe(r,t.label),!d.isFile()||!u.isFile()||u.isSymbolicLink()||f!==s||!hn(o,d)||!hn(o,u))throw new Error(`${t.label} changed while opening`);await t.hooks?.beforeRead?.();let m=await Rm(l,e,t.label);await t.hooks?.beforeFinalCheck?.();let[g,h,p]=await Promise.all([l.stat(),K.lstat(i),K.realpath(i)]);if(await Oe(n,t.label),await Oe(r,t.label),!h.isFile()||h.isSymbolicLink()||p!==s||!hn(o,g)||!hn(o,h))throw new Error(`${t.label} changed while reading`);return{bytes:m,hash:Nm("sha256").update(m).digest("hex"),size:m.length}}finally{await l.close()}}async function nl(t){let e=await rt(t),i;try{i=new bm("utf-8",{fatal:!0}).decode(e.bytes)}catch(n){throw new Error(`${t.label} is not valid UTF-8`,{cause:n})}return{...e,text:i}}var kN=256*1024,SN=1024*1024,EN=16*1024;var CN=64*1024*1024;var RN=new Am("utf-8",{fatal:!0});import vn from"path";import{createHash as Tm}from"crypto";function D(t){return Tm("sha256").update(t).digest("hex")}var WN={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},_m=1e3,Om=8*1024*1024,jm=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Hm=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),$m=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),Lm=new Set(["schema","include","exclude","hash"]),Fm=new Set(["provider","gitSelection","physicalSelection","projection"]),Mm=new Set(["provider","selection"]),Bm=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),Dm=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),qm=new Set(["schema","status","before","after"]),Vm=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),Wm=new Set(["path","hash","size","type","gitObjectId"]),zm=new Set(["path","size","type","reason"]),Jm=new Set(["ref","hash","count"]),Gm=new Set(["change-created","legacy-migration","explicit"]),Km=new Set(["file","directory","other"]),Um=new Set(["file-size","file-count","total-size","manifest-size","changed-during-read","unreadable","gitlink-unavailable","gitlink-dirty","gitlink-changed","legacy-gitlink-boundary","git-enumeration-limit","git-selection-changed","physical-enumeration-limit","physical-selection-changed"]),gn=/^[a-f0-9]{64}$/u,Ym=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;var zN=64*1024,JN=64*1024;var GN={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},KN={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};function mn(t,e){return t.hash===e.hash&&t.recordCount===e.recordCount&&t.storedRecordCount===e.storedRecordCount&&t.stdoutBytes===e.stdoutBytes&&t.overflow===e.overflow}var UN=(1n<<256n)-1n;function Xm(t,e){return t.hash===e.hash&&t.visitedNodeCount===e.visitedNodeCount&&t.recordCount===e.recordCount&&t.storedRecordCount===e.storedRecordCount&&t.encodedBytes===e.encodedBytes&&t.overflow===e.overflow&&t.unstable===e.unstable}function Qm(t){return Buffer.byteLength(JSON.stringify(t,null,2)+` +`,i)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let i=Ki(e),n=Ze(i);return n.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let i=Ki(e),n=Ze(i);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,i){return this.type!=="comment"||this.indent<=i?!1:e.every(n=>n.type==="newline"||n.type==="space")}*documentEnd(e){this.type!=="doc-mode"&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};Fc.Parser=ha});var Vc=w(Ft=>{"use strict";var Mc=ea(),Ep=xt(),Lt=_t(),Cp=Qn(),Rp=C(),Pp=da(),Bc=pa();function Dc(t){let e=t.prettyErrors!==!1;return{lineCounter:t.lineCounter||e&&new Pp.LineCounter||null,prettyErrors:e}}function Ap(t,e={}){let{lineCounter:i,prettyErrors:n}=Dc(e),r=new Bc.Parser(i?.addNewLine),a=new Mc.Composer(e),o=Array.from(a.compose(r.parse(t)));if(n&&i)for(let s of o)s.errors.forEach(Lt.prettifyError(t,i)),s.warnings.forEach(Lt.prettifyError(t,i));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function qc(t,e={}){let{lineCounter:i,prettyErrors:n}=Dc(e),r=new Bc.Parser(i?.addNewLine),a=new Mc.Composer(e),o=null;for(let s of a.compose(r.parse(t),!0,t.length))if(!o)o=s;else if(o.options.logLevel!=="silent"){o.errors.push(new Lt.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&i&&(o.errors.forEach(Lt.prettifyError(t,i)),o.warnings.forEach(Lt.prettifyError(t,i))),o}function xp(t,e,i){let n;typeof e=="function"?n=e:i===void 0&&e&&typeof e=="object"&&(i=e);let r=qc(t,i);if(!r)return null;if(r.warnings.forEach(a=>Cp.warn(r.options.logLevel,a)),r.errors.length>0){if(r.options.logLevel!=="silent")throw r.errors[0];r.errors=[]}return r.toJS(Object.assign({reviver:n},i))}function Tp(t,e,i){let n=null;if(typeof e=="function"||Array.isArray(e)?n=e:i===void 0&&e&&(i=e),typeof i=="string"&&(i=i.length),typeof i=="number"){let r=Math.round(i);i=r<1?void 0:r>8?{indent:8}:{indent:r}}if(t===void 0){let{keepUndefined:r}=i??e??{};if(!r)return}return Rp.isDocument(t)&&!n?t.toString(i):new Ep.Document(t,n,i).toString(i)}Ft.parse=xp;Ft.parseAllDocuments=Ap;Ft.parseDocument=qc;Ft.stringify=Tp});var Xi=w(P=>{"use strict";var Ip=ea(),_p=xt(),Op=jr(),ma=_t(),jp=ht(),we=C(),Hp=he(),$p=T(),Lp=me(),Fp=ve(),Mp=Ji(),Bp=ua(),Dp=da(),qp=pa(),Yi=Vc(),Wc=lt();P.Composer=Ip.Composer;P.Document=_p.Document;P.Schema=Op.Schema;P.YAMLError=ma.YAMLError;P.YAMLParseError=ma.YAMLParseError;P.YAMLWarning=ma.YAMLWarning;P.Alias=jp.Alias;P.isAlias=we.isAlias;P.isCollection=we.isCollection;P.isDocument=we.isDocument;P.isMap=we.isMap;P.isNode=we.isNode;P.isPair=we.isPair;P.isScalar=we.isScalar;P.isSeq=we.isSeq;P.Pair=Hp.Pair;P.Scalar=$p.Scalar;P.YAMLMap=Lp.YAMLMap;P.YAMLSeq=Fp.YAMLSeq;P.CST=Mp;P.Lexer=Bp.Lexer;P.LineCounter=Dp.LineCounter;P.Parser=qp.Parser;P.parse=Yi.parse;P.parseAllDocuments=Yi.parseAllDocuments;P.parseDocument=Yi.parseDocument;P.stringify=Yi.stringify;P.visit=Wc.visit;P.visitAsync=Wc.visitAsync});import{promises as Gv}from"fs";import st from"path";var ru=null;function au(t,e){let i=t;for(let n of e)i+="\0"+(typeof n=="string"?n:JSON.stringify(n));return i}function Ua(t,e){return(...i)=>{let n=ru;if(n===null)return e(...i);let r=au(`async:${t}`,i),a=n.entries.get(r);if(a)return a.value;let o=e(...i).catch(s=>{throw n.entries.delete(r),s});return n.entries.set(r,{value:o}),o}}import{readFileSync as ou}from"fs";import Ya from"path";var su=new Set(["applypatch","create","createfile","deletefile","edit","editfile","patch","strreplaceeditor","write","writefile","writefiletool"]),cu=new Set(["glob","grep","listfiles","read","readfile","search","view"]),Qa=["file_path","filePath","path","target_file","targetFile"],Za=["file_paths","filePaths","paths","files","targets"],eo=["operations","edits"],lu=["patch","diff","patchText","patch_text","changes"];function Hn(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function Xa(t){return t.toLowerCase().replace(/[^a-z0-9]+/gu,"")}function uu(t){for(let e of["tool_name","toolName","tool","name"]){let i=t[e];if(typeof i=="string"&&i.trim())return i.trim()}return null}function fu(t){for(let e of["cwd","working_directory","workspaceRoot"]){let i=t[e];if(!(typeof i!="string"||!i.trim()||!Ya.isAbsolute(i.trim())))return Ya.resolve(i.trim())}}function du(t){if(typeof t!="string")return t;let e=t.trim();if(!e.startsWith("{")&&!e.startsWith("["))return t;try{return JSON.parse(e)}catch{return t}}function hu(t){for(let e of["tool_input","toolInput","toolArgs","tool_args","arguments"])if(t[e]!==void 0)return du(t[e]);return t}function jn(t){let e=[],i=[/^\*\*\* (?:Add|Update|Delete) File:\s+(.+?)\s*$/gmu,/^\+\+\+\s+(?:b\/)?(.+?)\s*$/gmu];for(let n of i)for(let r of t.matchAll(n)){let a=r[1]?.trim();a&&a!=="/dev/null"&&e.push(a)}return e}function Ee(t,e){if(typeof e=="string"){let i=e.trim();i&&t.push(i);return}if(Array.isArray(e)){for(let i of e)Ee(t,i);return}if(Hn(e)){for(let i of Qa)Ee(t,e[i]);for(let i of Za)Ee(t,e[i]);for(let i of eo)Ee(t,e[i])}}function pu(t,e){let i=[],n=[e,t].filter(Hn);for(let r of n){for(let a of Qa)Ee(i,r[a]);for(let a of Za)Ee(i,r[a]);for(let a of eo)Ee(i,r[a]);for(let a of lu){let o=r[a];typeof o=="string"&&i.push(...jn(o))}}return typeof e=="string"&&i.push(...jn(e)),[...new Set(i)]}function ct(t,e){if(e?.trim())return{intent:"write",targets:[e.trim()],toolName:null};if(!t.trim())return{intent:"unknown",targets:[],toolName:null};let i;try{i=JSON.parse(t)}catch{let o=jn(t);return o.length>0?{intent:"write",targets:[...new Set(o)],toolName:"apply_patch"}:{intent:"unknown",targets:[],toolName:null}}if(!Hn(i))return{intent:"unknown",targets:[],toolName:null};let n=uu(i),r=pu(i,hu(i)),a=fu(i);return n&&su.has(Xa(n))?{intent:r.length>0?"write":"unknown",targets:r,toolName:n,...a?{cwd:a}:{}}:n&&cu.has(Xa(n))?{intent:"non-write",targets:[],toolName:n,...a?{cwd:a}:{}}:n?{intent:"unknown",targets:r,toolName:n,...a?{cwd:a}:{}}:{intent:r.length>0?"write":"unknown",targets:r,toolName:null,...a?{cwd:a}:{}}}function to(){let t=process.env.FILE_PATH;if(t?.trim()||process.stdin.isTTY)return ct("",t);try{return ct(ou(0,"utf8"),t)}catch{return ct("",t)}}var Fa=On(Xi(),1);import{promises as Ev}from"fs";import Me from"path";import{createHash as Jp}from"node:crypto";import{promises as G}from"node:fs";import B from"node:path";import{TextDecoder as Gp}from"node:util";var Vp=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),Wp=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function zp(t){return t.toLowerCase().startsWith(".env")}function Mt(t){let i=t.replaceAll("\\","/").split("/").filter(Boolean).map(n=>n.toLowerCase());return i.some(n=>zp(n))?"environment-file":i.some(n=>Wp.has(n))?"credential-config":i.includes(".git")?"git-metadata":i.some(n=>Vp.has(n))?"dependency-or-cache":i.join("/")===".comet/config.yaml"?"comet-config":i.join("/")===".comet/current-change.json"?"comet-selection":null}function ye(t){return t!==0&&t!==0n&&t!=="0"}function J(t,e){return ye(t.dev)&&ye(e.dev)&&ye(t.ino)&&ye(e.ino)}function I(t,e){let i=ye(t.dev)&&ye(e.dev);if(i&&t.dev!==e.dev)return!1;let n=ye(t.ino)&&ye(e.ino);return n&&t.ino!==e.ino?!1:i&&n?!0:t.birthtime===e.birthtime}var Zi=1024*1024;function va(t,e){let i=B.relative(t,e);return i===""||!B.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${B.sep}`)}function Kp(t){let e=B.posix.normalize(t);if(t.length===0||t!==t.trim()||t.includes("\\")||Array.from(t).some(r=>{let a=r.codePointAt(0)??0;return a<=31||a===127})||B.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes("..")||e!==t||e==="."||t.endsWith("/"))throw new Error(`Native artifact ref must be normalized and relative: ${t}`);let i=t.toLowerCase(),n=Mt(t);if(n||i==="runtime"||i.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${n??"native-runtime"}): ${t}`);return t}function Up(t){if(!Number.isSafeInteger(t)||t<1)throw new Error("Native artifact byte limit must be a positive integer");return t}function Yp(t,e){return I({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function Qi(t,e){let i={...t,birthtime:t.birthtimeMs},n={...e,birthtime:e.birthtimeMs};return J(i,n)?I(i,n):I(i,n)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.size===e.size}async function zc(t){let e=await G.lstat(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${t}`);return{path:t,realPath:await G.realpath(t),dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}async function Xp(t,e){let i=B.resolve(t),n=B.resolve(e);if(!va(i,n))throw new Error("Native artifact path is outside its root");let r=[await zc(i)],a=i;for(let o of B.relative(i,n).split(B.sep).filter(Boolean)){a=B.join(a,o);let s=await zc(a);if(!va(r[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);r.push(s)}return r}async function Jc(t){for(let e of t){let i=await G.lstat(e.path);if(!i.isDirectory()||i.isSymbolicLink()||!Yp(e,i)||await G.realpath(e.path)!==e.realPath)throw new Error(`Native artifact parent changed while reading: ${e.path}`)}}async function Ne(t){let e=Kp(t.ref),i=Up(t.maxBytes??Zi),n=B.resolve(t.root,...e.split("/")),r=await Xp(t.root,B.dirname(n));await t.hooks?.afterParentChainCaptured?.();let a=await G.lstat(n);if(!a.isFile()||a.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${e}`);if(a.size>i)throw new Error(`Native artifact exceeds ${i} bytes: ${e}`);let o=await G.realpath(n);if(!va(r[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${e}`);let s=await G.open(n,"r");try{let[c,l,d]=await Promise.all([s.stat(),G.lstat(n),G.realpath(n)]);if(await Jc(r),!c.isFile()||!l.isFile()||l.isSymbolicLink()||d!==o||!Qi(a,c)||!Qi(c,l))throw new Error(`Native artifact changed while opening: ${e}`);await t.hooks?.afterOpen?.();let u=[],f=0,m=Buffer.allocUnsafe(Math.min(64*1024,i+1));for(;;){let k=i+1-f,S=await s.read(m,0,Math.min(m.length,k),null);if(S.bytesRead===0)break;if(f+=S.bytesRead,f>i)throw new Error(`Native artifact exceeds ${i} bytes: ${e}`);u.push(Buffer.from(m.subarray(0,S.bytesRead)))}await t.hooks?.beforeFinalCheck?.();let[g,h,p]=await Promise.all([s.stat(),G.lstat(n),G.realpath(n)]);if(await Jc(r),!h.isFile()||h.isSymbolicLink()||p!==o||!Qi(c,g)||!Qi(c,h))throw new Error(`Native artifact changed while reading: ${e}`);let y=Buffer.concat(u,f),N;try{N=new Gp("utf-8",{fatal:!0}).decode(y)}catch(k){throw new Error(`Native artifact is not valid UTF-8: ${e}`,{cause:k})}return{ref:e,size:f,hash:Jp("sha256").update(y).digest("hex"),text:N}}finally{await s.close()}}var wa=On(Xi(),1);import en from"path";var Dt=64*1024,tn=1024,nn=64,Kc=5,Qp=[".agents/skills/**",".amazonq/skills/**",".augment/skills/**",".bob/skills/**",".claude/skills/**",".cline/skills/**",".codebuddy/skills/**",".continue/skills/**",".cospec/skills/**",".crush/skills/**",".cursor/skills/**",".factory/skills/**",".forge/skills/**",".gemini/skills/**",".github/skills/**",".iflow/skills/**",".junie/skills/**",".kilocode/skills/**",".kimi-code/skills/**",".kiro/skills/**",".lingma/skills/**",".mimocode/skills/**",".opencode/skills/**",".pi/skills/**",".qoder/skills/**",".qwen/skills/**",".roo/skills/**",".trae-cn/skills/**",".trae/skills/**",".windsurf/skills/**",".zcode/skills/**"],te={include:["**/*"],exclude:[...Qp],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4};function Zp(t,e){if(typeof t!="string")throw new Error(`${e} must be a string`);let i=t.trim();if(i.length===0||en.posix.isAbsolute(i)||en.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${e} must be a project-relative path`);if(i===".")return[];let n=i.replaceAll("\\","/").split("/");if(n.some(r=>r===".."))throw new Error(`${e} must stay inside the project root`);if(n.some(r=>r===""||r==="."))throw new Error(`${e} must not contain empty or dot path segments`);return n}function et(t){let e=Zp(t,"native.artifact_root");return e.length===0?".":e.join("/")}function Uc(t,e="docs"){let i=t??e;if(i!=="legacy"&&i!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return i}function ya(t,e,i=!1){if(typeof t!="string")throw new Error(`${e} must be a string`);let n=t.trim().replaceAll("\\","/");if(n.length===0||en.posix.isAbsolute(n)||en.win32.isAbsolute(n)||/^(?:~|[\\/])/u.test(n))throw new Error(`${e} must be relative to its declared path base`);let r=n.split("/");if(r.some(a=>a===".."))throw new Error(`${e} must stay inside its declared path base`);if(r.some(a=>a===""||a==="."))throw new Error(`${e} must not contain empty or dot path segments`);if(!i&&/[*?]/u.test(n))throw new Error(`${e} cannot contain wildcards`);return r.join("/")}function Bt(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function Yc(t,e,i){let n=t??e;if(n!=="en"&&n!=="zh-CN")throw new Error(`${i} must be en or zh-CN`);return n}function rn(t,e){if(typeof t!="string"||t.length===0||t.includes("\\")||t.includes("\0")||t.startsWith("/")||t.split("/").includes(".."))throw new Error(`${e} contains an unsafe pattern`);if(t.length>tn)throw new Error(`${e} exceeds ${tn} characters`);let i=0;for(let n=0;nnn)throw new Error(`${e} contains more than ${nn} wildcard tokens`);return t}function Gc(t,e,i){if(t===void 0)return[...i];if(!Array.isArray(t))throw new Error(`${e} contains an unsafe pattern`);return[...new Set(t.map(n=>rn(n,e)))].sort((n,r)=>n.localeCompare(r,"en"))}function ga(t,e,i){let n=t??e;if(!Number.isSafeInteger(n)||n<1)throw new Error(`${i} must be a positive integer`);return n}function em(t){if(t===void 0)return{...te,include:[...te.include],exclude:[...te.exclude]};let e=Bt(t,"native.snapshot");return{include:Gc(e.include,"native.snapshot.include",te.include),exclude:Gc(e.exclude,"native.snapshot.exclude",te.exclude),max_files:ga(e.max_files,te.max_files,"native.snapshot.max_files"),max_total_bytes:ga(e.max_total_bytes,te.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:ga(e.max_duration_ms,te.max_duration_ms,"native.snapshot.max_duration_ms")}}function tm(t){if(t===void 0)return;let e=Bt(t,"native.pending_root_move"),i=e.id,n=e.from_artifact_root,r=e.to_artifact_root,a=e.stage;if(typeof i!="string"||!/^[a-f0-9-]{8,}$/u.test(i))throw new Error("native.pending_root_move.id is invalid");if(typeof n!="string"||typeof r!="string")throw new Error("native.pending_root_move roots must be strings");if(a!=="copying"&&a!=="ready"&&a!=="switched")throw new Error("native.pending_root_move.stage is invalid");let o;if(e.cleanup!==void 0){let s=Bt(e.cleanup,"native.pending_root_move.cleanup"),c=s.kind,l=s.state,d=s.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof d!="string"||!/^[a-f0-9]{64}$/u.test(d))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:d}}return{id:i,fromArtifactRoot:et(n),toArtifactRoot:et(r),stage:a,...o?{cleanup:o}:{}}}function im(t,e={}){let i=Bt(t,"native"),n=i.artifact_root??(e.allowMissingArtifactRoot?"docs":void 0);if(typeof n!="string")throw new Error("native.artifact_root must be a string");let r=i.clarification_mode??"sequential";if(r!=="sequential"&&r!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let a=i.archive_confirmation??"automatic";if(a!=="automatic"&&a!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=i.max_verify_failures??Kc;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=tm(i.pending_root_move);return{artifact_root:et(n),language:Yc(i.language,"en","native.language"),clarification_mode:r,archive_confirmation:a,max_verify_failures:o,snapshot:em(i.snapshot),...s?{pending_root_move:s}:{}}}function nm(t){let e=Bt(t,"classic"),i=e.context_compression??"off";if(i!=="off"&&i!=="beta")throw new Error("classic.context_compression must be off or beta");let n=e.review_mode??"standard";if(n!=="off"&&n!=="standard"&&n!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let r=e.auto_transition??!0;if(typeof r!="boolean")throw new Error("classic.auto_transition must be true or false");return{artifact_layout:Uc(e.artifact_layout),language:Yc(e.language,"zh-CN","classic.language"),context_compression:i,review_mode:n,auto_transition:r}}function rm(t){let e=t??!0;if(typeof e!="boolean")throw new Error("ambient_resume must be true or false");return e}function am(t,e,i,n,r){let a=t.schema!==void 0;if(!(a||t.default_workflow!==void 0||t.workflows!==void 0||!r.allowPartialProject&&t.native!==void 0)||r.allowPartialProject&&!a)return null;if(t.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(t.default_workflow!=="native"&&t.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let s=t.workflows??[t.default_workflow];if(!Array.isArray(s)||s.length===0||s.some(l=>l!=="native"&&l!=="classic"))throw new Error("workflows must contain native and/or classic");let c=[...new Set(s)];if(!c.includes(t.default_workflow))throw new Error("workflows must include default_workflow");if(c.includes("native")&&!e)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:t.default_workflow,workflows:c,ambient_resume:n,...e?{native:e}:{},...i?{classic:i}:{}}}function qt(t,e={}){let i=(0,wa.parseDocument)(t,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${i.errors[0].message}`);let n=i.toJS();if(n==null)return{value:{},config:null,ambient_resume:!0};if(typeof n!="object"||Array.isArray(n))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let r=n,a=rm(r.ambient_resume),o=r.native===void 0?void 0:im(r.native,{allowMissingArtifactRoot:e.allowMissingNativeFields}),s=r.classic===void 0?void 0:nm(r.classic),c=am(r,o,s,a,{allowPartialProject:e.allowPartialProject??!1});return{value:r,config:c,ambient_resume:a,...o?{native:o}:{},...s?{classic:s}:{}}}import{createHash as sm}from"crypto";import{promises as sn}from"fs";import be from"path";import{constants as an,promises as Ie}from"fs";var ie=class extends Error{reason;constructor(e,i,n){super(i,n),this.name="RaceSafeReadError",this.reason=e}};function Na(t){return"birthtimeNs"in t&&typeof t.birthtimeNs=="bigint"?t.birthtimeNs:t.birthtimeMs}function Xc(t){return"ctimeNs"in t&&typeof t.ctimeNs=="bigint"?t.ctimeNs:t.ctimeMs}function Vt(t){return{dev:t.dev,ino:t.ino,birthtime:Na(t)}}function on(t,e){let i=Vt(t),n=Vt(e);return J(i,n)?I(i,n):I(i,n)&&Na(t)===Na(e)&&Xc(t)===Xc(e)&&t.size===e.size}async function tt(t,e,i={}){if(!Number.isSafeInteger(e)||e<1)throw new Error("race-safe read byte limit must be a positive integer");let n=i.label??"file",r=i.bigint===!0,a=await Ie.lstat(t,{bigint:r});if(!a.isFile()||a.isSymbolicLink())throw new ie("not-regular-file",`${n} must be a regular file`);if(BigInt(a.size)>BigInt(e))throw new ie("too-large",`${n} exceeds ${e} bytes`);let o=await Ie.realpath(t);await i.verify?.("pre-open",{realPath:o,identity:Vt(a)});let s=process.platform==="win32"?an.O_RDONLY:an.O_RDONLY|an.O_NOFOLLOW|an.O_NONBLOCK,c;try{c=await Ie.open(t,s)}catch(l){throw l.code==="ELOOP"?new ie("not-regular-file",`${n} must be a regular file`,{cause:l}):l}try{let[l,d,u]=await Promise.all([c.stat({bigint:r}),Ie.lstat(t,{bigint:r}),Ie.realpath(t)]);if(!l.isFile()||!d.isFile()||d.isSymbolicLink()||u!==o||!on(a,l)||!on(a,d))throw new ie("changed",`${n} changed while opening`);await i.verify?.("post-open",{realPath:u,identity:Vt(l)}),await i.hooks?.afterOpen?.();let f=[],m=0,g=Buffer.allocUnsafe(Math.min(64*1024,e+1));for(;;){let N=e+1-m,{bytesRead:k}=await c.read(g,0,Math.min(g.length,N),null);if(k===0)break;if(m+=k,m>e)throw new ie("too-large",`${n} exceeds ${e} bytes`);f.push(Buffer.from(g.subarray(0,k)))}await i.hooks?.beforeFinalCheck?.();let[h,p,y]=await Promise.all([c.stat({bigint:r}),Ie.lstat(t,{bigint:r}),Ie.realpath(t)]);if(!p.isFile()||p.isSymbolicLink()||y!==o||!on(a,h)||!on(a,p))throw new ie("changed",`${n} changed while reading`);return await i.verify?.("post-read",{realPath:y,identity:Vt(h)}),{bytes:Buffer.concat(f,m),stat:h,realPath:y}}finally{await c.close()}}function om(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}function ba(t,e){let i=be.relative(t,e);return i===""||!be.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${be.sep}`)}async function Qc(t,e){let i=be.resolve(t),n=await sn.lstat(i);if(!n.isDirectory()||n.isSymbolicLink())throw new Error(`${e} project root must be a real directory`);return sn.realpath(i)}async function Zc(t,e,i,n){let r=t;for(let a=0;a{if(!ba(a,s.realPath))throw new Error(`${n.label} resolves outside the project root`);await Zc(r.projectRoot,a,r.relative.split("/"),{label:n.label,expected:"file"})}})}var zt=".comet/config.yaml";function cm(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function ka(t,e={}){return(await cn(t,e)).document}async function lm(t){try{return(await _e(t,zt,Dt,{label:zt})).bytes}catch(e){if(cm(e))return null;throw e}}function um(t){return t?{exists:!0,sha256:sm("sha256").update(t).digest("hex")}:{exists:!1,sha256:null}}async function cn(t,e={}){let i=await lm(t);return{document:i?qt(i.toString("utf8"),e):null,identity:um(i)}}var Hy=16*1024;import{promises as it}from"fs";import A from"path";import mm from"os";var Ra=".comet/config.yaml";async function Ca(t){try{return await it.lstat(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function vm(t){try{let e=await it.readFile(t,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(e)}catch(e){if(e.code==="ENOENT")return!1;throw e}}function Jt(t,e){let i=A.relative(t,e);return i===""||!A.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${A.sep}`)}async function Gt(t){let e=[],i=t;for(;!await Ca(i);){let r=A.dirname(i);if(r===i)break;e.push(A.basename(i)),i=r}let n=await it.realpath(i);return A.resolve(n,...e.reverse())}async function tl(t){try{return(await it.lstat(t)).isSymbolicLink()}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function Pa(t){let e=A.resolve(t);try{(await it.stat(e)).isDirectory()||(e=A.dirname(e))}catch(r){if(r.code!=="ENOENT")throw r}let i=e,n=A.resolve(mm.homedir());for(;;){if(!(e===n&&i!==n)){let o=A.join(e,...Ra.split("/")),s=e===i||await vm(o);if(await Ca(o)&&s)return e}if(await Ca(A.join(e,".git")))return e;let a=A.dirname(e);if(a===e)return i;e=a}}function Aa(t){return et(t)}async function gm(t,e){let i=Aa(e),n=A.resolve(t,...i.split("/")),r=await it.realpath(t),a=await Gt(n);if(!Jt(r,a))throw new Error("native.artifact_root resolves outside the project root");return n}async function un(t,e){let i=Aa(e),n=await gm(t,i),r=A.join(n,"comet");if(await tl(r))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([Gt(n),Gt(r)]);if(!Jt(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");return{projectRoot:A.resolve(t),configFile:A.join(t,...Ra.split("/")),artifactRoot:n,artifactRootRef:i,nativeRoot:r,specsDir:A.join(r,"specs"),changesDir:A.join(r,"changes"),archiveDir:A.join(r,"archive"),runtimeDir:A.join(r,"runtime"),locksDir:A.join(r,"runtime","locks"),transactionsDir:A.join(r,"runtime","transactions")}}function ne(t,e){return Jt(A.resolve(t),A.resolve(e))}async function H(t,e){let i=A.resolve(t),n=A.resolve(e);if(!Jt(i,n))throw new Error(`Path is outside the Native root: ${e}`);if(await tl(i))throw new Error(`Native root must not be a symbolic link: ${t}`);let[r,a]=await Promise.all([Gt(i),Gt(n)]);if(!Jt(r,a))throw new Error(`Path resolves outside the Native root: ${e}`);return n}var fn=rn;async function nt(t){let e=(await ka(t))?.config??null;return e?.native?e:null}import{AsyncLocalStorage as ym}from"async_hooks";var aN=16*1024;var oN=new ym;import{TextDecoder as Am}from"util";import{createHash as Nm}from"node:crypto";import{constants as dn,promises as K}from"node:fs";import U from"node:path";import{TextDecoder as bm}from"node:util";function pn(t,e){let i=U.relative(t,e);return i===""||!U.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${U.sep}`)}function km(t){if(!Number.isSafeInteger(t)||t<1)throw new Error("Native protected file byte limit must be a positive integer");return t}function Sm(t,e){return I({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function Em(t){return{dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs,ctimeMs:t.ctimeMs,mtimeMs:t.mtimeMs,size:t.size}}function hn(t,e){return I({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.mtimeMs===e.mtimeMs&&t.size===e.size}async function Ta(t,e){let i=await K.lstat(t);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${e} parent must be a real directory: ${t}`);return{path:t,realPath:await K.realpath(t),dev:i.dev,ino:i.ino,birthtimeMs:i.birthtimeMs}}async function Cm(t,e,i){let n=U.resolve(t),r=U.resolve(e);if(!pn(n,r))throw new Error(`${i} is outside its managed root`);let a=[await Ta(n,i)],o=n;for(let s of U.relative(n,r).split(U.sep).filter(Boolean)){await Oe(a,i),o=U.join(o,s);let c=await Ta(o,i);if(!pn(a[0].realPath,c.realPath))throw new Error(`${i} parent resolves outside its managed root: ${o}`);a.push(c)}return await Oe(a,i),a}async function Oe(t,e){for(let i of t){let n=await K.lstat(i.path);if(!n.isDirectory()||n.isSymbolicLink()||!Sm(i,n)||await K.realpath(i.path)!==i.realPath)throw new Error(`${e} parent changed during I/O: ${i.path}`)}}async function Rm(t,e,i){let n=[],r=0,a=Buffer.allocUnsafe(Math.min(64*1024,e+1));for(;;){let o=e+1-r,{bytesRead:s}=await t.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(r+=s,r>e)throw new Error(`${i} exceeds ${e} bytes`);n.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(n,r)}async function rt(t){let e=km(t.maxBytes),i=U.resolve(t.file),n=await Cm(t.root,U.dirname(i),t.label),r=await Promise.all((t.forbiddenRoots??[]).map(d=>Ta(U.resolve(d),t.label)));await t.hooks?.afterParentChainCaptured?.(),await Oe(n,t.label);let a=await K.lstat(i);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${t.label} must be a regular file`);if(a.size>e)throw new Error(`${t.label} exceeds ${e} bytes`);let o=Em(a),s=await K.realpath(i);if(!pn(n[0].realPath,s))throw new Error(`${t.label} resolves outside its managed root`);if(r.some(d=>pn(d.realPath,s)))throw new Error(`${t.label} resolves inside an excluded root`);let c=process.platform==="win32"?dn.O_RDONLY:dn.O_RDONLY|dn.O_NOFOLLOW|dn.O_NONBLOCK,l=await K.open(i,c);try{let d=await l.stat();await t.hooks?.afterOpen?.();let[u,f]=await Promise.all([K.lstat(i),K.realpath(i)]);if(await Oe(n,t.label),await Oe(r,t.label),!d.isFile()||!u.isFile()||u.isSymbolicLink()||f!==s||!hn(o,d)||!hn(o,u))throw new Error(`${t.label} changed while opening`);await t.hooks?.beforeRead?.();let m=await Rm(l,e,t.label);await t.hooks?.beforeFinalCheck?.();let[g,h,p]=await Promise.all([l.stat(),K.lstat(i),K.realpath(i)]);if(await Oe(n,t.label),await Oe(r,t.label),!h.isFile()||h.isSymbolicLink()||p!==s||!hn(o,g)||!hn(o,h))throw new Error(`${t.label} changed while reading`);return{bytes:m,hash:Nm("sha256").update(m).digest("hex"),size:m.length}}finally{await l.close()}}async function nl(t){let e=await rt(t),i;try{i=new bm("utf-8",{fatal:!0}).decode(e.bytes)}catch(n){throw new Error(`${t.label} is not valid UTF-8`,{cause:n})}return{...e,text:i}}var kN=256*1024,SN=1024*1024,EN=16*1024;var CN=64*1024*1024;var RN=new Am("utf-8",{fatal:!0});import vn from"path";import{createHash as Tm}from"crypto";function D(t){return Tm("sha256").update(t).digest("hex")}var WN={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},_m=1e3,Om=8*1024*1024,jm=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Hm=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),$m=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),Lm=new Set(["schema","include","exclude","hash"]),Fm=new Set(["provider","gitSelection","physicalSelection","projection"]),Mm=new Set(["provider","selection"]),Bm=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),Dm=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),qm=new Set(["schema","status","before","after"]),Vm=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),Wm=new Set(["path","hash","size","type","gitObjectId"]),zm=new Set(["path","size","type","reason"]),Jm=new Set(["ref","hash","count"]),Gm=new Set(["change-created","legacy-migration","explicit"]),Km=new Set(["file","directory","other"]),Um=new Set(["file-size","file-count","total-size","manifest-size","changed-during-read","unreadable","gitlink-unavailable","gitlink-dirty","gitlink-changed","legacy-gitlink-boundary","git-enumeration-limit","git-selection-changed","physical-enumeration-limit","physical-selection-changed"]),gn=/^[a-f0-9]{64}$/u,Ym=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;var zN=64*1024,JN=64*1024;var GN={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},KN={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};function mn(t,e){return t.hash===e.hash&&t.recordCount===e.recordCount&&t.storedRecordCount===e.storedRecordCount&&t.stdoutBytes===e.stdoutBytes&&t.overflow===e.overflow}var UN=(1n<<256n)-1n;function Xm(t,e){return t.hash===e.hash&&t.visitedNodeCount===e.visitedNodeCount&&t.recordCount===e.recordCount&&t.storedRecordCount===e.storedRecordCount&&t.encodedBytes===e.encodedBytes&&t.overflow===e.overflow&&t.unstable===e.unstable}function Qm(t){return Buffer.byteLength(JSON.stringify(t,null,2)+` `)}function Zm(t,e){return D(`comet.native.snapshot-policy.v1 -${JSON.stringify({include:t,exclude:e,hash:"sha256"})}`)}function Ia(t,e,i){let n=new Set(e),r=[...e];for(;r.length>0;){if(i&&!i())return null;let a=r.pop(),o=t[a];o&&(o.kind==="star"||o.kind==="globstar"||o.kind==="globstar-slash")&&!n.has(a+1)&&(n.add(a+1),r.push(a+1))}return n}function ev(t){let e=0;return()=>e>0?(e-=1,!0):t()?(e=63,!0):!1}function cl(t){let e=fn(t,"Native snapshot pattern"),i=[];for(let n=0;n{let a=r?ev(r):void 0;if(a&&!a())return!1;let o=Ia(i,new Set([0]),a);if(o===null)return!1;for(let s of n){if(a&&!a())return!1;let c=new Set;for(let l of o){if(a&&!a())return!1;let d=i[l];d&&(d.kind==="literal"&&d.value===s||d.kind==="question"&&s!=="/"?c.add(l+1):d.kind==="star"&&s!=="/"||d.kind==="globstar"?c.add(l):d.kind==="globstar-slash"&&(c.add(l),s==="/"&&c.add(l+1)))}if(o=Ia(i,c,a),o===null||o.size===0)return!1}return Ia(i,o,a)?.has(i.length)??!1}}function tv(t){if(t===void 0)return;let e=[...new Set(t.include.map(r=>fn(r,"include")))].sort((r,a)=>r.localeCompare(a,"en")),i=[...new Set(t.exclude.map(r=>fn(r,"exclude")))].sort((r,a)=>r.localeCompare(a,"en"));if(e.length===0)throw new Error("Native snapshot policy include must not be empty");let n=Zm(e,i);if("hash"in t&&t.hash!==n)throw new Error("Native snapshot policy hash is invalid");return{manifest:{schema:"comet.native.snapshot-policy.v1",include:e,exclude:i,hash:n},includeMatchers:e.map(cl),excludeMatchers:i.map(cl),excludedDirectoryPrefixes:i.flatMap(r=>{if(!r.endsWith("/**"))return[];let a=r.slice(0,-3);return/[*?]/u.test(a)?[]:[a]}).sort((r,a)=>r.localeCompare(a,"en"))}}function q(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function V(t,e,i){let n=Object.keys(t).find(r=>!e.has(r));if(n)throw new Error(`${i} contains unknown field: ${n}`)}function ot(t,e){if(!Number.isSafeInteger(t)||t<1)throw new Error(`${e} must be a positive integer`);return t}function re(t,e){if(!Number.isSafeInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return t}function fl(t,e){if(typeof t!="string"||t.length===0||t.includes("\\")||t.includes("\0"))throw new Error(`${e} must be a normalized project-relative path`);let i=vn.posix.normalize(t);if(i!==t||vn.posix.isAbsolute(t)||i===".."||i.startsWith("../"))throw new Error(`${e} must stay inside the project root`);return t}function iv(t,e){let i=q(t,`Native snapshot entry ${e}`);V(i,Wm,`Native snapshot entry ${e}`);let n=fl(i.path,`Native snapshot entry ${e} path`);if(typeof i.hash!="string"||!gn.test(i.hash))throw new Error(`Native snapshot entry ${e} hash is invalid`);if(i.type!=="file")throw new Error(`Native snapshot entry ${e} type is invalid`);let r={path:n,hash:i.hash,size:re(i.size,`Native snapshot entry ${e} size`),type:"file"};if(i.gitObjectId!==void 0){if(typeof i.gitObjectId!="string"||!Ym.test(i.gitObjectId))throw new Error(`Native snapshot entry ${e} gitObjectId is invalid`);r.gitObjectId=i.gitObjectId}return r}function nv(t,e){let i=q(t,`Native snapshot omission ${e}`);if(V(i,zm,`Native snapshot omission ${e}`),!Km.has(i.type))throw new Error(`Native snapshot omission ${e} type is invalid`);if(!Um.has(i.reason))throw new Error(`Native snapshot omission ${e} reason is invalid`);return{path:fl(i.path,`Native snapshot omission ${e} path`),size:i.size===null?null:re(i.size,`Native snapshot omission ${e} size`),type:i.type,reason:i.reason}}function rv(t){let e=q(t,"Native snapshot omission overflow");if(V(e,Jm,"Native snapshot omission overflow"),typeof e.hash!="string"||!gn.test(e.hash))throw new Error("Native snapshot omission overflow hash is invalid");let i=`native-snapshot://omitted-overflow/${e.hash}`;if(e.ref!==i)throw new Error("Native snapshot omission overflow ref is invalid");return{ref:i,hash:e.hash,count:ot(e.count,"Native snapshot omission overflow count")}}function at(t,e){let i=q(t,e);if(V(i,Dm,e),typeof i.hash!="string"||!gn.test(i.hash))throw new Error(`${e} hash is invalid`);if(typeof i.overflow!="boolean")throw new Error(`${e} overflow flag is invalid`);let n=re(i.recordCount,`${e} recordCount`),r=re(i.storedRecordCount,`${e} storedRecordCount`),a=re(i.stdoutBytes,`${e} stdoutBytes`);if(r>n||!i.overflow&&r!==n)throw new Error(`${e} stored record count is inconsistent`);return{hash:i.hash,recordCount:n,storedRecordCount:r,stdoutBytes:a,overflow:i.overflow}}function ll(t){let e=q(t,"Native Git selection evidence");if(V(e,Bm,"Native Git selection evidence"),e.schema!=="comet.native.git-selection.v1")throw new Error("Native Git selection evidence schema is invalid");if(e.status!=="overflow"&&e.status!=="changed"&&e.status!=="overflow-and-changed")throw new Error("Native Git selection evidence status is invalid");let i=at(e.stageBefore,"Native Git selection stageBefore"),n=at(e.combined,"Native Git selection combined"),r=at(e.stageAfter,"Native Git selection stageAfter"),a=at(e.finalStageBefore,"Native Git selection finalStageBefore"),o=at(e.finalCombined,"Native Git selection finalCombined"),s=at(e.finalStageAfter,"Native Git selection finalStageAfter"),c=[i,n,r,a,o,s].some(u=>u.overflow),l=!mn(i,r)||!mn(r,a)||!mn(n,o)||!mn(a,s),d=c&&l?"overflow-and-changed":c?"overflow":"changed";if(!c&&!l)throw new Error("Native Git selection evidence must describe an exceptional selection");if(e.status!==d)throw new Error("Native Git selection evidence status is inconsistent");return{schema:"comet.native.git-selection.v1",status:d,stageBefore:i,combined:n,stageAfter:r,finalStageBefore:a,finalCombined:o,finalStageAfter:s}}function ul(t,e){let i=q(t,e);if(V(i,Vm,e),typeof i.hash!="string"||!gn.test(i.hash))throw new Error(`${e} hash is invalid`);if(typeof i.overflow!="boolean"||typeof i.unstable!="boolean")throw new Error(`${e} flags are invalid`);let n=re(i.visitedNodeCount,`${e} visitedNodeCount`),r=re(i.recordCount,`${e} recordCount`),a=re(i.storedRecordCount,`${e} storedRecordCount`),o=re(i.encodedBytes,`${e} encodedBytes`);if(a>r||!i.overflow&&a!==r)throw new Error(`${e} stored record count is inconsistent`);return{hash:i.hash,visitedNodeCount:n,recordCount:r,storedRecordCount:a,encodedBytes:o,overflow:i.overflow,unstable:i.unstable}}function av(t){let e=q(t,"Native physical selection evidence");if(V(e,qm,"Native physical selection evidence"),e.schema!=="comet.native.physical-selection.v1")throw new Error("Native physical selection evidence schema is invalid");if(e.status!=="overflow"&&e.status!=="changed"&&e.status!=="overflow-and-changed")throw new Error("Native physical selection evidence status is invalid");let i=ul(e.before,"Native physical selection before"),n=ul(e.after,"Native physical selection after"),r=i.overflow||n.overflow,a=i.unstable||n.unstable||!Xm(i,n);if(!r&&!a)throw new Error("Native physical selection evidence must describe an exceptional selection");let o=r&&a?"overflow-and-changed":r?"overflow":"changed";if(e.status!==o)throw new Error("Native physical selection evidence status is inconsistent");return{schema:"comet.native.physical-selection.v1",status:o,before:i,after:n}}function dl(t){let e=q(t,"Native content snapshot manifest");if(V(e,Hm,"Native content snapshot manifest"),e.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!Gm.has(e.origin))throw new Error("Native content snapshot origin is invalid");let i;if(e.capture!==void 0){let v=q(e.capture,"Native content snapshot capture");if(V(v,Fm,"Native content snapshot capture"),v.provider!=="git"&&v.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let R=v.gitSelection===void 0?void 0:ll(v.gitSelection),b=v.physicalSelection===void 0?void 0:av(v.physicalSelection),x=null;if(v.projection!==void 0){let F=q(v.projection,"Native content snapshot projection");if(V(F,Mm,"Native content snapshot projection"),F.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");x={provider:"git",...F.selection===void 0?{}:{selection:ll(F.selection)}}}if(v.provider==="git"){if(b||x)throw new Error("Native Git capture cannot include physical or projection evidence");i={provider:"git",...R?{gitSelection:R}:{}}}else{if(R)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(b&&x)throw new Error("Native physical-tree capture cannot combine selection and projection");i=x?{provider:"physical-tree",projection:x}:{provider:"physical-tree",...b?{physicalSelection:b}:{}}}}if(typeof e.createdAt!="string"||Number.isNaN(Date.parse(e.createdAt)))throw new Error("Native content snapshot timestamp is invalid");if(typeof e.complete!="boolean")throw new Error("Native content snapshot complete flag is invalid");let n=q(e.limits,"Native content snapshot limits");V(n,$m,"Native content snapshot limits");let r={maxFiles:ot(n.maxFiles,"Native snapshot maxFiles"),maxFileBytes:ot(n.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:ot(n.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:ot(n.maxManifestBytes,"Native snapshot maxManifestBytes"),...n.maxDurationMs===void 0?{}:{maxDurationMs:ot(n.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(e.policy!==void 0){let v=q(e.policy,"Native snapshot policy");if(V(v,Lm,"Native snapshot policy"),v.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(v.include)||!Array.isArray(v.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=tv({include:v.include,exclude:v.exclude,hash:v.hash,schema:"comet.native.snapshot-policy.v1"}).manifest}if(!Array.isArray(e.entries)||!Array.isArray(e.omitted))throw new Error("Native content snapshot entries and omissions must be arrays");let o=e.entries.map(iv),s=e.omitted.map(nv),c=re(e.omittedCount,"Native content snapshot omittedCount"),l=e.omissionOverflow===void 0?void 0:rv(e.omissionOverflow);if(o.length>r.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(v=>v.size>r.maxFileBytes)||o.reduce((v,R)=>v+R.size,0)>r.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(v=>v.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>_m||c0&&l?.count!==d)throw new Error("Native content snapshot omission overflow is inconsistent");if(e.complete!==(c===0))throw new Error("Native content snapshot completeness is inconsistent");let u=s.filter(v=>v.reason==="git-enumeration-limit"),f=s.filter(v=>v.reason==="git-selection-changed");for(let v of[...u,...f])if(v.path!=="."||v.size!==null||v.type!=="directory")throw new Error("Native Git selection omission must use the project-root sentinel");if(u.length>1||f.length>1)throw new Error("Native Git selection omissions must not be duplicated");let m=i?.provider==="git"?i.gitSelection:i?.projection?.selection,g=m?.status==="overflow"||m?.status==="overflow-and-changed",h=m?.status==="changed"||m?.status==="overflow-and-changed";if(g!==(u.length===1))throw new Error("Native Git enumeration omission and selection evidence are inconsistent");if(h!==(f.length===1))throw new Error("Native Git selection-change omission and selection evidence are inconsistent");let p=s.filter(v=>v.reason==="physical-enumeration-limit"),y=s.filter(v=>v.reason==="physical-selection-changed");for(let v of[...p,...y])if(v.path!=="."||v.size!==null||v.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(p.length>1||y.length>1)throw new Error("Native physical selection omissions must not be duplicated");let N=i?.physicalSelection,k=N?.status==="overflow"||N?.status==="overflow-and-changed",S=N?.status==="changed"||N?.status==="overflow-and-changed";if(k!==(p.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(S!==(y.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");let E={schema:"comet.native.content-snapshot.v1",origin:e.origin,...i?{capture:i}:{},createdAt:e.createdAt,complete:e.complete,limits:r,...a?{policy:a}:{},entries:o,omitted:s,omittedCount:c,...l?{omissionOverflow:l}:{}};if(Qm(E)>r.maxManifestBytes)throw new Error("Native content snapshot exceeds its manifest byte limit");return E}function ov(t,e){if(!jm.test(e))throw new Error(`Invalid Native change name: ${e}`);let i=vn.join(t.changesDir,e);if(!ne(t.changesDir,i))throw new Error("Native change path escaped");return vn.join(i,"runtime","baseline-manifest.json")}async function hl(t,e){let i=ov(t,e);await H(t.nativeRoot,i);try{let n=await nl({root:t.nativeRoot,file:i,maxBytes:Om,label:"Native baseline snapshot manifest"});return dl(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}var dv=On(Xi(),1);var Qb=256*1024;var fk={runStateBytes:256*1024,trajectoryBytes:8*1024*1024,trajectoryEvents:4096,trajectoryEventBytes:256*1024,checkpointBytes:256*1024,pendingActionBytes:256*1024,contextBytes:1024*1024,artifactsBytes:1024*1024};import{createHash as vv}from"node:crypto";import{promises as yn}from"node:fs";import ke from"node:path";import{execFileSync as pv}from"child_process";import wn from"path";function _a(t,e){return pv("git",["-C",t,...e],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function mv(t,e){let i=wn.normalize(t),n=wn.normalize(e);return process.platform==="win32"?i.toLowerCase()===n.toLowerCase():i===n}function ml(t){try{let e=wn.resolve(_a(t,["rev-parse","--show-toplevel"])),n=_a(t,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),r=n?wn.resolve(n.slice(9)):e,a=null;try{a=_a(t,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!mv(e,r),currentWorktreeRoot:e,primaryWorktreeRoot:r,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}var Kt=/^[a-f0-9]{64}$/u,gv=16*1024,Oa=process.platform;function yl(t,e){let i=ke.relative(t,e);return ke.isAbsolute(i)||i===".."||i.startsWith(`..${ke.sep}`)?null:i.replaceAll("\\","/")||"."}function Nl(t){return Array.from(t).some(e=>{let i=e.codePointAt(0)??0;return i<=31||i===127})}function bl(t,e){if(t.length===0||Nl(t)||t.includes("\\")||ke.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes(".."))throw new Error(`${e} must be a portable project-relative path`);let i=ke.posix.normalize(t);if(i!==t||i===".."||i.startsWith("../"))throw new Error(`${e} must be a normalized project-relative path`);return i}function ja(t,e){return vv("sha256").update(`${t} -${e}`).digest("hex")}async function vl(t,e){let i=await yn.realpath(e),n=await yn.lstat(i);if(!n.isDirectory()||n.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let r=Oa==="win32"?ke.normalize(i).toLowerCase():i;return ja(t,`${r} +${JSON.stringify({include:t,exclude:e,hash:"sha256"})}`)}function _a(t,e,i){let n=new Set(e),r=[...e];for(;r.length>0;){if(i&&!i())return null;let a=r.pop(),o=t[a];o&&(o.kind==="star"||o.kind==="globstar"||o.kind==="globstar-slash")&&!n.has(a+1)&&(n.add(a+1),r.push(a+1))}return n}function ev(t){let e=0;return()=>e>0?(e-=1,!0):t()?(e=63,!0):!1}function cl(t){let e=fn(t,"Native snapshot pattern"),i=[];for(let n=0;n{let a=r?ev(r):void 0;if(a&&!a())return!1;let o=_a(i,new Set([0]),a);if(o===null)return!1;for(let s of n){if(a&&!a())return!1;let c=new Set;for(let l of o){if(a&&!a())return!1;let d=i[l];d&&(d.kind==="literal"&&d.value===s||d.kind==="question"&&s!=="/"?c.add(l+1):d.kind==="star"&&s!=="/"||d.kind==="globstar"?c.add(l):d.kind==="globstar-slash"&&(c.add(l),s==="/"&&c.add(l+1)))}if(o=_a(i,c,a),o===null||o.size===0)return!1}return _a(i,o,a)?.has(i.length)??!1}}function tv(t){if(t===void 0)return;let e=[...new Set(t.include.map(r=>fn(r,"include")))].sort((r,a)=>r.localeCompare(a,"en")),i=[...new Set(t.exclude.map(r=>fn(r,"exclude")))].sort((r,a)=>r.localeCompare(a,"en"));if(e.length===0)throw new Error("Native snapshot policy include must not be empty");let n=Zm(e,i);if("hash"in t&&t.hash!==n)throw new Error("Native snapshot policy hash is invalid");return{manifest:{schema:"comet.native.snapshot-policy.v1",include:e,exclude:i,hash:n},includeMatchers:e.map(cl),excludeMatchers:i.map(cl),excludedDirectoryPrefixes:i.flatMap(r=>{if(!r.endsWith("/**"))return[];let a=r.slice(0,-3);return/[*?]/u.test(a)?[]:[a]}).sort((r,a)=>r.localeCompare(a,"en"))}}function q(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function V(t,e,i){let n=Object.keys(t).find(r=>!e.has(r));if(n)throw new Error(`${i} contains unknown field: ${n}`)}function ot(t,e){if(!Number.isSafeInteger(t)||t<1)throw new Error(`${e} must be a positive integer`);return t}function re(t,e){if(!Number.isSafeInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return t}function fl(t,e){if(typeof t!="string"||t.length===0||t.includes("\\")||t.includes("\0"))throw new Error(`${e} must be a normalized project-relative path`);let i=vn.posix.normalize(t);if(i!==t||vn.posix.isAbsolute(t)||i===".."||i.startsWith("../"))throw new Error(`${e} must stay inside the project root`);return t}function iv(t,e){let i=q(t,`Native snapshot entry ${e}`);V(i,Wm,`Native snapshot entry ${e}`);let n=fl(i.path,`Native snapshot entry ${e} path`);if(typeof i.hash!="string"||!gn.test(i.hash))throw new Error(`Native snapshot entry ${e} hash is invalid`);if(i.type!=="file")throw new Error(`Native snapshot entry ${e} type is invalid`);let r={path:n,hash:i.hash,size:re(i.size,`Native snapshot entry ${e} size`),type:"file"};if(i.gitObjectId!==void 0){if(typeof i.gitObjectId!="string"||!Ym.test(i.gitObjectId))throw new Error(`Native snapshot entry ${e} gitObjectId is invalid`);r.gitObjectId=i.gitObjectId}return r}function nv(t,e){let i=q(t,`Native snapshot omission ${e}`);if(V(i,zm,`Native snapshot omission ${e}`),!Km.has(i.type))throw new Error(`Native snapshot omission ${e} type is invalid`);if(!Um.has(i.reason))throw new Error(`Native snapshot omission ${e} reason is invalid`);return{path:fl(i.path,`Native snapshot omission ${e} path`),size:i.size===null?null:re(i.size,`Native snapshot omission ${e} size`),type:i.type,reason:i.reason}}function rv(t){let e=q(t,"Native snapshot omission overflow");if(V(e,Jm,"Native snapshot omission overflow"),typeof e.hash!="string"||!gn.test(e.hash))throw new Error("Native snapshot omission overflow hash is invalid");let i=`native-snapshot://omitted-overflow/${e.hash}`;if(e.ref!==i)throw new Error("Native snapshot omission overflow ref is invalid");return{ref:i,hash:e.hash,count:ot(e.count,"Native snapshot omission overflow count")}}function at(t,e){let i=q(t,e);if(V(i,Dm,e),typeof i.hash!="string"||!gn.test(i.hash))throw new Error(`${e} hash is invalid`);if(typeof i.overflow!="boolean")throw new Error(`${e} overflow flag is invalid`);let n=re(i.recordCount,`${e} recordCount`),r=re(i.storedRecordCount,`${e} storedRecordCount`),a=re(i.stdoutBytes,`${e} stdoutBytes`);if(r>n||!i.overflow&&r!==n)throw new Error(`${e} stored record count is inconsistent`);return{hash:i.hash,recordCount:n,storedRecordCount:r,stdoutBytes:a,overflow:i.overflow}}function ll(t){let e=q(t,"Native Git selection evidence");if(V(e,Bm,"Native Git selection evidence"),e.schema!=="comet.native.git-selection.v1")throw new Error("Native Git selection evidence schema is invalid");if(e.status!=="overflow"&&e.status!=="changed"&&e.status!=="overflow-and-changed")throw new Error("Native Git selection evidence status is invalid");let i=at(e.stageBefore,"Native Git selection stageBefore"),n=at(e.combined,"Native Git selection combined"),r=at(e.stageAfter,"Native Git selection stageAfter"),a=at(e.finalStageBefore,"Native Git selection finalStageBefore"),o=at(e.finalCombined,"Native Git selection finalCombined"),s=at(e.finalStageAfter,"Native Git selection finalStageAfter"),c=[i,n,r,a,o,s].some(u=>u.overflow),l=!mn(i,r)||!mn(r,a)||!mn(n,o)||!mn(a,s),d=c&&l?"overflow-and-changed":c?"overflow":"changed";if(!c&&!l)throw new Error("Native Git selection evidence must describe an exceptional selection");if(e.status!==d)throw new Error("Native Git selection evidence status is inconsistent");return{schema:"comet.native.git-selection.v1",status:d,stageBefore:i,combined:n,stageAfter:r,finalStageBefore:a,finalCombined:o,finalStageAfter:s}}function ul(t,e){let i=q(t,e);if(V(i,Vm,e),typeof i.hash!="string"||!gn.test(i.hash))throw new Error(`${e} hash is invalid`);if(typeof i.overflow!="boolean"||typeof i.unstable!="boolean")throw new Error(`${e} flags are invalid`);let n=re(i.visitedNodeCount,`${e} visitedNodeCount`),r=re(i.recordCount,`${e} recordCount`),a=re(i.storedRecordCount,`${e} storedRecordCount`),o=re(i.encodedBytes,`${e} encodedBytes`);if(a>r||!i.overflow&&a!==r)throw new Error(`${e} stored record count is inconsistent`);return{hash:i.hash,visitedNodeCount:n,recordCount:r,storedRecordCount:a,encodedBytes:o,overflow:i.overflow,unstable:i.unstable}}function av(t){let e=q(t,"Native physical selection evidence");if(V(e,qm,"Native physical selection evidence"),e.schema!=="comet.native.physical-selection.v1")throw new Error("Native physical selection evidence schema is invalid");if(e.status!=="overflow"&&e.status!=="changed"&&e.status!=="overflow-and-changed")throw new Error("Native physical selection evidence status is invalid");let i=ul(e.before,"Native physical selection before"),n=ul(e.after,"Native physical selection after"),r=i.overflow||n.overflow,a=i.unstable||n.unstable||!Xm(i,n);if(!r&&!a)throw new Error("Native physical selection evidence must describe an exceptional selection");let o=r&&a?"overflow-and-changed":r?"overflow":"changed";if(e.status!==o)throw new Error("Native physical selection evidence status is inconsistent");return{schema:"comet.native.physical-selection.v1",status:o,before:i,after:n}}function dl(t){let e=q(t,"Native content snapshot manifest");if(V(e,Hm,"Native content snapshot manifest"),e.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!Gm.has(e.origin))throw new Error("Native content snapshot origin is invalid");let i;if(e.capture!==void 0){let v=q(e.capture,"Native content snapshot capture");if(V(v,Fm,"Native content snapshot capture"),v.provider!=="git"&&v.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let R=v.gitSelection===void 0?void 0:ll(v.gitSelection),b=v.physicalSelection===void 0?void 0:av(v.physicalSelection),x=null;if(v.projection!==void 0){let F=q(v.projection,"Native content snapshot projection");if(V(F,Mm,"Native content snapshot projection"),F.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");x={provider:"git",...F.selection===void 0?{}:{selection:ll(F.selection)}}}if(v.provider==="git"){if(b||x)throw new Error("Native Git capture cannot include physical or projection evidence");i={provider:"git",...R?{gitSelection:R}:{}}}else{if(R)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(b&&x)throw new Error("Native physical-tree capture cannot combine selection and projection");i=x?{provider:"physical-tree",projection:x}:{provider:"physical-tree",...b?{physicalSelection:b}:{}}}}if(typeof e.createdAt!="string"||Number.isNaN(Date.parse(e.createdAt)))throw new Error("Native content snapshot timestamp is invalid");if(typeof e.complete!="boolean")throw new Error("Native content snapshot complete flag is invalid");let n=q(e.limits,"Native content snapshot limits");V(n,$m,"Native content snapshot limits");let r={maxFiles:ot(n.maxFiles,"Native snapshot maxFiles"),maxFileBytes:ot(n.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:ot(n.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:ot(n.maxManifestBytes,"Native snapshot maxManifestBytes"),...n.maxDurationMs===void 0?{}:{maxDurationMs:ot(n.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(e.policy!==void 0){let v=q(e.policy,"Native snapshot policy");if(V(v,Lm,"Native snapshot policy"),v.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(v.include)||!Array.isArray(v.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=tv({include:v.include,exclude:v.exclude,hash:v.hash,schema:"comet.native.snapshot-policy.v1"}).manifest}if(!Array.isArray(e.entries)||!Array.isArray(e.omitted))throw new Error("Native content snapshot entries and omissions must be arrays");let o=e.entries.map(iv),s=e.omitted.map(nv),c=re(e.omittedCount,"Native content snapshot omittedCount"),l=e.omissionOverflow===void 0?void 0:rv(e.omissionOverflow);if(o.length>r.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(v=>v.size>r.maxFileBytes)||o.reduce((v,R)=>v+R.size,0)>r.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(v=>v.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>_m||c0&&l?.count!==d)throw new Error("Native content snapshot omission overflow is inconsistent");if(e.complete!==(c===0))throw new Error("Native content snapshot completeness is inconsistent");let u=s.filter(v=>v.reason==="git-enumeration-limit"),f=s.filter(v=>v.reason==="git-selection-changed");for(let v of[...u,...f])if(v.path!=="."||v.size!==null||v.type!=="directory")throw new Error("Native Git selection omission must use the project-root sentinel");if(u.length>1||f.length>1)throw new Error("Native Git selection omissions must not be duplicated");let m=i?.provider==="git"?i.gitSelection:i?.projection?.selection,g=m?.status==="overflow"||m?.status==="overflow-and-changed",h=m?.status==="changed"||m?.status==="overflow-and-changed";if(g!==(u.length===1))throw new Error("Native Git enumeration omission and selection evidence are inconsistent");if(h!==(f.length===1))throw new Error("Native Git selection-change omission and selection evidence are inconsistent");let p=s.filter(v=>v.reason==="physical-enumeration-limit"),y=s.filter(v=>v.reason==="physical-selection-changed");for(let v of[...p,...y])if(v.path!=="."||v.size!==null||v.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(p.length>1||y.length>1)throw new Error("Native physical selection omissions must not be duplicated");let N=i?.physicalSelection,k=N?.status==="overflow"||N?.status==="overflow-and-changed",S=N?.status==="changed"||N?.status==="overflow-and-changed";if(k!==(p.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(S!==(y.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");let E={schema:"comet.native.content-snapshot.v1",origin:e.origin,...i?{capture:i}:{},createdAt:e.createdAt,complete:e.complete,limits:r,...a?{policy:a}:{},entries:o,omitted:s,omittedCount:c,...l?{omissionOverflow:l}:{}};if(Qm(E)>r.maxManifestBytes)throw new Error("Native content snapshot exceeds its manifest byte limit");return E}function ov(t,e){if(!jm.test(e))throw new Error(`Invalid Native change name: ${e}`);let i=vn.join(t.changesDir,e);if(!ne(t.changesDir,i))throw new Error("Native change path escaped");return vn.join(i,"runtime","baseline-manifest.json")}async function hl(t,e){let i=ov(t,e);await H(t.nativeRoot,i);try{let n=await nl({root:t.nativeRoot,file:i,maxBytes:Om,label:"Native baseline snapshot manifest"});return dl(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}var dv=On(Xi(),1);var Qb=256*1024;var fk={runStateBytes:256*1024,trajectoryBytes:8*1024*1024,trajectoryEvents:4096,trajectoryEventBytes:256*1024,checkpointBytes:256*1024,pendingActionBytes:256*1024,contextBytes:1024*1024,artifactsBytes:1024*1024};import{createHash as vv}from"node:crypto";import{promises as yn}from"node:fs";import ke from"node:path";import{execFileSync as pv}from"child_process";import wn from"path";function Oa(t,e){return pv("git",["-C",t,...e],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function mv(t,e){let i=wn.normalize(t),n=wn.normalize(e);return process.platform==="win32"?i.toLowerCase()===n.toLowerCase():i===n}function ml(t){try{let e=wn.resolve(Oa(t,["rev-parse","--show-toplevel"])),n=Oa(t,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),r=n?wn.resolve(n.slice(9)):e,a=null;try{a=Oa(t,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!mv(e,r),currentWorktreeRoot:e,primaryWorktreeRoot:r,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}var Kt=/^[a-f0-9]{64}$/u,gv=16*1024,ja=process.platform;function yl(t,e){let i=ke.relative(t,e);return ke.isAbsolute(i)||i===".."||i.startsWith(`..${ke.sep}`)?null:i.replaceAll("\\","/")||"."}function Nl(t){return Array.from(t).some(e=>{let i=e.codePointAt(0)??0;return i<=31||i===127})}function bl(t,e){if(t.length===0||Nl(t)||t.includes("\\")||ke.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes(".."))throw new Error(`${e} must be a portable project-relative path`);let i=ke.posix.normalize(t);if(i!==t||i===".."||i.startsWith("../"))throw new Error(`${e} must be a normalized project-relative path`);return i}function Ha(t,e){return vv("sha256").update(`${t} +${e}`).digest("hex")}async function vl(t,e){let i=await yn.realpath(e),n=await yn.lstat(i);if(!n.isDirectory()||n.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let r=ja==="win32"?ke.normalize(i).toLowerCase():i;return Ha(t,`${r} ${n.dev} ${n.ino} -${n.birthtimeMs}`)}async function gl(t,e){let i=await yn.realpath(e),n=await yn.lstat(i);if(!n.isDirectory()||n.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let r=Oa==="win32"?ke.normalize(i).toLowerCase():i;return ja(t,r)}function wv(t){if(typeof t!="string")throw new Error("Native workspace capturedAt is invalid");let e=new Date(t);if(!Number.isFinite(e.getTime())||e.toISOString()!==t)throw new Error("Native workspace capturedAt is invalid");return t}function wl(t,e){if(t===null)return null;if(typeof t!="string"||t.length===0||t.trim()!==t||Nl(t))throw new Error(`${e} must be a non-empty branch name or null`);return t}function kl(t){if(!new Set(["current","branch","worktree"]).has(t.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(wl(t.changeBranch,"Native workspace change branch"),wl(t.targetBranch,"Native workspace target branch"),(t.isolation==="branch"||t.isolation==="worktree")&&(t.changeBranch===null||t.targetBranch===null))throw new Error("Native isolated workspace requires change and target branches")}function Nn(t){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Native workspace identity must be an object");let e=t,i=new Set(["schema","capturedAt","capturedRevision","nativeRootRef","projectRootId","nativeRootId","projectRootPathId","nativeRootPathId","sessionHash","isolation","changeBranch","targetBranch","finish"]),n=Object.keys(e).filter(o=>!i.has(o));if(n.length>0)throw new Error(`Native workspace identity has unknown field(s): ${n.join(", ")}`);if(e.schema!=="comet.native.workspace.v2"&&e.schema!=="comet.native.workspace.v3")throw new Error("Unsupported Native workspace identity");if(!Number.isSafeInteger(e.capturedRevision)||e.capturedRevision<1||typeof e.nativeRootRef!="string"||!Kt.test(String(e.projectRootId))||!Kt.test(String(e.nativeRootId)))throw new Error("Native workspace identity is invalid");wv(e.capturedAt),bl(e.nativeRootRef,"Native workspace root ref");let r=e.projectRootPathId!==void 0,a=e.nativeRootPathId!==void 0;if(r!==a)throw new Error("Native workspace path identities must be provided together");if(r&&!Kt.test(String(e.projectRootPathId))||a&&!Kt.test(String(e.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(e.sessionHash!==void 0&&!Kt.test(String(e.sessionHash)))throw new Error("Native workspace session hash is invalid");if(e.schema==="comet.native.workspace.v2"){if(e.isolation!==void 0||e.changeBranch!==void 0||e.targetBranch!==void 0||e.finish!==void 0)throw new Error("Native workspace v2 identity cannot contain a workspace binding");return}if(typeof e.isolation!="string"||e.changeBranch===void 0||e.targetBranch===void 0||e.finish===void 0)throw new Error("Native workspace v3 identity requires a workspace binding");if(kl(e),e.finish!==null&&!new Set(["merge","push","pull-request","keep"]).has(e.finish))throw new Error("Native workspace finish must be merge, push, pull-request, keep, or null")}function yv(t,e){return ke.join(t.changesDir,e,"runtime","workspace.json")}function Nv(t,e){let i=yl(t.nativeRoot,yv(t,e));if(!i||i===".")throw new Error("Native workspace file escaped its root");return bl(i,"Native workspace file ref")}async function bv(t,e){try{let i=await Ne({root:t.nativeRoot,ref:Nv(t,e),maxBytes:gv});return JSON.parse(i.text)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function kv(t){if(!Number.isSafeInteger(t.revision)||t.revision<1)throw new Error("Native workspace revision must be a positive integer");let e=yl(t.paths.projectRoot,t.paths.nativeRoot);if(!e)throw new Error("Native root is outside the project root");let[i,n,r,a]=await Promise.all([vl("comet.native.workspace-project-root.v2",t.paths.projectRoot),vl("comet.native.workspace-native-root.v2",t.paths.nativeRoot),gl("comet.native.workspace-project-root-path.v2",t.paths.projectRoot),gl("comet.native.workspace-native-root-path.v2",t.paths.nativeRoot)]),o=(t.now??new Date).toISOString();if(t.finish&&!t.binding)throw new Error("Native workspace finish requires a workspace binding");t.binding&&kl(t.binding);let s={capturedAt:o,capturedRevision:t.revision,nativeRootRef:e,projectRootId:i,nativeRootId:n,projectRootPathId:r,nativeRootPathId:a,...t.sessionId?{sessionHash:ja("comet.native.workspace-session.v2",`${i} +${n.birthtimeMs}`)}async function gl(t,e){let i=await yn.realpath(e),n=await yn.lstat(i);if(!n.isDirectory()||n.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let r=ja==="win32"?ke.normalize(i).toLowerCase():i;return Ha(t,r)}function wv(t){if(typeof t!="string")throw new Error("Native workspace capturedAt is invalid");let e=new Date(t);if(!Number.isFinite(e.getTime())||e.toISOString()!==t)throw new Error("Native workspace capturedAt is invalid");return t}function wl(t,e){if(t===null)return null;if(typeof t!="string"||t.length===0||t.trim()!==t||Nl(t))throw new Error(`${e} must be a non-empty branch name or null`);return t}function kl(t){if(!new Set(["current","branch","worktree"]).has(t.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(wl(t.changeBranch,"Native workspace change branch"),wl(t.targetBranch,"Native workspace target branch"),(t.isolation==="branch"||t.isolation==="worktree")&&(t.changeBranch===null||t.targetBranch===null))throw new Error("Native isolated workspace requires change and target branches")}function Nn(t){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Native workspace identity must be an object");let e=t,i=new Set(["schema","capturedAt","capturedRevision","nativeRootRef","projectRootId","nativeRootId","projectRootPathId","nativeRootPathId","sessionHash","isolation","changeBranch","targetBranch","finish"]),n=Object.keys(e).filter(o=>!i.has(o));if(n.length>0)throw new Error(`Native workspace identity has unknown field(s): ${n.join(", ")}`);if(e.schema!=="comet.native.workspace.v2"&&e.schema!=="comet.native.workspace.v3")throw new Error("Unsupported Native workspace identity");if(!Number.isSafeInteger(e.capturedRevision)||e.capturedRevision<1||typeof e.nativeRootRef!="string"||!Kt.test(String(e.projectRootId))||!Kt.test(String(e.nativeRootId)))throw new Error("Native workspace identity is invalid");wv(e.capturedAt),bl(e.nativeRootRef,"Native workspace root ref");let r=e.projectRootPathId!==void 0,a=e.nativeRootPathId!==void 0;if(r!==a)throw new Error("Native workspace path identities must be provided together");if(r&&!Kt.test(String(e.projectRootPathId))||a&&!Kt.test(String(e.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(e.sessionHash!==void 0&&!Kt.test(String(e.sessionHash)))throw new Error("Native workspace session hash is invalid");if(e.schema==="comet.native.workspace.v2"){if(e.isolation!==void 0||e.changeBranch!==void 0||e.targetBranch!==void 0||e.finish!==void 0)throw new Error("Native workspace v2 identity cannot contain a workspace binding");return}if(typeof e.isolation!="string"||e.changeBranch===void 0||e.targetBranch===void 0||e.finish===void 0)throw new Error("Native workspace v3 identity requires a workspace binding");if(kl(e),e.finish!==null&&!new Set(["merge","push","pull-request","keep"]).has(e.finish))throw new Error("Native workspace finish must be merge, push, pull-request, keep, or null")}function yv(t,e){return ke.join(t.changesDir,e,"runtime","workspace.json")}function Nv(t,e){let i=yl(t.nativeRoot,yv(t,e));if(!i||i===".")throw new Error("Native workspace file escaped its root");return bl(i,"Native workspace file ref")}async function bv(t,e){try{let i=await Ne({root:t.nativeRoot,ref:Nv(t,e),maxBytes:gv});return JSON.parse(i.text)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function kv(t){if(!Number.isSafeInteger(t.revision)||t.revision<1)throw new Error("Native workspace revision must be a positive integer");let e=yl(t.paths.projectRoot,t.paths.nativeRoot);if(!e)throw new Error("Native root is outside the project root");let[i,n,r,a]=await Promise.all([vl("comet.native.workspace-project-root.v2",t.paths.projectRoot),vl("comet.native.workspace-native-root.v2",t.paths.nativeRoot),gl("comet.native.workspace-project-root-path.v2",t.paths.projectRoot),gl("comet.native.workspace-native-root-path.v2",t.paths.nativeRoot)]),o=(t.now??new Date).toISOString();if(t.finish&&!t.binding)throw new Error("Native workspace finish requires a workspace binding");t.binding&&kl(t.binding);let s={capturedAt:o,capturedRevision:t.revision,nativeRootRef:e,projectRootId:i,nativeRootId:n,projectRootPathId:r,nativeRootPathId:a,...t.sessionId?{sessionHash:Ha("comet.native.workspace-session.v2",`${i} ${n} -${t.sessionId}`)}:{}},c=t.binding?{schema:"comet.native.workspace.v3",...s,...t.binding,finish:t.finish??null}:{schema:"comet.native.workspace.v2",...s};return Nn(c),c}async function bn(t,e){let i=await bv(t,e);return i===null||i&&typeof i=="object"&&!Array.isArray(i)&&i.schema==="comet.native.workspace.v1"?null:(Nn(i),i)}async function Sl(t){Nn(t.identity);let e=await kv({paths:t.paths,name:"workspace-advisory",revision:t.identity.capturedRevision}),i=[],n=[];return e.nativeRootRef!==t.identity.nativeRootRef&&i.push("native-root-ref"),t.identity.projectRootPathId&&t.identity.nativeRootPathId?(e.projectRootPathId!==t.identity.projectRootPathId&&i.push("project-root-path"),e.nativeRootPathId!==t.identity.nativeRootPathId&&i.push("native-root-path")):(e.projectRootId!==t.identity.projectRootId&&i.push("project-root-legacy-identity"),e.nativeRootId!==t.identity.nativeRootId&&i.push("native-root-legacy-identity")),Oa==="win32"&&i.length>0&&i.every(a=>a==="project-root-legacy-identity"||a==="native-root-legacy-identity")?n.push("workspace-inspection-unavailable"):i.length>0&&n.push("workspace-root-changed"),{state:n.length===0?"aligned":n.includes("workspace-root-changed")?"drifted":"unknown",findingCodes:n,driftComponents:i}}async function El(t){if(Nn(t.identity),t.identity.schema==="comet.native.workspace.v2")return{state:"legacy",code:"workspace-binding-legacy",message:"Legacy Native workspace metadata has no isolation binding"};if((await Sl(t)).state==="drifted")return{state:"drifted",code:"workspace-binding-root-changed",message:"Native change is being accessed from a different working directory"};let i=ml(t.paths.projectRoot);return t.identity.changeBranch===null?i.isGitWorktree?{state:"drifted",code:"workspace-branch-changed",message:"Native change was created outside Git but is now being accessed inside Git"}:{state:"aligned",code:null,message:null}:i.isGitWorktree?i.currentBranch!==t.identity.changeBranch?{state:"drifted",code:"workspace-branch-changed",message:`Native change is bound to branch ${t.identity.changeBranch}, but the current branch is ${i.currentBranch??"detached HEAD"}`}:t.identity.isolation==="worktree"&&!i.isSecondaryWorktree?{state:"drifted",code:"workspace-kind-changed",message:"Native change is bound to a linked Git worktree"}:{state:"aligned",code:null,message:null}:{state:"drifted",code:"workspace-vcs-unavailable",message:"Native change requires its bound Git working directory"}}async function Cl(t,e){let i=await bn(t,e);if(i===null)return null;let n=await El({paths:t,identity:i});if(n.state==="drifted")throw new Error(`${n.code}: ${n.message}`);return i}var $e="comet.native.v3",Le="comet.native.v2",Fe="comet.native.v1";var Rl=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],Cv=new Set(Rl),Pl=new Set([...Rl,"minimum_runtime_version","revision"]),Rv=new Set([...Pl,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),Pv=new Set(["capability","operation","source","base_hash"]),Av=new Set(["shape","build","verify","archive"]),xv=new Set(["implicit","confirmed"]),Tv=new Set(["pending","pass","fail"]),De="comet-state.yaml",$a=/^[a-f0-9]{64}$/u,Al=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Iv=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,kn=class extends Error{constructor(i,n){super(`Native change ${i} uses ${n}; run comet native doctor ${i} --repair before mutating it`);this.change=i;this.schema=n;this.name="NativeSchemaMigrationRequiredError"}change;schema;code="native-schema-migration-required"},Be=class extends Error{constructor(i,n){super(i!==$e||n===null?`Unsupported Native change schema ${i} for runtime protocol ${3}`:`Native change ${i} requires runtime protocol ${n}; current protocol is ${3}`);this.schema=i;this.minimumRuntimeVersion=n;this.name="NativeRuntimeCompatibilityError"}schema;minimumRuntimeVersion;code="native-runtime-incompatible"},Sn=class extends Error{constructor(i,n,r){super(`Native change ${i} revision conflict: expected ${n}, actual ${r}`);this.change=i;this.expectedRevision=n;this.actualRevision=r;this.name="NativeChangeRevisionConflictError"}change;expectedRevision;actualRevision;code="native-change-revision-conflict"},En=class extends Error{constructor(i,n){super(`Native working directory already contains active change${n.length===1?"":"s"} ${n.join(", ")}; create the new change in a separate worktree`);this.requestedIsolation=i;this.activeChanges=n;this.name="NativeWorkspaceIsolationRequiredError"}requestedIsolation;activeChanges;code="native-workspace-isolation-required"},Cn=class extends Error{constructor(i,n,r,a,o,s=null,c=null){super(`Native change ${i} baseline is incomplete (${n} omitted entr${n===1?"y":"ies"}). Adjust native.snapshot scope or resource budgets in .comet/config.yaml, then retry.`);this.change=i;this.omittedCount=n;this.omittedByReason=r;this.samplePaths=a;this.sampleTruncated=o;this.effectiveLimits=s;this.policyHash=c;this.name="NativeBaselineIncompleteError"}change;omittedCount;omittedByReason;samplePaths;sampleTruncated;effectiveLimits;policyHash;code="native-baseline-incomplete"},eS=["# Outcome","","# Scope","","# Non-goals","","# Acceptance examples","","# Constraints and invariants","","# Decisions","","# Open questions","","# Verification expectations",""].join(` -`);function Yt(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function xl(t,e,i){let n=Object.keys(t).filter(r=>!e.has(r));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`)}function Rn(t){if(!Al.test(t))throw new Error(`Invalid Native change name: ${t}`)}function _v(t){if(!Al.test(t))throw new Error(`Invalid Native capability id: ${t}`)}function Tl(t,e){if(t.length===0||Me.isAbsolute(t)||/^(?:[A-Za-z]:|~|[\\/])/u.test(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`${e} must stay inside the Native change`)}function Ov(t,e){let i=Yt(t,`spec_changes[${e}]`);if(xl(i,Pv,`spec_changes[${e}]`),typeof i.capability!="string")throw new Error("spec change capability is required");if(_v(i.capability),i.operation!=="create"&&i.operation!=="replace"&&i.operation!=="remove")throw new Error(`Invalid spec operation for ${i.capability}`);let n=i.source,r=i.base_hash;if(n!==void 0&&typeof n!="string")throw new Error(`Spec source for ${i.capability} must be a string`);if(typeof n=="string"&&Tl(n,`Spec source for ${i.capability}`),i.operation==="create"){if(!n)throw new Error(`Create spec ${i.capability} requires source`);if(r!==null)throw new Error(`Create spec ${i.capability} requires null base_hash`)}else if(i.operation==="replace"){if(!n)throw new Error(`Replace spec ${i.capability} requires source`);if(typeof r!="string"||!$a.test(r))throw new Error(`Replace spec ${i.capability} requires a SHA-256 base_hash`)}else{if(n!==void 0)throw new Error(`Remove spec ${i.capability} forbids source`);if(typeof r!="string"||!$a.test(r))throw new Error(`Remove spec ${i.capability} requires a SHA-256 base_hash`)}return{capability:i.capability,operation:i.operation,...typeof n=="string"?{source:n}:{},base_hash:r}}function jv(t){return/^\d{4}-\d{2}-\d{2}$/u.test(t)?new Date(`${t}T00:00:00.000Z`).toISOString().slice(0,10)===t:!1}function Fa(t,e){if(xl(t,e,De),typeof t.name!="string")throw new Error("Native change name is required");if(Rn(t.name),t.language!=="en"&&t.language!=="zh-CN")throw new Error("Native change language must be en or zh-CN");if(typeof t.phase!="string"||!Av.has(t.phase))throw new Error("Native change phase is invalid");if(t.brief!=="brief.md")throw new Error("Native change brief must be brief.md");if(t.approval!==null&&!xv.has(t.approval))throw new Error("Native change approval is invalid");if(!Array.isArray(t.spec_changes))throw new Error("Native spec_changes must be an array");let i=t.spec_changes.map(Ov),n=i.map(r=>r.capability).filter((r,a,o)=>o.indexOf(r)!==a);if(n.length>0)throw new Error(`Duplicate Native capability operation: ${[...new Set(n)].join(", ")}`);if(typeof t.verification_result!="string"||!Tv.has(t.verification_result))throw new Error("Native verification_result is invalid");if(t.verification_report!==null&&typeof t.verification_report!="string")throw new Error("Native verification_report must be a string or null");if(typeof t.verification_report=="string"&&Tl(t.verification_report,"Native verification_report"),typeof t.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof t.created_at!="string"||!jv(t.created_at))throw new Error("Native created_at must be a valid YYYY-MM-DD date");if(t.run_id!==null&&(typeof t.run_id!="string"||t.run_id.length===0))throw new Error("Native run_id must be a non-empty string or null");return{name:t.name,language:t.language,phase:t.phase,brief:"brief.md",approval:t.approval,spec_changes:i,verification_result:t.verification_result,verification_report:t.verification_report,archived:t.archived,created_at:t.created_at,run_id:t.run_id}}function Ma(t){let e=Yt(t,De);if(e.schema!==Fe)throw new Error(`Expected ${Fe}`);return{schema:Fe,...Fa(e,Cv)}}function Ut(t,e){if(!Number.isSafeInteger(t)||t<1)throw new Error(`${e} must be a positive integer`);return t}function Ha(t,e,i){if(t===null)return null;let n=typeof t=="string"?Iv.exec(t):null;if(!n||n[1]!==i)throw new Error(`${e} must be null or runtime/evidence/${i}/.json relative to the Native change`);return t}function Hv(t){if(t==null)return null;if(typeof t!="string"||!$a.test(t))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return t}function $v(t){if(t===void 0)return"legacy-v1";if(t!=="legacy-v1")throw new Error("Native verification_protocol must be legacy-v1");return t}function Ba(t){let e=Yt(t,De);if(e.schema!==Le)throw new Error(`Expected ${Le}`);if(Ut(e.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${Le} minimum_runtime_version must be 2`);return{schema:Le,minimum_runtime_version:2,revision:Ut(e.revision,"Native v2 revision"),...Fa(e,Pl)}}function Da(t){let e=Yt(t,De);if(e.schema!==$e){if(e.schema===Fe||e.schema===Le){let o=e.schema===Fe?Ma(e):Ba(e);throw new kn(o.name,o.schema)}throw new Be(typeof e.schema=="string"?e.schema:"(missing)",typeof e.minimum_runtime_version=="number"?e.minimum_runtime_version:null)}let i=Ut(e.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)throw new Be(e.schema,i);if(i!==3)throw new Error(`Native ${e.schema} minimum_runtime_version must be ${3}`);let n=Ut(e.revision,"Native revision"),r=Fa(e,Rv),a=Hv(e.approved_contract_hash);if(r.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:$e,minimum_runtime_version:3,revision:n,verification_protocol:$v(e.verification_protocol),...r,approved_contract_hash:a,implementation_scope:Ha(e.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:Ha(e.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:Ha(e.partial_allowance,"Native partial_allowance","allowances")}}function Lv(t){let e=Yt(t,De);if(e.schema===Fe){let r=Ma(e);return{status:"migration-required",schema:r.schema,minimumRuntimeVersion:1,state:r,message:`Native change ${r.name} requires migration to ${$e}`}}if(e.schema===Le){let r=Ba(e);return{status:"migration-required",schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,state:r,message:`Native change ${r.name} requires migration to ${$e}`}}if(e.schema!==$e){let r=typeof e.minimum_runtime_version=="number"&&Number.isSafeInteger(e.minimum_runtime_version)?e.minimum_runtime_version:null;return{status:"runtime-incompatible",schema:typeof e.schema=="string"?e.schema:"(missing)",minimumRuntimeVersion:r,state:null,message:new Be(typeof e.schema=="string"?e.schema:"(missing)",r).message}}let i=Ut(e.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)return{status:"runtime-incompatible",schema:e.schema,minimumRuntimeVersion:i,state:null,message:new Be(e.schema,i).message};let n=Da(e);return{status:"current",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n}}function Y(t,e){Rn(e);let i=Me.join(t.changesDir,e);if(!ne(t.changesDir,i))throw new Error("Native change path escaped");return i}async function qa(t,e){let i=Me.join(Y(t,e),"runtime","schema-migration.json");await H(t.nativeRoot,i);try{return await Ev.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}var Fv=256*1024;async function Mv(t,e=Me.dirname(t)){let i=Me.relative(e,t).split(Me.sep).join("/"),n=await Ne({root:e,ref:i,maxBytes:Fv}),r=(0,La.parseDocument)(n.text,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`Invalid Native change file ${t}: ${r.errors[0].message}`);return r.toJS()}async function Bv(t,e){let i=Me.join(Y(t,e),De);await H(t.nativeRoot,i);let n=Lv(await Mv(i,t.nativeRoot));if(n.state&&n.state.name!==e)throw new Error(`Native change directory/name mismatch: ${e}`);return await qa(t,e)?{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimumRuntimeVersion,state:n.state,message:`Native schema migration is incomplete for ${e}; run doctor --repair`}:(n.status==="current"&&n.state&&await Dv(t,n.state),n)}async function Dv(t,e){if(await hl(t,e.name)!==null&&e.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${e.verification_protocol}`)}async function se(t,e){let i=await Bv(t,e);if(i.status==="migration-required")throw new kn(e,i.schema);if(i.status==="runtime-incompatible"||!i.state)throw new Be(i.schema,i.minimumRuntimeVersion);return await Cl(t,e),i.state}import qv from"path";var Va="comet.selection.v2",Vv=16*1024;function _l(t){return qv.join(t,".comet","current-change.json")}function Wv(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function Il(t){return t===null||typeof t=="string"}function zv(t){let e;try{e=JSON.parse(t)}catch(i){throw new Error(`current change selection contains invalid JSON: ${i instanceof Error?i.message:String(i)}`,{cause:i})}if(!Wv(e))throw new Error("current change selection must be a JSON object");if(e.version===1){if(typeof e.change!="string")throw new Error("legacy current change selection change must be a string");if(e.branch!==void 0&&!Il(e.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:Va,workflow:"classic",change:e.change,branch:e.branch??null},legacy:!0}}if(e.schema!==Va)throw new Error(`current change selection schema must be ${Va}`);if(e.workflow!=="native"&&e.workflow!=="classic")throw new Error("current change selection workflow must be native or classic");if(typeof e.change!="string")throw new Error("current change selection change must be a string");if(!Il(e.branch))throw new Error("current change selection branch must be a string or null");if(e.workflow==="native"&&e.branch!==null)throw new Error("Native current change selection branch must be null");return{selection:e,legacy:!1}}async function Ol(t){let e;try{let n=_l(t),{bytes:r}=await tt(n,Vv,{label:"current change selection"});e=r.toString("utf8")}catch(n){if(n.code==="ENOENT")return{status:"missing"};throw new Error(`cannot read current change selection: ${n instanceof Error?n.message:String(n)}`,{cause:n})}return{status:"selected",...zv(e)}}var dS=16*1024;async function Jv(t){let e=await Ol(t.projectRoot);return e.status==="missing"||e.selection.workflow!=="native"?null:(Rn(e.selection.change),e.selection)}async function jl(t){let e=await Jv(t);return e?(await se(t,e.change),e.change):null}function Pn(t,e){let i=st.relative(t,e);return i===""||!i.startsWith("..")&&!st.isAbsolute(i)}function Kv(t,e,i){return i.targets.length>0&&i.targets.every(n=>{let r=st.resolve(t,n);return Pn(t,r)?st.relative(t,r).replaceAll("\\","/")===".comet/config.yaml"||Pn(e,r):!0})}async function Uv(t){let e=await nt(t);if(!e||!(e.workflows??[e.default_workflow]).includes("native"))return null;let i=await un(t,e.native.artifact_root),n;try{n=await Gv.readdir(i.changesDir,{withFileTypes:!0})}catch(a){if(a.code==="ENOENT")return{paths:i,changes:[]};throw a}let r=[];for(let a of n.sort((o,s)=>o.name.localeCompare(s.name))){if(!a.isDirectory()||a.isSymbolicLink())continue;let o=await se(i,a.name);o.archived||r.push(o)}return{paths:i,changes:r}}var Yv=Ka("nativeActiveContext",t=>Uv(t));async function Hl(){let{intent:t,targets:e}=await to();return{intent:t,targets:e}}async function $l(t,e,i){let n=await Yv(t);if(!n)return{allowed:!0,reason:"Native workflow is not enabled"};if(e.intent==="non-write")return{allowed:!0,reason:"Hook event is not a write"};if(n.changes.length===0)return{allowed:!0,reason:Kv(t,n.paths.nativeRoot,e)?"Native control artifact write":"No Native changes exist"};let r;if(i){if(r=n.changes.find(s=>s.name===i),!r)return{allowed:!1,reason:`Selected Native change ${i} is missing or archived; resume /comet-native before retrying`,workflow:"native",change:i}}else if(n.changes.length===1)r=n.changes[0];else{let s=await jl(n.paths);if(r=n.changes.find(c=>c.name===s),!r)return{allowed:!1,reason:"Multiple Native changes are active; select the change to resume before writing code",workflow:"native"}}if(r.phase==="build")return{allowed:!0,reason:"Native change is in Build",workflow:"native",phase:r.phase,change:r.name};if(e.intent==="unknown"||e.targets.length===0)return{allowed:!0,reason:"Hook write target was not attributed to the guarded project",workflow:"native",phase:r.phase,change:r.name};let a=!1,o=!1;for(let s of e.targets){let c=st.resolve(t,s);if(!Pn(t,c)){o=!0;continue}if(st.relative(t,c).replaceAll("\\","/")===".comet/config.yaml"||Pn(n.paths.nativeRoot,c)){a=!0;continue}return{allowed:!1,reason:`Native change ${r.name} is in ${r.phase}; implementation writes are only allowed in build. Resume /comet-native to continue safely`,workflow:"native",phase:r.phase,change:r.name}}return{allowed:!0,reason:a?"Native control artifact write":o?"Write target is outside the guarded project":"No guarded write target was provided",workflow:"native",phase:r.phase,change:r.name}}import _g from"path";var Qv=["Outcome","Scope","Non-goals","Acceptance examples"],$S=[...Qv,"Constraints and invariants","Decisions","Open questions","Verification expectations"];import{createHash as Zv}from"crypto";function X(t){throw new TypeError(`Value is not valid canonical JSON: ${t}`)}function eg(t,e){e.has(t)&&X("cyclic structures are not supported"),e.add(t);try{let i=Object.keys(t);for(let n=0;nn!==String(r)))&&X("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(t).length>0&&X("symbol properties are not supported"),`[${t.map(n=>Wa(n,e)).join(",")}]`}finally{e.delete(t)}}function tg(t,e){let i=Object.getPrototypeOf(t);i!==Object.prototype&&i!==null&&X("only plain objects are supported"),e.has(t)&&X("cyclic structures are not supported"),Object.getOwnPropertySymbols(t).length>0&&X("symbol properties are not supported"),e.add(t);try{let n=Object.getOwnPropertyDescriptors(t);return`{${Object.keys(t).sort().map(o=>{let s=n[o];return(!s||!("value"in s))&&X("accessor properties are not supported"),`${JSON.stringify(o)}:${Wa(s.value,e)}`}).join(",")}}`}finally{e.delete(t)}}function Wa(t,e){if(t===null)return"null";switch(typeof t){case"boolean":return t?"true":"false";case"string":return JSON.stringify(t);case"number":return Number.isFinite(t)||X("numbers must be finite"),JSON.stringify(Object.is(t,-0)?0:t);case"object":return Array.isArray(t)?eg(t,e):tg(t,e);case"bigint":case"function":case"symbol":case"undefined":return X(`${typeof t} values are not supported`)}return X("unsupported value type")}function za(t){return Wa(t,new Set)}function Q(t,e){if(t.length===0)throw new TypeError("Canonical hash tag must be non-empty");if(/[\r\n]/u.test(t))throw new TypeError("Canonical hash tag must not contain a line break");return Zv("sha256").update(`${t} -${za(e)}`).digest("hex")}var ig=Object.freeze({maxChanges:32,maxSpecsPerChange:64,maxArtifactsPerChange:128,maxTotalSpecs:512,maxTotalArtifacts:1024,maxSignalsPerRelationship:8,maxRelationships:256,maxSerializedBytes:64*1024,maxNameBytes:128,maxCapabilityBytes:128,maxArtifactPathBytes:512});var Ll=1024*1024;var Ml="scoped-text-safety",ng=1,rg=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128});var ag="comet.native.checker-policy.v1";var eE=Q(ag,{policy:Ml,version:ng,limits:rg,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"});var og=["contract-before-does-not-match-scope","implementation-before-does-not-match-scope","contract-changed-during-check","implementation-changed-during-check","contract-after-does-not-match-scope","implementation-after-does-not-match-scope"],tE=new Set(og);var cg=Ll,yE=3*cg;var Bl={root:"/comet/native-runtime",packageKind:"runtime",definition:{apiVersion:"comet/v1alpha1",kind:"Skill",metadata:{name:"comet-native-runtime",version:"3",description:"Comet-owned state runtime for the Native workflow."},goal:{statement:"Advance a Native change only after its current guard passes.",inputs:[],outputs:[],success:["The Native change and Run state agree on the next phase."]},orchestration:{mode:"deterministic",entry:"shape",steps:[{id:"shape",action:{type:"checkpoint"},next:"build"},{id:"build",action:{type:"checkpoint"},next:"verify"},{id:"verify",action:{type:"checkpoint"},next:"archive"},{id:"archive",action:{type:"checkpoint"}}]},skills:[],agents:[],tools:[]},guardrails:{allowedSkills:[],allowedAgents:[],allowedTools:[],maxIterations:Number.MAX_SAFE_INTEGER,maxRetriesPerAction:2,confirmationRequiredFor:[]},evals:[]},lg=D("comet-native-runtime:v3:semantic-repair-budget"),GE=[{skillVersion:"2",skillHash:D("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:D("comet-native-runtime:v1")}];var ql=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],PC=new Set(ql),mg=new Set([...ql,"minimum_runtime_version","revision"]),AC=new Set([...mg,"operation"]),xC=512*1024,vg=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),TC=new Set([...vg,"implementationScopeHash","repairScopeHash","repairStagnation"]);var OC=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),Vl=Object.freeze({maxCriteria:1024});var BC={maxAcceptanceCriteria:Vl.maxCriteria};var zC={maxSpecs:64,maxFileBytes:Zi,maxTotalBytes:4*1024*1024};import{execFile as Cg,spawn as OR}from"node:child_process";import{promisify as Rg}from"node:util";var iR={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024};var ER=512*1024;var Xt=class extends Error{recovery;constructor(e,i){super(e),this.name="NativeReceiptScopeStaleError",this.recovery=i}};var KR=64*1024;var UR=3600*1e3;var YR=Rg(Cg);var XR=["$ProgressPreference = 'SilentlyContinue'","$encoded = $env:COMET_NATIVE_COMMAND_PAYLOAD","Remove-Item Env:COMET_NATIVE_COMMAND_PAYLOAD -ErrorAction SilentlyContinue","$json = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($encoded))","$payload = ConvertFrom-Json $json","$commandArgs = @($payload.arguments)","& $payload.command @commandArgs","if ($null -eq $LASTEXITCODE) { if ($?) { exit 0 } else { exit 1 } }","exit $LASTEXITCODE"].join("; ");var xn=class extends Error{details;constructor(e){let i=e.length===0?"Native verification receipt binding is invalid":`Native verification receipt binding is invalid (${e.length} receipt(s)): ${e.map(n=>`${n.ref}${n.acceptanceId?`[${n.acceptanceId}]`:""} -> ${n.mismatches.join("; ")}`).join(" | ")}`;super(i),this.name="NativeVerificationReceiptBindingError",this.details=e}};var LP={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};var UP=16*1024*1024,YP=256*1024,XP=16*1024;var FA=16*1024*1024,Tn=class extends Error{constructor(i,n,r,a){super(`Canonical spec conflict for ${i}: expected ${n??"(missing)"}, actual ${r??"(missing)"}`);this.capability=i;this.expectedHash=n;this.actualHash=r;this.canonicalPath=a;this.name="NativeSpecConflictError"}capability;expectedHash;actualHash;canonicalPath;code="native-spec-conflict"},In=class extends Error{constructor(i,n=i.ready?"Native Archive preflight no longer matches the expected hash":`Native Archive preflight is blocked: ${i.findingCodes.join(", ")}`){super(n);this.preflight=i;this.name="NativeArchivePreflightError"}preflight;code="native-archive-preflight"};var UA=10*1024*1024,ce=class extends Error{};function zl(t,e){let i=t.flatMap((n,r)=>n===e?[r]:[]);if(i.length>1)throw new ce(`${e} may only be provided once`);return i.length===0?!1:(t.splice(i[0],1),!0)}function _n(t,e){let i=t.flatMap((a,o)=>a===e?[o]:[]);if(i.length>1)throw new ce(`${e} may only be provided once`);if(i.length===0)return;let n=i[0],r=t[n+1];if(r===void 0||r.startsWith("--"))throw new ce(`${e} requires a value`);return t.splice(n,2),r}function Jl(t){if(t.length>0)throw new ce(`Unexpected argument: ${t[0]}`)}async function Gl(t){return t?_g.resolve(t):Ra(process.cwd())}function Kl(t,e){if(e instanceof ce)return{command:t,exitCode:64,error:{code:"usage",message:e.message}};if(e instanceof Tn)return{command:t,exitCode:73,data:{capability:e.capability,expectedHash:e.expectedHash,actualHash:e.actualHash,canonicalPath:e.canonicalPath},error:{code:"conflict",message:e.message}};if(e instanceof In)return{command:t,exitCode:73,data:e.preflight,error:{code:"conflict",message:e.message}};if(e instanceof Sn)return{command:t,exitCode:73,data:{change:e.change,expectedRevision:e.expectedRevision,actualRevision:e.actualRevision,outcome:"revision-conflict"},error:{code:"conflict",message:e.message}};if(e instanceof En)return{command:t,exitCode:73,data:{requestedIsolation:e.requestedIsolation,activeChanges:e.activeChanges,requiredAction:"create-native-worktree"},error:{code:"workspace-isolation-required",message:e.message}};if(e instanceof Cn)return{command:t,exitCode:65,data:{change:e.change,complete:!1,omittedCount:e.omittedCount,omittedByReason:e.omittedByReason,samplePaths:e.samplePaths,sampleTruncated:e.sampleTruncated,effectiveLimits:e.effectiveLimits,policyHash:e.policyHash,configPath:".comet/config.yaml",supportedFixes:["increase native.snapshot.max_files, native.snapshot.max_total_bytes, or native.snapshot.max_duration_ms","add an explicit native.snapshot.exclude pattern for data outside implementation scope"],requiredAction:"resolve-native-baseline"},error:{code:"baseline-incomplete",message:e.message}};if(e instanceof xn)return{command:t,exitCode:65,data:{receiptBindingFailures:e.details},error:{code:"invalid-data",message:e.message}};if(e instanceof Xt)return{command:t,exitCode:65,data:e.recovery,error:{code:"implementation-scope-stale",message:e.message}};if(e instanceof Error){let i=e.code;if(i&&new Set(["EACCES","EPERM","EIO","EMFILE","ENFILE","ENOSPC","EROFS"]).has(i))return{command:t,exitCode:70,error:{code:"internal",message:e.message}};let n=/\b(lock|transaction|conflict|occupied|incomplete|recovery)\b/iu.test(e.message);return{command:t,exitCode:n?73:65,error:{code:n?"conflict":"invalid-data",message:e.message}}}return{command:t,exitCode:70,error:{code:"internal",message:String(e)}}}function Ul(t,e){return e?{exitCode:t.exitCode,stdout:JSON.stringify({command:t.command,exitCode:t.exitCode,...t.data===void 0?{}:{data:t.data},...t.error===void 0?{}:{error:t.error}})+` +${t.sessionId}`)}:{}},c=t.binding?{schema:"comet.native.workspace.v3",...s,...t.binding,finish:t.finish??null}:{schema:"comet.native.workspace.v2",...s};return Nn(c),c}async function bn(t,e){let i=await bv(t,e);return i===null||i&&typeof i=="object"&&!Array.isArray(i)&&i.schema==="comet.native.workspace.v1"?null:(Nn(i),i)}async function Sl(t){Nn(t.identity);let e=await kv({paths:t.paths,name:"workspace-advisory",revision:t.identity.capturedRevision}),i=[],n=[];return e.nativeRootRef!==t.identity.nativeRootRef&&i.push("native-root-ref"),t.identity.projectRootPathId&&t.identity.nativeRootPathId?(e.projectRootPathId!==t.identity.projectRootPathId&&i.push("project-root-path"),e.nativeRootPathId!==t.identity.nativeRootPathId&&i.push("native-root-path")):(e.projectRootId!==t.identity.projectRootId&&i.push("project-root-legacy-identity"),e.nativeRootId!==t.identity.nativeRootId&&i.push("native-root-legacy-identity")),ja==="win32"&&i.length>0&&i.every(a=>a==="project-root-legacy-identity"||a==="native-root-legacy-identity")?n.push("workspace-inspection-unavailable"):i.length>0&&n.push("workspace-root-changed"),{state:n.length===0?"aligned":n.includes("workspace-root-changed")?"drifted":"unknown",findingCodes:n,driftComponents:i}}async function El(t){if(Nn(t.identity),t.identity.schema==="comet.native.workspace.v2")return{state:"legacy",code:"workspace-binding-legacy",message:"Legacy Native workspace metadata has no isolation binding"};if((await Sl(t)).state==="drifted")return{state:"drifted",code:"workspace-binding-root-changed",message:"Native change is being accessed from a different working directory"};let i=ml(t.paths.projectRoot);return t.identity.changeBranch===null?i.isGitWorktree?{state:"drifted",code:"workspace-branch-changed",message:"Native change was created outside Git but is now being accessed inside Git"}:{state:"aligned",code:null,message:null}:i.isGitWorktree?i.currentBranch!==t.identity.changeBranch?{state:"drifted",code:"workspace-branch-changed",message:`Native change is bound to branch ${t.identity.changeBranch}, but the current branch is ${i.currentBranch??"detached HEAD"}`}:t.identity.isolation==="worktree"&&!i.isSecondaryWorktree?{state:"drifted",code:"workspace-kind-changed",message:"Native change is bound to a linked Git worktree"}:{state:"aligned",code:null,message:null}:{state:"drifted",code:"workspace-vcs-unavailable",message:"Native change requires its bound Git working directory"}}async function Cl(t,e){let i=await bn(t,e);if(i===null)return null;let n=await El({paths:t,identity:i});if(n.state==="drifted")throw new Error(`${n.code}: ${n.message}`);return i}var $e="comet.native.v3",Le="comet.native.v2",Fe="comet.native.v1";var Rl=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],Cv=new Set(Rl),Pl=new Set([...Rl,"minimum_runtime_version","revision"]),Rv=new Set([...Pl,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),Pv=new Set(["capability","operation","source","base_hash"]),Av=new Set(["shape","build","verify","archive"]),xv=new Set(["implicit","confirmed"]),Tv=new Set(["pending","pass","fail"]),De="comet-state.yaml",La=/^[a-f0-9]{64}$/u,Al=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Iv=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,kn=class extends Error{constructor(i,n){super(`Native change ${i} uses ${n}; run comet native doctor ${i} --repair before mutating it`);this.change=i;this.schema=n;this.name="NativeSchemaMigrationRequiredError"}change;schema;code="native-schema-migration-required"},Be=class extends Error{constructor(i,n){super(i!==$e||n===null?`Unsupported Native change schema ${i} for runtime protocol ${3}`:`Native change ${i} requires runtime protocol ${n}; current protocol is ${3}`);this.schema=i;this.minimumRuntimeVersion=n;this.name="NativeRuntimeCompatibilityError"}schema;minimumRuntimeVersion;code="native-runtime-incompatible"},Sn=class extends Error{constructor(i,n,r){super(`Native change ${i} revision conflict: expected ${n}, actual ${r}`);this.change=i;this.expectedRevision=n;this.actualRevision=r;this.name="NativeChangeRevisionConflictError"}change;expectedRevision;actualRevision;code="native-change-revision-conflict"},En=class extends Error{constructor(i,n){super(`Native working directory already contains active change${n.length===1?"":"s"} ${n.join(", ")}; create the new change in a separate worktree`);this.requestedIsolation=i;this.activeChanges=n;this.name="NativeWorkspaceIsolationRequiredError"}requestedIsolation;activeChanges;code="native-workspace-isolation-required"},Cn=class extends Error{constructor(i,n,r,a,o,s=null,c=null){super(`Native change ${i} baseline is incomplete (${n} omitted entr${n===1?"y":"ies"}). Adjust native.snapshot scope or resource budgets in .comet/config.yaml, then retry.`);this.change=i;this.omittedCount=n;this.omittedByReason=r;this.samplePaths=a;this.sampleTruncated=o;this.effectiveLimits=s;this.policyHash=c;this.name="NativeBaselineIncompleteError"}change;omittedCount;omittedByReason;samplePaths;sampleTruncated;effectiveLimits;policyHash;code="native-baseline-incomplete"},eS=["# Outcome","","# Scope","","# Non-goals","","# Acceptance examples","","# Constraints and invariants","","# Decisions","","# Open questions","","# Verification expectations",""].join(` +`);function Yt(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function xl(t,e,i){let n=Object.keys(t).filter(r=>!e.has(r));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`)}function Rn(t){if(!Al.test(t))throw new Error(`Invalid Native change name: ${t}`)}function _v(t){if(!Al.test(t))throw new Error(`Invalid Native capability id: ${t}`)}function Tl(t,e){if(t.length===0||Me.isAbsolute(t)||/^(?:[A-Za-z]:|~|[\\/])/u.test(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`${e} must stay inside the Native change`)}function Ov(t,e){let i=Yt(t,`spec_changes[${e}]`);if(xl(i,Pv,`spec_changes[${e}]`),typeof i.capability!="string")throw new Error("spec change capability is required");if(_v(i.capability),i.operation!=="create"&&i.operation!=="replace"&&i.operation!=="remove")throw new Error(`Invalid spec operation for ${i.capability}`);let n=i.source,r=i.base_hash;if(n!==void 0&&typeof n!="string")throw new Error(`Spec source for ${i.capability} must be a string`);if(typeof n=="string"&&Tl(n,`Spec source for ${i.capability}`),i.operation==="create"){if(!n)throw new Error(`Create spec ${i.capability} requires source`);if(r!==null)throw new Error(`Create spec ${i.capability} requires null base_hash`)}else if(i.operation==="replace"){if(!n)throw new Error(`Replace spec ${i.capability} requires source`);if(typeof r!="string"||!La.test(r))throw new Error(`Replace spec ${i.capability} requires a SHA-256 base_hash`)}else{if(n!==void 0)throw new Error(`Remove spec ${i.capability} forbids source`);if(typeof r!="string"||!La.test(r))throw new Error(`Remove spec ${i.capability} requires a SHA-256 base_hash`)}return{capability:i.capability,operation:i.operation,...typeof n=="string"?{source:n}:{},base_hash:r}}function jv(t){return/^\d{4}-\d{2}-\d{2}$/u.test(t)?new Date(`${t}T00:00:00.000Z`).toISOString().slice(0,10)===t:!1}function Ma(t,e){if(xl(t,e,De),typeof t.name!="string")throw new Error("Native change name is required");if(Rn(t.name),t.language!=="en"&&t.language!=="zh-CN")throw new Error("Native change language must be en or zh-CN");if(typeof t.phase!="string"||!Av.has(t.phase))throw new Error("Native change phase is invalid");if(t.brief!=="brief.md")throw new Error("Native change brief must be brief.md");if(t.approval!==null&&!xv.has(t.approval))throw new Error("Native change approval is invalid");if(!Array.isArray(t.spec_changes))throw new Error("Native spec_changes must be an array");let i=t.spec_changes.map(Ov),n=i.map(r=>r.capability).filter((r,a,o)=>o.indexOf(r)!==a);if(n.length>0)throw new Error(`Duplicate Native capability operation: ${[...new Set(n)].join(", ")}`);if(typeof t.verification_result!="string"||!Tv.has(t.verification_result))throw new Error("Native verification_result is invalid");if(t.verification_report!==null&&typeof t.verification_report!="string")throw new Error("Native verification_report must be a string or null");if(typeof t.verification_report=="string"&&Tl(t.verification_report,"Native verification_report"),typeof t.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof t.created_at!="string"||!jv(t.created_at))throw new Error("Native created_at must be a valid YYYY-MM-DD date");if(t.run_id!==null&&(typeof t.run_id!="string"||t.run_id.length===0))throw new Error("Native run_id must be a non-empty string or null");return{name:t.name,language:t.language,phase:t.phase,brief:"brief.md",approval:t.approval,spec_changes:i,verification_result:t.verification_result,verification_report:t.verification_report,archived:t.archived,created_at:t.created_at,run_id:t.run_id}}function Ba(t){let e=Yt(t,De);if(e.schema!==Fe)throw new Error(`Expected ${Fe}`);return{schema:Fe,...Ma(e,Cv)}}function Ut(t,e){if(!Number.isSafeInteger(t)||t<1)throw new Error(`${e} must be a positive integer`);return t}function $a(t,e,i){if(t===null)return null;let n=typeof t=="string"?Iv.exec(t):null;if(!n||n[1]!==i)throw new Error(`${e} must be null or runtime/evidence/${i}/.json relative to the Native change`);return t}function Hv(t){if(t==null)return null;if(typeof t!="string"||!La.test(t))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return t}function $v(t){if(t===void 0)return"legacy-v1";if(t!=="legacy-v1")throw new Error("Native verification_protocol must be legacy-v1");return t}function Da(t){let e=Yt(t,De);if(e.schema!==Le)throw new Error(`Expected ${Le}`);if(Ut(e.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${Le} minimum_runtime_version must be 2`);return{schema:Le,minimum_runtime_version:2,revision:Ut(e.revision,"Native v2 revision"),...Ma(e,Pl)}}function qa(t){let e=Yt(t,De);if(e.schema!==$e){if(e.schema===Fe||e.schema===Le){let o=e.schema===Fe?Ba(e):Da(e);throw new kn(o.name,o.schema)}throw new Be(typeof e.schema=="string"?e.schema:"(missing)",typeof e.minimum_runtime_version=="number"?e.minimum_runtime_version:null)}let i=Ut(e.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)throw new Be(e.schema,i);if(i!==3)throw new Error(`Native ${e.schema} minimum_runtime_version must be ${3}`);let n=Ut(e.revision,"Native revision"),r=Ma(e,Rv),a=Hv(e.approved_contract_hash);if(r.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:$e,minimum_runtime_version:3,revision:n,verification_protocol:$v(e.verification_protocol),...r,approved_contract_hash:a,implementation_scope:$a(e.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:$a(e.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:$a(e.partial_allowance,"Native partial_allowance","allowances")}}function Lv(t){let e=Yt(t,De);if(e.schema===Fe){let r=Ba(e);return{status:"migration-required",schema:r.schema,minimumRuntimeVersion:1,state:r,message:`Native change ${r.name} requires migration to ${$e}`}}if(e.schema===Le){let r=Da(e);return{status:"migration-required",schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,state:r,message:`Native change ${r.name} requires migration to ${$e}`}}if(e.schema!==$e){let r=typeof e.minimum_runtime_version=="number"&&Number.isSafeInteger(e.minimum_runtime_version)?e.minimum_runtime_version:null;return{status:"runtime-incompatible",schema:typeof e.schema=="string"?e.schema:"(missing)",minimumRuntimeVersion:r,state:null,message:new Be(typeof e.schema=="string"?e.schema:"(missing)",r).message}}let i=Ut(e.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)return{status:"runtime-incompatible",schema:e.schema,minimumRuntimeVersion:i,state:null,message:new Be(e.schema,i).message};let n=qa(e);return{status:"current",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n}}function Y(t,e){Rn(e);let i=Me.join(t.changesDir,e);if(!ne(t.changesDir,i))throw new Error("Native change path escaped");return i}async function Va(t,e){let i=Me.join(Y(t,e),"runtime","schema-migration.json");await H(t.nativeRoot,i);try{return await Ev.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}var Fv=256*1024;async function Mv(t,e=Me.dirname(t)){let i=Me.relative(e,t).split(Me.sep).join("/"),n=await Ne({root:e,ref:i,maxBytes:Fv}),r=(0,Fa.parseDocument)(n.text,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`Invalid Native change file ${t}: ${r.errors[0].message}`);return r.toJS()}async function Bv(t,e){let i=Me.join(Y(t,e),De);await H(t.nativeRoot,i);let n=Lv(await Mv(i,t.nativeRoot));if(n.state&&n.state.name!==e)throw new Error(`Native change directory/name mismatch: ${e}`);return await Va(t,e)?{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimumRuntimeVersion,state:n.state,message:`Native schema migration is incomplete for ${e}; run doctor --repair`}:(n.status==="current"&&n.state&&await Dv(t,n.state),n)}async function Dv(t,e){if(await hl(t,e.name)!==null&&e.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${e.verification_protocol}`)}async function se(t,e){let i=await Bv(t,e);if(i.status==="migration-required")throw new kn(e,i.schema);if(i.status==="runtime-incompatible"||!i.state)throw new Be(i.schema,i.minimumRuntimeVersion);return await Cl(t,e),i.state}import qv from"path";var Wa="comet.selection.v2",Vv=16*1024;function _l(t){return qv.join(t,".comet","current-change.json")}function Wv(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function Il(t){return t===null||typeof t=="string"}function zv(t){let e;try{e=JSON.parse(t)}catch(i){throw new Error(`current change selection contains invalid JSON: ${i instanceof Error?i.message:String(i)}`,{cause:i})}if(!Wv(e))throw new Error("current change selection must be a JSON object");if(e.version===1){if(typeof e.change!="string")throw new Error("legacy current change selection change must be a string");if(e.branch!==void 0&&!Il(e.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:Wa,workflow:"classic",change:e.change,branch:e.branch??null},legacy:!0}}if(e.schema!==Wa)throw new Error(`current change selection schema must be ${Wa}`);if(e.workflow!=="native"&&e.workflow!=="classic")throw new Error("current change selection workflow must be native or classic");if(typeof e.change!="string")throw new Error("current change selection change must be a string");if(!Il(e.branch))throw new Error("current change selection branch must be a string or null");if(e.workflow==="native"&&e.branch!==null)throw new Error("Native current change selection branch must be null");return{selection:e,legacy:!1}}async function Ol(t){let e;try{let n=_l(t),{bytes:r}=await tt(n,Vv,{label:"current change selection"});e=r.toString("utf8")}catch(n){if(n.code==="ENOENT")return{status:"missing"};throw new Error(`cannot read current change selection: ${n instanceof Error?n.message:String(n)}`,{cause:n})}return{status:"selected",...zv(e)}}var dS=16*1024;async function Jv(t){let e=await Ol(t.projectRoot);return e.status==="missing"||e.selection.workflow!=="native"?null:(Rn(e.selection.change),e.selection)}async function jl(t){let e=await Jv(t);return e?(await se(t,e.change),e.change):null}function Pn(t,e){let i=st.relative(t,e);return i===""||!i.startsWith("..")&&!st.isAbsolute(i)}function Kv(t,e,i){return i.targets.length>0&&i.targets.every(n=>{let r=st.resolve(t,n);return Pn(t,r)?st.relative(t,r).replaceAll("\\","/")===".comet/config.yaml"||Pn(e,r):!0})}async function Uv(t){let e=await nt(t);if(!e||!(e.workflows??[e.default_workflow]).includes("native"))return null;let i=await un(t,e.native.artifact_root),n;try{n=await Gv.readdir(i.changesDir,{withFileTypes:!0})}catch(a){if(a.code==="ENOENT")return{paths:i,changes:[]};throw a}let r=[];for(let a of n.sort((o,s)=>o.name.localeCompare(s.name))){if(!a.isDirectory()||a.isSymbolicLink())continue;let o=await se(i,a.name);o.archived||r.push(o)}return{paths:i,changes:r}}var Yv=Ua("nativeActiveContext",t=>Uv(t));async function Hl(){let{intent:t,targets:e}=await to();return{intent:t,targets:e}}async function $l(t,e,i){let n=await Yv(t);if(!n)return{allowed:!0,reason:"Native workflow is not enabled"};if(e.intent==="non-write")return{allowed:!0,reason:"Hook event is not a write"};if(n.changes.length===0)return{allowed:!0,reason:Kv(t,n.paths.nativeRoot,e)?"Native control artifact write":"No Native changes exist"};let r;if(i){if(r=n.changes.find(s=>s.name===i),!r)return{allowed:!1,reason:`Selected Native change ${i} is missing or archived; resume /comet-native before retrying`,workflow:"native",change:i}}else if(n.changes.length===1)r=n.changes[0];else{let s=await jl(n.paths);if(r=n.changes.find(c=>c.name===s),!r)return{allowed:!1,reason:"Multiple Native changes are active; select the change to resume before writing code",workflow:"native"}}if(r.phase==="build")return{allowed:!0,reason:"Native change is in Build",workflow:"native",phase:r.phase,change:r.name};if(e.intent==="unknown"||e.targets.length===0)return{allowed:!0,reason:"Hook write target was not attributed to the guarded project",workflow:"native",phase:r.phase,change:r.name};let a=!1,o=!1;for(let s of e.targets){let c=st.resolve(t,s);if(!Pn(t,c)){o=!0;continue}if(st.relative(t,c).replaceAll("\\","/")===".comet/config.yaml"||Pn(n.paths.nativeRoot,c)){a=!0;continue}return{allowed:!1,reason:`Native change ${r.name} is in ${r.phase}; implementation writes are only allowed in build. Resume /comet-native to continue safely`,workflow:"native",phase:r.phase,change:r.name}}return{allowed:!0,reason:a?"Native control artifact write":o?"Write target is outside the guarded project":"No guarded write target was provided",workflow:"native",phase:r.phase,change:r.name}}import _g from"path";var Qv=["Outcome","Scope","Non-goals","Acceptance examples"],$S=[...Qv,"Constraints and invariants","Decisions","Open questions","Verification expectations"];import{createHash as Zv}from"crypto";function X(t){throw new TypeError(`Value is not valid canonical JSON: ${t}`)}function eg(t,e){e.has(t)&&X("cyclic structures are not supported"),e.add(t);try{let i=Object.keys(t);for(let n=0;nn!==String(r)))&&X("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(t).length>0&&X("symbol properties are not supported"),`[${t.map(n=>za(n,e)).join(",")}]`}finally{e.delete(t)}}function tg(t,e){let i=Object.getPrototypeOf(t);i!==Object.prototype&&i!==null&&X("only plain objects are supported"),e.has(t)&&X("cyclic structures are not supported"),Object.getOwnPropertySymbols(t).length>0&&X("symbol properties are not supported"),e.add(t);try{let n=Object.getOwnPropertyDescriptors(t);return`{${Object.keys(t).sort().map(o=>{let s=n[o];return(!s||!("value"in s))&&X("accessor properties are not supported"),`${JSON.stringify(o)}:${za(s.value,e)}`}).join(",")}}`}finally{e.delete(t)}}function za(t,e){if(t===null)return"null";switch(typeof t){case"boolean":return t?"true":"false";case"string":return JSON.stringify(t);case"number":return Number.isFinite(t)||X("numbers must be finite"),JSON.stringify(Object.is(t,-0)?0:t);case"object":return Array.isArray(t)?eg(t,e):tg(t,e);case"bigint":case"function":case"symbol":case"undefined":return X(`${typeof t} values are not supported`)}return X("unsupported value type")}function Ja(t){return za(t,new Set)}function Q(t,e){if(t.length===0)throw new TypeError("Canonical hash tag must be non-empty");if(/[\r\n]/u.test(t))throw new TypeError("Canonical hash tag must not contain a line break");return Zv("sha256").update(`${t} +${Ja(e)}`).digest("hex")}var ig=Object.freeze({maxChanges:32,maxSpecsPerChange:64,maxArtifactsPerChange:128,maxTotalSpecs:512,maxTotalArtifacts:1024,maxSignalsPerRelationship:8,maxRelationships:256,maxSerializedBytes:64*1024,maxNameBytes:128,maxCapabilityBytes:128,maxArtifactPathBytes:512});var Ll=1024*1024;var Ml="scoped-text-safety",ng=1,rg=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128});var ag="comet.native.checker-policy.v1";var eE=Q(ag,{policy:Ml,version:ng,limits:rg,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"});var og=["contract-before-does-not-match-scope","implementation-before-does-not-match-scope","contract-changed-during-check","implementation-changed-during-check","contract-after-does-not-match-scope","implementation-after-does-not-match-scope"],tE=new Set(og);var cg=Ll,yE=3*cg;var Bl={root:"/comet/native-runtime",packageKind:"runtime",definition:{apiVersion:"comet/v1alpha1",kind:"Skill",metadata:{name:"comet-native-runtime",version:"3",description:"Comet-owned state runtime for the Native workflow."},goal:{statement:"Advance a Native change only after its current guard passes.",inputs:[],outputs:[],success:["The Native change and Run state agree on the next phase."]},orchestration:{mode:"deterministic",entry:"shape",steps:[{id:"shape",action:{type:"checkpoint"},next:"build"},{id:"build",action:{type:"checkpoint"},next:"verify"},{id:"verify",action:{type:"checkpoint"},next:"archive"},{id:"archive",action:{type:"checkpoint"}}]},skills:[],agents:[],tools:[]},guardrails:{allowedSkills:[],allowedAgents:[],allowedTools:[],maxIterations:Number.MAX_SAFE_INTEGER,maxRetriesPerAction:2,confirmationRequiredFor:[]},evals:[]},lg=D("comet-native-runtime:v3:semantic-repair-budget"),GE=[{skillVersion:"2",skillHash:D("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:D("comet-native-runtime:v1")}];var ql=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],PC=new Set(ql),mg=new Set([...ql,"minimum_runtime_version","revision"]),AC=new Set([...mg,"operation"]),xC=512*1024,vg=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),TC=new Set([...vg,"implementationScopeHash","repairScopeHash","repairStagnation"]);var OC=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),Vl=Object.freeze({maxCriteria:1024});var BC={maxAcceptanceCriteria:Vl.maxCriteria};var zC={maxSpecs:64,maxFileBytes:Zi,maxTotalBytes:4*1024*1024};import{execFile as Cg,spawn as OR}from"node:child_process";import{promisify as Rg}from"node:util";var iR={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024};var ER=512*1024;var Xt=class extends Error{recovery;constructor(e,i){super(e),this.name="NativeReceiptScopeStaleError",this.recovery=i}};var KR=64*1024;var UR=3600*1e3;var YR=Rg(Cg);var XR=["$ProgressPreference = 'SilentlyContinue'","$encoded = $env:COMET_NATIVE_COMMAND_PAYLOAD","Remove-Item Env:COMET_NATIVE_COMMAND_PAYLOAD -ErrorAction SilentlyContinue","$json = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($encoded))","$payload = ConvertFrom-Json $json","$commandArgs = @($payload.arguments)","& $payload.command @commandArgs","if ($null -eq $LASTEXITCODE) { if ($?) { exit 0 } else { exit 1 } }","exit $LASTEXITCODE"].join("; ");var xn=class extends Error{details;constructor(e){let i=e.length===0?"Native verification receipt binding is invalid":`Native verification receipt binding is invalid (${e.length} receipt(s)): ${e.map(n=>`${n.ref}${n.acceptanceId?`[${n.acceptanceId}]`:""} -> ${n.mismatches.join("; ")}`).join(" | ")}`;super(i),this.name="NativeVerificationReceiptBindingError",this.details=e}};var LP={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};var UP=16*1024*1024,YP=256*1024,XP=16*1024;var FA=16*1024*1024,Tn=class extends Error{constructor(i,n,r,a){super(`Canonical spec conflict for ${i}: expected ${n??"(missing)"}, actual ${r??"(missing)"}`);this.capability=i;this.expectedHash=n;this.actualHash=r;this.canonicalPath=a;this.name="NativeSpecConflictError"}capability;expectedHash;actualHash;canonicalPath;code="native-spec-conflict"},In=class extends Error{constructor(i,n=i.ready?"Native Archive preflight no longer matches the expected hash":`Native Archive preflight is blocked: ${i.findingCodes.join(", ")}`){super(n);this.preflight=i;this.name="NativeArchivePreflightError"}preflight;code="native-archive-preflight"};var UA=10*1024*1024,ce=class extends Error{};function zl(t,e){let i=t.flatMap((n,r)=>n===e?[r]:[]);if(i.length>1)throw new ce(`${e} may only be provided once`);return i.length===0?!1:(t.splice(i[0],1),!0)}function _n(t,e){let i=t.flatMap((a,o)=>a===e?[o]:[]);if(i.length>1)throw new ce(`${e} may only be provided once`);if(i.length===0)return;let n=i[0],r=t[n+1];if(r===void 0||r.startsWith("--"))throw new ce(`${e} requires a value`);return t.splice(n,2),r}function Jl(t){if(t.length>0)throw new ce(`Unexpected argument: ${t[0]}`)}async function Gl(t){return t?_g.resolve(t):Pa(process.cwd())}function Kl(t,e){if(e instanceof ce)return{command:t,exitCode:64,error:{code:"usage",message:e.message}};if(e instanceof Tn)return{command:t,exitCode:73,data:{capability:e.capability,expectedHash:e.expectedHash,actualHash:e.actualHash,canonicalPath:e.canonicalPath},error:{code:"conflict",message:e.message}};if(e instanceof In)return{command:t,exitCode:73,data:e.preflight,error:{code:"conflict",message:e.message}};if(e instanceof Sn)return{command:t,exitCode:73,data:{change:e.change,expectedRevision:e.expectedRevision,actualRevision:e.actualRevision,outcome:"revision-conflict"},error:{code:"conflict",message:e.message}};if(e instanceof En)return{command:t,exitCode:73,data:{requestedIsolation:e.requestedIsolation,activeChanges:e.activeChanges,requiredAction:"create-native-worktree"},error:{code:"workspace-isolation-required",message:e.message}};if(e instanceof Cn)return{command:t,exitCode:65,data:{change:e.change,complete:!1,omittedCount:e.omittedCount,omittedByReason:e.omittedByReason,samplePaths:e.samplePaths,sampleTruncated:e.sampleTruncated,effectiveLimits:e.effectiveLimits,policyHash:e.policyHash,configPath:".comet/config.yaml",supportedFixes:["increase native.snapshot.max_files, native.snapshot.max_total_bytes, or native.snapshot.max_duration_ms","add an explicit native.snapshot.exclude pattern for data outside implementation scope"],requiredAction:"resolve-native-baseline"},error:{code:"baseline-incomplete",message:e.message}};if(e instanceof xn)return{command:t,exitCode:65,data:{receiptBindingFailures:e.details},error:{code:"invalid-data",message:e.message}};if(e instanceof Xt)return{command:t,exitCode:65,data:e.recovery,error:{code:"implementation-scope-stale",message:e.message}};if(e instanceof Error){let i=e.code;if(i&&new Set(["EACCES","EPERM","EIO","EMFILE","ENFILE","ENOSPC","EROFS"]).has(i))return{command:t,exitCode:70,error:{code:"internal",message:e.message}};let n=/\b(lock|transaction|conflict|occupied|incomplete|recovery)\b/iu.test(e.message);return{command:t,exitCode:n?73:65,error:{code:n?"conflict":"invalid-data",message:e.message}}}return{command:t,exitCode:70,error:{code:"internal",message:String(e)}}}function Ul(t,e){return e?{exitCode:t.exitCode,stdout:JSON.stringify({command:t.command,exitCode:t.exitCode,...t.data===void 0?{}:{data:t.data},...t.error===void 0?{}:{error:t.error}})+` `}:t.error?{exitCode:t.exitCode,stderr:t.error.message}:{exitCode:t.exitCode,stdout:t.text}}async function Yl(t,e){let i=_n(t,"--hook-output");if(i!==void 0&&i!=="copilot")throw new ce("--hook-output must be copilot");Jl(t);let n=await $l(e,await Hl());return i==="copilot"?{command:"hook-guard",exitCode:0,data:n,text:n.allowed?`{} `:`${JSON.stringify({permissionDecision:"deny",permissionDecisionReason:n.reason})} `}:n.allowed?{command:"hook-guard",exitCode:0,data:n}:{command:"hook-guard",exitCode:2,data:n,error:{code:"blocked",message:n.reason}}}function Og(t){return{exitCode:t.exitCode,stdout:JSON.stringify({command:t.command,exitCode:t.exitCode,...t.data===void 0?{}:{data:t.data},...t.error===void 0?{}:{error:t.error}})+` diff --git a/assets/skills/comet-native/scripts/comet-native-runtime.mjs b/assets/skills/comet-native/scripts/comet-native-runtime.mjs index b859d2774..aa62d4794 100644 --- a/assets/skills/comet-native/scripts/comet-native-runtime.mjs +++ b/assets/skills/comet-native/scripts/comet-native-runtime.mjs @@ -1,17 +1,17 @@ #!/usr/bin/env node import { createRequire as __cometCreateRequire } from 'module'; const require = __cometCreateRequire(import.meta.url); -var kE=Object.create;var Hp=Object.defineProperty;var SE=Object.getOwnPropertyDescriptor;var EE=Object.getOwnPropertyNames;var RE=Object.getPrototypeOf,CE=Object.prototype.hasOwnProperty;var As=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,i)=>(typeof require<"u"?require:t)[i]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var P=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(i){throw t=0,i}};var PE=(e,t,i,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of EE(t))!CE.call(e,r)&&r!==i&&Hp(e,r,{get:()=>t[r],enumerable:!(n=SE(t,r))||n.enumerable});return e};var Ts=(e,t,i)=>(i=e!=null?kE(RE(e)):{},PE(t||!e||!e.__esModule?Hp(i,"default",{value:e,enumerable:!0}):i,e));var K=P(Be=>{"use strict";var $u=Symbol.for("yaml.alias"),Lp=Symbol.for("yaml.document"),js=Symbol.for("yaml.map"),Bp=Symbol.for("yaml.pair"),Hu=Symbol.for("yaml.scalar"),Os=Symbol.for("yaml.seq"),xi=Symbol.for("yaml.node.type"),_E=e=>!!e&&typeof e=="object"&&e[xi]===$u,IE=e=>!!e&&typeof e=="object"&&e[xi]===Lp,jE=e=>!!e&&typeof e=="object"&&e[xi]===js,OE=e=>!!e&&typeof e=="object"&&e[xi]===Bp,qp=e=>!!e&&typeof e=="object"&&e[xi]===Hu,$E=e=>!!e&&typeof e=="object"&&e[xi]===Os;function Vp(e){if(e&&typeof e=="object")switch(e[xi]){case js:case Os:return!0}return!1}function HE(e){if(e&&typeof e=="object")switch(e[xi]){case $u:case js:case Hu:case Os:return!0}return!1}var DE=e=>(qp(e)||Vp(e))&&!!e.anchor;Be.ALIAS=$u;Be.DOC=Lp;Be.MAP=js;Be.NODE_TYPE=xi;Be.PAIR=Bp;Be.SCALAR=Hu;Be.SEQ=Os;Be.hasAnchor=DE;Be.isAlias=_E;Be.isCollection=Vp;Be.isDocument=IE;Be.isMap=jE;Be.isNode=HE;Be.isPair=OE;Be.isScalar=qp;Be.isSeq=$E});var Oa=P(Du=>{"use strict";var _e=K(),rt=Symbol("break visit"),Wp=Symbol("skip children"),oi=Symbol("remove node");function $s(e,t){let i=Jp(t);_e.isDocument(e)?Tr(null,e.contents,i,Object.freeze([e]))===oi&&(e.contents=null):Tr(null,e,i,Object.freeze([]))}$s.BREAK=rt;$s.SKIP=Wp;$s.REMOVE=oi;function Tr(e,t,i,n){let r=zp(e,t,i,n);if(_e.isNode(r)||_e.isPair(r))return Gp(e,n,r),Tr(e,r,i,n);if(typeof r!="symbol"){if(_e.isCollection(t)){n=Object.freeze(n.concat(t));for(let a=0;a{"use strict";var Up=K(),ME=Oa(),FE={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},LE=e=>e.replace(/[!,[\]{}]/g,t=>FE[t]),$a=class e{constructor(t,i){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,i)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},e.defaultTags);break}return t}add(t,i){this.atNextDocument&&(this.yaml={explicit:e.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},e.defaultTags),this.atNextDocument=!1);let n=t.trim().split(/[ \t]+/),r=n.shift();switch(r){case"%TAG":{if(n.length!==2&&(i(0,"%TAG directive should contain exactly two parts"),n.length<2))return!1;let[a,o]=n;return this.tags[a]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,n.length!==1)return i(0,"%YAML directive should contain exactly one part"),!1;let[a]=n;if(a==="1.1"||a==="1.2")return this.yaml.version=a,!0;{let o=/^\d+\.\d+$/.test(a);return i(6,`Unsupported YAML version ${a}`,o),!1}}default:return i(0,`Unknown directive ${r}`,!0),!1}}tagName(t,i){if(t==="!")return"!";if(t[0]!=="!")return i(`Not a valid tag: ${t}`),null;if(t[1]==="<"){let o=t.slice(2,-1);return o==="!"||o==="!!"?(i(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&i("Verbatim tags must end with a >"),o)}let[,n,r]=t.match(/^(.*!)([^!]*)$/s);r||i(`The ${t} tag has no suffix`);let a=this.tags[n];if(a)try{return a+decodeURIComponent(r)}catch(o){return i(String(o)),null}return n==="!"?t:(i(`Could not resolve tag: ${t}`),null)}tagString(t){for(let[i,n]of Object.entries(this.tags))if(t.startsWith(n))return i+LE(t.substring(n.length));return t[0]==="!"?t:`!<${t}>`}toString(t){let i=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],n=Object.entries(this.tags),r;if(t&&n.length>0&&Up.isNode(t.contents)){let a={};ME.visit(t.contents,(o,s)=>{Up.isNode(s)&&s.tag&&(a[s.tag]=!0)}),r=Object.keys(a)}else r=[];for(let[a,o]of n)a==="!!"&&o==="tag:yaml.org,2002:"||(!t||r.some(s=>s.startsWith(o)))&&i.push(`%TAG ${a} ${o}`);return i.join(` -`)}};$a.defaultYaml={explicit:!1,version:"1.2"};$a.defaultTags={"!!":"tag:yaml.org,2002:"};Kp.Directives=$a});var Ds=P(Ha=>{"use strict";var Yp=K(),BE=Oa();function qE(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let i=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw new Error(i)}return!0}function Xp(e){let t=new Set;return BE.visit(e,{Value(i,n){n.anchor&&t.add(n.anchor)}}),t}function Qp(e,t){for(let i=1;;++i){let n=`${e}${i}`;if(!t.has(n))return n}}function VE(e,t){let i=[],n=new Map,r=null;return{onAnchor:a=>{i.push(a),r??(r=Xp(e));let o=Qp(t,r);return r.add(o),o},setAnchors:()=>{for(let a of i){let o=n.get(a);if(typeof o=="object"&&o.anchor&&(Yp.isScalar(o.node)||Yp.isCollection(o.node)))o.node.anchor=o.anchor;else{let s=new Error("Failed to resolve repeated object (this should not happen)");throw s.source=a,s}}},sourceObjects:n}}Ha.anchorIsValid=qE;Ha.anchorNames=Xp;Ha.createNodeAnchors=VE;Ha.findNewAnchor=Qp});var Fu=P(Zp=>{"use strict";function Da(e,t,i,n){if(n&&typeof n=="object")if(Array.isArray(n))for(let r=0,a=n.length;r{"use strict";var WE=K();function em(e,t,i){if(Array.isArray(e))return e.map((n,r)=>em(n,String(r),i));if(e&&typeof e.toJSON=="function"){if(!i||!WE.hasAnchor(e))return e.toJSON(t,i);let n={aliasCount:0,count:1,res:void 0};i.anchors.set(e,n),i.onCreate=a=>{n.res=a,delete i.onCreate};let r=e.toJSON(t,i);return i.onCreate&&i.onCreate(r),r}return typeof e=="bigint"&&!i?.keep?Number(e):e}tm.toJS=em});var Ms=P(nm=>{"use strict";var JE=Fu(),im=K(),zE=en(),Lu=class{constructor(t){Object.defineProperty(this,im.NODE_TYPE,{value:t})}clone(){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(t.range=this.range.slice()),t}toJS(t,{mapAsMap:i,maxAliasCount:n,onAnchor:r,reviver:a}={}){if(!im.isDocument(t))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:t,keep:!0,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},s=zE.toJS(this,"",o);if(typeof r=="function")for(let{count:c,res:l}of o.anchors.values())r(l,c);return typeof a=="function"?JE.applyReviver(a,{"":s},"",s):s}};nm.NodeBase=Lu});var Ma=P(rm=>{"use strict";var GE=Ds(),UE=Oa(),Ir=K(),KE=Ms(),YE=en(),Bu=class extends KE.NodeBase{constructor(t){super(Ir.ALIAS),this.source=t,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(t,i){if(i?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let n;i?.aliasResolveCache?n=i.aliasResolveCache:(n=[],UE.visit(t,{Node:(a,o)=>{(Ir.isAlias(o)||Ir.hasAnchor(o))&&n.push(o)}}),i&&(i.aliasResolveCache=n));let r;for(let a of n){if(a===this)break;a.anchor===this.source&&(r=a)}return r}toJSON(t,i){if(!i)return{source:this.source};let{anchors:n,doc:r,maxAliasCount:a}=i,o=this.resolve(r,i);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let s=n.get(o);if(s||(YE.toJS(o,null,i),s=n.get(o)),s?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(a>=0&&(s.count+=1,s.aliasCount===0&&(s.aliasCount=Fs(r,o,n)),s.count*s.aliasCount>a)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return s.res}toString(t,i,n){let r=`*${this.source}`;if(t){if(GE.anchorIsValid(this.source),t.options.verifyAliasOrder&&!t.anchors.has(this.source)){let a=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(a)}if(t.implicitKey)return`${r} `}return r}};function Fs(e,t,i){if(Ir.isAlias(t)){let n=t.resolve(e),r=i&&n&&i.get(n);return r?r.count*r.aliasCount:0}else if(Ir.isCollection(t)){let n=0;for(let r of t.items){let a=Fs(e,r,i);a>n&&(n=a)}return n}else if(Ir.isPair(t)){let n=Fs(e,t.key,i),r=Fs(e,t.value,i);return Math.max(n,r)}return 1}rm.Alias=Bu});var Re=P(qu=>{"use strict";var XE=K(),QE=Ms(),ZE=en(),eR=e=>!e||typeof e!="function"&&typeof e!="object",tn=class extends QE.NodeBase{constructor(t){super(XE.SCALAR),this.value=t}toJSON(t,i){return i?.keep?this.value:ZE.toJS(this.value,t,i)}toString(){return String(this.value)}};tn.BLOCK_FOLDED="BLOCK_FOLDED";tn.BLOCK_LITERAL="BLOCK_LITERAL";tn.PLAIN="PLAIN";tn.QUOTE_DOUBLE="QUOTE_DOUBLE";tn.QUOTE_SINGLE="QUOTE_SINGLE";qu.Scalar=tn;qu.isScalarValue=eR});var Fa=P(om=>{"use strict";var tR=Ma(),Jn=K(),am=Re(),iR="tag:yaml.org,2002:";function nR(e,t,i){if(t){let n=i.filter(a=>a.tag===t),r=n.find(a=>!a.format)??n[0];if(!r)throw new Error(`Tag ${t} not found`);return r}return i.find(n=>n.identify?.(e)&&!n.format)}function rR(e,t,i){if(Jn.isDocument(e)&&(e=e.contents),Jn.isNode(e))return e;if(Jn.isPair(e)){let d=i.schema[Jn.MAP].createNode?.(i.schema,null,i);return d.items.push(e),d}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:n,onAnchor:r,onTagObj:a,schema:o,sourceObjects:s}=i,c;if(n&&e&&typeof e=="object"){if(c=s.get(e),c)return c.anchor??(c.anchor=r(e)),new tR.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=iR+t.slice(2));let l=nR(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let d=new am.Scalar(e);return c&&(c.node=d),d}l=e instanceof Map?o[Jn.MAP]:Symbol.iterator in Object(e)?o[Jn.SEQ]:o[Jn.MAP]}a&&(a(l),delete i.onTagObj);let u=l?.createNode?l.createNode(i.schema,e,i):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(i.schema,e,i):new am.Scalar(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}om.createNode=rR});var Bs=P(Ls=>{"use strict";var aR=Fa(),si=K(),oR=Ms();function Vu(e,t,i){let n=i;for(let r=t.length-1;r>=0;--r){let a=t[r];if(typeof a=="number"&&Number.isInteger(a)&&a>=0){let o=[];o[a]=n,n=o}else n=new Map([[a,n]])}return aR.createNode(n,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}var sm=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,Wu=class extends oR.NodeBase{constructor(t,i){super(t),Object.defineProperty(this,"schema",{value:i,configurable:!0,enumerable:!1,writable:!0})}clone(t){let i=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return t&&(i.schema=t),i.items=i.items.map(n=>si.isNode(n)||si.isPair(n)?n.clone(t):n),this.range&&(i.range=this.range.slice()),i}addIn(t,i){if(sm(t))this.add(i);else{let[n,...r]=t,a=this.get(n,!0);if(si.isCollection(a))a.addIn(r,i);else if(a===void 0&&this.schema)this.set(n,Vu(this.schema,r,i));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}}deleteIn(t){let[i,...n]=t;if(n.length===0)return this.delete(i);let r=this.get(i,!0);if(si.isCollection(r))return r.deleteIn(n);throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}getIn(t,i){let[n,...r]=t,a=this.get(n,!0);return r.length===0?!i&&si.isScalar(a)?a.value:a:si.isCollection(a)?a.getIn(r,i):void 0}hasAllNullValues(t){return this.items.every(i=>{if(!si.isPair(i))return!1;let n=i.value;return n==null||t&&si.isScalar(n)&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn(t){let[i,...n]=t;if(n.length===0)return this.has(i);let r=this.get(i,!0);return si.isCollection(r)?r.hasIn(n):!1}setIn(t,i){let[n,...r]=t;if(r.length===0)this.set(n,i);else{let a=this.get(n,!0);if(si.isCollection(a))a.setIn(r,i);else if(a===void 0&&this.schema)this.set(n,Vu(this.schema,r,i));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}}};Ls.Collection=Wu;Ls.collectionFromPath=Vu;Ls.isEmptyPath=sm});var La=P(qs=>{"use strict";var sR=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function Ju(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var cR=(e,t,i)=>e.endsWith(` +var kE=Object.create;var Dp=Object.defineProperty;var SE=Object.getOwnPropertyDescriptor;var EE=Object.getOwnPropertyNames;var RE=Object.getPrototypeOf,CE=Object.prototype.hasOwnProperty;var As=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,i)=>(typeof require<"u"?require:t)[i]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var P=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(i){throw t=0,i}};var PE=(e,t,i,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of EE(t))!CE.call(e,r)&&r!==i&&Dp(e,r,{get:()=>t[r],enumerable:!(n=SE(t,r))||n.enumerable});return e};var Ts=(e,t,i)=>(i=e!=null?kE(RE(e)):{},PE(t||!e||!e.__esModule?Dp(i,"default",{value:e,enumerable:!0}):i,e));var K=P(Be=>{"use strict";var $u=Symbol.for("yaml.alias"),Bp=Symbol.for("yaml.document"),js=Symbol.for("yaml.map"),qp=Symbol.for("yaml.pair"),Hu=Symbol.for("yaml.scalar"),Os=Symbol.for("yaml.seq"),xi=Symbol.for("yaml.node.type"),_E=e=>!!e&&typeof e=="object"&&e[xi]===$u,IE=e=>!!e&&typeof e=="object"&&e[xi]===Bp,jE=e=>!!e&&typeof e=="object"&&e[xi]===js,OE=e=>!!e&&typeof e=="object"&&e[xi]===qp,Vp=e=>!!e&&typeof e=="object"&&e[xi]===Hu,$E=e=>!!e&&typeof e=="object"&&e[xi]===Os;function Wp(e){if(e&&typeof e=="object")switch(e[xi]){case js:case Os:return!0}return!1}function HE(e){if(e&&typeof e=="object")switch(e[xi]){case $u:case js:case Hu:case Os:return!0}return!1}var DE=e=>(Vp(e)||Wp(e))&&!!e.anchor;Be.ALIAS=$u;Be.DOC=Bp;Be.MAP=js;Be.NODE_TYPE=xi;Be.PAIR=qp;Be.SCALAR=Hu;Be.SEQ=Os;Be.hasAnchor=DE;Be.isAlias=_E;Be.isCollection=Wp;Be.isDocument=IE;Be.isMap=jE;Be.isNode=HE;Be.isPair=OE;Be.isScalar=Vp;Be.isSeq=$E});var Oa=P(Du=>{"use strict";var _e=K(),rt=Symbol("break visit"),Jp=Symbol("skip children"),oi=Symbol("remove node");function $s(e,t){let i=zp(t);_e.isDocument(e)?Tr(null,e.contents,i,Object.freeze([e]))===oi&&(e.contents=null):Tr(null,e,i,Object.freeze([]))}$s.BREAK=rt;$s.SKIP=Jp;$s.REMOVE=oi;function Tr(e,t,i,n){let r=Gp(e,t,i,n);if(_e.isNode(r)||_e.isPair(r))return Up(e,n,r),Tr(e,r,i,n);if(typeof r!="symbol"){if(_e.isCollection(t)){n=Object.freeze(n.concat(t));for(let a=0;a{"use strict";var Kp=K(),ME=Oa(),FE={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},LE=e=>e.replace(/[!,[\]{}]/g,t=>FE[t]),$a=class e{constructor(t,i){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,i)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},e.defaultTags);break}return t}add(t,i){this.atNextDocument&&(this.yaml={explicit:e.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},e.defaultTags),this.atNextDocument=!1);let n=t.trim().split(/[ \t]+/),r=n.shift();switch(r){case"%TAG":{if(n.length!==2&&(i(0,"%TAG directive should contain exactly two parts"),n.length<2))return!1;let[a,o]=n;return this.tags[a]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,n.length!==1)return i(0,"%YAML directive should contain exactly one part"),!1;let[a]=n;if(a==="1.1"||a==="1.2")return this.yaml.version=a,!0;{let o=/^\d+\.\d+$/.test(a);return i(6,`Unsupported YAML version ${a}`,o),!1}}default:return i(0,`Unknown directive ${r}`,!0),!1}}tagName(t,i){if(t==="!")return"!";if(t[0]!=="!")return i(`Not a valid tag: ${t}`),null;if(t[1]==="<"){let o=t.slice(2,-1);return o==="!"||o==="!!"?(i(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&i("Verbatim tags must end with a >"),o)}let[,n,r]=t.match(/^(.*!)([^!]*)$/s);r||i(`The ${t} tag has no suffix`);let a=this.tags[n];if(a)try{return a+decodeURIComponent(r)}catch(o){return i(String(o)),null}return n==="!"?t:(i(`Could not resolve tag: ${t}`),null)}tagString(t){for(let[i,n]of Object.entries(this.tags))if(t.startsWith(n))return i+LE(t.substring(n.length));return t[0]==="!"?t:`!<${t}>`}toString(t){let i=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],n=Object.entries(this.tags),r;if(t&&n.length>0&&Kp.isNode(t.contents)){let a={};ME.visit(t.contents,(o,s)=>{Kp.isNode(s)&&s.tag&&(a[s.tag]=!0)}),r=Object.keys(a)}else r=[];for(let[a,o]of n)a==="!!"&&o==="tag:yaml.org,2002:"||(!t||r.some(s=>s.startsWith(o)))&&i.push(`%TAG ${a} ${o}`);return i.join(` +`)}};$a.defaultYaml={explicit:!1,version:"1.2"};$a.defaultTags={"!!":"tag:yaml.org,2002:"};Yp.Directives=$a});var Ds=P(Ha=>{"use strict";var Xp=K(),BE=Oa();function qE(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let i=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw new Error(i)}return!0}function Qp(e){let t=new Set;return BE.visit(e,{Value(i,n){n.anchor&&t.add(n.anchor)}}),t}function Zp(e,t){for(let i=1;;++i){let n=`${e}${i}`;if(!t.has(n))return n}}function VE(e,t){let i=[],n=new Map,r=null;return{onAnchor:a=>{i.push(a),r??(r=Qp(e));let o=Zp(t,r);return r.add(o),o},setAnchors:()=>{for(let a of i){let o=n.get(a);if(typeof o=="object"&&o.anchor&&(Xp.isScalar(o.node)||Xp.isCollection(o.node)))o.node.anchor=o.anchor;else{let s=new Error("Failed to resolve repeated object (this should not happen)");throw s.source=a,s}}},sourceObjects:n}}Ha.anchorIsValid=qE;Ha.anchorNames=Qp;Ha.createNodeAnchors=VE;Ha.findNewAnchor=Zp});var Fu=P(em=>{"use strict";function Da(e,t,i,n){if(n&&typeof n=="object")if(Array.isArray(n))for(let r=0,a=n.length;r{"use strict";var WE=K();function tm(e,t,i){if(Array.isArray(e))return e.map((n,r)=>tm(n,String(r),i));if(e&&typeof e.toJSON=="function"){if(!i||!WE.hasAnchor(e))return e.toJSON(t,i);let n={aliasCount:0,count:1,res:void 0};i.anchors.set(e,n),i.onCreate=a=>{n.res=a,delete i.onCreate};let r=e.toJSON(t,i);return i.onCreate&&i.onCreate(r),r}return typeof e=="bigint"&&!i?.keep?Number(e):e}im.toJS=tm});var Ms=P(rm=>{"use strict";var JE=Fu(),nm=K(),zE=en(),Lu=class{constructor(t){Object.defineProperty(this,nm.NODE_TYPE,{value:t})}clone(){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(t.range=this.range.slice()),t}toJS(t,{mapAsMap:i,maxAliasCount:n,onAnchor:r,reviver:a}={}){if(!nm.isDocument(t))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:t,keep:!0,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},s=zE.toJS(this,"",o);if(typeof r=="function")for(let{count:c,res:l}of o.anchors.values())r(l,c);return typeof a=="function"?JE.applyReviver(a,{"":s},"",s):s}};rm.NodeBase=Lu});var Ma=P(am=>{"use strict";var GE=Ds(),UE=Oa(),Ir=K(),KE=Ms(),YE=en(),Bu=class extends KE.NodeBase{constructor(t){super(Ir.ALIAS),this.source=t,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(t,i){if(i?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let n;i?.aliasResolveCache?n=i.aliasResolveCache:(n=[],UE.visit(t,{Node:(a,o)=>{(Ir.isAlias(o)||Ir.hasAnchor(o))&&n.push(o)}}),i&&(i.aliasResolveCache=n));let r;for(let a of n){if(a===this)break;a.anchor===this.source&&(r=a)}return r}toJSON(t,i){if(!i)return{source:this.source};let{anchors:n,doc:r,maxAliasCount:a}=i,o=this.resolve(r,i);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let s=n.get(o);if(s||(YE.toJS(o,null,i),s=n.get(o)),s?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(a>=0&&(s.count+=1,s.aliasCount===0&&(s.aliasCount=Fs(r,o,n)),s.count*s.aliasCount>a)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return s.res}toString(t,i,n){let r=`*${this.source}`;if(t){if(GE.anchorIsValid(this.source),t.options.verifyAliasOrder&&!t.anchors.has(this.source)){let a=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(a)}if(t.implicitKey)return`${r} `}return r}};function Fs(e,t,i){if(Ir.isAlias(t)){let n=t.resolve(e),r=i&&n&&i.get(n);return r?r.count*r.aliasCount:0}else if(Ir.isCollection(t)){let n=0;for(let r of t.items){let a=Fs(e,r,i);a>n&&(n=a)}return n}else if(Ir.isPair(t)){let n=Fs(e,t.key,i),r=Fs(e,t.value,i);return Math.max(n,r)}return 1}am.Alias=Bu});var Re=P(qu=>{"use strict";var XE=K(),QE=Ms(),ZE=en(),eR=e=>!e||typeof e!="function"&&typeof e!="object",tn=class extends QE.NodeBase{constructor(t){super(XE.SCALAR),this.value=t}toJSON(t,i){return i?.keep?this.value:ZE.toJS(this.value,t,i)}toString(){return String(this.value)}};tn.BLOCK_FOLDED="BLOCK_FOLDED";tn.BLOCK_LITERAL="BLOCK_LITERAL";tn.PLAIN="PLAIN";tn.QUOTE_DOUBLE="QUOTE_DOUBLE";tn.QUOTE_SINGLE="QUOTE_SINGLE";qu.Scalar=tn;qu.isScalarValue=eR});var Fa=P(sm=>{"use strict";var tR=Ma(),Jn=K(),om=Re(),iR="tag:yaml.org,2002:";function nR(e,t,i){if(t){let n=i.filter(a=>a.tag===t),r=n.find(a=>!a.format)??n[0];if(!r)throw new Error(`Tag ${t} not found`);return r}return i.find(n=>n.identify?.(e)&&!n.format)}function rR(e,t,i){if(Jn.isDocument(e)&&(e=e.contents),Jn.isNode(e))return e;if(Jn.isPair(e)){let d=i.schema[Jn.MAP].createNode?.(i.schema,null,i);return d.items.push(e),d}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:n,onAnchor:r,onTagObj:a,schema:o,sourceObjects:s}=i,c;if(n&&e&&typeof e=="object"){if(c=s.get(e),c)return c.anchor??(c.anchor=r(e)),new tR.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=iR+t.slice(2));let l=nR(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let d=new om.Scalar(e);return c&&(c.node=d),d}l=e instanceof Map?o[Jn.MAP]:Symbol.iterator in Object(e)?o[Jn.SEQ]:o[Jn.MAP]}a&&(a(l),delete i.onTagObj);let u=l?.createNode?l.createNode(i.schema,e,i):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(i.schema,e,i):new om.Scalar(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}sm.createNode=rR});var Bs=P(Ls=>{"use strict";var aR=Fa(),si=K(),oR=Ms();function Vu(e,t,i){let n=i;for(let r=t.length-1;r>=0;--r){let a=t[r];if(typeof a=="number"&&Number.isInteger(a)&&a>=0){let o=[];o[a]=n,n=o}else n=new Map([[a,n]])}return aR.createNode(n,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}var cm=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,Wu=class extends oR.NodeBase{constructor(t,i){super(t),Object.defineProperty(this,"schema",{value:i,configurable:!0,enumerable:!1,writable:!0})}clone(t){let i=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return t&&(i.schema=t),i.items=i.items.map(n=>si.isNode(n)||si.isPair(n)?n.clone(t):n),this.range&&(i.range=this.range.slice()),i}addIn(t,i){if(cm(t))this.add(i);else{let[n,...r]=t,a=this.get(n,!0);if(si.isCollection(a))a.addIn(r,i);else if(a===void 0&&this.schema)this.set(n,Vu(this.schema,r,i));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}}deleteIn(t){let[i,...n]=t;if(n.length===0)return this.delete(i);let r=this.get(i,!0);if(si.isCollection(r))return r.deleteIn(n);throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}getIn(t,i){let[n,...r]=t,a=this.get(n,!0);return r.length===0?!i&&si.isScalar(a)?a.value:a:si.isCollection(a)?a.getIn(r,i):void 0}hasAllNullValues(t){return this.items.every(i=>{if(!si.isPair(i))return!1;let n=i.value;return n==null||t&&si.isScalar(n)&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn(t){let[i,...n]=t;if(n.length===0)return this.has(i);let r=this.get(i,!0);return si.isCollection(r)?r.hasIn(n):!1}setIn(t,i){let[n,...r]=t;if(r.length===0)this.set(n,i);else{let a=this.get(n,!0);if(si.isCollection(a))a.setIn(r,i);else if(a===void 0&&this.schema)this.set(n,Vu(this.schema,r,i));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}}};Ls.Collection=Wu;Ls.collectionFromPath=Vu;Ls.isEmptyPath=cm});var La=P(qs=>{"use strict";var sR=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function Ju(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var cR=(e,t,i)=>e.endsWith(` `)?Ju(i,t):i.includes(` `)?` -`+Ju(i,t):(e.endsWith(" ")?"":" ")+i;qs.indentComment=Ju;qs.lineComment=cR;qs.stringifyComment=sR});var lm=P(Ba=>{"use strict";var lR="flow",zu="block",Vs="quoted";function uR(e,t,i="flow",{indentAtStart:n,lineWidth:r=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!r||r<0)return e;rr-Math.max(2,a)?l.push(0):d=r-n);let f,h,m=!1,p=-1,v=-1,S=-1;i===zu&&(p=cm(e,p,t.length),p!==-1&&(d=p+c));for(let N;N=e[p+=1];){if(i===Vs&&N==="\\"){switch(v=p,e[p+1]){case"x":p+=3;break;case"u":p+=5;break;case"U":p+=9;break;default:p+=1}S=p}if(N===` -`)i===zu&&(p=cm(e,p,t.length)),d=p+t.length+c,f=void 0;else{if(N===" "&&h&&h!==" "&&h!==` +`+Ju(i,t):(e.endsWith(" ")?"":" ")+i;qs.indentComment=Ju;qs.lineComment=cR;qs.stringifyComment=sR});var um=P(Ba=>{"use strict";var lR="flow",zu="block",Vs="quoted";function uR(e,t,i="flow",{indentAtStart:n,lineWidth:r=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!r||r<0)return e;rr-Math.max(2,a)?l.push(0):d=r-n);let f,h,m=!1,p=-1,v=-1,S=-1;i===zu&&(p=lm(e,p,t.length),p!==-1&&(d=p+c));for(let N;N=e[p+=1];){if(i===Vs&&N==="\\"){switch(v=p,e[p+1]){case"x":p+=3;break;case"u":p+=5;break;case"U":p+=9;break;default:p+=1}S=p}if(N===` +`)i===zu&&(p=lm(e,p,t.length)),d=p+t.length+c,f=void 0;else{if(N===" "&&h&&h!==" "&&h!==` `&&h!==" "){let b=e[p+1];b&&b!==" "&&b!==` `&&b!==" "&&(f=p)}if(p>=d)if(f)l.push(f),d=f+c,f=void 0;else if(i===Vs){for(;h===" "||h===" ";)h=N,N=e[p+=1],m=!0;let b=p>S+1?p-2:v-1;if(u[b])return e;l.push(b),u[b]=!0,d=b+c,f=void 0}else m=!0}h=N}if(m&&s&&s(),l.length===0)return e;o&&o();let k=e.slice(0,l[0]);for(let N=0;N{"use strict";var Bt=Re(),nn=lm(),Js=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),zs=e=>/^(%|---|\.\.\.)/m.test(e);function dR(e,t,i){if(!t||t<0)return!1;let n=t-i,r=e.length;if(r<=n)return!1;for(let a=0,o=0;a{"use strict";var Bt=Re(),nn=um(),Js=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),zs=e=>/^(%|---|\.\.\.)/m.test(e);function dR(e,t,i){if(!t||t<0)return!1;let n=t-i,r=e.length;if(r<=n)return!1;for(let a=0,o=0;an)return!0;if(o=a+1,r-o<=n)return!1}return!0}function qa(e,t){let i=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return i;let{implicitKey:n}=t,r=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(zs(e)?" ":""),o="",s=0;for(let c=0,l=i[c];l;l=i[++c])if(l===" "&&i[c+1]==="\\"&&i[c+2]==="n"&&(o+=i.slice(s,c)+"\\ ",c+=1,s=c,l="\\"),l==="\\")switch(i[c+1]){case"u":{o+=i.slice(s,c);let u=i.substr(c+2,4);switch(u){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:u.substr(0,2)==="00"?o+="\\x"+u.substr(2):o+=i.substr(c,6)}c+=5,s=c+1}break;case"n":if(n||i[c+2]==='"'||i.length'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||u||!a.includes(` `)?jr(a,t):Ws(e,t,i,n);if(!s&&!u&&r!==Bt.Scalar.PLAIN&&a.includes(` `))return Ws(e,t,i,n);if(zs(a)){if(c==="")return t.forceBlockIndent=!0,Ws(e,t,i,n);if(s&&c===l)return jr(a,t)}let d=a.replace(/\n+/g,`$& -${c}`);if(o){let f=p=>p.default&&p.tag!=="tag:yaml.org,2002:str"&&p.test?.test(d),{compat:h,tags:m}=t.doc.schema;if(m.some(f)||h?.some(f))return jr(a,t)}return s?d:nn.foldFlowLines(d,c,nn.FOLD_FLOW,Js(t,!1))}function hR(e,t,i,n){let{implicitKey:r,inFlow:a}=t,o=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)}),{type:s}=e;s!==Bt.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=Bt.Scalar.QUOTE_DOUBLE);let c=u=>{switch(u){case Bt.Scalar.BLOCK_FOLDED:case Bt.Scalar.BLOCK_LITERAL:return r||a?jr(o.value,t):Ws(o,t,i,n);case Bt.Scalar.QUOTE_DOUBLE:return qa(o.value,t);case Bt.Scalar.QUOTE_SINGLE:return Gu(o.value,t);case Bt.Scalar.PLAIN:return fR(o,t,i,n);default:return null}},l=c(s);if(l===null){let{defaultKeyType:u,defaultStringType:d}=t.options,f=r&&u||d;if(l=c(f),l===null)throw new Error(`Unsupported default string type ${f}`)}return l}um.stringifyString=hR});var Wa=P(Ku=>{"use strict";var pR=Ds(),rn=K(),mR=La(),vR=Va();function gR(e,t){let i=Object.assign({blockQuote:!0,commentString:mR.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},e.schema.toStringOptions,t),n;switch(i.collectionStyle){case"block":n=!1;break;case"flow":n=!0;break;default:n=null}return{anchors:new Set,doc:e,flowCollectionPadding:i.flowCollectionPadding?" ":"",indent:"",indentStep:typeof i.indent=="number"?" ".repeat(i.indent):" ",inFlow:n,options:i}}function wR(e,t){if(t.tag){let r=e.filter(a=>a.tag===t.tag);if(r.length>0)return r.find(a=>a.format===t.format)??r[0]}let i,n;if(rn.isScalar(t)){n=t.value;let r=e.filter(a=>a.identify?.(n));if(r.length>1){let a=r.filter(o=>o.test);a.length>0&&(r=a)}i=r.find(a=>a.format===t.format)??r.find(a=>!a.format)}else n=t,i=e.find(r=>r.nodeClass&&n instanceof r.nodeClass);if(!i){let r=n?.constructor?.name??(n===null?"null":typeof n);throw new Error(`Tag not resolved for ${r} value`)}return i}function yR(e,t,{anchors:i,doc:n}){if(!n.directives)return"";let r=[],a=(rn.isScalar(e)||rn.isCollection(e))&&e.anchor;a&&pR.anchorIsValid(a)&&(i.add(a),r.push(`&${a}`));let o=e.tag??(t.default?null:t.tag);return o&&r.push(n.directives.tagString(o)),r.join(" ")}function NR(e,t,i,n){if(rn.isPair(e))return e.toString(t,i,n);if(rn.isAlias(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw new TypeError("Cannot stringify circular structure without alias nodes");t.resolvedAliases?t.resolvedAliases.add(e):t.resolvedAliases=new Set([e]),e=e.resolve(t.doc)}let r,a=rn.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>r=c});r??(r=wR(t.doc.schema.tags,a));let o=yR(a,r,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);let s=typeof r.stringify=="function"?r.stringify(a,t,i,n):rn.isScalar(a)?vR.stringifyString(a,t,i,n):a.toString(t,i,n);return o?rn.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o} -${t.indent}${s}`:s}Ku.createStringifyContext=gR;Ku.stringify=NR});var pm=P(hm=>{"use strict";var Ai=K(),dm=Re(),fm=Wa(),Ja=La();function bR({key:e,value:t},i,n,r){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:d}}=i,f=Ai.isNode(e)&&e.comment||null;if(d){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(Ai.isCollection(e)||!Ai.isNode(e)&&typeof e=="object"){let w="With simple keys, collection cannot be used as a key value";throw new Error(w)}}let h=!d&&(!e||f&&t==null&&!i.inFlow||Ai.isCollection(e)||(Ai.isScalar(e)?e.type===dm.Scalar.BLOCK_FOLDED||e.type===dm.Scalar.BLOCK_LITERAL:typeof e=="object"));i=Object.assign({},i,{allNullValues:!1,implicitKey:!h&&(d||!a),indent:s+c});let m=!1,p=!1,v=fm.stringify(e,i,()=>m=!0,()=>p=!0);if(!h&&!i.inFlow&&v.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");h=!0}if(i.inFlow){if(a||t==null)return m&&n&&n(),v===""?"?":h?`? ${v}`:v}else if(a&&!d||t==null&&h)return v=`? ${v}`,f&&!m?v+=Ja.lineComment(v,i.indent,l(f)):p&&r&&r(),v;m&&(f=null),h?(f&&(v+=Ja.lineComment(v,i.indent,l(f))),v=`? ${v} -${s}:`):(v=`${v}:`,f&&(v+=Ja.lineComment(v,i.indent,l(f))));let S,k,N;Ai.isNode(t)?(S=!!t.spaceBefore,k=t.commentBefore,N=t.comment):(S=!1,k=null,N=null,t&&typeof t=="object"&&(t=o.createNode(t))),i.implicitKey=!1,!h&&!f&&Ai.isScalar(t)&&(i.indentAtStart=v.length+1),p=!1,!u&&c.length>=2&&!i.inFlow&&!h&&Ai.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(i.indent=i.indent.substring(2));let b=!1,R=fm.stringify(t,i,()=>b=!0,()=>p=!0),y=" ";if(f||S||k){if(y=S?` +${c}`);if(o){let f=p=>p.default&&p.tag!=="tag:yaml.org,2002:str"&&p.test?.test(d),{compat:h,tags:m}=t.doc.schema;if(m.some(f)||h?.some(f))return jr(a,t)}return s?d:nn.foldFlowLines(d,c,nn.FOLD_FLOW,Js(t,!1))}function hR(e,t,i,n){let{implicitKey:r,inFlow:a}=t,o=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)}),{type:s}=e;s!==Bt.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=Bt.Scalar.QUOTE_DOUBLE);let c=u=>{switch(u){case Bt.Scalar.BLOCK_FOLDED:case Bt.Scalar.BLOCK_LITERAL:return r||a?jr(o.value,t):Ws(o,t,i,n);case Bt.Scalar.QUOTE_DOUBLE:return qa(o.value,t);case Bt.Scalar.QUOTE_SINGLE:return Gu(o.value,t);case Bt.Scalar.PLAIN:return fR(o,t,i,n);default:return null}},l=c(s);if(l===null){let{defaultKeyType:u,defaultStringType:d}=t.options,f=r&&u||d;if(l=c(f),l===null)throw new Error(`Unsupported default string type ${f}`)}return l}dm.stringifyString=hR});var Wa=P(Ku=>{"use strict";var pR=Ds(),rn=K(),mR=La(),vR=Va();function gR(e,t){let i=Object.assign({blockQuote:!0,commentString:mR.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},e.schema.toStringOptions,t),n;switch(i.collectionStyle){case"block":n=!1;break;case"flow":n=!0;break;default:n=null}return{anchors:new Set,doc:e,flowCollectionPadding:i.flowCollectionPadding?" ":"",indent:"",indentStep:typeof i.indent=="number"?" ".repeat(i.indent):" ",inFlow:n,options:i}}function wR(e,t){if(t.tag){let r=e.filter(a=>a.tag===t.tag);if(r.length>0)return r.find(a=>a.format===t.format)??r[0]}let i,n;if(rn.isScalar(t)){n=t.value;let r=e.filter(a=>a.identify?.(n));if(r.length>1){let a=r.filter(o=>o.test);a.length>0&&(r=a)}i=r.find(a=>a.format===t.format)??r.find(a=>!a.format)}else n=t,i=e.find(r=>r.nodeClass&&n instanceof r.nodeClass);if(!i){let r=n?.constructor?.name??(n===null?"null":typeof n);throw new Error(`Tag not resolved for ${r} value`)}return i}function yR(e,t,{anchors:i,doc:n}){if(!n.directives)return"";let r=[],a=(rn.isScalar(e)||rn.isCollection(e))&&e.anchor;a&&pR.anchorIsValid(a)&&(i.add(a),r.push(`&${a}`));let o=e.tag??(t.default?null:t.tag);return o&&r.push(n.directives.tagString(o)),r.join(" ")}function NR(e,t,i,n){if(rn.isPair(e))return e.toString(t,i,n);if(rn.isAlias(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw new TypeError("Cannot stringify circular structure without alias nodes");t.resolvedAliases?t.resolvedAliases.add(e):t.resolvedAliases=new Set([e]),e=e.resolve(t.doc)}let r,a=rn.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>r=c});r??(r=wR(t.doc.schema.tags,a));let o=yR(a,r,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);let s=typeof r.stringify=="function"?r.stringify(a,t,i,n):rn.isScalar(a)?vR.stringifyString(a,t,i,n):a.toString(t,i,n);return o?rn.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o} +${t.indent}${s}`:s}Ku.createStringifyContext=gR;Ku.stringify=NR});var mm=P(pm=>{"use strict";var Ai=K(),fm=Re(),hm=Wa(),Ja=La();function bR({key:e,value:t},i,n,r){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:d}}=i,f=Ai.isNode(e)&&e.comment||null;if(d){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(Ai.isCollection(e)||!Ai.isNode(e)&&typeof e=="object"){let w="With simple keys, collection cannot be used as a key value";throw new Error(w)}}let h=!d&&(!e||f&&t==null&&!i.inFlow||Ai.isCollection(e)||(Ai.isScalar(e)?e.type===fm.Scalar.BLOCK_FOLDED||e.type===fm.Scalar.BLOCK_LITERAL:typeof e=="object"));i=Object.assign({},i,{allNullValues:!1,implicitKey:!h&&(d||!a),indent:s+c});let m=!1,p=!1,v=hm.stringify(e,i,()=>m=!0,()=>p=!0);if(!h&&!i.inFlow&&v.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");h=!0}if(i.inFlow){if(a||t==null)return m&&n&&n(),v===""?"?":h?`? ${v}`:v}else if(a&&!d||t==null&&h)return v=`? ${v}`,f&&!m?v+=Ja.lineComment(v,i.indent,l(f)):p&&r&&r(),v;m&&(f=null),h?(f&&(v+=Ja.lineComment(v,i.indent,l(f))),v=`? ${v} +${s}:`):(v=`${v}:`,f&&(v+=Ja.lineComment(v,i.indent,l(f))));let S,k,N;Ai.isNode(t)?(S=!!t.spaceBefore,k=t.commentBefore,N=t.comment):(S=!1,k=null,N=null,t&&typeof t=="object"&&(t=o.createNode(t))),i.implicitKey=!1,!h&&!f&&Ai.isScalar(t)&&(i.indentAtStart=v.length+1),p=!1,!u&&c.length>=2&&!i.inFlow&&!h&&Ai.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(i.indent=i.indent.substring(2));let b=!1,R=hm.stringify(t,i,()=>b=!0,()=>p=!0),y=" ";if(f||S||k){if(y=S?` `:"",k){let w=l(k);y+=` ${Ja.indentComment(w,i.indent)}`}R===""&&!i.inFlow?y===` `&&N&&(y=` @@ -44,32 +44,32 @@ ${Ja.indentComment(w,i.indent)}`}R===""&&!i.inFlow?y===` ${i.indent}`}else if(!h&&Ai.isCollection(t)){let w=R[0],g=R.indexOf(` `),E=g!==-1,O=i.inFlow??t.flow??t.items.length===0;if(E||!O){let B=!1;if(E&&(w==="&"||w==="!")){let q=R.indexOf(" ");w==="&"&&q!==-1&&q{"use strict";var mm=As("process");function kR(e,...t){e==="debug"&&console.log(...t)}function SR(e,t){(e==="debug"||e==="warn")&&(typeof mm.emitWarning=="function"?mm.emitWarning(t):console.warn(t))}Yu.debug=kR;Yu.warn=SR});var Xs=P(Ys=>{"use strict";var Ks=K(),vm=Re(),Gs="<<",Us={identify:e=>e===Gs||typeof e=="symbol"&&e.description===Gs,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new vm.Scalar(Symbol(Gs)),{addToJSMap:gm}),stringify:()=>Gs},ER=(e,t)=>(Us.identify(t)||Ks.isScalar(t)&&(!t.type||t.type===vm.Scalar.PLAIN)&&Us.identify(t.value))&&e?.doc.schema.tags.some(i=>i.tag===Us.tag&&i.default);function gm(e,t,i){let n=wm(e,i);if(Ks.isSeq(n))for(let r of n.items)Qu(e,t,r);else if(Array.isArray(n))for(let r of n)Qu(e,t,r);else Qu(e,t,n)}function Qu(e,t,i){let n=wm(e,i);if(!Ks.isMap(n))throw new Error("Merge sources must be maps or map aliases");let r=n.toJSON(null,e,Map);for(let[a,o]of r)t instanceof Map?t.has(a)||t.set(a,o):t instanceof Set?t.add(a):Object.prototype.hasOwnProperty.call(t,a)||Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0});return t}function wm(e,t){return e&&Ks.isAlias(t)?t.resolve(e.doc,e):t}Ys.addMergeToJSMap=gm;Ys.isMergeKey=ER;Ys.merge=Us});var ed=P(bm=>{"use strict";var RR=Xu(),ym=Xs(),CR=Wa(),Nm=K(),Zu=en();function PR(e,t,{key:i,value:n}){if(Nm.isNode(i)&&i.addToJSMap)i.addToJSMap(e,t,n);else if(ym.isMergeKey(e,i))ym.addMergeToJSMap(e,t,n);else{let r=Zu.toJS(i,"",e);if(t instanceof Map)t.set(r,Zu.toJS(n,r,e));else if(t instanceof Set)t.add(r);else{let a=xR(i,r,e),o=Zu.toJS(n,a,e);a in t?Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[a]=o}}return t}function xR(e,t,i){if(t===null)return"";if(typeof t!="object")return String(t);if(Nm.isNode(e)&&i?.doc){let n=CR.createStringifyContext(i.doc,{});n.anchors=new Set;for(let a of i.anchors.keys())n.anchors.add(a.anchor);n.inFlow=!0,n.inStringifyKey=!0;let r=e.toString(n);if(!i.mapKeyWarned){let a=JSON.stringify(r);a.length>40&&(a=a.substring(0,36)+'..."'),RR.warn(i.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${a}. Set mapAsMap: true to use object keys.`),i.mapKeyWarned=!0}return r}return JSON.stringify(t)}bm.addPairToJSMap=PR});var an=P(td=>{"use strict";var km=Fa(),AR=pm(),TR=ed(),Qs=K();function _R(e,t,i){let n=km.createNode(e,void 0,i),r=km.createNode(t,void 0,i);return new Zs(n,r)}var Zs=class e{constructor(t,i=null){Object.defineProperty(this,Qs.NODE_TYPE,{value:Qs.PAIR}),this.key=t,this.value=i}clone(t){let{key:i,value:n}=this;return Qs.isNode(i)&&(i=i.clone(t)),Qs.isNode(n)&&(n=n.clone(t)),new e(i,n)}toJSON(t,i){let n=i?.mapAsMap?new Map:{};return TR.addPairToJSMap(i,n,this)}toString(t,i,n){return t?.doc?AR.stringifyPair(this,t,i,n):JSON.stringify(this)}};td.Pair=Zs;td.createPair=_R});var id=P(Em=>{"use strict";var zn=K(),Sm=Wa(),ec=La();function IR(e,t,i){return(t.inFlow??e.flow?OR:jR)(e,t,i)}function jR({comment:e,items:t},i,{blockItemPrefix:n,flowChars:r,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=i,u=Object.assign({},i,{indent:a,type:null}),d=!1,f=[];for(let m=0;mv=null,()=>d=!0);v&&(S+=ec.lineComment(S,a,l(v))),d&&v&&(d=!1),f.push(n+S)}let h;if(f.length===0)h=r.start+r.end;else{h=f[0];for(let m=1;m{"use strict";var vm=As("process");function kR(e,...t){e==="debug"&&console.log(...t)}function SR(e,t){(e==="debug"||e==="warn")&&(typeof vm.emitWarning=="function"?vm.emitWarning(t):console.warn(t))}Yu.debug=kR;Yu.warn=SR});var Xs=P(Ys=>{"use strict";var Ks=K(),gm=Re(),Gs="<<",Us={identify:e=>e===Gs||typeof e=="symbol"&&e.description===Gs,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new gm.Scalar(Symbol(Gs)),{addToJSMap:wm}),stringify:()=>Gs},ER=(e,t)=>(Us.identify(t)||Ks.isScalar(t)&&(!t.type||t.type===gm.Scalar.PLAIN)&&Us.identify(t.value))&&e?.doc.schema.tags.some(i=>i.tag===Us.tag&&i.default);function wm(e,t,i){let n=ym(e,i);if(Ks.isSeq(n))for(let r of n.items)Qu(e,t,r);else if(Array.isArray(n))for(let r of n)Qu(e,t,r);else Qu(e,t,n)}function Qu(e,t,i){let n=ym(e,i);if(!Ks.isMap(n))throw new Error("Merge sources must be maps or map aliases");let r=n.toJSON(null,e,Map);for(let[a,o]of r)t instanceof Map?t.has(a)||t.set(a,o):t instanceof Set?t.add(a):Object.prototype.hasOwnProperty.call(t,a)||Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0});return t}function ym(e,t){return e&&Ks.isAlias(t)?t.resolve(e.doc,e):t}Ys.addMergeToJSMap=wm;Ys.isMergeKey=ER;Ys.merge=Us});var ed=P(km=>{"use strict";var RR=Xu(),Nm=Xs(),CR=Wa(),bm=K(),Zu=en();function PR(e,t,{key:i,value:n}){if(bm.isNode(i)&&i.addToJSMap)i.addToJSMap(e,t,n);else if(Nm.isMergeKey(e,i))Nm.addMergeToJSMap(e,t,n);else{let r=Zu.toJS(i,"",e);if(t instanceof Map)t.set(r,Zu.toJS(n,r,e));else if(t instanceof Set)t.add(r);else{let a=xR(i,r,e),o=Zu.toJS(n,a,e);a in t?Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[a]=o}}return t}function xR(e,t,i){if(t===null)return"";if(typeof t!="object")return String(t);if(bm.isNode(e)&&i?.doc){let n=CR.createStringifyContext(i.doc,{});n.anchors=new Set;for(let a of i.anchors.keys())n.anchors.add(a.anchor);n.inFlow=!0,n.inStringifyKey=!0;let r=e.toString(n);if(!i.mapKeyWarned){let a=JSON.stringify(r);a.length>40&&(a=a.substring(0,36)+'..."'),RR.warn(i.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${a}. Set mapAsMap: true to use object keys.`),i.mapKeyWarned=!0}return r}return JSON.stringify(t)}km.addPairToJSMap=PR});var an=P(td=>{"use strict";var Sm=Fa(),AR=mm(),TR=ed(),Qs=K();function _R(e,t,i){let n=Sm.createNode(e,void 0,i),r=Sm.createNode(t,void 0,i);return new Zs(n,r)}var Zs=class e{constructor(t,i=null){Object.defineProperty(this,Qs.NODE_TYPE,{value:Qs.PAIR}),this.key=t,this.value=i}clone(t){let{key:i,value:n}=this;return Qs.isNode(i)&&(i=i.clone(t)),Qs.isNode(n)&&(n=n.clone(t)),new e(i,n)}toJSON(t,i){let n=i?.mapAsMap?new Map:{};return TR.addPairToJSMap(i,n,this)}toString(t,i,n){return t?.doc?AR.stringifyPair(this,t,i,n):JSON.stringify(this)}};td.Pair=Zs;td.createPair=_R});var id=P(Rm=>{"use strict";var zn=K(),Em=Wa(),ec=La();function IR(e,t,i){return(t.inFlow??e.flow?OR:jR)(e,t,i)}function jR({comment:e,items:t},i,{blockItemPrefix:n,flowChars:r,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=i,u=Object.assign({},i,{indent:a,type:null}),d=!1,f=[];for(let m=0;mv=null,()=>d=!0);v&&(S+=ec.lineComment(S,a,l(v))),d&&v&&(d=!1),f.push(n+S)}let h;if(f.length===0)h=r.start+r.end;else{h=f[0];for(let m=1;mv=null);l||(l=d.length>u||S.includes(` +`+ec.indentComment(l(e),c),s&&s()):d&&o&&o(),h}function OR({items:e},t,{flowChars:i,itemIndent:n}){let{indent:r,indentStep:a,flowCollectionPadding:o,options:{commentString:s}}=t;n+=a;let c=Object.assign({},t,{indent:n,inFlow:!0,type:null}),l=!1,u=0,d=[];for(let m=0;mv=null);l||(l=d.length>u||S.includes(` `)),m0&&(l||(l=d.reduce((k,N)=>k+N.length+2,2)+(S.length+2)>t.options.lineWidth)),l&&(S+=",")),v&&(S+=ec.lineComment(S,n,s(v))),d.push(S),u=d.length}let{start:f,end:h}=i;if(d.length===0)return f+h;if(!l){let m=d.reduce((p,v)=>p+v.length+2,2);l=t.options.lineWidth>0&&m>t.options.lineWidth}if(l){let m=f;for(let p of d)m+=p?` ${a}${r}${p}`:` `;return`${m} -${r}${h}`}else return`${f}${o}${d.join(" ")}${o}${h}`}function tc({indent:e,options:{commentString:t}},i,n,r){if(n&&r&&(n=n.replace(/^\n+/,"")),n){let a=ec.indentComment(t(n),e);i.push(a.trimStart())}}Em.stringifyCollection=IR});var sn=P(rd=>{"use strict";var $R=id(),HR=ed(),DR=Bs(),on=K(),ic=an(),MR=Re();function za(e,t){let i=on.isScalar(t)?t.value:t;for(let n of e)if(on.isPair(n)&&(n.key===t||n.key===i||on.isScalar(n.key)&&n.key.value===i))return n}var nd=class extends DR.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(on.MAP,t),this.items=[]}static from(t,i,n){let{keepUndefined:r,replacer:a}=n,o=new this(t),s=(c,l)=>{if(typeof a=="function")l=a.call(i,c,l);else if(Array.isArray(a)&&!a.includes(c))return;(l!==void 0||r)&&o.items.push(ic.createPair(c,l,n))};if(i instanceof Map)for(let[c,l]of i)s(c,l);else if(i&&typeof i=="object")for(let c of Object.keys(i))s(c,i[c]);return typeof t.sortMapEntries=="function"&&o.items.sort(t.sortMapEntries),o}add(t,i){let n;on.isPair(t)?n=t:!t||typeof t!="object"||!("key"in t)?n=new ic.Pair(t,t?.value):n=new ic.Pair(t.key,t.value);let r=za(this.items,n.key),a=this.schema?.sortMapEntries;if(r){if(!i)throw new Error(`Key ${n.key} already set`);on.isScalar(r.value)&&MR.isScalarValue(n.value)?r.value.value=n.value:r.value=n.value}else if(a){let o=this.items.findIndex(s=>a(n,s)<0);o===-1?this.items.push(n):this.items.splice(o,0,n)}else this.items.push(n)}delete(t){let i=za(this.items,t);return i?this.items.splice(this.items.indexOf(i),1).length>0:!1}get(t,i){let r=za(this.items,t)?.value;return(!i&&on.isScalar(r)?r.value:r)??void 0}has(t){return!!za(this.items,t)}set(t,i){this.add(new ic.Pair(t,i),!0)}toJSON(t,i,n){let r=n?new n:i?.mapAsMap?new Map:{};i?.onCreate&&i.onCreate(r);for(let a of this.items)HR.addPairToJSMap(i,r,a);return r}toString(t,i,n){if(!t)return JSON.stringify(this);for(let r of this.items)if(!on.isPair(r))throw new Error(`Map items must all be pairs; found ${JSON.stringify(r)} instead`);return!t.allNullValues&&this.hasAllNullValues(!1)&&(t=Object.assign({},t,{allNullValues:!0})),$R.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:n,onComment:i})}};rd.YAMLMap=nd;rd.findPair=za});var Or=P(Cm=>{"use strict";var FR=K(),Rm=sn(),LR={collection:"map",default:!0,nodeClass:Rm.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return FR.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,i)=>Rm.YAMLMap.from(e,t,i)};Cm.map=LR});var cn=P(Pm=>{"use strict";var BR=Fa(),qR=id(),VR=Bs(),rc=K(),WR=Re(),JR=en(),ad=class extends VR.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(rc.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let i=nc(t);return typeof i!="number"?!1:this.items.splice(i,1).length>0}get(t,i){let n=nc(t);if(typeof n!="number")return;let r=this.items[n];return!i&&rc.isScalar(r)?r.value:r}has(t){let i=nc(t);return typeof i=="number"&&i=0?t:null}Pm.YAMLSeq=ad});var $r=P(Am=>{"use strict";var zR=K(),xm=cn(),GR={collection:"seq",default:!0,nodeClass:xm.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return zR.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,i)=>xm.YAMLSeq.from(e,t,i)};Am.seq=GR});var Ga=P(Tm=>{"use strict";var UR=Va(),KR={identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify(e,t,i,n){return t=Object.assign({actualString:!0},t),UR.stringifyString(e,t,i,n)}};Tm.string=KR});var ac=P(jm=>{"use strict";var _m=Re(),Im={identify:e=>e==null,createNode:()=>new _m.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new _m.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&Im.test.test(e)?e:t.options.nullStr};jm.nullTag=Im});var od=P($m=>{"use strict";var YR=Re(),Om={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new YR.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},i){if(e&&Om.test.test(e)){let n=e[0]==="t"||e[0]==="T";if(t===n)return e}return t?i.options.trueStr:i.options.falseStr}};$m.boolTag=Om});var Hr=P(Hm=>{"use strict";function XR({format:e,minFractionDigits:t,tag:i,value:n}){if(typeof n=="bigint")return String(n);let r=typeof n=="number"?n:Number(n);if(!isFinite(r))return isNaN(r)?".nan":r<0?"-.inf":".inf";let a=Object.is(n,-0)?"-0":JSON.stringify(n);if(!e&&t&&(!i||i==="tag:yaml.org,2002:float")&&/^-?\d/.test(a)&&!a.includes("e")){let o=a.indexOf(".");o<0&&(o=a.length,a+=".");let s=t-(a.length-o-1);for(;s-- >0;)a+="0"}return a}Hm.stringifyNumber=XR});var cd=P(oc=>{"use strict";var QR=Re(),sd=Hr(),ZR={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()==="nan"?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:sd.stringifyNumber},eC={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():sd.stringifyNumber(e)}},tC={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(e){let t=new QR.Scalar(parseFloat(e)),i=e.indexOf(".");return i!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-i-1),t},stringify:sd.stringifyNumber};oc.float=tC;oc.floatExp=eC;oc.floatNaN=ZR});var ud=P(cc=>{"use strict";var Dm=Hr(),sc=e=>typeof e=="bigint"||Number.isInteger(e),ld=(e,t,i,{intAsBigInt:n})=>n?BigInt(e):parseInt(e.substring(t),i);function Mm(e,t,i){let{value:n}=e;return sc(n)&&n>=0?i+n.toString(t):Dm.stringifyNumber(e)}var iC={identify:e=>sc(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,i)=>ld(e,2,8,i),stringify:e=>Mm(e,8,"0o")},nC={identify:sc,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,i)=>ld(e,0,10,i),stringify:Dm.stringifyNumber},rC={identify:e=>sc(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,i)=>ld(e,2,16,i),stringify:e=>Mm(e,16,"0x")};cc.int=nC;cc.intHex=rC;cc.intOct=iC});var Lm=P(Fm=>{"use strict";var aC=Or(),oC=ac(),sC=$r(),cC=Ga(),lC=od(),dd=cd(),fd=ud(),uC=[aC.map,sC.seq,cC.string,oC.nullTag,lC.boolTag,fd.intOct,fd.int,fd.intHex,dd.floatNaN,dd.floatExp,dd.float];Fm.schema=uC});var Vm=P(qm=>{"use strict";var dC=Re(),fC=Or(),hC=$r();function Bm(e){return typeof e=="bigint"||Number.isInteger(e)}var lc=({value:e})=>JSON.stringify(e),pC=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:lc},{identify:e=>e==null,createNode:()=>new dC.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:lc},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:lc},{identify:Bm,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:i})=>i?BigInt(e):parseInt(e,10),stringify:({value:e})=>Bm(e)?e.toString():JSON.stringify(e)},{identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:e=>parseFloat(e),stringify:lc}],mC={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},vC=[fC.map,hC.seq].concat(pC,mC);qm.schema=vC});var pd=P(Wm=>{"use strict";var Ua=As("buffer"),hd=Re(),gC=Va(),wC={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof Ua.Buffer=="function")return Ua.Buffer.from(e,"base64");if(typeof atob=="function"){let i=atob(e.replace(/[\n\r]/g,"")),n=new Uint8Array(i.length);for(let r=0;r{"use strict";var uc=K(),md=an(),yC=Re(),NC=cn();function Jm(e,t){if(uc.isSeq(e))for(let i=0;i1&&t("Each pair must have its own sequence indicator");let r=n.items[0]||new md.Pair(new yC.Scalar(null));if(n.commentBefore&&(r.key.commentBefore=r.key.commentBefore?`${n.commentBefore} +${r}${h}`}else return`${f}${o}${d.join(" ")}${o}${h}`}function tc({indent:e,options:{commentString:t}},i,n,r){if(n&&r&&(n=n.replace(/^\n+/,"")),n){let a=ec.indentComment(t(n),e);i.push(a.trimStart())}}Rm.stringifyCollection=IR});var sn=P(rd=>{"use strict";var $R=id(),HR=ed(),DR=Bs(),on=K(),ic=an(),MR=Re();function za(e,t){let i=on.isScalar(t)?t.value:t;for(let n of e)if(on.isPair(n)&&(n.key===t||n.key===i||on.isScalar(n.key)&&n.key.value===i))return n}var nd=class extends DR.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(on.MAP,t),this.items=[]}static from(t,i,n){let{keepUndefined:r,replacer:a}=n,o=new this(t),s=(c,l)=>{if(typeof a=="function")l=a.call(i,c,l);else if(Array.isArray(a)&&!a.includes(c))return;(l!==void 0||r)&&o.items.push(ic.createPair(c,l,n))};if(i instanceof Map)for(let[c,l]of i)s(c,l);else if(i&&typeof i=="object")for(let c of Object.keys(i))s(c,i[c]);return typeof t.sortMapEntries=="function"&&o.items.sort(t.sortMapEntries),o}add(t,i){let n;on.isPair(t)?n=t:!t||typeof t!="object"||!("key"in t)?n=new ic.Pair(t,t?.value):n=new ic.Pair(t.key,t.value);let r=za(this.items,n.key),a=this.schema?.sortMapEntries;if(r){if(!i)throw new Error(`Key ${n.key} already set`);on.isScalar(r.value)&&MR.isScalarValue(n.value)?r.value.value=n.value:r.value=n.value}else if(a){let o=this.items.findIndex(s=>a(n,s)<0);o===-1?this.items.push(n):this.items.splice(o,0,n)}else this.items.push(n)}delete(t){let i=za(this.items,t);return i?this.items.splice(this.items.indexOf(i),1).length>0:!1}get(t,i){let r=za(this.items,t)?.value;return(!i&&on.isScalar(r)?r.value:r)??void 0}has(t){return!!za(this.items,t)}set(t,i){this.add(new ic.Pair(t,i),!0)}toJSON(t,i,n){let r=n?new n:i?.mapAsMap?new Map:{};i?.onCreate&&i.onCreate(r);for(let a of this.items)HR.addPairToJSMap(i,r,a);return r}toString(t,i,n){if(!t)return JSON.stringify(this);for(let r of this.items)if(!on.isPair(r))throw new Error(`Map items must all be pairs; found ${JSON.stringify(r)} instead`);return!t.allNullValues&&this.hasAllNullValues(!1)&&(t=Object.assign({},t,{allNullValues:!0})),$R.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:n,onComment:i})}};rd.YAMLMap=nd;rd.findPair=za});var Or=P(Pm=>{"use strict";var FR=K(),Cm=sn(),LR={collection:"map",default:!0,nodeClass:Cm.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return FR.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,i)=>Cm.YAMLMap.from(e,t,i)};Pm.map=LR});var cn=P(xm=>{"use strict";var BR=Fa(),qR=id(),VR=Bs(),rc=K(),WR=Re(),JR=en(),ad=class extends VR.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(rc.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let i=nc(t);return typeof i!="number"?!1:this.items.splice(i,1).length>0}get(t,i){let n=nc(t);if(typeof n!="number")return;let r=this.items[n];return!i&&rc.isScalar(r)?r.value:r}has(t){let i=nc(t);return typeof i=="number"&&i=0?t:null}xm.YAMLSeq=ad});var $r=P(Tm=>{"use strict";var zR=K(),Am=cn(),GR={collection:"seq",default:!0,nodeClass:Am.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return zR.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,i)=>Am.YAMLSeq.from(e,t,i)};Tm.seq=GR});var Ga=P(_m=>{"use strict";var UR=Va(),KR={identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify(e,t,i,n){return t=Object.assign({actualString:!0},t),UR.stringifyString(e,t,i,n)}};_m.string=KR});var ac=P(Om=>{"use strict";var Im=Re(),jm={identify:e=>e==null,createNode:()=>new Im.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Im.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&jm.test.test(e)?e:t.options.nullStr};Om.nullTag=jm});var od=P(Hm=>{"use strict";var YR=Re(),$m={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new YR.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},i){if(e&&$m.test.test(e)){let n=e[0]==="t"||e[0]==="T";if(t===n)return e}return t?i.options.trueStr:i.options.falseStr}};Hm.boolTag=$m});var Hr=P(Dm=>{"use strict";function XR({format:e,minFractionDigits:t,tag:i,value:n}){if(typeof n=="bigint")return String(n);let r=typeof n=="number"?n:Number(n);if(!isFinite(r))return isNaN(r)?".nan":r<0?"-.inf":".inf";let a=Object.is(n,-0)?"-0":JSON.stringify(n);if(!e&&t&&(!i||i==="tag:yaml.org,2002:float")&&/^-?\d/.test(a)&&!a.includes("e")){let o=a.indexOf(".");o<0&&(o=a.length,a+=".");let s=t-(a.length-o-1);for(;s-- >0;)a+="0"}return a}Dm.stringifyNumber=XR});var cd=P(oc=>{"use strict";var QR=Re(),sd=Hr(),ZR={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()==="nan"?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:sd.stringifyNumber},eC={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():sd.stringifyNumber(e)}},tC={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(e){let t=new QR.Scalar(parseFloat(e)),i=e.indexOf(".");return i!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-i-1),t},stringify:sd.stringifyNumber};oc.float=tC;oc.floatExp=eC;oc.floatNaN=ZR});var ud=P(cc=>{"use strict";var Mm=Hr(),sc=e=>typeof e=="bigint"||Number.isInteger(e),ld=(e,t,i,{intAsBigInt:n})=>n?BigInt(e):parseInt(e.substring(t),i);function Fm(e,t,i){let{value:n}=e;return sc(n)&&n>=0?i+n.toString(t):Mm.stringifyNumber(e)}var iC={identify:e=>sc(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,i)=>ld(e,2,8,i),stringify:e=>Fm(e,8,"0o")},nC={identify:sc,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,i)=>ld(e,0,10,i),stringify:Mm.stringifyNumber},rC={identify:e=>sc(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,i)=>ld(e,2,16,i),stringify:e=>Fm(e,16,"0x")};cc.int=nC;cc.intHex=rC;cc.intOct=iC});var Bm=P(Lm=>{"use strict";var aC=Or(),oC=ac(),sC=$r(),cC=Ga(),lC=od(),dd=cd(),fd=ud(),uC=[aC.map,sC.seq,cC.string,oC.nullTag,lC.boolTag,fd.intOct,fd.int,fd.intHex,dd.floatNaN,dd.floatExp,dd.float];Lm.schema=uC});var Wm=P(Vm=>{"use strict";var dC=Re(),fC=Or(),hC=$r();function qm(e){return typeof e=="bigint"||Number.isInteger(e)}var lc=({value:e})=>JSON.stringify(e),pC=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:lc},{identify:e=>e==null,createNode:()=>new dC.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:lc},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:lc},{identify:qm,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:i})=>i?BigInt(e):parseInt(e,10),stringify:({value:e})=>qm(e)?e.toString():JSON.stringify(e)},{identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:e=>parseFloat(e),stringify:lc}],mC={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},vC=[fC.map,hC.seq].concat(pC,mC);Vm.schema=vC});var pd=P(Jm=>{"use strict";var Ua=As("buffer"),hd=Re(),gC=Va(),wC={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof Ua.Buffer=="function")return Ua.Buffer.from(e,"base64");if(typeof atob=="function"){let i=atob(e.replace(/[\n\r]/g,"")),n=new Uint8Array(i.length);for(let r=0;r{"use strict";var uc=K(),md=an(),yC=Re(),NC=cn();function zm(e,t){if(uc.isSeq(e))for(let i=0;i1&&t("Each pair must have its own sequence indicator");let r=n.items[0]||new md.Pair(new yC.Scalar(null));if(n.commentBefore&&(r.key.commentBefore=r.key.commentBefore?`${n.commentBefore} ${r.key.commentBefore}`:n.commentBefore),n.comment){let a=r.value??r.key;a.comment=a.comment?`${n.comment} -${a.comment}`:n.comment}n=r}e.items[i]=uc.isPair(n)?n:new md.Pair(n)}}else t("Expected a sequence for this tag");return e}function zm(e,t,i){let{replacer:n}=i,r=new NC.YAMLSeq(e);r.tag="tag:yaml.org,2002:pairs";let a=0;if(t&&Symbol.iterator in Object(t))for(let o of t){typeof n=="function"&&(o=n.call(t,String(a++),o));let s,c;if(Array.isArray(o))if(o.length===2)s=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)s=l[0],c=o[s];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else s=o;r.items.push(md.createPair(s,c,i))}return r}var bC={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Jm,createNode:zm};dc.createPairs=zm;dc.pairs=bC;dc.resolvePairs=Jm});var wd=P(gd=>{"use strict";var Gm=K(),vd=en(),Ka=sn(),kC=cn(),Um=fc(),Gn=class e extends kC.YAMLSeq{constructor(){super(),this.add=Ka.YAMLMap.prototype.add.bind(this),this.delete=Ka.YAMLMap.prototype.delete.bind(this),this.get=Ka.YAMLMap.prototype.get.bind(this),this.has=Ka.YAMLMap.prototype.has.bind(this),this.set=Ka.YAMLMap.prototype.set.bind(this),this.tag=e.tag}toJSON(t,i){if(!i)return super.toJSON(t);let n=new Map;i?.onCreate&&i.onCreate(n);for(let r of this.items){let a,o;if(Gm.isPair(r)?(a=vd.toJS(r.key,"",i),o=vd.toJS(r.value,a,i)):a=vd.toJS(r,"",i),n.has(a))throw new Error("Ordered maps must not include duplicate keys");n.set(a,o)}return n}static from(t,i,n){let r=Um.createPairs(t,i,n),a=new this;return a.items=r.items,a}};Gn.tag="tag:yaml.org,2002:omap";var SC={collection:"seq",identify:e=>e instanceof Map,nodeClass:Gn,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let i=Um.resolvePairs(e,t),n=[];for(let{key:r}of i.items)Gm.isScalar(r)&&(n.includes(r.value)?t(`Ordered maps must not include duplicate keys: ${r.value}`):n.push(r.value));return Object.assign(new Gn,i)},createNode:(e,t,i)=>Gn.from(e,t,i)};gd.YAMLOMap=Gn;gd.omap=SC});var Zm=P(yd=>{"use strict";var Km=Re();function Ym({value:e,source:t},i){return t&&(e?Xm:Qm).test.test(t)?t:e?i.options.trueStr:i.options.falseStr}var Xm={identify:e=>e===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new Km.Scalar(!0),stringify:Ym},Qm={identify:e=>e===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new Km.Scalar(!1),stringify:Ym};yd.falseTag=Qm;yd.trueTag=Xm});var ev=P(hc=>{"use strict";var EC=Re(),Nd=Hr(),RC={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()==="nan"?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Nd.stringifyNumber},CC={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e.replace(/_/g,"")),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():Nd.stringifyNumber(e)}},PC={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(e){let t=new EC.Scalar(parseFloat(e.replace(/_/g,""))),i=e.indexOf(".");if(i!==-1){let n=e.substring(i+1).replace(/_/g,"");n[n.length-1]==="0"&&(t.minFractionDigits=n.length)}return t},stringify:Nd.stringifyNumber};hc.float=PC;hc.floatExp=CC;hc.floatNaN=RC});var iv=P(Xa=>{"use strict";var tv=Hr(),Ya=e=>typeof e=="bigint"||Number.isInteger(e);function pc(e,t,i,{intAsBigInt:n}){let r=e[0];if((r==="-"||r==="+")&&(t+=1),e=e.substring(t).replace(/_/g,""),n){switch(i){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`;break}let o=BigInt(e);return r==="-"?BigInt(-1)*o:o}let a=parseInt(e,i);return r==="-"?-1*a:a}function bd(e,t,i){let{value:n}=e;if(Ya(n)){let r=n.toString(t);return n<0?"-"+i+r.substr(1):i+r}return tv.stringifyNumber(e)}var xC={identify:Ya,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,i)=>pc(e,2,2,i),stringify:e=>bd(e,2,"0b")},AC={identify:Ya,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,i)=>pc(e,1,8,i),stringify:e=>bd(e,8,"0")},TC={identify:Ya,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,i)=>pc(e,0,10,i),stringify:tv.stringifyNumber},_C={identify:Ya,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,i)=>pc(e,2,16,i),stringify:e=>bd(e,16,"0x")};Xa.int=TC;Xa.intBin=xC;Xa.intHex=_C;Xa.intOct=AC});var Sd=P(kd=>{"use strict";var gc=K(),mc=an(),vc=sn(),Un=class e extends vc.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let i;gc.isPair(t)?i=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?i=new mc.Pair(t.key,null):i=new mc.Pair(t,null),vc.findPair(this.items,i.key)||this.items.push(i)}get(t,i){let n=vc.findPair(this.items,t);return!i&&gc.isPair(n)?gc.isScalar(n.key)?n.key.value:n.key:n}set(t,i){if(typeof i!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof i}`);let n=vc.findPair(this.items,t);n&&!i?this.items.splice(this.items.indexOf(n),1):!n&&i&&this.items.push(new mc.Pair(t))}toJSON(t,i){return super.toJSON(t,i,Set)}toString(t,i,n){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),i,n);throw new Error("Set items must all have null values")}static from(t,i,n){let{replacer:r}=n,a=new this(t);if(i&&Symbol.iterator in Object(i))for(let o of i)typeof r=="function"&&(o=r.call(i,o,o)),a.items.push(mc.createPair(o,null,n));return a}};Un.tag="tag:yaml.org,2002:set";var IC={collection:"map",identify:e=>e instanceof Set,nodeClass:Un,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,i)=>Un.from(e,t,i),resolve(e,t){if(gc.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new Un,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};kd.YAMLSet=Un;kd.set=IC});var Rd=P(wc=>{"use strict";var jC=Hr();function Ed(e,t){let i=e[0],n=i==="-"||i==="+"?e.substring(1):e,r=o=>t?BigInt(o):Number(o),a=n.replace(/_/g,"").split(":").reduce((o,s)=>o*r(60)+r(s),r(0));return i==="-"?r(-1)*a:a}function nv(e){let{value:t}=e,i=o=>o;if(typeof t=="bigint")i=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return jC.stringifyNumber(e);let n="";t<0&&(n="-",t*=i(-1));let r=i(60),a=[t%r];return t<60?a.unshift(0):(t=(t-a[0])/r,a.unshift(t%r),t>=60&&(t=(t-a[0])/r,a.unshift(t))),n+a.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var OC={identify:e=>typeof e=="bigint"||Number.isInteger(e),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(e,t,{intAsBigInt:i})=>Ed(e,i),stringify:nv},$C={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:e=>Ed(e,!1),stringify:nv},rv={identify:e=>e instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(e){let t=e.match(rv.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,i,n,r,a,o,s]=t.map(Number),c=t[7]?Number((t[7]+"00").substr(1,3)):0,l=Date.UTC(i,n-1,r,a||0,o||0,s||0,c),u=t[8];if(u&&u!=="Z"){let d=Ed(u,!1);Math.abs(d)<30&&(d*=60),l-=6e4*d}return new Date(l)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};wc.floatTime=$C;wc.intTime=OC;wc.timestamp=rv});var sv=P(ov=>{"use strict";var HC=Or(),DC=ac(),MC=$r(),FC=Ga(),LC=pd(),av=Zm(),Cd=ev(),yc=iv(),BC=Xs(),qC=wd(),VC=fc(),WC=Sd(),Pd=Rd(),JC=[HC.map,MC.seq,FC.string,DC.nullTag,av.trueTag,av.falseTag,yc.intBin,yc.intOct,yc.int,yc.intHex,Cd.floatNaN,Cd.floatExp,Cd.float,LC.binary,BC.merge,qC.omap,VC.pairs,WC.set,Pd.intTime,Pd.floatTime,Pd.timestamp];ov.schema=JC});var gv=P(Td=>{"use strict";var dv=Or(),zC=ac(),fv=$r(),GC=Ga(),UC=od(),xd=cd(),Ad=ud(),KC=Lm(),YC=Vm(),hv=pd(),Qa=Xs(),pv=wd(),mv=fc(),cv=sv(),vv=Sd(),Nc=Rd(),lv=new Map([["core",KC.schema],["failsafe",[dv.map,fv.seq,GC.string]],["json",YC.schema],["yaml11",cv.schema],["yaml-1.1",cv.schema]]),uv={binary:hv.binary,bool:UC.boolTag,float:xd.float,floatExp:xd.floatExp,floatNaN:xd.floatNaN,floatTime:Nc.floatTime,int:Ad.int,intHex:Ad.intHex,intOct:Ad.intOct,intTime:Nc.intTime,map:dv.map,merge:Qa.merge,null:zC.nullTag,omap:pv.omap,pairs:mv.pairs,seq:fv.seq,set:vv.set,timestamp:Nc.timestamp},XC={"tag:yaml.org,2002:binary":hv.binary,"tag:yaml.org,2002:merge":Qa.merge,"tag:yaml.org,2002:omap":pv.omap,"tag:yaml.org,2002:pairs":mv.pairs,"tag:yaml.org,2002:set":vv.set,"tag:yaml.org,2002:timestamp":Nc.timestamp};function QC(e,t,i){let n=lv.get(t);if(n&&!e)return i&&!n.includes(Qa.merge)?n.concat(Qa.merge):n.slice();let r=n;if(!r)if(Array.isArray(e))r=[];else{let a=Array.from(lv.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${t}"; use one of ${a} or define customTags array`)}if(Array.isArray(e))for(let a of e)r=r.concat(a);else typeof e=="function"&&(r=e(r.slice()));return i&&(r=r.concat(Qa.merge)),r.reduce((a,o)=>{let s=typeof o=="string"?uv[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(uv).map(u=>JSON.stringify(u)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return a.includes(s)||a.push(s),a},[])}Td.coreKnownTags=XC;Td.getTags=QC});var jd=P(wv=>{"use strict";var _d=K(),ZC=Or(),eP=$r(),tP=Ga(),bc=gv(),iP=(e,t)=>e.keyt.key?1:0,Id=class e{constructor({compat:t,customTags:i,merge:n,resolveKnownTags:r,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?bc.getTags(t,"compat"):t?bc.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=r?bc.coreKnownTags:{},this.tags=bc.getTags(i,this.name,n),this.toStringOptions=s??null,Object.defineProperty(this,_d.MAP,{value:ZC.map}),Object.defineProperty(this,_d.SCALAR,{value:tP.string}),Object.defineProperty(this,_d.SEQ,{value:eP.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?iP:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};wv.Schema=Id});var Nv=P(yv=>{"use strict";var nP=K(),Od=Wa(),Za=La();function rP(e,t){let i=[],n=t.directives===!0;if(t.directives!==!1&&e.directives){let c=e.directives.toString(e);c?(i.push(c),n=!0):e.directives.docStart&&(n=!0)}n&&i.push("---");let r=Od.createStringifyContext(e,t),{commentString:a}=r.options;if(e.commentBefore){i.length!==1&&i.unshift("");let c=a(e.commentBefore);i.unshift(Za.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(nP.isNode(e.contents)){if(e.contents.spaceBefore&&n&&i.push(""),e.contents.commentBefore){let u=a(e.contents.commentBefore);i.push(Za.indentComment(u,""))}r.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=Od.stringify(e.contents,r,()=>s=null,c);s&&(l+=Za.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&i[i.length-1]==="---"?i[i.length-1]=`--- ${l}`:i.push(l)}else i.push(Od.stringify(e.contents,r));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(` +${a.comment}`:n.comment}n=r}e.items[i]=uc.isPair(n)?n:new md.Pair(n)}}else t("Expected a sequence for this tag");return e}function Gm(e,t,i){let{replacer:n}=i,r=new NC.YAMLSeq(e);r.tag="tag:yaml.org,2002:pairs";let a=0;if(t&&Symbol.iterator in Object(t))for(let o of t){typeof n=="function"&&(o=n.call(t,String(a++),o));let s,c;if(Array.isArray(o))if(o.length===2)s=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)s=l[0],c=o[s];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else s=o;r.items.push(md.createPair(s,c,i))}return r}var bC={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:zm,createNode:Gm};dc.createPairs=Gm;dc.pairs=bC;dc.resolvePairs=zm});var wd=P(gd=>{"use strict";var Um=K(),vd=en(),Ka=sn(),kC=cn(),Km=fc(),Gn=class e extends kC.YAMLSeq{constructor(){super(),this.add=Ka.YAMLMap.prototype.add.bind(this),this.delete=Ka.YAMLMap.prototype.delete.bind(this),this.get=Ka.YAMLMap.prototype.get.bind(this),this.has=Ka.YAMLMap.prototype.has.bind(this),this.set=Ka.YAMLMap.prototype.set.bind(this),this.tag=e.tag}toJSON(t,i){if(!i)return super.toJSON(t);let n=new Map;i?.onCreate&&i.onCreate(n);for(let r of this.items){let a,o;if(Um.isPair(r)?(a=vd.toJS(r.key,"",i),o=vd.toJS(r.value,a,i)):a=vd.toJS(r,"",i),n.has(a))throw new Error("Ordered maps must not include duplicate keys");n.set(a,o)}return n}static from(t,i,n){let r=Km.createPairs(t,i,n),a=new this;return a.items=r.items,a}};Gn.tag="tag:yaml.org,2002:omap";var SC={collection:"seq",identify:e=>e instanceof Map,nodeClass:Gn,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let i=Km.resolvePairs(e,t),n=[];for(let{key:r}of i.items)Um.isScalar(r)&&(n.includes(r.value)?t(`Ordered maps must not include duplicate keys: ${r.value}`):n.push(r.value));return Object.assign(new Gn,i)},createNode:(e,t,i)=>Gn.from(e,t,i)};gd.YAMLOMap=Gn;gd.omap=SC});var ev=P(yd=>{"use strict";var Ym=Re();function Xm({value:e,source:t},i){return t&&(e?Qm:Zm).test.test(t)?t:e?i.options.trueStr:i.options.falseStr}var Qm={identify:e=>e===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new Ym.Scalar(!0),stringify:Xm},Zm={identify:e=>e===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new Ym.Scalar(!1),stringify:Xm};yd.falseTag=Zm;yd.trueTag=Qm});var tv=P(hc=>{"use strict";var EC=Re(),Nd=Hr(),RC={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()==="nan"?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Nd.stringifyNumber},CC={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e.replace(/_/g,"")),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():Nd.stringifyNumber(e)}},PC={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(e){let t=new EC.Scalar(parseFloat(e.replace(/_/g,""))),i=e.indexOf(".");if(i!==-1){let n=e.substring(i+1).replace(/_/g,"");n[n.length-1]==="0"&&(t.minFractionDigits=n.length)}return t},stringify:Nd.stringifyNumber};hc.float=PC;hc.floatExp=CC;hc.floatNaN=RC});var nv=P(Xa=>{"use strict";var iv=Hr(),Ya=e=>typeof e=="bigint"||Number.isInteger(e);function pc(e,t,i,{intAsBigInt:n}){let r=e[0];if((r==="-"||r==="+")&&(t+=1),e=e.substring(t).replace(/_/g,""),n){switch(i){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`;break}let o=BigInt(e);return r==="-"?BigInt(-1)*o:o}let a=parseInt(e,i);return r==="-"?-1*a:a}function bd(e,t,i){let{value:n}=e;if(Ya(n)){let r=n.toString(t);return n<0?"-"+i+r.substr(1):i+r}return iv.stringifyNumber(e)}var xC={identify:Ya,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,i)=>pc(e,2,2,i),stringify:e=>bd(e,2,"0b")},AC={identify:Ya,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,i)=>pc(e,1,8,i),stringify:e=>bd(e,8,"0")},TC={identify:Ya,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,i)=>pc(e,0,10,i),stringify:iv.stringifyNumber},_C={identify:Ya,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,i)=>pc(e,2,16,i),stringify:e=>bd(e,16,"0x")};Xa.int=TC;Xa.intBin=xC;Xa.intHex=_C;Xa.intOct=AC});var Sd=P(kd=>{"use strict";var gc=K(),mc=an(),vc=sn(),Un=class e extends vc.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let i;gc.isPair(t)?i=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?i=new mc.Pair(t.key,null):i=new mc.Pair(t,null),vc.findPair(this.items,i.key)||this.items.push(i)}get(t,i){let n=vc.findPair(this.items,t);return!i&&gc.isPair(n)?gc.isScalar(n.key)?n.key.value:n.key:n}set(t,i){if(typeof i!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof i}`);let n=vc.findPair(this.items,t);n&&!i?this.items.splice(this.items.indexOf(n),1):!n&&i&&this.items.push(new mc.Pair(t))}toJSON(t,i){return super.toJSON(t,i,Set)}toString(t,i,n){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),i,n);throw new Error("Set items must all have null values")}static from(t,i,n){let{replacer:r}=n,a=new this(t);if(i&&Symbol.iterator in Object(i))for(let o of i)typeof r=="function"&&(o=r.call(i,o,o)),a.items.push(mc.createPair(o,null,n));return a}};Un.tag="tag:yaml.org,2002:set";var IC={collection:"map",identify:e=>e instanceof Set,nodeClass:Un,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,i)=>Un.from(e,t,i),resolve(e,t){if(gc.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new Un,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};kd.YAMLSet=Un;kd.set=IC});var Rd=P(wc=>{"use strict";var jC=Hr();function Ed(e,t){let i=e[0],n=i==="-"||i==="+"?e.substring(1):e,r=o=>t?BigInt(o):Number(o),a=n.replace(/_/g,"").split(":").reduce((o,s)=>o*r(60)+r(s),r(0));return i==="-"?r(-1)*a:a}function rv(e){let{value:t}=e,i=o=>o;if(typeof t=="bigint")i=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return jC.stringifyNumber(e);let n="";t<0&&(n="-",t*=i(-1));let r=i(60),a=[t%r];return t<60?a.unshift(0):(t=(t-a[0])/r,a.unshift(t%r),t>=60&&(t=(t-a[0])/r,a.unshift(t))),n+a.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var OC={identify:e=>typeof e=="bigint"||Number.isInteger(e),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(e,t,{intAsBigInt:i})=>Ed(e,i),stringify:rv},$C={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:e=>Ed(e,!1),stringify:rv},av={identify:e=>e instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(e){let t=e.match(av.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,i,n,r,a,o,s]=t.map(Number),c=t[7]?Number((t[7]+"00").substr(1,3)):0,l=Date.UTC(i,n-1,r,a||0,o||0,s||0,c),u=t[8];if(u&&u!=="Z"){let d=Ed(u,!1);Math.abs(d)<30&&(d*=60),l-=6e4*d}return new Date(l)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};wc.floatTime=$C;wc.intTime=OC;wc.timestamp=av});var cv=P(sv=>{"use strict";var HC=Or(),DC=ac(),MC=$r(),FC=Ga(),LC=pd(),ov=ev(),Cd=tv(),yc=nv(),BC=Xs(),qC=wd(),VC=fc(),WC=Sd(),Pd=Rd(),JC=[HC.map,MC.seq,FC.string,DC.nullTag,ov.trueTag,ov.falseTag,yc.intBin,yc.intOct,yc.int,yc.intHex,Cd.floatNaN,Cd.floatExp,Cd.float,LC.binary,BC.merge,qC.omap,VC.pairs,WC.set,Pd.intTime,Pd.floatTime,Pd.timestamp];sv.schema=JC});var wv=P(Td=>{"use strict";var fv=Or(),zC=ac(),hv=$r(),GC=Ga(),UC=od(),xd=cd(),Ad=ud(),KC=Bm(),YC=Wm(),pv=pd(),Qa=Xs(),mv=wd(),vv=fc(),lv=cv(),gv=Sd(),Nc=Rd(),uv=new Map([["core",KC.schema],["failsafe",[fv.map,hv.seq,GC.string]],["json",YC.schema],["yaml11",lv.schema],["yaml-1.1",lv.schema]]),dv={binary:pv.binary,bool:UC.boolTag,float:xd.float,floatExp:xd.floatExp,floatNaN:xd.floatNaN,floatTime:Nc.floatTime,int:Ad.int,intHex:Ad.intHex,intOct:Ad.intOct,intTime:Nc.intTime,map:fv.map,merge:Qa.merge,null:zC.nullTag,omap:mv.omap,pairs:vv.pairs,seq:hv.seq,set:gv.set,timestamp:Nc.timestamp},XC={"tag:yaml.org,2002:binary":pv.binary,"tag:yaml.org,2002:merge":Qa.merge,"tag:yaml.org,2002:omap":mv.omap,"tag:yaml.org,2002:pairs":vv.pairs,"tag:yaml.org,2002:set":gv.set,"tag:yaml.org,2002:timestamp":Nc.timestamp};function QC(e,t,i){let n=uv.get(t);if(n&&!e)return i&&!n.includes(Qa.merge)?n.concat(Qa.merge):n.slice();let r=n;if(!r)if(Array.isArray(e))r=[];else{let a=Array.from(uv.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${t}"; use one of ${a} or define customTags array`)}if(Array.isArray(e))for(let a of e)r=r.concat(a);else typeof e=="function"&&(r=e(r.slice()));return i&&(r=r.concat(Qa.merge)),r.reduce((a,o)=>{let s=typeof o=="string"?dv[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(dv).map(u=>JSON.stringify(u)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return a.includes(s)||a.push(s),a},[])}Td.coreKnownTags=XC;Td.getTags=QC});var jd=P(yv=>{"use strict";var _d=K(),ZC=Or(),eP=$r(),tP=Ga(),bc=wv(),iP=(e,t)=>e.keyt.key?1:0,Id=class e{constructor({compat:t,customTags:i,merge:n,resolveKnownTags:r,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?bc.getTags(t,"compat"):t?bc.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=r?bc.coreKnownTags:{},this.tags=bc.getTags(i,this.name,n),this.toStringOptions=s??null,Object.defineProperty(this,_d.MAP,{value:ZC.map}),Object.defineProperty(this,_d.SCALAR,{value:tP.string}),Object.defineProperty(this,_d.SEQ,{value:eP.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?iP:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};yv.Schema=Id});var bv=P(Nv=>{"use strict";var nP=K(),Od=Wa(),Za=La();function rP(e,t){let i=[],n=t.directives===!0;if(t.directives!==!1&&e.directives){let c=e.directives.toString(e);c?(i.push(c),n=!0):e.directives.docStart&&(n=!0)}n&&i.push("---");let r=Od.createStringifyContext(e,t),{commentString:a}=r.options;if(e.commentBefore){i.length!==1&&i.unshift("");let c=a(e.commentBefore);i.unshift(Za.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(nP.isNode(e.contents)){if(e.contents.spaceBefore&&n&&i.push(""),e.contents.commentBefore){let u=a(e.contents.commentBefore);i.push(Za.indentComment(u,""))}r.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=Od.stringify(e.contents,r,()=>s=null,c);s&&(l+=Za.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&i[i.length-1]==="---"?i[i.length-1]=`--- ${l}`:i.push(l)}else i.push(Od.stringify(e.contents,r));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(` `)?(i.push("..."),i.push(Za.indentComment(c,""))):i.push(`... ${c}`)}else i.push("...");else{let c=e.comment;c&&o&&(c=c.replace(/^\n+/,"")),c&&((!o||s)&&i[i.length-1]!==""&&i.push(""),i.push(Za.indentComment(a(c),"")))}return i.join(` `)+` -`}yv.stringifyDocument=rP});var eo=P(bv=>{"use strict";var aP=Ma(),Dr=Bs(),Ct=K(),oP=an(),sP=en(),cP=jd(),lP=Nv(),$d=Ds(),uP=Fu(),dP=Fa(),Hd=Mu(),Dd=class e{constructor(t,i,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,Ct.NODE_TYPE,{value:Ct.DOC});let r=null;typeof i=="function"||Array.isArray(i)?r=i:n===void 0&&i&&(n=i,i=void 0);let a=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},n);this.options=a;let{version:o}=a;n?._directives?(this.directives=n._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new Hd.Directives({version:o}),this.setSchema(o,n),this.contents=t===void 0?null:this.createNode(t,r,n)}clone(){let t=Object.create(e.prototype,{[Ct.NODE_TYPE]:{value:Ct.DOC}});return t.commentBefore=this.commentBefore,t.comment=this.comment,t.errors=this.errors.slice(),t.warnings=this.warnings.slice(),t.options=Object.assign({},this.options),this.directives&&(t.directives=this.directives.clone()),t.schema=this.schema.clone(),t.contents=Ct.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){Mr(this.contents)&&this.contents.add(t)}addIn(t,i){Mr(this.contents)&&this.contents.addIn(t,i)}createAlias(t,i){if(!t.anchor){let n=$d.anchorNames(this);t.anchor=!i||n.has(i)?$d.findNewAnchor(i||"a",n):i}return new aP.Alias(t.anchor)}createNode(t,i,n){let r;if(typeof i=="function")t=i.call({"":t},"",t),r=i;else if(Array.isArray(i)){let v=k=>typeof k=="number"||k instanceof String||k instanceof Number,S=i.filter(v).map(String);S.length>0&&(i=i.concat(S)),r=i}else n===void 0&&i&&(n=i,i=void 0);let{aliasDuplicateObjects:a,anchorPrefix:o,flow:s,keepUndefined:c,onTagObj:l,tag:u}=n??{},{onAnchor:d,setAnchors:f,sourceObjects:h}=$d.createNodeAnchors(this,o||"a"),m={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:d,onTagObj:l,replacer:r,schema:this.schema,sourceObjects:h},p=dP.createNode(t,u,m);return s&&Ct.isCollection(p)&&(p.flow=!0),f(),p}createPair(t,i,n={}){let r=this.createNode(t,null,n),a=this.createNode(i,null,n);return new oP.Pair(r,a)}delete(t){return Mr(this.contents)?this.contents.delete(t):!1}deleteIn(t){return Dr.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):Mr(this.contents)?this.contents.deleteIn(t):!1}get(t,i){return Ct.isCollection(this.contents)?this.contents.get(t,i):void 0}getIn(t,i){return Dr.isEmptyPath(t)?!i&&Ct.isScalar(this.contents)?this.contents.value:this.contents:Ct.isCollection(this.contents)?this.contents.getIn(t,i):void 0}has(t){return Ct.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return Dr.isEmptyPath(t)?this.contents!==void 0:Ct.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,i){this.contents==null?this.contents=Dr.collectionFromPath(this.schema,[t],i):Mr(this.contents)&&this.contents.set(t,i)}setIn(t,i){Dr.isEmptyPath(t)?this.contents=i:this.contents==null?this.contents=Dr.collectionFromPath(this.schema,Array.from(t),i):Mr(this.contents)&&this.contents.setIn(t,i)}setSchema(t,i={}){typeof t=="number"&&(t=String(t));let n;switch(t){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new Hd.Directives({version:"1.1"}),n={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=t:this.directives=new Hd.Directives({version:t}),n={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,n=null;break;default:{let r=JSON.stringify(t);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${r}`)}}if(i.schema instanceof Object)this.schema=i.schema;else if(n)this.schema=new cP.Schema(Object.assign(n,i));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:t,jsonArg:i,mapAsMap:n,maxAliasCount:r,onAnchor:a,reviver:o}={}){let s={anchors:new Map,doc:this,keep:!t,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},c=sP.toJS(this.contents,i??"",s);if(typeof a=="function")for(let{count:l,res:u}of s.anchors.values())a(u,l);return typeof o=="function"?uP.applyReviver(o,{"":c},"",c):c}toJSON(t,i){return this.toJS({json:!0,jsonArg:t,mapAsMap:!1,onAnchor:i})}toString(t={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in t&&(!Number.isInteger(t.indent)||Number(t.indent)<=0)){let i=JSON.stringify(t.indent);throw new Error(`"indent" option must be a positive integer, not ${i}`)}return lP.stringifyDocument(this,t)}};function Mr(e){if(Ct.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}bv.Document=Dd});var no=P(io=>{"use strict";var to=class extends Error{constructor(t,i,n,r){super(),this.name=t,this.code=n,this.message=r,this.pos=i}},Md=class extends to{constructor(t,i,n){super("YAMLParseError",t,i,n)}},Fd=class extends to{constructor(t,i,n){super("YAMLWarning",t,i,n)}},fP=(e,t)=>i=>{if(i.pos[0]===-1)return;i.linePos=i.pos.map(s=>t.linePos(s));let{line:n,col:r}=i.linePos[0];i.message+=` at line ${n}, column ${r}`;let a=r-1,o=e.substring(t.lineStarts[n-1],t.lineStarts[n]).replace(/[\n\r]+$/,"");if(a>=60&&o.length>80){let s=Math.min(a-39,o.length-79);o="…"+o.substring(s),a-=s-1}if(o.length>80&&(o=o.substring(0,79)+"…"),n>1&&/^ *$/.test(o.substring(0,a))){let s=e.substring(t.lineStarts[n-2],t.lineStarts[n-1]);s.length>80&&(s=s.substring(0,79)+`… +`}Nv.stringifyDocument=rP});var eo=P(kv=>{"use strict";var aP=Ma(),Dr=Bs(),Ct=K(),oP=an(),sP=en(),cP=jd(),lP=bv(),$d=Ds(),uP=Fu(),dP=Fa(),Hd=Mu(),Dd=class e{constructor(t,i,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,Ct.NODE_TYPE,{value:Ct.DOC});let r=null;typeof i=="function"||Array.isArray(i)?r=i:n===void 0&&i&&(n=i,i=void 0);let a=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},n);this.options=a;let{version:o}=a;n?._directives?(this.directives=n._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new Hd.Directives({version:o}),this.setSchema(o,n),this.contents=t===void 0?null:this.createNode(t,r,n)}clone(){let t=Object.create(e.prototype,{[Ct.NODE_TYPE]:{value:Ct.DOC}});return t.commentBefore=this.commentBefore,t.comment=this.comment,t.errors=this.errors.slice(),t.warnings=this.warnings.slice(),t.options=Object.assign({},this.options),this.directives&&(t.directives=this.directives.clone()),t.schema=this.schema.clone(),t.contents=Ct.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){Mr(this.contents)&&this.contents.add(t)}addIn(t,i){Mr(this.contents)&&this.contents.addIn(t,i)}createAlias(t,i){if(!t.anchor){let n=$d.anchorNames(this);t.anchor=!i||n.has(i)?$d.findNewAnchor(i||"a",n):i}return new aP.Alias(t.anchor)}createNode(t,i,n){let r;if(typeof i=="function")t=i.call({"":t},"",t),r=i;else if(Array.isArray(i)){let v=k=>typeof k=="number"||k instanceof String||k instanceof Number,S=i.filter(v).map(String);S.length>0&&(i=i.concat(S)),r=i}else n===void 0&&i&&(n=i,i=void 0);let{aliasDuplicateObjects:a,anchorPrefix:o,flow:s,keepUndefined:c,onTagObj:l,tag:u}=n??{},{onAnchor:d,setAnchors:f,sourceObjects:h}=$d.createNodeAnchors(this,o||"a"),m={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:d,onTagObj:l,replacer:r,schema:this.schema,sourceObjects:h},p=dP.createNode(t,u,m);return s&&Ct.isCollection(p)&&(p.flow=!0),f(),p}createPair(t,i,n={}){let r=this.createNode(t,null,n),a=this.createNode(i,null,n);return new oP.Pair(r,a)}delete(t){return Mr(this.contents)?this.contents.delete(t):!1}deleteIn(t){return Dr.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):Mr(this.contents)?this.contents.deleteIn(t):!1}get(t,i){return Ct.isCollection(this.contents)?this.contents.get(t,i):void 0}getIn(t,i){return Dr.isEmptyPath(t)?!i&&Ct.isScalar(this.contents)?this.contents.value:this.contents:Ct.isCollection(this.contents)?this.contents.getIn(t,i):void 0}has(t){return Ct.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return Dr.isEmptyPath(t)?this.contents!==void 0:Ct.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,i){this.contents==null?this.contents=Dr.collectionFromPath(this.schema,[t],i):Mr(this.contents)&&this.contents.set(t,i)}setIn(t,i){Dr.isEmptyPath(t)?this.contents=i:this.contents==null?this.contents=Dr.collectionFromPath(this.schema,Array.from(t),i):Mr(this.contents)&&this.contents.setIn(t,i)}setSchema(t,i={}){typeof t=="number"&&(t=String(t));let n;switch(t){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new Hd.Directives({version:"1.1"}),n={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=t:this.directives=new Hd.Directives({version:t}),n={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,n=null;break;default:{let r=JSON.stringify(t);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${r}`)}}if(i.schema instanceof Object)this.schema=i.schema;else if(n)this.schema=new cP.Schema(Object.assign(n,i));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:t,jsonArg:i,mapAsMap:n,maxAliasCount:r,onAnchor:a,reviver:o}={}){let s={anchors:new Map,doc:this,keep:!t,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},c=sP.toJS(this.contents,i??"",s);if(typeof a=="function")for(let{count:l,res:u}of s.anchors.values())a(u,l);return typeof o=="function"?uP.applyReviver(o,{"":c},"",c):c}toJSON(t,i){return this.toJS({json:!0,jsonArg:t,mapAsMap:!1,onAnchor:i})}toString(t={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in t&&(!Number.isInteger(t.indent)||Number(t.indent)<=0)){let i=JSON.stringify(t.indent);throw new Error(`"indent" option must be a positive integer, not ${i}`)}return lP.stringifyDocument(this,t)}};function Mr(e){if(Ct.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}kv.Document=Dd});var no=P(io=>{"use strict";var to=class extends Error{constructor(t,i,n,r){super(),this.name=t,this.code=n,this.message=r,this.pos=i}},Md=class extends to{constructor(t,i,n){super("YAMLParseError",t,i,n)}},Fd=class extends to{constructor(t,i,n){super("YAMLWarning",t,i,n)}},fP=(e,t)=>i=>{if(i.pos[0]===-1)return;i.linePos=i.pos.map(s=>t.linePos(s));let{line:n,col:r}=i.linePos[0];i.message+=` at line ${n}, column ${r}`;let a=r-1,o=e.substring(t.lineStarts[n-1],t.lineStarts[n]).replace(/[\n\r]+$/,"");if(a>=60&&o.length>80){let s=Math.min(a-39,o.length-79);o="…"+o.substring(s),a-=s-1}if(o.length>80&&(o=o.substring(0,79)+"…"),n>1&&/^ *$/.test(o.substring(0,a))){let s=e.substring(t.lineStarts[n-2],t.lineStarts[n-1]);s.length>80&&(s=s.substring(0,79)+`… `),o=s+o}if(/[^ ]/.test(o)){let s=1,c=i.linePos[1];c?.line===n&&c.col>r&&(s=Math.max(1,Math.min(c.col-r,80-a)));let l=" ".repeat(a)+"^".repeat(s);i.message+=`: ${o} ${l} -`}};io.YAMLError=to;io.YAMLParseError=Md;io.YAMLWarning=Fd;io.prettifyError=fP});var ro=P(kv=>{"use strict";function hP(e,{flow:t,indicator:i,next:n,offset:r,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,u=s,d="",f="",h=!1,m=!1,p=null,v=null,S=null,k=null,N=null,b=null,R=null;for(let g of e)switch(m&&(g.type!=="space"&&g.type!=="newline"&&g.type!=="comma"&&a(g.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m=!1),p&&(l&&g.type!=="comment"&&g.type!=="newline"&&a(p,"TAB_AS_INDENT","Tabs are not allowed as indentation"),p=null),g.type){case"space":!t&&(i!=="doc-start"||n?.type!=="flow-collection")&&g.source.includes(" ")&&(p=g),u=!0;break;case"comment":{u||a(g,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let E=g.source.substring(1)||" ";d?d+=f+E:d=E,f="",l=!1;break}case"newline":l?d?d+=g.source:(!b||i!=="seq-item-ind")&&(c=!0):f+=g.source,l=!0,h=!0,(v||S)&&(k=g),u=!0;break;case"anchor":v&&a(g,"MULTIPLE_ANCHORS","A node can have at most one anchor"),g.source.endsWith(":")&&a(g.offset+g.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),v=g,R??(R=g.offset),l=!1,u=!1,m=!0;break;case"tag":{S&&a(g,"MULTIPLE_TAGS","A node can have at most one tag"),S=g,R??(R=g.offset),l=!1,u=!1,m=!0;break}case i:(v||S)&&a(g,"BAD_PROP_ORDER",`Anchors and tags must be after the ${g.source} indicator`),b&&a(g,"UNEXPECTED_TOKEN",`Unexpected ${g.source} in ${t??"collection"}`),b=g,l=i==="seq-item-ind"||i==="explicit-key-ind",u=!1;break;case"comma":if(t){N&&a(g,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),N=g,l=!1,u=!1;break}default:a(g,"UNEXPECTED_TOKEN",`Unexpected ${g.type} token`),l=!1,u=!1}let y=e[e.length-1],w=y?y.offset+y.source.length:r;return m&&n&&n.type!=="space"&&n.type!=="newline"&&n.type!=="comma"&&(n.type!=="scalar"||n.source!=="")&&a(n.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),p&&(l&&p.indent<=o||n?.type==="block-map"||n?.type==="block-seq")&&a(p,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:N,found:b,spaceBefore:c,comment:d,hasNewline:h,anchor:v,tag:S,newlineAfterProp:k,end:w,start:R??w}}kv.resolveProps=hP});var kc=P(Sv=>{"use strict";function Ld(e){if(!e)return null;switch(e.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(e.source.includes(` -`))return!0;if(e.end){for(let t of e.end)if(t.type==="newline")return!0}return!1;case"flow-collection":for(let t of e.items){for(let i of t.start)if(i.type==="newline")return!0;if(t.sep){for(let i of t.sep)if(i.type==="newline")return!0}if(Ld(t.key)||Ld(t.value))return!0}return!1;default:return!0}}Sv.containsNewline=Ld});var Bd=P(Ev=>{"use strict";var pP=kc();function mP(e,t,i){if(t?.type==="flow-collection"){let n=t.end[0];n.indent===e&&(n.source==="]"||n.source==="}")&&pP.containsNewline(t)&&i(n,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Ev.flowIndentCheck=mP});var qd=P(Cv=>{"use strict";var Rv=K();function vP(e,t,i){let{uniqueKeys:n}=e.options;if(n===!1)return!1;let r=typeof n=="function"?n:(a,o)=>a===o||Rv.isScalar(a)&&Rv.isScalar(o)&&a.value===o.value;return t.some(a=>r(a.key,i))}Cv.mapIncludes=vP});var Iv=P(_v=>{"use strict";var Pv=an(),gP=sn(),xv=ro(),wP=kc(),Av=Bd(),yP=qd(),Tv="All mapping items must start at the same column";function NP({composeNode:e,composeEmptyNode:t},i,n,r,a){let o=a?.nodeClass??gP.YAMLMap,s=new o(i.schema);i.atRoot&&(i.atRoot=!1);let c=n.offset,l=null;for(let u of n.items){let{start:d,key:f,sep:h,value:m}=u,p=xv.resolveProps(d,{indicator:"explicit-key-ind",next:f??h?.[0],offset:c,onError:r,parentIndent:n.indent,startOnNewline:!0}),v=!p.found;if(v){if(f&&(f.type==="block-seq"?r(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in f&&f.indent!==n.indent&&r(c,"BAD_INDENT",Tv)),!p.anchor&&!p.tag&&!h){l=p.end,p.comment&&(s.comment?s.comment+=` -`+p.comment:s.comment=p.comment);continue}(p.newlineAfterProp||wP.containsNewline(f))&&r(f??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else p.found?.indent!==n.indent&&r(c,"BAD_INDENT",Tv);i.atKey=!0;let S=p.end,k=f?e(i,f,p,r):t(i,S,d,null,p,r);i.schema.compat&&Av.flowIndentCheck(n.indent,f,r),i.atKey=!1,yP.mapIncludes(i,s.items,k)&&r(S,"DUPLICATE_KEY","Map keys must be unique");let N=xv.resolveProps(h??[],{indicator:"map-value-ind",next:m,offset:k.range[2],onError:r,parentIndent:n.indent,startOnNewline:!f||f.type==="block-scalar"});if(c=N.end,N.found){v&&(m?.type==="block-map"&&!N.hasNewline&&r(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),i.options.strict&&p.start{"use strict";var bP=cn(),kP=ro(),SP=Bd();function EP({composeNode:e,composeEmptyNode:t},i,n,r,a){let o=a?.nodeClass??bP.YAMLSeq,s=new o(i.schema);i.atRoot&&(i.atRoot=!1),i.atKey&&(i.atKey=!1);let c=n.offset,l=null;for(let{start:u,value:d}of n.items){let f=kP.resolveProps(u,{indicator:"seq-item-ind",next:d,offset:c,onError:r,parentIndent:n.indent,startOnNewline:!0});if(!f.found)if(f.anchor||f.tag||d)d?.type==="block-seq"?r(f.end,"BAD_INDENT","All sequence items must start at the same column"):r(c,"MISSING_CHAR","Sequence item without - indicator");else{l=f.end,f.comment&&(s.comment=f.comment);continue}let h=d?e(i,d,f,r):t(i,f.end,u,null,f,r);i.schema.compat&&SP.flowIndentCheck(n.indent,d,r),c=h.range[2],s.items.push(h)}return s.range=[n.offset,c,l??c],s}jv.resolveBlockSeq=EP});var Fr=P($v=>{"use strict";function RP(e,t,i,n){let r="";if(e){let a=!1,o="";for(let s of e){let{source:c,type:l}=s;switch(l){case"space":a=!0;break;case"comment":{i&&!a&&n(s,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let u=c.substring(1)||" ";r?r+=o+u:r=u,o="";break}case"newline":r&&(o+=c),a=!0;break;default:n(s,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}t+=c.length}}return{comment:r,offset:t}}$v.resolveEnd=RP});var Fv=P(Mv=>{"use strict";var CP=K(),PP=an(),Hv=sn(),xP=cn(),AP=Fr(),Dv=ro(),TP=kc(),_P=qd(),Vd="Block collections are not allowed within flow collections",Wd=e=>e&&(e.type==="block-map"||e.type==="block-seq");function IP({composeNode:e,composeEmptyNode:t},i,n,r,a){let o=n.start.source==="{",s=o?"flow map":"flow sequence",c=a?.nodeClass??(o?Hv.YAMLMap:xP.YAMLSeq),l=new c(i.schema);l.flow=!0;let u=i.atRoot;u&&(i.atRoot=!1),i.atKey&&(i.atKey=!1);let d=n.offset+n.start.source.length;for(let v=0;v{"use strict";function hP(e,{flow:t,indicator:i,next:n,offset:r,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,u=s,d="",f="",h=!1,m=!1,p=null,v=null,S=null,k=null,N=null,b=null,R=null;for(let g of e)switch(m&&(g.type!=="space"&&g.type!=="newline"&&g.type!=="comma"&&a(g.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m=!1),p&&(l&&g.type!=="comment"&&g.type!=="newline"&&a(p,"TAB_AS_INDENT","Tabs are not allowed as indentation"),p=null),g.type){case"space":!t&&(i!=="doc-start"||n?.type!=="flow-collection")&&g.source.includes(" ")&&(p=g),u=!0;break;case"comment":{u||a(g,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let E=g.source.substring(1)||" ";d?d+=f+E:d=E,f="",l=!1;break}case"newline":l?d?d+=g.source:(!b||i!=="seq-item-ind")&&(c=!0):f+=g.source,l=!0,h=!0,(v||S)&&(k=g),u=!0;break;case"anchor":v&&a(g,"MULTIPLE_ANCHORS","A node can have at most one anchor"),g.source.endsWith(":")&&a(g.offset+g.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),v=g,R??(R=g.offset),l=!1,u=!1,m=!0;break;case"tag":{S&&a(g,"MULTIPLE_TAGS","A node can have at most one tag"),S=g,R??(R=g.offset),l=!1,u=!1,m=!0;break}case i:(v||S)&&a(g,"BAD_PROP_ORDER",`Anchors and tags must be after the ${g.source} indicator`),b&&a(g,"UNEXPECTED_TOKEN",`Unexpected ${g.source} in ${t??"collection"}`),b=g,l=i==="seq-item-ind"||i==="explicit-key-ind",u=!1;break;case"comma":if(t){N&&a(g,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),N=g,l=!1,u=!1;break}default:a(g,"UNEXPECTED_TOKEN",`Unexpected ${g.type} token`),l=!1,u=!1}let y=e[e.length-1],w=y?y.offset+y.source.length:r;return m&&n&&n.type!=="space"&&n.type!=="newline"&&n.type!=="comma"&&(n.type!=="scalar"||n.source!=="")&&a(n.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),p&&(l&&p.indent<=o||n?.type==="block-map"||n?.type==="block-seq")&&a(p,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:N,found:b,spaceBefore:c,comment:d,hasNewline:h,anchor:v,tag:S,newlineAfterProp:k,end:w,start:R??w}}Sv.resolveProps=hP});var kc=P(Ev=>{"use strict";function Ld(e){if(!e)return null;switch(e.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(e.source.includes(` +`))return!0;if(e.end){for(let t of e.end)if(t.type==="newline")return!0}return!1;case"flow-collection":for(let t of e.items){for(let i of t.start)if(i.type==="newline")return!0;if(t.sep){for(let i of t.sep)if(i.type==="newline")return!0}if(Ld(t.key)||Ld(t.value))return!0}return!1;default:return!0}}Ev.containsNewline=Ld});var Bd=P(Rv=>{"use strict";var pP=kc();function mP(e,t,i){if(t?.type==="flow-collection"){let n=t.end[0];n.indent===e&&(n.source==="]"||n.source==="}")&&pP.containsNewline(t)&&i(n,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Rv.flowIndentCheck=mP});var qd=P(Pv=>{"use strict";var Cv=K();function vP(e,t,i){let{uniqueKeys:n}=e.options;if(n===!1)return!1;let r=typeof n=="function"?n:(a,o)=>a===o||Cv.isScalar(a)&&Cv.isScalar(o)&&a.value===o.value;return t.some(a=>r(a.key,i))}Pv.mapIncludes=vP});var jv=P(Iv=>{"use strict";var xv=an(),gP=sn(),Av=ro(),wP=kc(),Tv=Bd(),yP=qd(),_v="All mapping items must start at the same column";function NP({composeNode:e,composeEmptyNode:t},i,n,r,a){let o=a?.nodeClass??gP.YAMLMap,s=new o(i.schema);i.atRoot&&(i.atRoot=!1);let c=n.offset,l=null;for(let u of n.items){let{start:d,key:f,sep:h,value:m}=u,p=Av.resolveProps(d,{indicator:"explicit-key-ind",next:f??h?.[0],offset:c,onError:r,parentIndent:n.indent,startOnNewline:!0}),v=!p.found;if(v){if(f&&(f.type==="block-seq"?r(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in f&&f.indent!==n.indent&&r(c,"BAD_INDENT",_v)),!p.anchor&&!p.tag&&!h){l=p.end,p.comment&&(s.comment?s.comment+=` +`+p.comment:s.comment=p.comment);continue}(p.newlineAfterProp||wP.containsNewline(f))&&r(f??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else p.found?.indent!==n.indent&&r(c,"BAD_INDENT",_v);i.atKey=!0;let S=p.end,k=f?e(i,f,p,r):t(i,S,d,null,p,r);i.schema.compat&&Tv.flowIndentCheck(n.indent,f,r),i.atKey=!1,yP.mapIncludes(i,s.items,k)&&r(S,"DUPLICATE_KEY","Map keys must be unique");let N=Av.resolveProps(h??[],{indicator:"map-value-ind",next:m,offset:k.range[2],onError:r,parentIndent:n.indent,startOnNewline:!f||f.type==="block-scalar"});if(c=N.end,N.found){v&&(m?.type==="block-map"&&!N.hasNewline&&r(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),i.options.strict&&p.start{"use strict";var bP=cn(),kP=ro(),SP=Bd();function EP({composeNode:e,composeEmptyNode:t},i,n,r,a){let o=a?.nodeClass??bP.YAMLSeq,s=new o(i.schema);i.atRoot&&(i.atRoot=!1),i.atKey&&(i.atKey=!1);let c=n.offset,l=null;for(let{start:u,value:d}of n.items){let f=kP.resolveProps(u,{indicator:"seq-item-ind",next:d,offset:c,onError:r,parentIndent:n.indent,startOnNewline:!0});if(!f.found)if(f.anchor||f.tag||d)d?.type==="block-seq"?r(f.end,"BAD_INDENT","All sequence items must start at the same column"):r(c,"MISSING_CHAR","Sequence item without - indicator");else{l=f.end,f.comment&&(s.comment=f.comment);continue}let h=d?e(i,d,f,r):t(i,f.end,u,null,f,r);i.schema.compat&&SP.flowIndentCheck(n.indent,d,r),c=h.range[2],s.items.push(h)}return s.range=[n.offset,c,l??c],s}Ov.resolveBlockSeq=EP});var Fr=P(Hv=>{"use strict";function RP(e,t,i,n){let r="";if(e){let a=!1,o="";for(let s of e){let{source:c,type:l}=s;switch(l){case"space":a=!0;break;case"comment":{i&&!a&&n(s,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let u=c.substring(1)||" ";r?r+=o+u:r=u,o="";break}case"newline":r&&(o+=c),a=!0;break;default:n(s,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}t+=c.length}}return{comment:r,offset:t}}Hv.resolveEnd=RP});var Lv=P(Fv=>{"use strict";var CP=K(),PP=an(),Dv=sn(),xP=cn(),AP=Fr(),Mv=ro(),TP=kc(),_P=qd(),Vd="Block collections are not allowed within flow collections",Wd=e=>e&&(e.type==="block-map"||e.type==="block-seq");function IP({composeNode:e,composeEmptyNode:t},i,n,r,a){let o=n.start.source==="{",s=o?"flow map":"flow sequence",c=a?.nodeClass??(o?Dv.YAMLMap:xP.YAMLSeq),l=new c(i.schema);l.flow=!0;let u=i.atRoot;u&&(i.atRoot=!1),i.atKey&&(i.atKey=!1);let d=n.offset+n.start.source.length;for(let v=0;v0){let v=AP.resolveEnd(m,p,i.options.strict,r);v.comment&&(l.comment?l.comment+=` -`+v.comment:l.comment=v.comment),l.range=[n.offset,p,v.offset]}else l.range=[n.offset,p,p];return l}Mv.resolveFlowCollection=IP});var Bv=P(Lv=>{"use strict";var jP=K(),OP=Re(),$P=sn(),HP=cn(),DP=Iv(),MP=Ov(),FP=Fv();function Jd(e,t,i,n,r,a){let o=i.type==="block-map"?DP.resolveBlockMap(e,t,i,n,a):i.type==="block-seq"?MP.resolveBlockSeq(e,t,i,n,a):FP.resolveFlowCollection(e,t,i,n,a),s=o.constructor;return r==="!"||r===s.tagName?(o.tag=s.tagName,o):(r&&(o.tag=r),o)}function LP(e,t,i,n,r){let a=n.tag,o=a?t.directives.tagName(a.source,f=>r(a,"TAG_RESOLVE_FAILED",f)):null;if(i.type==="block-seq"){let{anchor:f,newlineAfterProp:h}=n,m=f&&a?f.offset>a.offset?f:a:f??a;m&&(!h||h.offsetf.tag===o&&f.collection===s);if(!c){let f=t.schema.knownTags[o];if(f?.collection===s)t.schema.tags.push(Object.assign({},f,{default:!1})),c=f;else return f?r(a,"BAD_COLLECTION_TYPE",`${f.tag} used for ${s} collection, but expects ${f.collection??"scalar"}`,!0):r(a,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),Jd(e,t,i,r,o)}let l=Jd(e,t,i,r,o,c),u=c.resolve?.(l,f=>r(a,"TAG_RESOLVE_FAILED",f),t.options)??l,d=jP.isNode(u)?u:new OP.Scalar(u);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}Lv.composeCollection=LP});var Gd=P(qv=>{"use strict";var zd=Re();function BP(e,t,i){let n=t.offset,r=qP(t,e.options.strict,i);if(!r)return{value:"",type:null,comment:"",range:[n,n,n]};let a=r.mode===">"?zd.Scalar.BLOCK_FOLDED:zd.Scalar.BLOCK_LITERAL,o=t.source?VP(t.source):[],s=o.length;for(let p=o.length-1;p>=0;--p){let v=o[p][1];if(v===""||v==="\r")s=p;else break}if(s===0){let p=r.chomp==="+"&&o.length>0?` +`+w:g.comment=w,y.comment=y.comment.substring(w.length+1)}}if(!o&&!b&&!y.found){let w=R?e(i,R,y,r):t(i,y.end,b,null,y,r);l.items.push(w),d=w.range[2],Wd(R)&&r(w.range,"BLOCK_IN_FLOW",Vd)}else{i.atKey=!0;let w=y.end,g=N?e(i,N,y,r):t(i,w,k,null,y,r);Wd(N)&&r(g.range,"BLOCK_IN_FLOW",Vd),i.atKey=!1;let E=Mv.resolveProps(b??[],{flow:s,indicator:"map-value-ind",next:R,offset:g.range[2],onError:r,parentIndent:n.indent,startOnNewline:!1});if(E.found){if(!o&&!y.found&&i.options.strict){if(b)for(let q of b){if(q===E.found)break;if(q.type==="newline"){r(q,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}y.start0){let v=AP.resolveEnd(m,p,i.options.strict,r);v.comment&&(l.comment?l.comment+=` +`+v.comment:l.comment=v.comment),l.range=[n.offset,p,v.offset]}else l.range=[n.offset,p,p];return l}Fv.resolveFlowCollection=IP});var qv=P(Bv=>{"use strict";var jP=K(),OP=Re(),$P=sn(),HP=cn(),DP=jv(),MP=$v(),FP=Lv();function Jd(e,t,i,n,r,a){let o=i.type==="block-map"?DP.resolveBlockMap(e,t,i,n,a):i.type==="block-seq"?MP.resolveBlockSeq(e,t,i,n,a):FP.resolveFlowCollection(e,t,i,n,a),s=o.constructor;return r==="!"||r===s.tagName?(o.tag=s.tagName,o):(r&&(o.tag=r),o)}function LP(e,t,i,n,r){let a=n.tag,o=a?t.directives.tagName(a.source,f=>r(a,"TAG_RESOLVE_FAILED",f)):null;if(i.type==="block-seq"){let{anchor:f,newlineAfterProp:h}=n,m=f&&a?f.offset>a.offset?f:a:f??a;m&&(!h||h.offsetf.tag===o&&f.collection===s);if(!c){let f=t.schema.knownTags[o];if(f?.collection===s)t.schema.tags.push(Object.assign({},f,{default:!1})),c=f;else return f?r(a,"BAD_COLLECTION_TYPE",`${f.tag} used for ${s} collection, but expects ${f.collection??"scalar"}`,!0):r(a,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),Jd(e,t,i,r,o)}let l=Jd(e,t,i,r,o,c),u=c.resolve?.(l,f=>r(a,"TAG_RESOLVE_FAILED",f),t.options)??l,d=jP.isNode(u)?u:new OP.Scalar(u);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}Bv.composeCollection=LP});var Gd=P(Vv=>{"use strict";var zd=Re();function BP(e,t,i){let n=t.offset,r=qP(t,e.options.strict,i);if(!r)return{value:"",type:null,comment:"",range:[n,n,n]};let a=r.mode===">"?zd.Scalar.BLOCK_FOLDED:zd.Scalar.BLOCK_LITERAL,o=t.source?VP(t.source):[],s=o.length;for(let p=o.length-1;p>=0;--p){let v=o[p][1];if(v===""||v==="\r")s=p;else break}if(s===0){let p=r.chomp==="+"&&o.length>0?` `.repeat(Math.max(1,o.length-1)):"",v=n+r.length;return t.source&&(v+=t.source.length),{value:p,type:a,comment:r.comment,range:[n,v,v]}}let c=t.indent+r.indent,l=t.offset+r.length,u=0;for(let p=0;pc&&(c=v.length);else{v.length=s;--p)o[p][0].length>c&&(s=p+1);let d="",f="",h=!1;for(let p=0;pc||S[0]===" "?(f===" "?f=` @@ -84,7 +84,7 @@ ${l} `+o[p][0].slice(c);d[d.length-1]!==` `&&(d+=` `);break;default:d+=` -`}let m=n+r.length+t.source.length;return{value:d,type:a,comment:r.comment,range:[n,m,m]}}function qP({offset:e,props:t},i,n){if(t[0].type!=="block-scalar-header")return n(t[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:r}=t[0],a=r[0],o=0,s="",c=-1;for(let f=1;f{"use strict";var Ud=Re(),WP=Fr();function JP(e,t,i){let{offset:n,type:r,source:a,end:o}=e,s,c,l=(f,h,m)=>i(n+f,h,m);switch(r){case"scalar":s=Ud.Scalar.PLAIN,c=zP(a,l);break;case"single-quoted-scalar":s=Ud.Scalar.QUOTE_SINGLE,c=GP(a,l);break;case"double-quoted-scalar":s=Ud.Scalar.QUOTE_DOUBLE,c=UP(a,l);break;default:return i(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${r}`),{value:"",type:null,comment:"",range:[n,n+a.length,n+a.length]}}let u=n+a.length,d=WP.resolveEnd(o,u,t,i);return{value:c,type:s,comment:d.comment,range:[n,u,d.offset]}}function zP(e,t){let i="";switch(e[0]){case" ":i="a tab character";break;case",":i="flow indicator character ,";break;case"%":i="directive indicator character %";break;case"|":case">":{i=`block scalar indicator ${e[0]}`;break}case"@":case"`":{i=`reserved character ${e[0]}`;break}}return i&&t(0,"BAD_SCALAR_START",`Plain value cannot start with ${i}`),Vv(e)}function GP(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),Vv(e.slice(1,-1)).replace(/''/g,"'")}function Vv(e){let t,i;try{t=new RegExp(`(.*?)(?{"use strict";var Ud=Re(),WP=Fr();function JP(e,t,i){let{offset:n,type:r,source:a,end:o}=e,s,c,l=(f,h,m)=>i(n+f,h,m);switch(r){case"scalar":s=Ud.Scalar.PLAIN,c=zP(a,l);break;case"single-quoted-scalar":s=Ud.Scalar.QUOTE_SINGLE,c=GP(a,l);break;case"double-quoted-scalar":s=Ud.Scalar.QUOTE_DOUBLE,c=UP(a,l);break;default:return i(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${r}`),{value:"",type:null,comment:"",range:[n,n+a.length,n+a.length]}}let u=n+a.length,d=WP.resolveEnd(o,u,t,i);return{value:c,type:s,comment:d.comment,range:[n,u,d.offset]}}function zP(e,t){let i="";switch(e[0]){case" ":i="a tab character";break;case",":i="flow indicator character ,";break;case"%":i="directive indicator character %";break;case"|":case">":{i=`block scalar indicator ${e[0]}`;break}case"@":case"`":{i=`reserved character ${e[0]}`;break}}return i&&t(0,"BAD_SCALAR_START",`Plain value cannot start with ${i}`),Wv(e)}function GP(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),Wv(e.slice(1,-1)).replace(/''/g,"'")}function Wv(e){let t,i;try{t=new RegExp(`(.*?)(?{"use strict";var Kn=K(),Jv=Re(),QP=Gd(),ZP=Kd();function ex(e,t,i,n){let{value:r,type:a,comment:o,range:s}=t.type==="block-scalar"?QP.resolveBlockScalar(e,t,n):ZP.resolveFlowScalar(t,e.options.strict,n),c=i?e.directives.tagName(i.source,d=>n(i,"TAG_RESOLVE_FAILED",d)):null,l;e.options.stringKeys&&e.atKey?l=e.schema[Kn.SCALAR]:c?l=tx(e.schema,r,c,i,n):t.type==="scalar"?l=ix(e,r,t,n):l=e.schema[Kn.SCALAR];let u;try{let d=l.resolve(r,f=>n(i??t,"TAG_RESOLVE_FAILED",f),e.options);u=Kn.isScalar(d)?d:new Jv.Scalar(d)}catch(d){let f=d instanceof Error?d.message:String(d);n(i??t,"TAG_RESOLVE_FAILED",f),u=new Jv.Scalar(r)}return u.range=s,u.source=r,a&&(u.type=a),c&&(u.tag=c),l.format&&(u.format=l.format),o&&(u.comment=o),u}function tx(e,t,i,n,r){if(i==="!")return e[Kn.SCALAR];let a=[];for(let s of e.tags)if(!s.collection&&s.tag===i)if(s.default&&s.test)a.push(s);else return s;for(let s of a)if(s.test?.test(t))return s;let o=e.knownTags[i];return o&&!o.collection?(e.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(r(n,"TAG_RESOLVE_FAILED",`Unresolved tag: ${i}`,i!=="tag:yaml.org,2002:str"),e[Kn.SCALAR])}function ix({atKey:e,directives:t,schema:i},n,r,a){let o=i.tags.find(s=>(s.default===!0||e&&s.default==="key")&&s.test?.test(n))||i[Kn.SCALAR];if(i.compat){let s=i.compat.find(c=>c.default&&c.test?.test(n))??i[Kn.SCALAR];if(o.tag!==s.tag){let c=t.tagString(o.tag),l=t.tagString(s.tag),u=`Value may be parsed as either ${c} or ${l}`;a(r,"TAG_RESOLVE_FAILED",u,!0)}}return o}zv.composeScalar=ex});var Kv=P(Uv=>{"use strict";function nx(e,t,i){if(t){i??(i=t.length);for(let n=i-1;n>=0;--n){let r=t[n];switch(r.type){case"space":case"comment":case"newline":e-=r.source.length;continue}for(r=t[++n];r?.type==="space";)e+=r.source.length,r=t[++n];break}}return e}Uv.emptyScalarPosition=nx});var Qv=P(Xd=>{"use strict";var rx=Ma(),ax=K(),ox=Bv(),Yv=Gv(),sx=Fr(),cx=Kv(),lx={composeNode:Xv,composeEmptyNode:Yd};function Xv(e,t,i,n){let r=e.atKey,{spaceBefore:a,comment:o,anchor:s,tag:c}=i,l,u=!0;switch(t.type){case"alias":l=ux(e,t,n),(s||c)&&n(t,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=Yv.composeScalar(e,t,c,n),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=ox.composeCollection(lx,e,t,i,n),s&&(l.anchor=s.source.substring(1))}catch(d){let f=d instanceof Error?d.message:String(d);n(t,"RESOURCE_EXHAUSTION",f)}break;default:{let d=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;n(t,"UNEXPECTED_TOKEN",d),u=!1}}return l??(l=Yd(e,t.offset,void 0,null,i,n)),s&&l.anchor===""&&n(s,"BAD_ALIAS","Anchor cannot be an empty string"),r&&e.options.stringKeys&&(!ax.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&n(c??t,"NON_STRING_KEY","With stringKeys, all keys must be strings"),a&&(l.spaceBefore=!0),o&&(t.type==="scalar"&&t.source===""?l.comment=o:l.commentBefore=o),e.options.keepSourceTokens&&u&&(l.srcToken=t),l}function Yd(e,t,i,n,{spaceBefore:r,comment:a,anchor:o,tag:s,end:c},l){let u={type:"scalar",offset:cx.emptyScalarPosition(t,i,n),indent:-1,source:""},d=Yv.composeScalar(e,u,s,l);return o&&(d.anchor=o.source.substring(1),d.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),r&&(d.spaceBefore=!0),a&&(d.comment=a,d.range[2]=c),d}function ux({options:e},{offset:t,source:i,end:n},r){let a=new rx.Alias(i.substring(1));a.source===""&&r(t,"BAD_ALIAS","Alias cannot be an empty string"),a.source.endsWith(":")&&r(t+i.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=t+i.length,s=sx.resolveEnd(n,o,e.strict,r);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}Xd.composeEmptyNode=Yd;Xd.composeNode=Xv});var tg=P(eg=>{"use strict";var dx=eo(),Zv=Qv(),fx=Fr(),hx=ro();function px(e,t,{offset:i,start:n,value:r,end:a},o){let s=Object.assign({_directives:t},e),c=new dx.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=hx.resolveProps(n,{indicator:"doc-start",next:r??a?.[0],offset:i,onError:o,parentIndent:0,startOnNewline:!0});u.found&&(c.directives.docStart=!0,r&&(r.type==="block-map"||r.type==="block-seq")&&!u.hasNewline&&o(u.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=r?Zv.composeNode(l,r,u,o):Zv.composeEmptyNode(l,u.end,n,null,u,o);let d=c.contents.range[2],f=fx.resolveEnd(a,d,!1,o);return f.comment&&(c.comment=f.comment),c.range=[i,d,f.offset],c}eg.composeDoc=px});var Zd=P(rg=>{"use strict";var mx=As("process"),vx=Mu(),gx=eo(),ao=no(),ig=K(),wx=tg(),yx=Fr();function oo(e){if(typeof e=="number")return[e,e+1];if(Array.isArray(e))return e.length===2?e:[e[0],e[1]];let{offset:t,source:i}=e;return[t,t+(typeof i=="string"?i.length:1)]}function ng(e){let t="",i=!1,n=!1;for(let r=0;r{"use strict";var Kn=K(),zv=Re(),QP=Gd(),ZP=Kd();function ex(e,t,i,n){let{value:r,type:a,comment:o,range:s}=t.type==="block-scalar"?QP.resolveBlockScalar(e,t,n):ZP.resolveFlowScalar(t,e.options.strict,n),c=i?e.directives.tagName(i.source,d=>n(i,"TAG_RESOLVE_FAILED",d)):null,l;e.options.stringKeys&&e.atKey?l=e.schema[Kn.SCALAR]:c?l=tx(e.schema,r,c,i,n):t.type==="scalar"?l=ix(e,r,t,n):l=e.schema[Kn.SCALAR];let u;try{let d=l.resolve(r,f=>n(i??t,"TAG_RESOLVE_FAILED",f),e.options);u=Kn.isScalar(d)?d:new zv.Scalar(d)}catch(d){let f=d instanceof Error?d.message:String(d);n(i??t,"TAG_RESOLVE_FAILED",f),u=new zv.Scalar(r)}return u.range=s,u.source=r,a&&(u.type=a),c&&(u.tag=c),l.format&&(u.format=l.format),o&&(u.comment=o),u}function tx(e,t,i,n,r){if(i==="!")return e[Kn.SCALAR];let a=[];for(let s of e.tags)if(!s.collection&&s.tag===i)if(s.default&&s.test)a.push(s);else return s;for(let s of a)if(s.test?.test(t))return s;let o=e.knownTags[i];return o&&!o.collection?(e.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(r(n,"TAG_RESOLVE_FAILED",`Unresolved tag: ${i}`,i!=="tag:yaml.org,2002:str"),e[Kn.SCALAR])}function ix({atKey:e,directives:t,schema:i},n,r,a){let o=i.tags.find(s=>(s.default===!0||e&&s.default==="key")&&s.test?.test(n))||i[Kn.SCALAR];if(i.compat){let s=i.compat.find(c=>c.default&&c.test?.test(n))??i[Kn.SCALAR];if(o.tag!==s.tag){let c=t.tagString(o.tag),l=t.tagString(s.tag),u=`Value may be parsed as either ${c} or ${l}`;a(r,"TAG_RESOLVE_FAILED",u,!0)}}return o}Gv.composeScalar=ex});var Yv=P(Kv=>{"use strict";function nx(e,t,i){if(t){i??(i=t.length);for(let n=i-1;n>=0;--n){let r=t[n];switch(r.type){case"space":case"comment":case"newline":e-=r.source.length;continue}for(r=t[++n];r?.type==="space";)e+=r.source.length,r=t[++n];break}}return e}Kv.emptyScalarPosition=nx});var Zv=P(Xd=>{"use strict";var rx=Ma(),ax=K(),ox=qv(),Xv=Uv(),sx=Fr(),cx=Yv(),lx={composeNode:Qv,composeEmptyNode:Yd};function Qv(e,t,i,n){let r=e.atKey,{spaceBefore:a,comment:o,anchor:s,tag:c}=i,l,u=!0;switch(t.type){case"alias":l=ux(e,t,n),(s||c)&&n(t,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=Xv.composeScalar(e,t,c,n),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=ox.composeCollection(lx,e,t,i,n),s&&(l.anchor=s.source.substring(1))}catch(d){let f=d instanceof Error?d.message:String(d);n(t,"RESOURCE_EXHAUSTION",f)}break;default:{let d=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;n(t,"UNEXPECTED_TOKEN",d),u=!1}}return l??(l=Yd(e,t.offset,void 0,null,i,n)),s&&l.anchor===""&&n(s,"BAD_ALIAS","Anchor cannot be an empty string"),r&&e.options.stringKeys&&(!ax.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&n(c??t,"NON_STRING_KEY","With stringKeys, all keys must be strings"),a&&(l.spaceBefore=!0),o&&(t.type==="scalar"&&t.source===""?l.comment=o:l.commentBefore=o),e.options.keepSourceTokens&&u&&(l.srcToken=t),l}function Yd(e,t,i,n,{spaceBefore:r,comment:a,anchor:o,tag:s,end:c},l){let u={type:"scalar",offset:cx.emptyScalarPosition(t,i,n),indent:-1,source:""},d=Xv.composeScalar(e,u,s,l);return o&&(d.anchor=o.source.substring(1),d.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),r&&(d.spaceBefore=!0),a&&(d.comment=a,d.range[2]=c),d}function ux({options:e},{offset:t,source:i,end:n},r){let a=new rx.Alias(i.substring(1));a.source===""&&r(t,"BAD_ALIAS","Alias cannot be an empty string"),a.source.endsWith(":")&&r(t+i.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=t+i.length,s=sx.resolveEnd(n,o,e.strict,r);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}Xd.composeEmptyNode=Yd;Xd.composeNode=Qv});var ig=P(tg=>{"use strict";var dx=eo(),eg=Zv(),fx=Fr(),hx=ro();function px(e,t,{offset:i,start:n,value:r,end:a},o){let s=Object.assign({_directives:t},e),c=new dx.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=hx.resolveProps(n,{indicator:"doc-start",next:r??a?.[0],offset:i,onError:o,parentIndent:0,startOnNewline:!0});u.found&&(c.directives.docStart=!0,r&&(r.type==="block-map"||r.type==="block-seq")&&!u.hasNewline&&o(u.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=r?eg.composeNode(l,r,u,o):eg.composeEmptyNode(l,u.end,n,null,u,o);let d=c.contents.range[2],f=fx.resolveEnd(a,d,!1,o);return f.comment&&(c.comment=f.comment),c.range=[i,d,f.offset],c}tg.composeDoc=px});var Zd=P(ag=>{"use strict";var mx=As("process"),vx=Mu(),gx=eo(),ao=no(),ng=K(),wx=ig(),yx=Fr();function oo(e){if(typeof e=="number")return[e,e+1];if(Array.isArray(e))return e.length===2?e:[e[0],e[1]];let{offset:t,source:i}=e;return[t,t+(typeof i=="string"?i.length:1)]}function rg(e){let t="",i=!1,n=!1;for(let r=0;r{let o=oo(i);a?this.warnings.push(new ao.YAMLWarning(o,n,r)):this.errors.push(new ao.YAMLParseError(o,n,r))},this.directives=new vx.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,i){let{comment:n,afterEmptyLine:r}=ng(this.prelude);if(n){let a=t.contents;if(i)t.comment=t.comment?`${t.comment} -${n}`:n;else if(r||t.directives.docStart||!a)t.commentBefore=n;else if(ig.isCollection(a)&&!a.flow&&a.items.length>0){let o=a.items[0];ig.isPair(o)&&(o=o.key);let s=o.commentBefore;o.commentBefore=s?`${n} +`)+(a.substring(1)||" "),i=!0,n=!1;break;case"%":e[r+1]?.[0]!=="#"&&(r+=1),i=!1;break;default:i||(n=!0),i=!1}}return{comment:t,afterEmptyLine:n}}var Qd=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(i,n,r,a)=>{let o=oo(i);a?this.warnings.push(new ao.YAMLWarning(o,n,r)):this.errors.push(new ao.YAMLParseError(o,n,r))},this.directives=new vx.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,i){let{comment:n,afterEmptyLine:r}=rg(this.prelude);if(n){let a=t.contents;if(i)t.comment=t.comment?`${t.comment} +${n}`:n;else if(r||t.directives.docStart||!a)t.commentBefore=n;else if(ng.isCollection(a)&&!a.flow&&a.items.length>0){let o=a.items[0];ng.isPair(o)&&(o=o.key);let s=o.commentBefore;o.commentBefore=s?`${n} ${s}`:n}else{let o=a.commentBefore;a.commentBefore=o?`${n} -${o}`:n}}if(i){for(let a=0;a{let a=oo(t);a[0]+=i,this.onError(a,"BAD_DIRECTIVE",n,r)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let i=wx.composeDoc(this.options,this.directives,t,this.onError);this.atDirectives&&!i.directives.docStart&&this.onError(t,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(i,!1),this.doc&&(yield this.doc),this.doc=i,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(t.source);break;case"error":{let i=t.source?`${t.message}: ${JSON.stringify(t.source)}`:t.message,n=new ao.YAMLParseError(oo(t),"UNEXPECTED_TOKEN",i);this.atDirectives||!this.doc?this.errors.push(n):this.doc.errors.push(n);break}case"doc-end":{if(!this.doc){let n="Unexpected doc-end without preceding document";this.errors.push(new ao.YAMLParseError(oo(t),"UNEXPECTED_TOKEN",n));break}this.doc.directives.docEnd=!0;let i=yx.resolveEnd(t.end,t.offset+t.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),i.comment){let n=this.doc.comment;this.doc.comment=n?`${n} -${i.comment}`:i.comment}this.doc.range[2]=i.offset;break}default:this.errors.push(new ao.YAMLParseError(oo(t),"UNEXPECTED_TOKEN",`Unsupported token ${t.type}`))}}*end(t=!1,i=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(t){let n=Object.assign({_directives:this.directives},this.options),r=new gx.Document(void 0,n);this.atDirectives&&this.onError(i,"MISSING_CHAR","Missing directives-end indicator line"),r.range=[0,i,i],this.decorate(r,!1),yield r}}};rg.Composer=Qd});var sg=P(Sc=>{"use strict";var Nx=Gd(),bx=Kd(),kx=no(),ag=Va();function Sx(e,t=!0,i){if(e){let n=(r,a,o)=>{let s=typeof r=="number"?r:Array.isArray(r)?r[0]:r.offset;if(i)i(s,a,o);else throw new kx.YAMLParseError([s,s+1],a,o)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return bx.resolveFlowScalar(e,t,n);case"block-scalar":return Nx.resolveBlockScalar({options:{strict:t}},e,n)}}return null}function Ex(e,t){let{implicitKey:i=!1,indent:n,inFlow:r=!1,offset:a=-1,type:o="PLAIN"}=t,s=ag.stringifyString({type:o,value:e},{implicitKey:i,indent:n>0?" ".repeat(n):"",inFlow:r,options:{blockQuote:!0,lineWidth:-1}}),c=t.end??[{type:"newline",offset:-1,indent:n,source:` +${o}`:n}}if(i){for(let a=0;a{let a=oo(t);a[0]+=i,this.onError(a,"BAD_DIRECTIVE",n,r)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let i=wx.composeDoc(this.options,this.directives,t,this.onError);this.atDirectives&&!i.directives.docStart&&this.onError(t,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(i,!1),this.doc&&(yield this.doc),this.doc=i,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(t.source);break;case"error":{let i=t.source?`${t.message}: ${JSON.stringify(t.source)}`:t.message,n=new ao.YAMLParseError(oo(t),"UNEXPECTED_TOKEN",i);this.atDirectives||!this.doc?this.errors.push(n):this.doc.errors.push(n);break}case"doc-end":{if(!this.doc){let n="Unexpected doc-end without preceding document";this.errors.push(new ao.YAMLParseError(oo(t),"UNEXPECTED_TOKEN",n));break}this.doc.directives.docEnd=!0;let i=yx.resolveEnd(t.end,t.offset+t.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),i.comment){let n=this.doc.comment;this.doc.comment=n?`${n} +${i.comment}`:i.comment}this.doc.range[2]=i.offset;break}default:this.errors.push(new ao.YAMLParseError(oo(t),"UNEXPECTED_TOKEN",`Unsupported token ${t.type}`))}}*end(t=!1,i=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(t){let n=Object.assign({_directives:this.directives},this.options),r=new gx.Document(void 0,n);this.atDirectives&&this.onError(i,"MISSING_CHAR","Missing directives-end indicator line"),r.range=[0,i,i],this.decorate(r,!1),yield r}}};ag.Composer=Qd});var cg=P(Sc=>{"use strict";var Nx=Gd(),bx=Kd(),kx=no(),og=Va();function Sx(e,t=!0,i){if(e){let n=(r,a,o)=>{let s=typeof r=="number"?r:Array.isArray(r)?r[0]:r.offset;if(i)i(s,a,o);else throw new kx.YAMLParseError([s,s+1],a,o)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return bx.resolveFlowScalar(e,t,n);case"block-scalar":return Nx.resolveBlockScalar({options:{strict:t}},e,n)}}return null}function Ex(e,t){let{implicitKey:i=!1,indent:n,inFlow:r=!1,offset:a=-1,type:o="PLAIN"}=t,s=og.stringifyString({type:o,value:e},{implicitKey:i,indent:n>0?" ".repeat(n):"",inFlow:r,options:{blockQuote:!0,lineWidth:-1}}),c=t.end??[{type:"newline",offset:-1,indent:n,source:` `}];switch(s[0]){case"|":case">":{let l=s.indexOf(` `),u=s.substring(0,l),d=s.substring(l+1)+` -`,f=[{type:"block-scalar-header",offset:a,indent:n,source:u}];return og(f,c)||f.push({type:"newline",offset:-1,indent:n,source:` -`}),{type:"block-scalar",offset:a,indent:n,props:f,source:d}}case'"':return{type:"double-quoted-scalar",offset:a,indent:n,source:s,end:c};case"'":return{type:"single-quoted-scalar",offset:a,indent:n,source:s,end:c};default:return{type:"scalar",offset:a,indent:n,source:s,end:c}}}function Rx(e,t,i={}){let{afterKey:n=!1,implicitKey:r=!1,inFlow:a=!1,type:o}=i,s="indent"in e?e.indent:null;if(n&&typeof s=="number"&&(s+=2),!o)switch(e.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let l=e.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let c=ag.stringifyString({type:o,value:t},{implicitKey:r||s===null,indent:s!==null&&s>0?" ".repeat(s):"",inFlow:a,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":Cx(e,c);break;case'"':ef(e,c,"double-quoted-scalar");break;case"'":ef(e,c,"single-quoted-scalar");break;default:ef(e,c,"scalar")}}function Cx(e,t){let i=t.indexOf(` +`,f=[{type:"block-scalar-header",offset:a,indent:n,source:u}];return sg(f,c)||f.push({type:"newline",offset:-1,indent:n,source:` +`}),{type:"block-scalar",offset:a,indent:n,props:f,source:d}}case'"':return{type:"double-quoted-scalar",offset:a,indent:n,source:s,end:c};case"'":return{type:"single-quoted-scalar",offset:a,indent:n,source:s,end:c};default:return{type:"scalar",offset:a,indent:n,source:s,end:c}}}function Rx(e,t,i={}){let{afterKey:n=!1,implicitKey:r=!1,inFlow:a=!1,type:o}=i,s="indent"in e?e.indent:null;if(n&&typeof s=="number"&&(s+=2),!o)switch(e.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let l=e.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let c=og.stringifyString({type:o,value:t},{implicitKey:r||s===null,indent:s!==null&&s>0?" ".repeat(s):"",inFlow:a,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":Cx(e,c);break;case'"':ef(e,c,"double-quoted-scalar");break;case"'":ef(e,c,"single-quoted-scalar");break;default:ef(e,c,"scalar")}}function Cx(e,t){let i=t.indexOf(` `),n=t.substring(0,i),r=t.substring(i+1)+` -`;if(e.type==="block-scalar"){let a=e.props[0];if(a.type!=="block-scalar-header")throw new Error("Invalid block scalar header");a.source=n,e.source=r}else{let{offset:a}=e,o="indent"in e?e.indent:-1,s=[{type:"block-scalar-header",offset:a,indent:o,source:n}];og(s,"end"in e?e.end:void 0)||s.push({type:"newline",offset:-1,indent:o,source:` -`});for(let c of Object.keys(e))c!=="type"&&c!=="offset"&&delete e[c];Object.assign(e,{type:"block-scalar",indent:o,props:s,source:r})}}function og(e,t){if(t)for(let i of t)switch(i.type){case"space":case"comment":e.push(i);break;case"newline":return e.push(i),!0}return!1}function ef(e,t,i){switch(e.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":e.type=i,e.source=t;break;case"block-scalar":{let n=e.props.slice(1),r=t.length;e.props[0].type==="block-scalar-header"&&(r-=e.props[0].source.length);for(let a of n)a.offset+=r;delete e.props,Object.assign(e,{type:i,source:t,end:n});break}case"block-map":case"block-seq":{let r={type:"newline",offset:e.offset+t.length,indent:e.indent,source:` -`};delete e.items,Object.assign(e,{type:i,source:t,end:[r]});break}default:{let n="indent"in e?e.indent:-1,r="end"in e&&Array.isArray(e.end)?e.end.filter(a=>a.type==="space"||a.type==="comment"||a.type==="newline"):[];for(let a of Object.keys(e))a!=="type"&&a!=="offset"&&delete e[a];Object.assign(e,{type:i,indent:n,source:t,end:r})}}}Sc.createScalarToken=Ex;Sc.resolveAsScalar=Sx;Sc.setScalarValue=Rx});var lg=P(cg=>{"use strict";var Px=e=>"type"in e?Rc(e):Ec(e);function Rc(e){switch(e.type){case"block-scalar":{let t="";for(let i of e.props)t+=Rc(i);return t+e.source}case"block-map":case"block-seq":{let t="";for(let i of e.items)t+=Ec(i);return t}case"flow-collection":{let t=e.start.source;for(let i of e.items)t+=Ec(i);for(let i of e.end)t+=i.source;return t}case"document":{let t=Ec(e);if(e.end)for(let i of e.end)t+=i.source;return t}default:{let t=e.source;if("end"in e&&e.end)for(let i of e.end)t+=i.source;return t}}}function Ec({start:e,key:t,sep:i,value:n}){let r="";for(let a of e)r+=a.source;if(t&&(r+=Rc(t)),i)for(let a of i)r+=a.source;return n&&(r+=Rc(n)),r}cg.stringify=Px});var hg=P(fg=>{"use strict";var tf=Symbol("break visit"),xx=Symbol("skip children"),ug=Symbol("remove item");function Yn(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),dg(Object.freeze([]),e,t)}Yn.BREAK=tf;Yn.SKIP=xx;Yn.REMOVE=ug;Yn.itemAtPath=(e,t)=>{let i=e;for(let[n,r]of t){let a=i?.[n];if(a&&"items"in a)i=a.items[r];else return}return i};Yn.parentCollection=(e,t)=>{let i=Yn.itemAtPath(e,t.slice(0,-1)),n=t[t.length-1][0],r=i?.[n];if(r&&"items"in r)return r;throw new Error("Parent collection not found")};function dg(e,t,i){let n=i(t,e);if(typeof n=="symbol")return n;for(let r of["key","value"]){let a=t[r];if(a&&"items"in a){for(let o=0;o{"use strict";var nf=sg(),Ax=lg(),Tx=hg(),rf="\uFEFF",af="",of="",sf="",_x=e=>!!e&&"items"in e,Ix=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function jx(e){switch(e){case rf:return"";case af:return"";case of:return"";case sf:return"";default:return JSON.stringify(e)}}function Ox(e){switch(e){case rf:return"byte-order-mark";case af:return"doc-mode";case of:return"flow-error-end";case sf:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case` +`;if(e.type==="block-scalar"){let a=e.props[0];if(a.type!=="block-scalar-header")throw new Error("Invalid block scalar header");a.source=n,e.source=r}else{let{offset:a}=e,o="indent"in e?e.indent:-1,s=[{type:"block-scalar-header",offset:a,indent:o,source:n}];sg(s,"end"in e?e.end:void 0)||s.push({type:"newline",offset:-1,indent:o,source:` +`});for(let c of Object.keys(e))c!=="type"&&c!=="offset"&&delete e[c];Object.assign(e,{type:"block-scalar",indent:o,props:s,source:r})}}function sg(e,t){if(t)for(let i of t)switch(i.type){case"space":case"comment":e.push(i);break;case"newline":return e.push(i),!0}return!1}function ef(e,t,i){switch(e.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":e.type=i,e.source=t;break;case"block-scalar":{let n=e.props.slice(1),r=t.length;e.props[0].type==="block-scalar-header"&&(r-=e.props[0].source.length);for(let a of n)a.offset+=r;delete e.props,Object.assign(e,{type:i,source:t,end:n});break}case"block-map":case"block-seq":{let r={type:"newline",offset:e.offset+t.length,indent:e.indent,source:` +`};delete e.items,Object.assign(e,{type:i,source:t,end:[r]});break}default:{let n="indent"in e?e.indent:-1,r="end"in e&&Array.isArray(e.end)?e.end.filter(a=>a.type==="space"||a.type==="comment"||a.type==="newline"):[];for(let a of Object.keys(e))a!=="type"&&a!=="offset"&&delete e[a];Object.assign(e,{type:i,indent:n,source:t,end:r})}}}Sc.createScalarToken=Ex;Sc.resolveAsScalar=Sx;Sc.setScalarValue=Rx});var ug=P(lg=>{"use strict";var Px=e=>"type"in e?Rc(e):Ec(e);function Rc(e){switch(e.type){case"block-scalar":{let t="";for(let i of e.props)t+=Rc(i);return t+e.source}case"block-map":case"block-seq":{let t="";for(let i of e.items)t+=Ec(i);return t}case"flow-collection":{let t=e.start.source;for(let i of e.items)t+=Ec(i);for(let i of e.end)t+=i.source;return t}case"document":{let t=Ec(e);if(e.end)for(let i of e.end)t+=i.source;return t}default:{let t=e.source;if("end"in e&&e.end)for(let i of e.end)t+=i.source;return t}}}function Ec({start:e,key:t,sep:i,value:n}){let r="";for(let a of e)r+=a.source;if(t&&(r+=Rc(t)),i)for(let a of i)r+=a.source;return n&&(r+=Rc(n)),r}lg.stringify=Px});var pg=P(hg=>{"use strict";var tf=Symbol("break visit"),xx=Symbol("skip children"),dg=Symbol("remove item");function Yn(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),fg(Object.freeze([]),e,t)}Yn.BREAK=tf;Yn.SKIP=xx;Yn.REMOVE=dg;Yn.itemAtPath=(e,t)=>{let i=e;for(let[n,r]of t){let a=i?.[n];if(a&&"items"in a)i=a.items[r];else return}return i};Yn.parentCollection=(e,t)=>{let i=Yn.itemAtPath(e,t.slice(0,-1)),n=t[t.length-1][0],r=i?.[n];if(r&&"items"in r)return r;throw new Error("Parent collection not found")};function fg(e,t,i){let n=i(t,e);if(typeof n=="symbol")return n;for(let r of["key","value"]){let a=t[r];if(a&&"items"in a){for(let o=0;o{"use strict";var nf=cg(),Ax=ug(),Tx=pg(),rf="\uFEFF",af="",of="",sf="",_x=e=>!!e&&"items"in e,Ix=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function jx(e){switch(e){case rf:return"";case af:return"";case of:return"";case sf:return"";default:return JSON.stringify(e)}}function Ox(e){switch(e){case rf:return"byte-order-mark";case af:return"doc-mode";case of:return"flow-error-end";case sf:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case` `:case`\r -`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(e[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}at.createScalarToken=nf.createScalarToken;at.resolveAsScalar=nf.resolveAsScalar;at.setScalarValue=nf.setScalarValue;at.stringify=Ax.stringify;at.visit=Tx.visit;at.BOM=rf;at.DOCUMENT=af;at.FLOW_END=of;at.SCALAR=sf;at.isCollection=_x;at.isScalar=Ix;at.prettyToken=jx;at.tokenType=Ox});var uf=P(mg=>{"use strict";var so=Cc();function qt(e){switch(e){case void 0:case" ":case` -`:case"\r":case" ":return!0;default:return!1}}var pg=new Set("0123456789ABCDEFabcdef"),$x=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Pc=new Set(",[]{}"),Hx=new Set(` ,[]{} +`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(e[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}at.createScalarToken=nf.createScalarToken;at.resolveAsScalar=nf.resolveAsScalar;at.setScalarValue=nf.setScalarValue;at.stringify=Ax.stringify;at.visit=Tx.visit;at.BOM=rf;at.DOCUMENT=af;at.FLOW_END=of;at.SCALAR=sf;at.isCollection=_x;at.isScalar=Ix;at.prettyToken=jx;at.tokenType=Ox});var uf=P(vg=>{"use strict";var so=Cc();function qt(e){switch(e){case void 0:case" ":case` +`:case"\r":case" ":return!0;default:return!1}}var mg=new Set("0123456789ABCDEFabcdef"),$x=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Pc=new Set(",[]{}"),Hx=new Set(` ,[]{} \r `),cf=e=>!e||Hx.has(e),lf=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(t,i=!1){if(t){if(typeof t!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+t:t,this.lineEndPos=null}this.atEnd=!i;let n=this.next??"stream";for(;n&&(i||this.hasChars(1));)n=yield*this.parseNext(n)}atLineEnd(){let t=this.pos,i=this.buffer[t];for(;i===" "||i===" ";)i=this.buffer[++t];return!i||i==="#"||i===` `?!0:i==="\r"?this.buffer[t+1]===` `:!1}charAt(t){return this.buffer[this.pos+t]}continueScalar(t){let i=this.buffer[t];if(this.indentNext>0){let n=0;for(;i===" ";)i=this.buffer[++n+t];if(i==="\r"){let r=this.buffer[n+t+1];if(r===` @@ -133,13 +133,13 @@ ${i.comment}`:i.comment}this.doc.range[2]=i.offset;break}default:this.errors.pus `&&a>=this.pos&&a+1+i>s)t=a;else break}while(!0);return yield so.SCALAR,yield*this.pushToIndex(t+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let t=this.flowLevel>0,i=this.pos-1,n=this.pos-1,r;for(;r=this.buffer[++n];)if(r===":"){let a=this.buffer[n+1];if(qt(a)||t&&Pc.has(a))break;i=n}else if(qt(r)){let a=this.buffer[n+1];if(r==="\r"&&(a===` `?(n+=1,r=` `,a=this.buffer[n+1]):i=n),a==="#"||t&&Pc.has(a))break;if(r===` -`){let o=this.continueScalar(n+1);if(o===-1)break;n=Math.max(n,o-2)}}else{if(t&&Pc.has(r))break;i=n}return!r&&!this.atEnd?this.setNext("plain-scalar"):(yield so.SCALAR,yield*this.pushToIndex(i+1,!0),t?"flow":"doc")}*pushCount(t){return t>0?(yield this.buffer.substr(this.pos,t),this.pos+=t,t):0}*pushToIndex(t,i){let n=this.buffer.slice(this.pos,t);return n?(yield n,this.pos+=n.length,n.length):(i&&(yield""),0)}*pushIndicators(){let t=0;e:for(;;){switch(this.charAt(0)){case"!":t+=yield*this.pushTag(),t+=yield*this.pushSpaces(!0);continue e;case"&":t+=yield*this.pushUntil(cf),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let i=this.flowLevel>0,n=this.charAt(1);if(qt(n)||i&&Pc.has(n)){i?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,t+=yield*this.pushCount(1),t+=yield*this.pushSpaces(!0);continue e}}}break e}return t}*pushTag(){if(this.charAt(1)==="<"){let t=this.pos+2,i=this.buffer[t];for(;!qt(i)&&i!==">";)i=this.buffer[++t];return yield*this.pushToIndex(i===">"?t+1:t,!1)}else{let t=this.pos+1,i=this.buffer[t];for(;i;)if($x.has(i))i=this.buffer[++t];else if(i==="%"&&pg.has(this.buffer[t+1])&&pg.has(this.buffer[t+2]))i=this.buffer[t+=3];else break;return yield*this.pushToIndex(t,!1)}}*pushNewline(){let t=this.buffer[this.pos];return t===` +`){let o=this.continueScalar(n+1);if(o===-1)break;n=Math.max(n,o-2)}}else{if(t&&Pc.has(r))break;i=n}return!r&&!this.atEnd?this.setNext("plain-scalar"):(yield so.SCALAR,yield*this.pushToIndex(i+1,!0),t?"flow":"doc")}*pushCount(t){return t>0?(yield this.buffer.substr(this.pos,t),this.pos+=t,t):0}*pushToIndex(t,i){let n=this.buffer.slice(this.pos,t);return n?(yield n,this.pos+=n.length,n.length):(i&&(yield""),0)}*pushIndicators(){let t=0;e:for(;;){switch(this.charAt(0)){case"!":t+=yield*this.pushTag(),t+=yield*this.pushSpaces(!0);continue e;case"&":t+=yield*this.pushUntil(cf),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let i=this.flowLevel>0,n=this.charAt(1);if(qt(n)||i&&Pc.has(n)){i?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,t+=yield*this.pushCount(1),t+=yield*this.pushSpaces(!0);continue e}}}break e}return t}*pushTag(){if(this.charAt(1)==="<"){let t=this.pos+2,i=this.buffer[t];for(;!qt(i)&&i!==">";)i=this.buffer[++t];return yield*this.pushToIndex(i===">"?t+1:t,!1)}else{let t=this.pos+1,i=this.buffer[t];for(;i;)if($x.has(i))i=this.buffer[++t];else if(i==="%"&&mg.has(this.buffer[t+1])&&mg.has(this.buffer[t+2]))i=this.buffer[t+=3];else break;return yield*this.pushToIndex(t,!1)}}*pushNewline(){let t=this.buffer[this.pos];return t===` `?yield*this.pushCount(1):t==="\r"&&this.charAt(1)===` -`?yield*this.pushCount(2):0}*pushSpaces(t){let i=this.pos-1,n;do n=this.buffer[++i];while(n===" "||t&&n===" ");let r=i-this.pos;return r>0&&(yield this.buffer.substr(this.pos,r),this.pos=i),r}*pushUntil(t){let i=this.pos,n=this.buffer[i];for(;!t(n);)n=this.buffer[++i];return yield*this.pushToIndex(i,!1)}};mg.Lexer=lf});var ff=P(vg=>{"use strict";var df=class{constructor(){this.lineStarts=[],this.addNewLine=t=>this.lineStarts.push(t),this.linePos=t=>{let i=0,n=this.lineStarts.length;for(;i>1;this.lineStarts[a]{"use strict";var Dx=As("process"),gg=Cc(),Mx=uf();function ln(e,t){for(let i=0;i=0;)switch(e[t].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;e[++t]?.type==="space";);return e.splice(t,e.length)}function Ac(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let i=0;i0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let t=this.peek(1);if(this.type==="doc-end"&&t?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!t)return yield*this.stream();switch(t.type){case"document":return yield*this.document(t);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(t);case"block-scalar":return yield*this.blockScalar(t);case"block-map":return yield*this.blockMap(t);case"block-seq":return yield*this.blockSequence(t);case"flow-collection":return yield*this.flowCollection(t);case"doc-end":return yield*this.documentEnd(t)}yield*this.pop()}peek(t){return this.stack[this.stack.length-t]}*pop(t){let i=t??this.stack.pop();if(!i)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield i;else{let n=this.peek(1);switch(i.type==="block-scalar"?i.indent="indent"in n?n.indent:0:i.type==="flow-collection"&&n.type==="document"&&(i.indent=0),i.type==="flow-collection"&&yg(i),n.type){case"document":n.value=i;break;case"block-scalar":n.props.push(i);break;case"block-map":{let r=n.items[n.items.length-1];if(r.value){n.items.push({start:[],key:i,sep:[]}),this.onKeyLine=!0;return}else if(r.sep)r.value=i;else{Object.assign(r,{key:i,sep:[]}),this.onKeyLine=!r.explicitKey;return}break}case"block-seq":{let r=n.items[n.items.length-1];r.value?n.items.push({start:[],value:i}):r.value=i;break}case"flow-collection":{let r=n.items[n.items.length-1];!r||r.value?n.items.push({start:[],key:i,sep:[]}):r.sep?r.value=i:Object.assign(r,{key:i,sep:[]});return}default:yield*this.pop(),yield*this.pop(i)}if((n.type==="document"||n.type==="block-map"||n.type==="block-seq")&&(i.type==="block-map"||i.type==="block-seq")){let r=i.items[i.items.length-1];r&&!r.sep&&!r.value&&r.start.length>0&&wg(r.start)===-1&&(i.indent===0||r.start.every(a=>a.type!=="comment"||a.indent0&&(yield this.buffer.substr(this.pos,r),this.pos=i),r}*pushUntil(t){let i=this.pos,n=this.buffer[i];for(;!t(n);)n=this.buffer[++i];return yield*this.pushToIndex(i,!1)}};vg.Lexer=lf});var ff=P(gg=>{"use strict";var df=class{constructor(){this.lineStarts=[],this.addNewLine=t=>this.lineStarts.push(t),this.linePos=t=>{let i=0,n=this.lineStarts.length;for(;i>1;this.lineStarts[a]{"use strict";var Dx=As("process"),wg=Cc(),Mx=uf();function ln(e,t){for(let i=0;i=0;)switch(e[t].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;e[++t]?.type==="space";);return e.splice(t,e.length)}function Ac(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let i=0;i0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let t=this.peek(1);if(this.type==="doc-end"&&t?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!t)return yield*this.stream();switch(t.type){case"document":return yield*this.document(t);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(t);case"block-scalar":return yield*this.blockScalar(t);case"block-map":return yield*this.blockMap(t);case"block-seq":return yield*this.blockSequence(t);case"flow-collection":return yield*this.flowCollection(t);case"doc-end":return yield*this.documentEnd(t)}yield*this.pop()}peek(t){return this.stack[this.stack.length-t]}*pop(t){let i=t??this.stack.pop();if(!i)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield i;else{let n=this.peek(1);switch(i.type==="block-scalar"?i.indent="indent"in n?n.indent:0:i.type==="flow-collection"&&n.type==="document"&&(i.indent=0),i.type==="flow-collection"&&Ng(i),n.type){case"document":n.value=i;break;case"block-scalar":n.props.push(i);break;case"block-map":{let r=n.items[n.items.length-1];if(r.value){n.items.push({start:[],key:i,sep:[]}),this.onKeyLine=!0;return}else if(r.sep)r.value=i;else{Object.assign(r,{key:i,sep:[]}),this.onKeyLine=!r.explicitKey;return}break}case"block-seq":{let r=n.items[n.items.length-1];r.value?n.items.push({start:[],value:i}):r.value=i;break}case"flow-collection":{let r=n.items[n.items.length-1];!r||r.value?n.items.push({start:[],key:i,sep:[]}):r.sep?r.value=i:Object.assign(r,{key:i,sep:[]});return}default:yield*this.pop(),yield*this.pop(i)}if((n.type==="document"||n.type==="block-map"||n.type==="block-seq")&&(i.type==="block-map"||i.type==="block-seq")){let r=i.items[i.items.length-1];r&&!r.sep&&!r.value&&r.start.length>0&&yg(r.start)===-1&&(i.indent===0||r.start.every(a=>a.type!=="comment"||a.indent=t.indent){let n=!this.onKeyLine&&this.indent===t.indent,r=n&&(i.sep||i.explicitKey)&&this.type!=="seq-item-ind",a=[];if(r&&i.sep&&!i.value){let o=[];for(let s=0;st.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(a=i.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":r||i.value?(a.push(this.sourceToken),t.items.push({start:a}),this.onKeyLine=!0):i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"explicit-key-ind":!i.sep&&!i.explicitKey?(i.start.push(this.sourceToken),i.explicitKey=!0):r||i.value?(a.push(this.sourceToken),t.items.push({start:a,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(i.explicitKey)if(i.sep)if(i.value)t.items.push({start:[],key:null,sep:[this.sourceToken]});else if(ln(i.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:a,key:null,sep:[this.sourceToken]}]});else if(Ng(i.key)&&!ln(i.sep,"newline")){let o=Lr(i.start),s=i.key,c=i.sep;c.push(this.sourceToken),delete i.key,delete i.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:s,sep:c}]})}else a.length>0?i.sep=i.sep.concat(a,this.sourceToken):i.sep.push(this.sourceToken);else if(ln(i.start,"newline"))Object.assign(i,{key:null,sep:[this.sourceToken]});else{let o=Lr(i.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else i.sep?i.value||r?t.items.push({start:a,key:null,sep:[this.sourceToken]}):ln(i.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):i.sep.push(this.sourceToken):Object.assign(i,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);r||i.value?(t.items.push({start:a,key:o,sep:[]}),this.onKeyLine=!0):i.sep?this.stack.push(o):(Object.assign(i,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(t);if(o){if(o.type==="block-seq"){if(!i.explicitKey&&i.sep&&!ln(i.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else n&&t.items.push({start:a});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(t){let i=t.items[t.items.length-1];switch(this.type){case"newline":if(i.value){let n="end"in i.value?i.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else i.start.push(this.sourceToken);return;case"space":case"comment":if(i.value)t.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(i.start,t.indent)){let r=t.items[t.items.length-2]?.value?.end;if(Array.isArray(r)){Ac(r,i.start),r.push(this.sourceToken),t.items.pop();return}}i.start.push(this.sourceToken)}return;case"anchor":case"tag":if(i.value||this.indent<=t.indent)break;i.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==t.indent)break;i.value||ln(i.start,"seq-item-ind")?t.items.push({start:[this.sourceToken]}):i.start.push(this.sourceToken);return}if(this.indent>t.indent){let n=this.startBlockValue(t);if(n){this.stack.push(n);return}}yield*this.pop(),yield*this.step()}*flowCollection(t){let i=t.items[t.items.length-1];if(this.type==="flow-error-end"){let n;do yield*this.pop(),n=this.peek(1);while(n?.type==="flow-collection")}else if(t.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!i||i.sep?t.items.push({start:[this.sourceToken]}):i.start.push(this.sourceToken);return;case"map-value-ind":!i||i.value?t.items.push({start:[],key:null,sep:[this.sourceToken]}):i.sep?i.sep.push(this.sourceToken):Object.assign(i,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!i||i.value?t.items.push({start:[this.sourceToken]}):i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let r=this.flowScalar(this.type);!i||i.value?t.items.push({start:[],key:r,sep:[]}):i.sep?this.stack.push(r):Object.assign(i,{key:r,sep:[]});return}case"flow-map-end":case"flow-seq-end":t.end.push(this.sourceToken);return}let n=this.startBlockValue(t);n?this.stack.push(n):(yield*this.pop(),yield*this.step())}else{let n=this.peek(2);if(n.type==="block-map"&&(this.type==="map-value-ind"&&n.indent===t.indent||this.type==="newline"&&!n.items[n.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&n.type!=="flow-collection"){let r=xc(n),a=Lr(r);yg(t);let o=t.end.splice(1,t.end.length);o.push(this.sourceToken);let s={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:a,key:t,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(t)}}flowScalar(t){if(this.onNewLine){let i=this.source.indexOf(` +`,i)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(t){let i=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,i.value){let n="end"in i.value?i.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"space":case"comment":if(i.value)t.items.push({start:[this.sourceToken]});else if(i.sep)i.sep.push(this.sourceToken);else{if(this.atIndentedComment(i.start,t.indent)){let r=t.items[t.items.length-2]?.value?.end;if(Array.isArray(r)){Ac(r,i.start),r.push(this.sourceToken),t.items.pop();return}}i.start.push(this.sourceToken)}return}if(this.indent>=t.indent){let n=!this.onKeyLine&&this.indent===t.indent,r=n&&(i.sep||i.explicitKey)&&this.type!=="seq-item-ind",a=[];if(r&&i.sep&&!i.value){let o=[];for(let s=0;st.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(a=i.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":r||i.value?(a.push(this.sourceToken),t.items.push({start:a}),this.onKeyLine=!0):i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"explicit-key-ind":!i.sep&&!i.explicitKey?(i.start.push(this.sourceToken),i.explicitKey=!0):r||i.value?(a.push(this.sourceToken),t.items.push({start:a,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(i.explicitKey)if(i.sep)if(i.value)t.items.push({start:[],key:null,sep:[this.sourceToken]});else if(ln(i.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:a,key:null,sep:[this.sourceToken]}]});else if(bg(i.key)&&!ln(i.sep,"newline")){let o=Lr(i.start),s=i.key,c=i.sep;c.push(this.sourceToken),delete i.key,delete i.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:s,sep:c}]})}else a.length>0?i.sep=i.sep.concat(a,this.sourceToken):i.sep.push(this.sourceToken);else if(ln(i.start,"newline"))Object.assign(i,{key:null,sep:[this.sourceToken]});else{let o=Lr(i.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else i.sep?i.value||r?t.items.push({start:a,key:null,sep:[this.sourceToken]}):ln(i.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):i.sep.push(this.sourceToken):Object.assign(i,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);r||i.value?(t.items.push({start:a,key:o,sep:[]}),this.onKeyLine=!0):i.sep?this.stack.push(o):(Object.assign(i,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(t);if(o){if(o.type==="block-seq"){if(!i.explicitKey&&i.sep&&!ln(i.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else n&&t.items.push({start:a});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(t){let i=t.items[t.items.length-1];switch(this.type){case"newline":if(i.value){let n="end"in i.value?i.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else i.start.push(this.sourceToken);return;case"space":case"comment":if(i.value)t.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(i.start,t.indent)){let r=t.items[t.items.length-2]?.value?.end;if(Array.isArray(r)){Ac(r,i.start),r.push(this.sourceToken),t.items.pop();return}}i.start.push(this.sourceToken)}return;case"anchor":case"tag":if(i.value||this.indent<=t.indent)break;i.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==t.indent)break;i.value||ln(i.start,"seq-item-ind")?t.items.push({start:[this.sourceToken]}):i.start.push(this.sourceToken);return}if(this.indent>t.indent){let n=this.startBlockValue(t);if(n){this.stack.push(n);return}}yield*this.pop(),yield*this.step()}*flowCollection(t){let i=t.items[t.items.length-1];if(this.type==="flow-error-end"){let n;do yield*this.pop(),n=this.peek(1);while(n?.type==="flow-collection")}else if(t.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!i||i.sep?t.items.push({start:[this.sourceToken]}):i.start.push(this.sourceToken);return;case"map-value-ind":!i||i.value?t.items.push({start:[],key:null,sep:[this.sourceToken]}):i.sep?i.sep.push(this.sourceToken):Object.assign(i,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!i||i.value?t.items.push({start:[this.sourceToken]}):i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let r=this.flowScalar(this.type);!i||i.value?t.items.push({start:[],key:r,sep:[]}):i.sep?this.stack.push(r):Object.assign(i,{key:r,sep:[]});return}case"flow-map-end":case"flow-seq-end":t.end.push(this.sourceToken);return}let n=this.startBlockValue(t);n?this.stack.push(n):(yield*this.pop(),yield*this.step())}else{let n=this.peek(2);if(n.type==="block-map"&&(this.type==="map-value-ind"&&n.indent===t.indent||this.type==="newline"&&!n.items[n.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&n.type!=="flow-collection"){let r=xc(n),a=Lr(r);Ng(t);let o=t.end.splice(1,t.end.length);o.push(this.sourceToken);let s={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:a,key:t,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(t)}}flowScalar(t){if(this.onNewLine){let i=this.source.indexOf(` `)+1;for(;i!==0;)this.onNewLine(this.offset+i),i=this.source.indexOf(` -`,i)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let i=xc(t),n=Lr(i);return n.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let i=xc(t),n=Lr(i);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(t,i){return this.type!=="comment"||this.indent<=i?!1:t.every(n=>n.type==="newline"||n.type==="space")}*documentEnd(t){this.type!=="doc-mode"&&(t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(t){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};bg.Parser=hf});var Cg=P(lo=>{"use strict";var kg=Zd(),Fx=eo(),co=no(),Lx=Xu(),Bx=K(),qx=ff(),Sg=pf();function Eg(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new qx.LineCounter||null,prettyErrors:t}}function Vx(e,t={}){let{lineCounter:i,prettyErrors:n}=Eg(t),r=new Sg.Parser(i?.addNewLine),a=new kg.Composer(t),o=Array.from(a.compose(r.parse(e)));if(n&&i)for(let s of o)s.errors.forEach(co.prettifyError(e,i)),s.warnings.forEach(co.prettifyError(e,i));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function Rg(e,t={}){let{lineCounter:i,prettyErrors:n}=Eg(t),r=new Sg.Parser(i?.addNewLine),a=new kg.Composer(t),o=null;for(let s of a.compose(r.parse(e),!0,e.length))if(!o)o=s;else if(o.options.logLevel!=="silent"){o.errors.push(new co.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&i&&(o.errors.forEach(co.prettifyError(e,i)),o.warnings.forEach(co.prettifyError(e,i))),o}function Wx(e,t,i){let n;typeof t=="function"?n=t:i===void 0&&t&&typeof t=="object"&&(i=t);let r=Rg(e,i);if(!r)return null;if(r.warnings.forEach(a=>Lx.warn(r.options.logLevel,a)),r.errors.length>0){if(r.options.logLevel!=="silent")throw r.errors[0];r.errors=[]}return r.toJS(Object.assign({reviver:n},i))}function Jx(e,t,i){let n=null;if(typeof t=="function"||Array.isArray(t)?n=t:i===void 0&&t&&(i=t),typeof i=="string"&&(i=i.length),typeof i=="number"){let r=Math.round(i);i=r<1?void 0:r>8?{indent:8}:{indent:r}}if(e===void 0){let{keepUndefined:r}=i??t??{};if(!r)return}return Bx.isDocument(e)&&!n?e.toString(i):new Fx.Document(e,n,i).toString(i)}lo.parse=Wx;lo.parseAllDocuments=Vx;lo.parseDocument=Rg;lo.stringify=Jx});var uo=P(ee=>{"use strict";var zx=Zd(),Gx=eo(),Ux=jd(),mf=no(),Kx=Ma(),un=K(),Yx=an(),Xx=Re(),Qx=sn(),Zx=cn(),eA=Cc(),tA=uf(),iA=ff(),nA=pf(),Tc=Cg(),Pg=Oa();ee.Composer=zx.Composer;ee.Document=Gx.Document;ee.Schema=Ux.Schema;ee.YAMLError=mf.YAMLError;ee.YAMLParseError=mf.YAMLParseError;ee.YAMLWarning=mf.YAMLWarning;ee.Alias=Kx.Alias;ee.isAlias=un.isAlias;ee.isCollection=un.isCollection;ee.isDocument=un.isDocument;ee.isMap=un.isMap;ee.isNode=un.isNode;ee.isPair=un.isPair;ee.isScalar=un.isScalar;ee.isSeq=un.isSeq;ee.Pair=Yx.Pair;ee.Scalar=Xx.Scalar;ee.YAMLMap=Qx.YAMLMap;ee.YAMLSeq=Zx.YAMLSeq;ee.CST=eA;ee.Lexer=tA.Lexer;ee.LineCounter=iA.LineCounter;ee.Parser=nA.Parser;ee.parse=Tc.parse;ee.parseAllDocuments=Tc.parseAllDocuments;ee.parseDocument=Tc.parseDocument;ee.stringify=Tc.stringify;ee.visit=Pg.visit;ee.visitAsync=Pg.visitAsync});import{pathToFileURL as cM}from"url";import{randomUUID as gH}from"crypto";import{promises as wH}from"fs";import Ci from"path";import{isDeepStrictEqual as yH}from"util";import{createHash as xE}from"crypto";function Dp(e,t,i,n){return t.iteration>=i.maxIterations?{allowed:!1,reason:`Iteration budget exhausted: ${i.maxIterations}`}:e.type==="invoke_skill"&&!i.allowedSkills.includes(e.ref??"")?{allowed:!1,reason:`Skill is not allowed: ${e.ref??"(missing)"}`}:e.type==="call_tool"&&!i.allowedTools.includes(e.ref??"")?{allowed:!1,reason:`Tool is not allowed: ${e.ref??"(missing)"}`}:e.type==="handoff"&&!i.allowedAgents.includes(e.ref??"")?{allowed:!1,reason:`Agent is not allowed: ${e.ref??"(missing)"}`}:e.ref&&i.confirmationRequiredFor.includes(e.ref)&&!n.has(e.ref)?{allowed:!1,reason:`User confirmation required for: ${e.ref}`}:(t.retries[e.id]??0)>i.maxRetriesPerAction?{allowed:!1,reason:`Retry budget exhausted for action: ${e.id}`}:{allowed:!0}}function Mp(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let t of Reflect.ownKeys(e))Mp(e[t]);return Object.freeze(e)}function Zi(e){return Mp(structuredClone(e))}function ju(e,t,i,n){return e.resolveStep({pkg:Zi(t),state:Zi(i),context:Zi(n)})}function Fp(e,t,i,n,r,a){return e.resolveNext({pkg:Zi(t),state:Zi(i),step:Zi(n),outcome:Zi(r),context:Zi(a)})}function AE(e,t,i){return xE("sha256").update(`${e}:${t}:${i??"adaptive"}`).digest("hex").slice(0,16)}function Ou(e,t){return e.definition.orchestration.steps?.find(i=>i.id===t)}function _s(e,t,i,n,r){if(t.status!=="running")return{state:t,action:null,reason:`Run is ${t.status}`};if(t.pending)return{state:t,action:null,reason:`Action already pending: ${t.pending}`};if(t.orchestration==="adaptive")return{state:t,action:null,reason:"Adaptive orchestration requires an Agent candidate"};let a=ju(n,e,t,r);if(!a&&t.currentStep===null)return{state:{...t,status:"completed"},action:null};if(!a)return{state:{...t,status:"failed"},action:null,reason:`Unknown current step: ${t.currentStep}`};let o=Ou(e,a.id);if(!o)return{state:{...t,status:"failed"},action:null,reason:`Resolver returned unknown current step: ${a.id}`};let s=t.currentStep===o.id?t:{...t,currentStep:o.id},c={...o.action,id:AE(s.runId,s.iteration,o.id),stepId:o.id};return TE(e,s,c,i)}function TE(e,t,i,n){let r=Dp(i,t,e.guardrails,n);return r.allowed?{state:{...t,pending:i.id,status:"waiting"},action:i}:{state:t,action:null,reason:r.reason}}function Is(e,t,i,n,r){if(!t.pending||t.pending!==i.actionId)throw new Error(`Outcome does not match pending action: ${i.actionId}`);let a=t.orchestration==="deterministic"?ju(n,e,t,r):void 0,o=a?Ou(e,a.id):void 0;if(t.orchestration==="deterministic"&&!a)throw new Error(`Unknown current step: ${t.currentStep??"(missing)"}`);if(t.orchestration==="deterministic"&&!o)throw new Error(`Resolver returned unknown current step: ${a.id}`);if(i.status==="failed"){let c={...t.retries,[i.actionId]:(t.retries[i.actionId]??0)+1};return{...t,pending:null,status:"running",retries:c}}let s=t.orchestration==="deterministic"?Fp(n,e,t,o,i,r):t.currentStep;if(s!==null&&t.orchestration==="deterministic"&&!Ou(e,s))throw new Error(`Resolver returned unknown next step: ${s}`);return{...t,currentStep:s,iteration:t.iteration+1,pending:null,status:s===null&&t.orchestration==="deterministic"?"completed":"running"}}import{promises as ch}from"fs";import ky from"path";var zo=Ts(uo(),1);import{promises as $i}from"fs";import dt from"path";import{createHash as sA}from"node:crypto";import{promises as Vt}from"node:fs";import Pt from"node:path";import{TextDecoder as cA}from"node:util";import vf from"path";var rA=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),aA=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function oA(e){return e.toLowerCase().startsWith(".env")}function ci(e){let i=e.replaceAll("\\","/").split("/").filter(Boolean).map(n=>n.toLowerCase());return i.some(n=>oA(n))?"environment-file":i.some(n=>aA.has(n))?"credential-config":i.includes(".git")?"git-metadata":i.some(n=>rA.has(n))?"dependency-or-cache":i.join("/")===".comet/config.yaml"?"comet-config":i.join("/")===".comet/current-change.json"?"comet-selection":null}function fo(e,t){let i=ci(t);if(i)return i;let n=vf.resolve(e.projectRoot,...t.split("/")),r=vf.relative(e.projectRoot,e.nativeRoot).replaceAll("\\","/"),a=t.replaceAll("\\","/");return a===r||a.startsWith(`${r}/`)||n===vf.resolve(e.configFile)?"native-runtime":null}function dn(e){return e!==0&&e!==0n&&e!=="0"}function Ue(e,t){return dn(e.dev)&&dn(t.dev)&&dn(e.ino)&&dn(t.ino)}function M(e,t){let i=dn(e.dev)&&dn(t.dev);if(i&&e.dev!==t.dev)return!1;let n=dn(e.ino)&&dn(t.ino);return n&&e.ino!==t.ino?!1:i&&n?!0:e.birthtime===t.birthtime}var ho=1024*1024;function gf(e,t){let i=Pt.relative(e,t);return i===""||!Pt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Pt.sep}`)}function lA(e){let t=Pt.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(r=>{let a=r.codePointAt(0)??0;return a<=31||a===127})||Pt.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||t!==e||t==="."||e.endsWith("/"))throw new Error(`Native artifact ref must be normalized and relative: ${e}`);let i=e.toLowerCase(),n=ci(e);if(n||i==="runtime"||i.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${n??"native-runtime"}): ${e}`);return e}function uA(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function dA(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function _c(e,t){let i={...e,birthtime:e.birthtimeMs},n={...t,birthtime:t.birthtimeMs};return Ue(i,n)?M(i,n):M(i,n)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function xg(e){let t=await Vt.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await Vt.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function fA(e,t){let i=Pt.resolve(e),n=Pt.resolve(t);if(!gf(i,n))throw new Error("Native artifact path is outside its root");let r=[await xg(i)],a=i;for(let o of Pt.relative(i,n).split(Pt.sep).filter(Boolean)){a=Pt.join(a,o);let s=await xg(a);if(!gf(r[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);r.push(s)}return r}async function Ag(e){for(let t of e){let i=await Vt.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!dA(t,i)||await Vt.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function ye(e){let t=lA(e.ref),i=uA(e.maxBytes??ho),n=Pt.resolve(e.root,...t.split("/")),r=await fA(e.root,Pt.dirname(n));await e.hooks?.afterParentChainCaptured?.();let a=await Vt.lstat(n);if(!a.isFile()||a.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${t}`);if(a.size>i)throw new Error(`Native artifact exceeds ${i} bytes: ${t}`);let o=await Vt.realpath(n);if(!gf(r[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await Vt.open(n,"r");try{let[c,l,u]=await Promise.all([s.stat(),Vt.lstat(n),Vt.realpath(n)]);if(await Ag(r),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!_c(a,c)||!_c(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let d=[],f=0,h=Buffer.allocUnsafe(Math.min(64*1024,i+1));for(;;){let N=i+1-f,b=await s.read(h,0,Math.min(h.length,N),null);if(b.bytesRead===0)break;if(f+=b.bytesRead,f>i)throw new Error(`Native artifact exceeds ${i} bytes: ${t}`);d.push(Buffer.from(h.subarray(0,b.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[m,p,v]=await Promise.all([s.stat(),Vt.lstat(n),Vt.realpath(n)]);if(await Ag(r),!p.isFile()||p.isSymbolicLink()||v!==o||!_c(c,m)||!_c(c,p))throw new Error(`Native artifact changed while reading: ${t}`);let S=Buffer.concat(d,f),k;try{k=new cA("utf-8",{fatal:!0}).decode(S)}catch(N){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:N})}return{ref:t,size:f,hash:sA("sha256").update(S).digest("hex"),text:k}}finally{await s.close()}}import{randomUUID as hA}from"crypto";import{promises as Ke}from"fs";import Wt from"path";function yf(e,t){let i=Wt.relative(e,t);return i===""||!Wt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Wt.sep}`)}function pA(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function wf(e,t){let i={...e,birthtime:e.birthtimeMs},n={...t,birthtime:t.birthtimeMs};return Ue(i,n)?M(i,n):M(i,n)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Tg(e){let t=await Ke.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native atomic write parent must be a real directory: ${e}`);return{path:e,realPath:await Ke.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function po(e){for(let t of e){let i=await Ke.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!pA(t,i)||await Ke.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function mA(e,t){let i=Wt.resolve(e),n=Wt.resolve(t);if(!yf(i,n))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let r=[await Tg(i)],a=Wt.relative(i,n).split(Wt.sep).filter(Boolean),o=i;for(let s of a){await po(r),o=Wt.join(o,s);try{await Ke.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await Tg(o);if(!yf(r[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);r.push(c)}return await po(r),r}async function vA(e){let t;try{t=await Ke.open(e,"r"),await t.sync()}catch(i){let n=i.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(n??""))throw i}finally{await t?.close()}}async function _g(e,t,i={}){let n=Wt.dirname(e),r=i.containedRoot?await mA(i.containedRoot,n):null;r||await Ke.mkdir(n,{recursive:!0});let a=Wt.join(n,`.${Wt.basename(e)}.${hA()}.tmp`),o,s;try{if(await i.beforeTemporaryOpen?.(),o=await Ke.open(a,"wx"),s=await o.stat(),r){let[c,l]=await Promise.all([Ke.lstat(a),Ke.realpath(a)]);if(await po(r),!c.isFile()||c.isSymbolicLink()||!wf(s,c)||!yf(r[0].realPath,l))throw new Error("Native atomic write temporary file opened outside its managed parent")}if(typeof t=="string"?await o.writeFile(t,"utf8"):await o.writeFile(t),await o.sync(),!wf(s,await o.stat()))throw new Error("Native atomic write temporary file changed while writing");if(await o.close(),o=void 0,await i.beforeCommit?.(),r){await po(r);let c=await Ke.lstat(a);if(!c.isFile()||c.isSymbolicLink()||!s||!wf(c,s))throw new Error("Native atomic write temporary file changed before commit")}i.exclusive?(await Ke.link(a,e),await Ke.unlink(a)):await Ke.rename(a,e),await vA(n)}catch(c){if(await o?.close(),!r)await Ke.rm(a,{force:!0});else try{await po(r),await Ke.rm(a,{force:!0})}catch{}throw c}}async function $e(e,t,i={}){await _g(e,t,i)}async function Ig(e,t,i={}){await _g(e,t,i)}async function le(e,t,i={}){await $e(e,JSON.stringify(t,null,2)+` +`,i)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let i=xc(t),n=Lr(i);return n.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let i=xc(t),n=Lr(i);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(t,i){return this.type!=="comment"||this.indent<=i?!1:t.every(n=>n.type==="newline"||n.type==="space")}*documentEnd(t){this.type!=="doc-mode"&&(t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(t){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};kg.Parser=hf});var Pg=P(lo=>{"use strict";var Sg=Zd(),Fx=eo(),co=no(),Lx=Xu(),Bx=K(),qx=ff(),Eg=pf();function Rg(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new qx.LineCounter||null,prettyErrors:t}}function Vx(e,t={}){let{lineCounter:i,prettyErrors:n}=Rg(t),r=new Eg.Parser(i?.addNewLine),a=new Sg.Composer(t),o=Array.from(a.compose(r.parse(e)));if(n&&i)for(let s of o)s.errors.forEach(co.prettifyError(e,i)),s.warnings.forEach(co.prettifyError(e,i));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function Cg(e,t={}){let{lineCounter:i,prettyErrors:n}=Rg(t),r=new Eg.Parser(i?.addNewLine),a=new Sg.Composer(t),o=null;for(let s of a.compose(r.parse(e),!0,e.length))if(!o)o=s;else if(o.options.logLevel!=="silent"){o.errors.push(new co.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&i&&(o.errors.forEach(co.prettifyError(e,i)),o.warnings.forEach(co.prettifyError(e,i))),o}function Wx(e,t,i){let n;typeof t=="function"?n=t:i===void 0&&t&&typeof t=="object"&&(i=t);let r=Cg(e,i);if(!r)return null;if(r.warnings.forEach(a=>Lx.warn(r.options.logLevel,a)),r.errors.length>0){if(r.options.logLevel!=="silent")throw r.errors[0];r.errors=[]}return r.toJS(Object.assign({reviver:n},i))}function Jx(e,t,i){let n=null;if(typeof t=="function"||Array.isArray(t)?n=t:i===void 0&&t&&(i=t),typeof i=="string"&&(i=i.length),typeof i=="number"){let r=Math.round(i);i=r<1?void 0:r>8?{indent:8}:{indent:r}}if(e===void 0){let{keepUndefined:r}=i??t??{};if(!r)return}return Bx.isDocument(e)&&!n?e.toString(i):new Fx.Document(e,n,i).toString(i)}lo.parse=Wx;lo.parseAllDocuments=Vx;lo.parseDocument=Cg;lo.stringify=Jx});var uo=P(ee=>{"use strict";var zx=Zd(),Gx=eo(),Ux=jd(),mf=no(),Kx=Ma(),un=K(),Yx=an(),Xx=Re(),Qx=sn(),Zx=cn(),eA=Cc(),tA=uf(),iA=ff(),nA=pf(),Tc=Pg(),xg=Oa();ee.Composer=zx.Composer;ee.Document=Gx.Document;ee.Schema=Ux.Schema;ee.YAMLError=mf.YAMLError;ee.YAMLParseError=mf.YAMLParseError;ee.YAMLWarning=mf.YAMLWarning;ee.Alias=Kx.Alias;ee.isAlias=un.isAlias;ee.isCollection=un.isCollection;ee.isDocument=un.isDocument;ee.isMap=un.isMap;ee.isNode=un.isNode;ee.isPair=un.isPair;ee.isScalar=un.isScalar;ee.isSeq=un.isSeq;ee.Pair=Yx.Pair;ee.Scalar=Xx.Scalar;ee.YAMLMap=Qx.YAMLMap;ee.YAMLSeq=Zx.YAMLSeq;ee.CST=eA;ee.Lexer=tA.Lexer;ee.LineCounter=iA.LineCounter;ee.Parser=nA.Parser;ee.parse=Tc.parse;ee.parseAllDocuments=Tc.parseAllDocuments;ee.parseDocument=Tc.parseDocument;ee.stringify=Tc.stringify;ee.visit=xg.visit;ee.visitAsync=xg.visitAsync});import{pathToFileURL as cM}from"url";import{randomUUID as gH}from"crypto";import{promises as wH}from"fs";import Ci from"path";import{isDeepStrictEqual as yH}from"util";import{createHash as xE}from"crypto";function Mp(e,t,i,n){return t.iteration>=i.maxIterations?{allowed:!1,reason:`Iteration budget exhausted: ${i.maxIterations}`}:e.type==="invoke_skill"&&!i.allowedSkills.includes(e.ref??"")?{allowed:!1,reason:`Skill is not allowed: ${e.ref??"(missing)"}`}:e.type==="call_tool"&&!i.allowedTools.includes(e.ref??"")?{allowed:!1,reason:`Tool is not allowed: ${e.ref??"(missing)"}`}:e.type==="handoff"&&!i.allowedAgents.includes(e.ref??"")?{allowed:!1,reason:`Agent is not allowed: ${e.ref??"(missing)"}`}:e.ref&&i.confirmationRequiredFor.includes(e.ref)&&!n.has(e.ref)?{allowed:!1,reason:`User confirmation required for: ${e.ref}`}:(t.retries[e.id]??0)>i.maxRetriesPerAction?{allowed:!1,reason:`Retry budget exhausted for action: ${e.id}`}:{allowed:!0}}function Fp(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let t of Reflect.ownKeys(e))Fp(e[t]);return Object.freeze(e)}function Zi(e){return Fp(structuredClone(e))}function ju(e,t,i,n){return e.resolveStep({pkg:Zi(t),state:Zi(i),context:Zi(n)})}function Lp(e,t,i,n,r,a){return e.resolveNext({pkg:Zi(t),state:Zi(i),step:Zi(n),outcome:Zi(r),context:Zi(a)})}function AE(e,t,i){return xE("sha256").update(`${e}:${t}:${i??"adaptive"}`).digest("hex").slice(0,16)}function Ou(e,t){return e.definition.orchestration.steps?.find(i=>i.id===t)}function _s(e,t,i,n,r){if(t.status!=="running")return{state:t,action:null,reason:`Run is ${t.status}`};if(t.pending)return{state:t,action:null,reason:`Action already pending: ${t.pending}`};if(t.orchestration==="adaptive")return{state:t,action:null,reason:"Adaptive orchestration requires an Agent candidate"};let a=ju(n,e,t,r);if(!a&&t.currentStep===null)return{state:{...t,status:"completed"},action:null};if(!a)return{state:{...t,status:"failed"},action:null,reason:`Unknown current step: ${t.currentStep}`};let o=Ou(e,a.id);if(!o)return{state:{...t,status:"failed"},action:null,reason:`Resolver returned unknown current step: ${a.id}`};let s=t.currentStep===o.id?t:{...t,currentStep:o.id},c={...o.action,id:AE(s.runId,s.iteration,o.id),stepId:o.id};return TE(e,s,c,i)}function TE(e,t,i,n){let r=Mp(i,t,e.guardrails,n);return r.allowed?{state:{...t,pending:i.id,status:"waiting"},action:i}:{state:t,action:null,reason:r.reason}}function Is(e,t,i,n,r){if(!t.pending||t.pending!==i.actionId)throw new Error(`Outcome does not match pending action: ${i.actionId}`);let a=t.orchestration==="deterministic"?ju(n,e,t,r):void 0,o=a?Ou(e,a.id):void 0;if(t.orchestration==="deterministic"&&!a)throw new Error(`Unknown current step: ${t.currentStep??"(missing)"}`);if(t.orchestration==="deterministic"&&!o)throw new Error(`Resolver returned unknown current step: ${a.id}`);if(i.status==="failed"){let c={...t.retries,[i.actionId]:(t.retries[i.actionId]??0)+1};return{...t,pending:null,status:"running",retries:c}}let s=t.orchestration==="deterministic"?Lp(n,e,t,o,i,r):t.currentStep;if(s!==null&&t.orchestration==="deterministic"&&!Ou(e,s))throw new Error(`Resolver returned unknown next step: ${s}`);return{...t,currentStep:s,iteration:t.iteration+1,pending:null,status:s===null&&t.orchestration==="deterministic"?"completed":"running"}}import{promises as ch}from"fs";import Sy from"path";var zo=Ts(uo(),1);import{promises as $i}from"fs";import dt from"path";import{createHash as sA}from"node:crypto";import{promises as Vt}from"node:fs";import Pt from"node:path";import{TextDecoder as cA}from"node:util";import vf from"path";var rA=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),aA=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function oA(e){return e.toLowerCase().startsWith(".env")}function ci(e){let i=e.replaceAll("\\","/").split("/").filter(Boolean).map(n=>n.toLowerCase());return i.some(n=>oA(n))?"environment-file":i.some(n=>aA.has(n))?"credential-config":i.includes(".git")?"git-metadata":i.some(n=>rA.has(n))?"dependency-or-cache":i.join("/")===".comet/config.yaml"?"comet-config":i.join("/")===".comet/current-change.json"?"comet-selection":null}function fo(e,t){let i=ci(t);if(i)return i;let n=vf.resolve(e.projectRoot,...t.split("/")),r=vf.relative(e.projectRoot,e.nativeRoot).replaceAll("\\","/"),a=t.replaceAll("\\","/");return a===r||a.startsWith(`${r}/`)||n===vf.resolve(e.configFile)?"native-runtime":null}function dn(e){return e!==0&&e!==0n&&e!=="0"}function Ue(e,t){return dn(e.dev)&&dn(t.dev)&&dn(e.ino)&&dn(t.ino)}function M(e,t){let i=dn(e.dev)&&dn(t.dev);if(i&&e.dev!==t.dev)return!1;let n=dn(e.ino)&&dn(t.ino);return n&&e.ino!==t.ino?!1:i&&n?!0:e.birthtime===t.birthtime}var ho=1024*1024;function gf(e,t){let i=Pt.relative(e,t);return i===""||!Pt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Pt.sep}`)}function lA(e){let t=Pt.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(r=>{let a=r.codePointAt(0)??0;return a<=31||a===127})||Pt.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||t!==e||t==="."||e.endsWith("/"))throw new Error(`Native artifact ref must be normalized and relative: ${e}`);let i=e.toLowerCase(),n=ci(e);if(n||i==="runtime"||i.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${n??"native-runtime"}): ${e}`);return e}function uA(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function dA(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function _c(e,t){let i={...e,birthtime:e.birthtimeMs},n={...t,birthtime:t.birthtimeMs};return Ue(i,n)?M(i,n):M(i,n)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Ag(e){let t=await Vt.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await Vt.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function fA(e,t){let i=Pt.resolve(e),n=Pt.resolve(t);if(!gf(i,n))throw new Error("Native artifact path is outside its root");let r=[await Ag(i)],a=i;for(let o of Pt.relative(i,n).split(Pt.sep).filter(Boolean)){a=Pt.join(a,o);let s=await Ag(a);if(!gf(r[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);r.push(s)}return r}async function Tg(e){for(let t of e){let i=await Vt.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!dA(t,i)||await Vt.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function ye(e){let t=lA(e.ref),i=uA(e.maxBytes??ho),n=Pt.resolve(e.root,...t.split("/")),r=await fA(e.root,Pt.dirname(n));await e.hooks?.afterParentChainCaptured?.();let a=await Vt.lstat(n);if(!a.isFile()||a.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${t}`);if(a.size>i)throw new Error(`Native artifact exceeds ${i} bytes: ${t}`);let o=await Vt.realpath(n);if(!gf(r[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await Vt.open(n,"r");try{let[c,l,u]=await Promise.all([s.stat(),Vt.lstat(n),Vt.realpath(n)]);if(await Tg(r),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!_c(a,c)||!_c(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let d=[],f=0,h=Buffer.allocUnsafe(Math.min(64*1024,i+1));for(;;){let N=i+1-f,b=await s.read(h,0,Math.min(h.length,N),null);if(b.bytesRead===0)break;if(f+=b.bytesRead,f>i)throw new Error(`Native artifact exceeds ${i} bytes: ${t}`);d.push(Buffer.from(h.subarray(0,b.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[m,p,v]=await Promise.all([s.stat(),Vt.lstat(n),Vt.realpath(n)]);if(await Tg(r),!p.isFile()||p.isSymbolicLink()||v!==o||!_c(c,m)||!_c(c,p))throw new Error(`Native artifact changed while reading: ${t}`);let S=Buffer.concat(d,f),k;try{k=new cA("utf-8",{fatal:!0}).decode(S)}catch(N){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:N})}return{ref:t,size:f,hash:sA("sha256").update(S).digest("hex"),text:k}}finally{await s.close()}}import{randomUUID as hA}from"crypto";import{promises as Ke}from"fs";import Wt from"path";function yf(e,t){let i=Wt.relative(e,t);return i===""||!Wt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Wt.sep}`)}function pA(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function wf(e,t){let i={...e,birthtime:e.birthtimeMs},n={...t,birthtime:t.birthtimeMs};return Ue(i,n)?M(i,n):M(i,n)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function _g(e){let t=await Ke.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native atomic write parent must be a real directory: ${e}`);return{path:e,realPath:await Ke.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function po(e){for(let t of e){let i=await Ke.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!pA(t,i)||await Ke.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function mA(e,t){let i=Wt.resolve(e),n=Wt.resolve(t);if(!yf(i,n))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let r=[await _g(i)],a=Wt.relative(i,n).split(Wt.sep).filter(Boolean),o=i;for(let s of a){await po(r),o=Wt.join(o,s);try{await Ke.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await _g(o);if(!yf(r[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);r.push(c)}return await po(r),r}async function vA(e){let t;try{t=await Ke.open(e,"r"),await t.sync()}catch(i){let n=i.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(n??""))throw i}finally{await t?.close()}}async function Ig(e,t,i={}){let n=Wt.dirname(e),r=i.containedRoot?await mA(i.containedRoot,n):null;r||await Ke.mkdir(n,{recursive:!0});let a=Wt.join(n,`.${Wt.basename(e)}.${hA()}.tmp`),o,s;try{if(await i.beforeTemporaryOpen?.(),o=await Ke.open(a,"wx"),s=await o.stat(),r){let[c,l]=await Promise.all([Ke.lstat(a),Ke.realpath(a)]);if(await po(r),!c.isFile()||c.isSymbolicLink()||!wf(s,c)||!yf(r[0].realPath,l))throw new Error("Native atomic write temporary file opened outside its managed parent")}if(typeof t=="string"?await o.writeFile(t,"utf8"):await o.writeFile(t),await o.sync(),!wf(s,await o.stat()))throw new Error("Native atomic write temporary file changed while writing");if(await o.close(),o=void 0,await i.beforeCommit?.(),r){await po(r);let c=await Ke.lstat(a);if(!c.isFile()||c.isSymbolicLink()||!s||!wf(c,s))throw new Error("Native atomic write temporary file changed before commit")}i.exclusive?(await Ke.link(a,e),await Ke.unlink(a)):await Ke.rename(a,e),await vA(n)}catch(c){if(await o?.close(),!r)await Ke.rm(a,{force:!0});else try{await po(r),await Ke.rm(a,{force:!0})}catch{}throw c}}async function $e(e,t,i={}){await Ig(e,t,i)}async function jg(e,t,i={}){await Ig(e,t,i)}async function le(e,t,i={}){await $e(e,JSON.stringify(t,null,2)+` `,i)}import $A from"path";var vo=Ts(uo(),1);import jc from"path";var go=64*1024,Oc=1024,$c=64,Hc=5,gA=[".agents/skills/**",".amazonq/skills/**",".augment/skills/**",".bob/skills/**",".claude/skills/**",".cline/skills/**",".codebuddy/skills/**",".continue/skills/**",".cospec/skills/**",".crush/skills/**",".cursor/skills/**",".factory/skills/**",".forge/skills/**",".gemini/skills/**",".github/skills/**",".iflow/skills/**",".junie/skills/**",".kilocode/skills/**",".kimi-code/skills/**",".kiro/skills/**",".lingma/skills/**",".mimocode/skills/**",".opencode/skills/**",".pi/skills/**",".qoder/skills/**",".qwen/skills/**",".roo/skills/**",".trae-cn/skills/**",".trae/skills/**",".windsurf/skills/**",".zcode/skills/**"],ot={include:["**/*"],exclude:[...gA],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4},Ic={en:{schema:"# Configuration schema used by Comet. Do not edit this value.",default_workflow:"# Default workflow entered by /comet. Must also appear in workflows.",workflows:"# Workflows enabled in this project: native, classic, or both.",ambient_resume:`# Enables automatic recovery through the read-only Ambient Resume probe for both Native and Classic. Set false to disable it. # ambient_resume: true | false`,native:"# Native workflow settings. They do not change Classic state or behavior.","native.artifact_root":"# Root directory where Native stores Comet specs, changes, and runtime data.","native.language":`# Artifact language used by Native workflow documents. # language: en | zh-CN`,"native.clarification_mode":`# Controls whether Native asks one clarification at a time or every currently answerable question in a round. @@ -158,48 +158,48 @@ ${i.comment}`:i.comment}this.doc.range[2]=i.offset;break}default:this.errors.pus # 可选值:en | zh-CN`,"classic.context_compression":`# 新建 Classic change 是否启用 beta 上下文压缩。 # 可选值:off | beta`,"classic.review_mode":`# 新建 Classic change 默认使用的审查深度。 # 可选值:off | standard | thorough`,"classic.auto_transition":`# Classic 阶段通过后是否自动进入下一阶段。 -# 可选值:true | false`}};function Og(e,t){return Ic[t][e]}function wA(e,t,i){let n=/^(\s*)([a-z_]+):/u.exec(e);if(!n)return null;let r=n[1].length,a=n[2];if(r===0&&a in Ic.en)return a;if(r===2&&t){let o=`${t}.${a}`;if(o in Ic.en)return o}if(r===4&&t==="native"&&i==="snapshot"){let o=`native.snapshot.${a}`;if(o in Ic.en)return o}return null}function wo(e,t){let i=[],n=null,r=null;for(let a of(0,vo.stringify)(e).trimEnd().split(` -`)){let o=wA(a,n,r);if(o){let s=a.match(/^\s*/u)?.[0]??"";for(let c of Og(o,t).split(` +# 可选值:true | false`}};function $g(e,t){return Ic[t][e]}function wA(e,t,i){let n=/^(\s*)([a-z_]+):/u.exec(e);if(!n)return null;let r=n[1].length,a=n[2];if(r===0&&a in Ic.en)return a;if(r===2&&t){let o=`${t}.${a}`;if(o in Ic.en)return o}if(r===4&&t==="native"&&i==="snapshot"){let o=`native.snapshot.${a}`;if(o in Ic.en)return o}return null}function wo(e,t){let i=[],n=null,r=null;for(let a of(0,vo.stringify)(e).trimEnd().split(` +`)){let o=wA(a,n,r);if(o){let s=a.match(/^\s*/u)?.[0]??"";for(let c of $g(o,t).split(` `))i.push(`${s}${c}`)}i.push(a),/^[a-z_]+:/u.test(a)?(a.startsWith("native:")?n="native":a.startsWith("classic:")?n="classic":n=null,r=null):/^ {2}[a-z_]+:/u.test(a)&&n==="native"&&(r=a.startsWith(" snapshot:")?"snapshot":null)}return i.push(""),i.join(` -`)}function yA(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim();if(i.length===0||jc.posix.isAbsolute(i)||jc.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${t} must be a project-relative path`);if(i===".")return[];let n=i.replaceAll("\\","/").split("/");if(n.some(r=>r===".."))throw new Error(`${t} must stay inside the project root`);if(n.some(r=>r===""||r==="."))throw new Error(`${t} must not contain empty or dot path segments`);return n}function Xn(e){let t=yA(e,"native.artifact_root");return t.length===0?".":t.join("/")}function $g(e,t="docs"){let i=e??t;if(i!=="legacy"&&i!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return i}function bf(e,t,i=!1){if(typeof e!="string")throw new Error(`${t} must be a string`);let n=e.trim().replaceAll("\\","/");if(n.length===0||jc.posix.isAbsolute(n)||jc.win32.isAbsolute(n)||/^(?:~|[\\/])/u.test(n))throw new Error(`${t} must be relative to its declared path base`);let r=n.split("/");if(r.some(a=>a===".."))throw new Error(`${t} must stay inside its declared path base`);if(r.some(a=>a===""||a==="."))throw new Error(`${t} must not contain empty or dot path segments`);if(!i&&/[*?]/u.test(n))throw new Error(`${t} cannot contain wildcards`);return r.join("/")}function mo(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Hg(e,t,i){let n=e??t;if(n!=="en"&&n!=="zh-CN")throw new Error(`${i} must be en or zh-CN`);return n}function Dc(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||e.startsWith("/")||e.split("/").includes(".."))throw new Error(`${t} contains an unsafe pattern`);if(e.length>Oc)throw new Error(`${t} exceeds ${Oc} characters`);let i=0;for(let n=0;n$c)throw new Error(`${t} contains more than ${$c} wildcard tokens`);return e}function jg(e,t,i){if(e===void 0)return[...i];if(!Array.isArray(e))throw new Error(`${t} contains an unsafe pattern`);return[...new Set(e.map(n=>Dc(n,t)))].sort((n,r)=>n.localeCompare(r,"en"))}function Nf(e,t,i){let n=e??t;if(!Number.isSafeInteger(n)||n<1)throw new Error(`${i} must be a positive integer`);return n}function NA(e){if(e===void 0)return{...ot,include:[...ot.include],exclude:[...ot.exclude]};let t=mo(e,"native.snapshot");return{include:jg(t.include,"native.snapshot.include",ot.include),exclude:jg(t.exclude,"native.snapshot.exclude",ot.exclude),max_files:Nf(t.max_files,ot.max_files,"native.snapshot.max_files"),max_total_bytes:Nf(t.max_total_bytes,ot.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:Nf(t.max_duration_ms,ot.max_duration_ms,"native.snapshot.max_duration_ms")}}function bA(e){if(e===void 0)return;let t=mo(e,"native.pending_root_move"),i=t.id,n=t.from_artifact_root,r=t.to_artifact_root,a=t.stage;if(typeof i!="string"||!/^[a-f0-9-]{8,}$/u.test(i))throw new Error("native.pending_root_move.id is invalid");if(typeof n!="string"||typeof r!="string")throw new Error("native.pending_root_move roots must be strings");if(a!=="copying"&&a!=="ready"&&a!=="switched")throw new Error("native.pending_root_move.stage is invalid");let o;if(t.cleanup!==void 0){let s=mo(t.cleanup,"native.pending_root_move.cleanup"),c=s.kind,l=s.state,u=s.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof u!="string"||!/^[a-f0-9]{64}$/u.test(u))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:u}}return{id:i,fromArtifactRoot:Xn(n),toArtifactRoot:Xn(r),stage:a,...o?{cleanup:o}:{}}}function kA(e,t={}){let i=mo(e,"native"),n=i.artifact_root??(t.allowMissingArtifactRoot?"docs":void 0);if(typeof n!="string")throw new Error("native.artifact_root must be a string");let r=i.clarification_mode??"sequential";if(r!=="sequential"&&r!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let a=i.archive_confirmation??"automatic";if(a!=="automatic"&&a!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=i.max_verify_failures??Hc;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=bA(i.pending_root_move);return{artifact_root:Xn(n),language:Hg(i.language,"en","native.language"),clarification_mode:r,archive_confirmation:a,max_verify_failures:o,snapshot:NA(i.snapshot),...s?{pending_root_move:s}:{}}}function SA(e){let t=mo(e,"classic"),i=t.context_compression??"off";if(i!=="off"&&i!=="beta")throw new Error("classic.context_compression must be off or beta");let n=t.review_mode??"standard";if(n!=="off"&&n!=="standard"&&n!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let r=t.auto_transition??!0;if(typeof r!="boolean")throw new Error("classic.auto_transition must be true or false");return{artifact_layout:$g(t.artifact_layout),language:Hg(t.language,"zh-CN","classic.language"),context_compression:i,review_mode:n,auto_transition:r}}function EA(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function RA(e,t,i,n,r){let a=e.schema!==void 0;if(!(a||e.default_workflow!==void 0||e.workflows!==void 0||!r.allowPartialProject&&e.native!==void 0)||r.allowPartialProject&&!a)return null;if(e.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(e.default_workflow!=="native"&&e.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let s=e.workflows??[e.default_workflow];if(!Array.isArray(s)||s.length===0||s.some(l=>l!=="native"&&l!=="classic"))throw new Error("workflows must contain native and/or classic");let c=[...new Set(s)];if(!c.includes(e.default_workflow))throw new Error("workflows must include default_workflow");if(c.includes("native")&&!t)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:e.default_workflow,workflows:c,ambient_resume:n,...t?{native:t}:{},...i?{classic:i}:{}}}function qr(e,t={}){let i=(0,vo.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${i.errors[0].message}`);let n=i.toJS();if(n==null)return{value:{},config:null,ambient_resume:!0};if(typeof n!="object"||Array.isArray(n))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let r=n,a=EA(r.ambient_resume),o=r.native===void 0?void 0:kA(r.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),s=r.classic===void 0?void 0:SA(r.classic),c=RA(r,o,s,a,{allowPartialProject:t.allowPartialProject??!1});return{value:r,config:c,ambient_resume:a,...o?{native:o}:{},...s?{classic:s}:{}}}function Dg(e){return{id:e.id,from_artifact_root:e.fromArtifactRoot,to_artifact_root:e.toArtifactRoot,stage:e.stage,...e.cleanup?{cleanup:{kind:e.cleanup.kind,state:e.cleanup.state,manifest_hash:e.cleanup.manifestHash}}:{}}}function Mg(e){return{schema:e.schema,default_workflow:e.default_workflow,workflows:e.workflows??[e.default_workflow],ambient_resume:e.ambient_resume,...e.native?{native:{artifact_root:e.native.artifact_root,language:e.native.language,clarification_mode:e.native.clarification_mode,archive_confirmation:e.native.archive_confirmation,max_verify_failures:e.native.max_verify_failures,snapshot:e.native.snapshot,...e.native.pending_root_move?{pending_root_move:Dg(e.native.pending_root_move)}:{}}}:{},...e.classic?{classic:{artifact_layout:e.classic.artifact_layout,language:e.classic.language,context_compression:e.classic.context_compression,review_mode:e.classic.review_mode,auto_transition:e.classic.auto_transition}}:{}}}function Br(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function yo(e,t){let i=Mg(t),n=qr((0,vo.stringify)(i)).config;if(!n)throw new Error("Unsupported Comet project schema");let r={...e,schema:n.schema,default_workflow:n.default_workflow,workflows:n.workflows,ambient_resume:n.ambient_resume};if(n.native){let a=Br(e.native),o=Br(a.snapshot),s={...a,artifact_root:n.native.artifact_root,language:n.native.language,clarification_mode:n.native.clarification_mode,archive_confirmation:n.native.archive_confirmation,max_verify_failures:n.native.max_verify_failures,snapshot:{...o,...n.native.snapshot}};if(n.native.pending_root_move){let c=Br(a.pending_root_move),l=Dg(n.native.pending_root_move),u=Br(c.cleanup),d=Br(l.cleanup);s.pending_root_move={...c,...l,...l.cleanup?{cleanup:{...u,...d}}:{}}}else delete s.pending_root_move;r.native=s}return n.classic&&(r.classic={...Br(e.classic),artifact_layout:n.classic.artifact_layout,language:n.classic.language,context_compression:n.classic.context_compression,review_mode:n.classic.review_mode,auto_transition:n.classic.auto_transition}),r}function Mc(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,native:{artifact_root:Xn(e),language:t,clarification_mode:"sequential",archive_confirmation:"automatic",max_verify_failures:Hc,snapshot:{...ot,include:[...ot.include],exclude:[...ot.exclude]}}}}import{createHash as PA}from"crypto";import{promises as Bc}from"fs";import hn from"path";import{constants as Fc,promises as Qn}from"fs";var xt=class extends Error{reason;constructor(t,i,n){super(i,n),this.name="RaceSafeReadError",this.reason=t}};function kf(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function Fg(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function No(e){return{dev:e.dev,ino:e.ino,birthtime:kf(e)}}function Lc(e,t){let i=No(e),n=No(t);return Ue(i,n)?M(i,n):M(i,n)&&kf(e)===kf(t)&&Fg(e)===Fg(t)&&e.size===t.size}async function fn(e,t,i={}){if(!Number.isSafeInteger(t)||t<1)throw new Error("race-safe read byte limit must be a positive integer");let n=i.label??"file",r=i.bigint===!0,a=await Qn.lstat(e,{bigint:r});if(!a.isFile()||a.isSymbolicLink())throw new xt("not-regular-file",`${n} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new xt("too-large",`${n} exceeds ${t} bytes`);let o=await Qn.realpath(e);await i.verify?.("pre-open",{realPath:o,identity:No(a)});let s=process.platform==="win32"?Fc.O_RDONLY:Fc.O_RDONLY|Fc.O_NOFOLLOW|Fc.O_NONBLOCK,c;try{c=await Qn.open(e,s)}catch(l){throw l.code==="ELOOP"?new xt("not-regular-file",`${n} must be a regular file`,{cause:l}):l}try{let[l,u,d]=await Promise.all([c.stat({bigint:r}),Qn.lstat(e,{bigint:r}),Qn.realpath(e)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!Lc(a,l)||!Lc(a,u))throw new xt("changed",`${n} changed while opening`);await i.verify?.("post-open",{realPath:d,identity:No(l)}),await i.hooks?.afterOpen?.();let f=[],h=0,m=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let k=t+1-h,{bytesRead:N}=await c.read(m,0,Math.min(m.length,k),null);if(N===0)break;if(h+=N,h>t)throw new xt("too-large",`${n} exceeds ${t} bytes`);f.push(Buffer.from(m.subarray(0,N)))}await i.hooks?.beforeFinalCheck?.();let[p,v,S]=await Promise.all([c.stat({bigint:r}),Qn.lstat(e,{bigint:r}),Qn.realpath(e)]);if(!v.isFile()||v.isSymbolicLink()||S!==o||!Lc(a,p)||!Lc(a,v))throw new xt("changed",`${n} changed while reading`);return await i.verify?.("post-read",{realPath:S,identity:No(p)}),{bytes:Buffer.concat(f,h),stat:p,realPath:S}}finally{await c.close()}}function CA(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function Sf(e,t){let i=hn.relative(e,t);return i===""||!hn.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${hn.sep}`)}async function Lg(e,t){let i=hn.resolve(e),n=await Bc.lstat(i);if(!n.isDirectory()||n.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return Bc.realpath(i)}async function Bg(e,t,i,n){let r=e;for(let a=0;a{if(!Sf(a,s.realPath))throw new Error(`${n.label} resolves outside the project root`);await Bg(r.projectRoot,a,r.relative.split("/"),{label:n.label,expected:"file"})}})}var ko=".comet/config.yaml";function Ef(e,t){return e.exists===t.exists&&e.sha256===t.sha256}function xA(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function Rf(e,t={}){return(await So(e,t)).document}async function qg(e){try{return(await Zn(e,ko,go,{label:ko})).bytes}catch(t){if(xA(t))return null;throw t}}function Vg(e){return e?{exists:!0,sha256:PA("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function qc(e){return Vg(await qg(e))}async function So(e,t={}){let i=await qg(e);return{document:i?qr(i.toString("utf8"),t):null,identity:Vg(i)}}var w1=16*1024;async function Cf(e,t){if(!t)return;let i=await qc(e);if(!Ef(i,t))throw new Error("Project config changed before commit; rerun the operation")}import{promises as er}from"fs";import se from"path";import IA from"os";var Co=".comet/config.yaml";async function Pf(e){try{return await er.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function jA(e){try{let t=await er.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Eo(e,t){let i=se.relative(e,t);return i===""||!se.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${se.sep}`)}async function Ro(e){let t=[],i=e;for(;!await Pf(i);){let r=se.dirname(i);if(r===i)break;t.push(se.basename(i)),i=r}let n=await er.realpath(i);return se.resolve(n,...t.reverse())}async function Wg(e){try{return(await er.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Wc(e){let t=se.resolve(e);try{(await er.stat(t)).isDirectory()||(t=se.dirname(t))}catch(r){if(r.code!=="ENOENT")throw r}let i=t,n=se.resolve(IA.homedir());for(;;){if(!(t===n&&i!==n)){let o=se.join(t,...Co.split("/")),s=t===i||await jA(o);if(await Pf(o)&&s)return t}if(await Pf(se.join(t,".git")))return t;let a=se.dirname(t);if(a===t)return i;t=a}}function pn(e){return Xn(e)}async function OA(e,t){let i=pn(t),n=se.resolve(e,...i.split("/")),r=await er.realpath(e),a=await Ro(n);if(!Eo(r,a))throw new Error("native.artifact_root resolves outside the project root");return n}async function Ne(e,t){let i=pn(t),n=await OA(e,i),r=se.join(n,"comet");if(await Wg(r))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([Ro(n),Ro(r)]);if(!Eo(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");return{projectRoot:se.resolve(e),configFile:se.join(e,...Co.split("/")),artifactRoot:n,artifactRootRef:i,nativeRoot:r,specsDir:se.join(r,"specs"),changesDir:se.join(r,"changes"),archiveDir:se.join(r,"archive"),runtimeDir:se.join(r,"runtime"),locksDir:se.join(r,"runtime","locks"),transactionsDir:se.join(r,"runtime","transactions")}}async function Jc(e){let t=[e.specsDir,e.changesDir,e.archiveDir,e.locksDir,e.transactionsDir];await Promise.all(t.map(async i=>{await x(e.nativeRoot,i),await er.mkdir(i,{recursive:!0})}))}function $(e,t){return Eo(se.resolve(e),se.resolve(t))}async function x(e,t){let i=se.resolve(e),n=se.resolve(t);if(!Eo(i,n))throw new Error(`Path is outside the Native root: ${t}`);if(await Wg(i))throw new Error(`Native root must not be a symbolic link: ${e}`);let[r,a]=await Promise.all([Ro(i),Ro(n)]);if(!Eo(r,a))throw new Error(`Path resolves outside the Native root: ${t}`);return n}var zc=ot,Jg=Hc,Gc=Dc;function tr(e="docs",t="en"){return Mc(e,t)}async function re(e){let t=(await Rf(e))?.config??null;return t?.native?t:null}async function Vr(e){let t=await re(e);if(t?.native.pending_root_move)throw new Error(`Native root move ${t.native.pending_root_move.id} is incomplete; use comet native doctor --repair`)}async function li(e,t,i={}){let n=await So(e,{allowPartialProject:!0}),r=yo(n.document?.value??{},t),a=$A.join(e,...Co.split("/"));await $e(a,wo(r,t.native.language==="zh-CN"?"zh-CN":"en"),{containedRoot:e,beforeCommit:async()=>{await i.beforeCommit?.(),await Cf(e,n.identity)}})}async function zg(e){let t=await Wc(e.startPath),i=await re(t);if(!i&&e.allowMissingConfig===!1)throw new Error(`${Co} was not found`);if(i?.native.pending_root_move)throw new Error(`Native root move ${i.native.pending_root_move.id} is incomplete; use comet native doctor --repair`);let n=e.explicitArtifactRoot?pn(e.explicitArtifactRoot):void 0;if(i&&n&&n!==i.native.artifact_root)throw new Error(`Configured Native artifact root is ${i.native.artifact_root}; refusing conflicting root ${n}`);let r=i??tr(n??"docs"),a=await Ne(t,r.native.artifact_root);return{config:r,paths:a,configured:i!==null}}import{promises as gT}from"fs";import wT from"path";import{AsyncLocalStorage as HA}from"async_hooks";import{randomUUID as Kg}from"crypto";import{promises as At}from"fs";import Yg from"os";import pe from"path";var Gg=16*1024,xf=".coordinator",DA=5e3,Ug=new HA,Uc=new Map;function MA(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function FA(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Invalid Native lock metadata: ${t}`);let i=e;if(typeof i.id!="string"||i.id.length===0||typeof i.pid!="number"||!Number.isSafeInteger(i.pid)||i.pid<1||typeof i.hostname!="string"||i.hostname.length===0||typeof i.createdAt!="string"||i.createdAt.length===0||typeof i.operation!="string"||i.operation.length===0)throw new Error(`Invalid Native lock metadata: ${t}`);return i}function Xg(e){return{device:e.dev.toString(),inode:e.ino.toString(),size:e.size.toString(),birthtimeNs:e.birthtimeNs.toString(),ctimeNs:e.ctimeNs.toString(),mtimeNs:e.mtimeNs.toString()}}function Af(e,t){let i={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},n={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return Ue(i,n)?M(i,n):M(i,n)&&e.size===t.size}function Kc(e,t){return Af(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}function LA(e,t){return e.status!==t.status?!1:!e.owner||!e.identity||!t.owner||!t.identity?e.owner===t.owner&&e.identity===t.identity:e.owner.id===t.owner.id&&Kc(e.identity,t.identity)}async function ui(e){let t,i;try{let n=await fn(e,Gg,{bigint:!0,label:"Native lock"});t=n.bytes,i=n.stat}catch(n){if(n.code==="ENOENT")return null;throw n instanceof xt?n.reason==="too-large"?new Error(`Native lock metadata exceeds ${Gg} bytes: ${e}`,{cause:n}):n.reason==="not-regular-file"?new Error(`Native lock must be a regular file: ${e}`,{cause:n}):new Error(`Native lock changed while reading: ${e}`,{cause:n}):n}return{file:e,owner:FA(JSON.parse(t.toString("utf8")),e),identity:Xg(i)}}async function BA(e){return(await ui(e))?.owner??null}function Tf(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==Yg.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=GA(e.owner.pid);return{status:t===!0?"active":t===!1?"stale":"unknown",owner:e.owner,identity:e.identity}}async function qA(e,t){try{await At.lstat(t);return}catch(i){if(i.code!=="ENOENT")throw i}try{await At.rename(e,t)}catch(i){if(i.code!=="ENOENT")throw i}}async function Yc(e,t){let i=await ui(e.file);if(!i)return"missing";if(i.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Kc(i.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await At.mkdir(t,{recursive:!0});let n=pe.join(t,`${pe.basename(e.file)}.${e.owner.id}.${Kg()}.removed`);try{await At.rename(e.file,n)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let r=await ui(n);if(!r||r.owner.id!==e.owner.id||!Af(r.identity,e.identity))throw await qA(n,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await At.rm(n,{force:!0}),"removed"}function Qg(e){return{id:Kg(),pid:process.pid,hostname:Yg.hostname(),createdAt:new Date().toISOString(),operation:e}}async function Zg(e,t){let i;try{i=await At.open(e,"wx")}catch(n){if(n.code==="EEXIST"){let r=await BA(e);throw new Error(`Native lock is already held: ${e}${r?` by pid ${r.pid} for ${r.operation}`:""}`,{cause:n})}throw n}try{return await i.writeFile(JSON.stringify(t,null,2)+` -`,"utf8"),await i.sync(),Xg(await i.stat({bigint:!0}))}finally{await i.close()}}async function VA(e,t){let i=await x(e.nativeRoot,e.locksDir);await At.mkdir(i,{recursive:!0});let n=await x(e.nativeRoot,pe.join(i,xf));await At.mkdir(n,{recursive:!0});let r=Qg(t),a=pe.join(n,`.${r.id}.tmp`),o=pe.join(n,`${r.id}.claim`);try{let s=await Zg(a,r);await At.rename(a,o);let c=await ui(o);if(!c||!Af(s,c.identity))throw new Error(`Native lock coordinator claim changed while publishing: ${o}`);return{file:o,nativeRoot:e.nativeRoot,locksDir:i,owner:r,identity:c.identity}}finally{await At.rm(a,{force:!0})}}async function WA(e){let t=pe.dirname(e.file),i=!1,n=pe.basename(e.file);for(let r of await At.readdir(t,{withFileTypes:!0})){if(!r.isFile()||r.isSymbolicLink()||!r.name.endsWith(".claim"))continue;let a=pe.join(t,r.name);if(pe.resolve(a)!==pe.resolve(e.file))try{let o=await ui(a),s=Tf(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await Yc(o,t);continue}r.name=i)throw new Error(`Native lock coordinator is busy: ${e.locksDir}`);await new Promise(r=>setTimeout(r,2+Math.floor(Math.random()*7)))}}async function zA(e){let t=Uc.get(e)??Promise.resolve(),i,n=new Promise(a=>{i=a}),r=t.then(()=>n);return Uc.set(e,r),await t,()=>{i(),Uc.get(e)===r&&Uc.delete(e)}}async function Xc(e,t,i){let n=pe.resolve(e.locksDir),r=Ug.getStore();if(r?.has(n))return i();let a=await zA(n);try{let o=await JA(e,t),s=new Map(r??[]);return s.set(n,o),await Ug.run(s,async()=>{try{return await i()}finally{await ew(o)}})}finally{a()}}async function Qc(e,t,i){let n=[...new Map(e.map(a=>[pe.resolve(a.locksDir),a])).values()].sort((a,o)=>pe.resolve(a.locksDir).localeCompare(pe.resolve(o.locksDir))),r=async a=>{let o=n[a];return o?Xc(o,t,()=>r(a+1)):i()};return r(0)}async function di(e,t,i){return Xc(e,`acquire ${t}`,async()=>{let n=await x(e.nativeRoot,e.locksDir);await At.mkdir(n,{recursive:!0});let r=await x(e.nativeRoot,pe.join(n,MA(t))),a=Qg(i),o=await Zg(r,a);return{file:r,nativeRoot:e.nativeRoot,locksDir:n,owner:a,identity:o}})}async function fi(e){await ui(e.file)&&await Xc(e,`release ${pe.basename(e.file)}`,async()=>{let t=await ui(e.file);if(!t)return;if(t.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Kc(t.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);let i=pe.join(e.locksDir,xf);await Yc(t,i)})}function GA(e){try{return process.kill(e,0),!0}catch(t){let i=t.code;return i==="ESRCH"?!1:i==="EPERM"?!0:null}}async function Po(e){return Tf(await ui(e))}async function _f(e,t,i){return Xc(e,`take over ${pe.basename(t)}`,async()=>{let n=await x(e.nativeRoot,e.locksDir),r=await x(e.nativeRoot,t);if(pe.resolve(pe.dirname(r))!==pe.resolve(n))throw new Error(`Native lock takeover target is outside the lock directory: ${t}`);let a=await ui(r),o=Tf(a);if(o.status==="missing")return{status:"missing"};if(i&&!LA(i,o))return{status:"changed",diagnosis:o};if(o.status!=="stale"||!a)return{status:"changed",diagnosis:o};let s=pe.join(n,xf);return await Yc(a,s)==="removed"?{status:"removed",owner:a.owner}:{status:"missing"}})}import{promises as xo}from"fs";import tt from"path";import{TextDecoder as QA}from"util";import{createHash as UA}from"node:crypto";import{constants as Zc,promises as W}from"node:fs";import Q from"node:path";import{TextDecoder as KA}from"node:util";function Ye(e,t){let i=Q.relative(e,t);return i===""||!Q.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Q.sep}`)}function tw(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function Jr(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function iw(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Wr(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function mn(e,t){let i=await W.lstat(e);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await W.realpath(e),dev:i.dev,ino:i.ino,birthtimeMs:i.birthtimeMs}}async function vn(e,t,i){let n=Q.resolve(e),r=Q.resolve(t);if(!Ye(n,r))throw new Error(`${i} is outside its managed root`);let a=[await mn(n,i)],o=n;for(let s of Q.relative(n,r).split(Q.sep).filter(Boolean)){await we(a,i),o=Q.join(o,s);let c=await mn(o,i);if(!Ye(a[0].realPath,c.realPath))throw new Error(`${i} parent resolves outside its managed root: ${o}`);a.push(c)}return await we(a,i),a}async function we(e,t){for(let i of e){let n=await W.lstat(i.path);if(!n.isDirectory()||n.isSymbolicLink()||!Jr(i,n)||await W.realpath(i.path)!==i.realPath)throw new Error(`${t} parent changed during I/O: ${i.path}`)}}async function YA(e,t,i){let n=[],r=0,a=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let o=t+1-r,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(r+=s,r>t)throw new Error(`${i} exceeds ${t} bytes`);n.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(n,r)}async function ue(e){let t=tw(e.maxBytes),i=Q.resolve(e.file),n=await vn(e.root,Q.dirname(i),e.label),r=await Promise.all((e.forbiddenRoots??[]).map(u=>mn(Q.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await we(n,e.label);let a=await W.lstat(i);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);if(a.size>t)throw new Error(`${e.label} exceeds ${t} bytes`);let o=iw(a),s=await W.realpath(i);if(!Ye(n[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(r.some(u=>Ye(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?Zc.O_RDONLY:Zc.O_RDONLY|Zc.O_NOFOLLOW|Zc.O_NONBLOCK,l=await W.open(i,c);try{let u=await l.stat();await e.hooks?.afterOpen?.();let[d,f]=await Promise.all([W.lstat(i),W.realpath(i)]);if(await we(n,e.label),await we(r,e.label),!u.isFile()||!d.isFile()||d.isSymbolicLink()||f!==s||!Wr(o,u)||!Wr(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let h=await YA(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[m,p,v]=await Promise.all([l.stat(),W.lstat(i),W.realpath(i)]);if(await we(n,e.label),await we(r,e.label),!p.isFile()||p.isSymbolicLink()||v!==s||!Wr(o,m)||!Wr(o,p))throw new Error(`${e.label} changed while reading`);return{bytes:h,hash:UA("sha256").update(h).digest("hex"),size:h.length}}finally{await l.close()}}async function el(e){let t=await ue(e),i;try{i=new KA("utf-8",{fatal:!0}).decode(t.bytes)}catch(n){throw new Error(`${e.label} is not valid UTF-8`,{cause:n})}return{...t,text:i}}async function st(e){let t=await vn(e.root,e.directory,e.label),i;if(e.maxEntries===void 0)i=await W.readdir(e.directory,{withFileTypes:!0});else{let n=tw(e.maxEntries);i=[];let r=await W.opendir(e.directory);try{for await(let a of r)if(i.push(a),i.length>n)throw new Error(`${e.label} exceeds ${n} entries`)}finally{await r.close().catch(a=>{if(a.code!=="ERR_DIR_CLOSED")throw a})}}return await we(t,e.label),{entries:i,verify:()=>we(t,e.label)}}async function hi(e){let t=await vn(e.root,e.directory,e.label);return{verify:()=>we(t,e.label)}}async function XA(e){let t=Q.resolve(e.directory),i=Q.resolve(e.quarantine);if(Q.dirname(i)!==Q.dirname(t)||!Ye(Q.resolve(e.root),i)||i===t)throw new Error(`${e.label} quarantine must be a distinct sibling inside its root`);let n=await vn(e.root,Q.dirname(t),e.label),r=await mn(t,e.label);if(!Ye(n[0].realPath,r.realPath))throw new Error(`${e.label} resolves outside its managed root`);await e.beforeQuarantine?.(),await we(n,e.label);let a=await W.lstat(t);if(!a.isDirectory()||a.isSymbolicLink()||!Jr(r,a)||await W.realpath(t)!==r.realPath)throw new Error(`${e.label} changed before quarantine`);try{throw await W.lstat(i),new Error(`${e.label} quarantine path is occupied`)}catch(s){if(s.code!=="ENOENT")throw s}await W.rename(t,i),await we(n,e.label);let o=await W.lstat(i);if(!o.isDirectory()||o.isSymbolicLink()||!Jr(r,o))throw new Error(`${e.label} changed while quarantining`);await e.afterQuarantine?.(i);try{throw await W.lstat(t),new Error(`${e.label} path was recreated while quarantining`)}catch(s){if(s.code!=="ENOENT")throw s}return{quarantine:i,parentChain:n,identity:r}}async function nw(e){await XA(e)}async function tl(e){let t=Q.resolve(e.file),i=await vn(e.root,Q.dirname(t),e.label),n=await W.lstat(t);if(!n.isFile()||n.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);let r=iw(n),a=await W.realpath(t);if(!Ye(i[0].realPath,a))throw new Error(`${e.label} resolves outside its managed root`);let o=await ue({root:e.root,file:t,maxBytes:e.maxBytes,label:e.label});if(o.hash!==e.expectedHash||o.size!==e.expectedSize)throw new Error(`${e.label} changed before removal`);let[s,c]=await Promise.all([W.lstat(t),W.realpath(t)]);if(!s.isFile()||s.isSymbolicLink()||!Wr(r,s)||c!==a)throw new Error(`${e.label} changed while verifying removal`);await e.beforeRemove?.(),await we(i,e.label);let[l,u]=await Promise.all([W.lstat(t),W.realpath(t)]);if(!l.isFile()||l.isSymbolicLink()||!Wr(r,l)||u!==a)throw new Error(`${e.label} changed before removal`);await W.rm(t),await we(i,e.label)}async function If(e){let t=Q.resolve(e.directory),i=await vn(e.root,Q.dirname(t),e.label),n=await mn(t,e.label);if(!Ye(i[0].realPath,n.realPath))throw new Error(`${e.label} resolves outside its managed root`);await e.beforeRemove?.(),await we(i,e.label);let r=await W.lstat(t);if(!r.isDirectory()||r.isSymbolicLink()||!Jr(n,r)||await W.realpath(t)!==n.realPath)throw new Error(`${e.label} changed before removal`);await W.rmdir(t),await we(i,e.label)}async function pi(e){let t=Q.resolve(e.root),i=Q.resolve(e.directory);if(!Ye(t,i))throw new Error(`${e.label} is outside its managed root`);let n=[await mn(t,e.label)],r=t;for(let a of Q.relative(t,i).split(Q.sep).filter(Boolean)){await we(n,e.label),r=Q.join(r,a);try{await W.mkdir(r)}catch(s){if(s.code!=="EEXIST")throw s}let o=await mn(r,e.label);if(!Ye(n[0].realPath,o.realPath))throw new Error(`${e.label} resolves outside its managed root: ${r}`);n.push(o)}await we(n,e.label)}async function jf(e){let t=Q.resolve(e.root),i=Q.resolve(e.source),n=Q.resolve(e.target);if(i===n||!Ye(t,i)||!Ye(t,n)||Ye(i,n)||Ye(n,i))throw new Error(`${e.label} source and target must be distinct paths inside one root`);await pi({root:t,directory:Q.dirname(n),label:`${e.label} target parent`});let r=await vn(t,Q.dirname(i),e.label),a=await vn(t,Q.dirname(n),e.label),o=await mn(i,e.label);if(!Ye(r[0].realPath,o.realPath))throw new Error(`${e.label} source resolves outside its managed root`);try{throw await W.lstat(n),new Error(`${e.label} target already exists`)}catch(l){if(l.code!=="ENOENT")throw l}await e.beforeMove?.(),await Promise.all([we(r,e.label),we(a,e.label)]);let s=await W.lstat(i);if(!s.isDirectory()||s.isSymbolicLink()||!Jr(o,s)||await W.realpath(i)!==o.realPath)throw new Error(`${e.label} source changed before move`);await W.rename(i,n),await Promise.all([we(r,e.label),we(a,e.label)]);let c=await W.lstat(n);if(!c.isDirectory()||c.isSymbolicLink()||!Jr(o,c)||!Ye(r[0].realPath,await W.realpath(n)))throw new Error(`${e.label} source identity changed while moving`);try{throw await W.lstat(i),new Error(`${e.label} source was recreated while moving`)}catch(l){if(l.code!=="ENOENT")throw l}}async function Ti(e){let t=await ue({root:e.sourceRoot,file:e.source,maxBytes:e.maxBytes,label:e.label,hooks:e.hooks,forbiddenRoots:e.forbiddenRoots});if(e.expectedHash!==void 0&&t.hash!==e.expectedHash)throw new Error(`${e.label} content changed before copy`);await Ig(e.target,t.bytes,{containedRoot:e.targetRoot,exclusive:e.exclusive,beforeCommit:async()=>{if(await e.hooks?.beforeTargetCommit?.(),e.expectedTargetHash===void 0)return;if(e.expectedTargetHash===null){try{await W.lstat(e.target)}catch(r){if(r.code==="ENOENT")return;throw r}throw new Error(`${e.label} target changed before commit`)}if((await ue({root:e.targetRoot,file:e.target,maxBytes:e.maxBytes,label:`${e.label} existing target`})).hash!==e.expectedTargetHash)throw new Error(`${e.label} target changed before commit`)}});let i=await ue({root:e.targetRoot,file:e.target,maxBytes:e.maxBytes,label:`${e.label} target`});if(i.hash!==t.hash||i.size!==t.size)throw new Error(`${e.label} target could not be verified`);return i}var ZA=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),eT=new Set(["id","type","source","target","staged","backup"]),tT=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),iT=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]),nT=new Set(["sequence","timestamp","type","operationId"]),sw=new Set(["prepared","applying","committed","rolling-back","rolled-back"]),cw=new Set(["prepared","operation-started","operation-completed","archive-finalization-started","archive-finalized","commit","rollback-started","rollback-completed"]),rT=256*1024,aT=1024*1024,lw=16*1024,nl=1024,Hf=64*1024*1024,oT=2e4,uw=new QA("utf-8",{fatal:!0});function Ao(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function To(e,t,i){let n=Object.keys(e).filter(r=>!t.has(r));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`)}function Gr(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function Of(e,t){if(typeof e!="string"||e.length===0||tt.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function il(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function rw(e,t){if(Of(e,t),e.includes("\\")||e!==tt.posix.normalize(e)||e.split("/").includes(".")||e.endsWith("/")||Buffer.byteLength(e,"utf8")>1024)throw new Error(`${t} must be a normalized Native-relative ref`)}function sT(e,t){let i=Ao(e,`transaction operations[${t}]`);if(To(i,eT,`transaction operations[${t}]`),typeof i.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(i.id))throw new Error(`transaction operations[${t}].id is invalid`);if(i.type!=="write"&&i.type!=="remove"&&i.type!=="move")throw new Error(`transaction operation ${i.id} has an invalid type`);Of(i.target,`transaction operation ${i.id} target`);for(let n of["source","staged","backup"])i[n]!==void 0&&Of(i[n],`transaction operation ${i.id} ${n}`);if(i.type==="write"){if(i.staged===void 0||i.source!==void 0)throw new Error(`write operation ${i.id} requires staged and forbids source`)}else if(i.type==="remove"){if(i.source!==void 0||i.staged!==void 0)throw new Error(`remove operation ${i.id} forbids source and staged`)}else if(i.source===void 0||i.staged!==void 0||i.backup!==void 0)throw new Error(`move operation ${i.id} requires source and forbids staged and backup`);return i}function _o(e){let t=Ao(e,"Native Archive transaction journal");if(To(t,tT,"Native Archive transaction journal"),t.schema!=="comet.native.transaction.v2")throw new Error("Unsupported Native Archive transaction schema");if(typeof t.id!="string"||!/^[a-f0-9-]{8,}$/u.test(t.id))throw new Error("Native Archive transaction id is invalid");if(t.kind!=="archive")throw new Error("Native v2 transaction kind must be archive");if(typeof t.status!="string"||!sw.has(t.status))throw new Error("Native Archive transaction status is invalid");if(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change))throw new Error("Native Archive transaction change name is invalid");if(!Gr(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(il(t.preflightHash,"Native Archive transaction preflightHash"),!Array.isArray(t.operations)||t.operations.length>65)throw new Error("Native Archive transaction operations must be an array");let i=t.operations.map((s,c)=>{let l=Ao(s,`Archive transaction operations[${c}]`);if(To(l,iT,`Archive transaction operations[${c}]`),typeof l.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(l.id))throw new Error(`Archive transaction operations[${c}].id is invalid`);if(l.type!=="write"&&l.type!=="remove"&&l.type!=="move")throw new Error(`Archive transaction operation ${l.id} has an invalid type`);rw(l.target,`Archive transaction operation ${l.id} target`);for(let u of["source","staged","backup"])l[u]!==void 0&&rw(l[u],`Archive transaction operation ${l.id} ${u}`);if(l.expectedTargetHash!==null&&il(l.expectedTargetHash,`Archive transaction operation ${l.id} expectedTargetHash`),l.type==="write"){if(l.staged===void 0||l.source!==void 0||l.expectedSourceHash!==void 0)throw new Error(`Archive write operation ${l.id} requires staged and forbids source`);if(il(l.stagedHash,`Archive write operation ${l.id} stagedHash`),l.expectedTargetHash===null!=(l.backup===void 0))throw new Error(`Archive write operation ${l.id} backup must match target existence`)}else if(l.type==="remove"){if(l.source!==void 0||l.staged!==void 0||l.stagedHash!==void 0||l.expectedSourceHash!==void 0||l.backup===void 0||l.expectedTargetHash===null)throw new Error(`Archive remove operation ${l.id} requires a bound target and backup`)}else{if(l.source===void 0||l.staged!==void 0||l.stagedHash!==void 0||l.backup!==void 0||l.expectedTargetHash!==null)throw new Error(`Archive move operation ${l.id} requires source and an absent target`);il(l.expectedSourceHash,`Archive move operation ${l.id} expectedSourceHash`)}return l}),n=i.map(s=>s.id);if(new Set(n).size!==n.length)throw new Error("Native Archive transaction operation ids must be unique");let r=`runtime/transactions/${t.id}`,a=i.filter(s=>s.type==="move");if(a.length!==1||a[0].id!=="archive-change"||a[0].source!==`changes/${t.change}`||!new RegExp(`^archive/\\d{4}-\\d{2}-\\d{2}-${t.change}$`,"u").test(a[0].target)||i.at(-1)!==a[0])throw new Error("Native Archive transaction must end with its exact change move");let o=new Set;for(let s of i.slice(0,-1)){if(s.type==="move"||!/^specs\/[a-z][a-z0-9]*(?:-[a-z0-9]+)*\/spec\.md$/u.test(s.target)||o.has(s.target))throw new Error(`Native Archive transaction spec target is invalid: ${s.target}`);if(o.add(s.target),s.staged!==void 0&&!s.staged.startsWith(`${r}/staged/specs/`))throw new Error(`Native Archive transaction staged ref is invalid: ${s.staged}`);if(s.backup!==void 0&&!s.backup.startsWith(`${r}/backups/specs/`))throw new Error(`Native Archive transaction backup ref is invalid: ${s.backup}`)}return{schema:"comet.native.transaction.v2",id:t.id,kind:"archive",status:t.status,change:t.change,createdAt:t.createdAt,preflightHash:t.preflightHash,operations:i}}function Df(e){let t=Ao(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return _o(t);if(To(t,ZA,"Native transaction journal"),t.schema!=="comet.native.transaction.v1")throw new Error("Unsupported Native transaction schema");if(typeof t.id!="string"||!/^[a-f0-9-]{8,}$/u.test(t.id))throw new Error("Native transaction id is invalid");if(t.kind!=="archive"&&t.kind!=="root-move")throw new Error("Native transaction kind is invalid");if(typeof t.status!="string"||!sw.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!tt.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!tt.isAbsolute(t.nativeRoot))throw new Error("Native transaction roots must be absolute paths");if(t.change!==void 0&&(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change)))throw new Error("Native transaction change name is invalid");if(!Gr(t.createdAt))throw new Error("Native transaction createdAt is invalid");if(!Array.isArray(t.operations))throw new Error("Native transaction operations must be an array");let i=t.operations.map(sT),n=i.map(r=>r.id);if(new Set(n).size!==n.length)throw new Error("Native transaction operation ids must be unique");return{schema:"comet.native.transaction.v1",id:t.id,kind:t.kind,status:t.status,projectRoot:t.projectRoot,nativeRoot:t.nativeRoot,...typeof t.change=="string"?{change:t.change}:{},createdAt:t.createdAt,operations:i}}function dw(e,t){let i=Ao(e,`Native transaction event at line ${t}`);if(To(i,nT,`Native transaction event at line ${t}`),i.sequence!==t)throw new Error(`Native transaction event sequence at line ${t} must be ${t}`);if(!Gr(i.timestamp))throw new Error(`Native transaction event timestamp at line ${t} is invalid`);if(typeof i.type!="string"||!cw.has(i.type))throw new Error(`Native transaction event type at line ${t} is invalid`);let n=i.type==="operation-started"||i.type==="operation-completed";if(n&&(typeof i.operationId!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(i.operationId)||Buffer.byteLength(i.operationId,"utf8")>256)||!n&&i.operationId!==void 0)throw new Error(`Native transaction event operationId at line ${t} is invalid`);return{sequence:i.sequence,timestamp:i.timestamp,type:i.type,...typeof i.operationId=="string"?{operationId:i.operationId}:{}}}function cT(e){if(e.length>24)return!1;let t="0000-00-00T00:00:00.000Z";for(let n=0;nString(a+u).padStart(r,"0")).some(l=>l.startsWith(s)))return!1}return e.length>=10&&!Gr(`${e.slice(0,10)}T00:00:00.000Z`)?!1:e.length<24||Gr(e)}function zr(e,t){return e.lengthlw)return!1;let i=`{"sequence":${t},"timestamp":"`;if(zr(e,i))return!0;if(!e.startsWith(i))return!1;let n=e.slice(i.length),r=n.slice(0,Math.min(24,n.length));if(!cT(r))return!1;if(n.length<24)return!0;if(!Gr(r))return!1;let a='","type":"',o=n.slice(24);if(zr(o,a))return!0;if(!o.startsWith(a))return!1;let s=o.slice(a.length);for(let c of cw){if(zr(s,c))return!0;if(!s.startsWith(c))continue;let l=s.slice(c.length);if(c==="operation-started"||c==="operation-completed"){if(lT(l))return!0}else if(zr(l,'"}'))return!0}return!1}function dT(e,t){if(e.length===0)throw new Error("Blank transaction event line");if(Buffer.byteLength(e,"utf8")>lw)throw new Error(`Native transaction event at line ${t} is too large`);return dw(JSON.parse(e),t)}function fT(e){let t=e.split(` -`),i=t.at(-1)==="";if(i&&t.pop(),t.length>nl)throw new Error(`Native transaction event log exceeds ${nl} events`);let n=[];for(let r=0;rJSON.stringify(t)).join(` +`)}function yA(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim();if(i.length===0||jc.posix.isAbsolute(i)||jc.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${t} must be a project-relative path`);if(i===".")return[];let n=i.replaceAll("\\","/").split("/");if(n.some(r=>r===".."))throw new Error(`${t} must stay inside the project root`);if(n.some(r=>r===""||r==="."))throw new Error(`${t} must not contain empty or dot path segments`);return n}function Xn(e){let t=yA(e,"native.artifact_root");return t.length===0?".":t.join("/")}function Hg(e,t="docs"){let i=e??t;if(i!=="legacy"&&i!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return i}function bf(e,t,i=!1){if(typeof e!="string")throw new Error(`${t} must be a string`);let n=e.trim().replaceAll("\\","/");if(n.length===0||jc.posix.isAbsolute(n)||jc.win32.isAbsolute(n)||/^(?:~|[\\/])/u.test(n))throw new Error(`${t} must be relative to its declared path base`);let r=n.split("/");if(r.some(a=>a===".."))throw new Error(`${t} must stay inside its declared path base`);if(r.some(a=>a===""||a==="."))throw new Error(`${t} must not contain empty or dot path segments`);if(!i&&/[*?]/u.test(n))throw new Error(`${t} cannot contain wildcards`);return r.join("/")}function mo(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Dg(e,t,i){let n=e??t;if(n!=="en"&&n!=="zh-CN")throw new Error(`${i} must be en or zh-CN`);return n}function Dc(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||e.startsWith("/")||e.split("/").includes(".."))throw new Error(`${t} contains an unsafe pattern`);if(e.length>Oc)throw new Error(`${t} exceeds ${Oc} characters`);let i=0;for(let n=0;n$c)throw new Error(`${t} contains more than ${$c} wildcard tokens`);return e}function Og(e,t,i){if(e===void 0)return[...i];if(!Array.isArray(e))throw new Error(`${t} contains an unsafe pattern`);return[...new Set(e.map(n=>Dc(n,t)))].sort((n,r)=>n.localeCompare(r,"en"))}function Nf(e,t,i){let n=e??t;if(!Number.isSafeInteger(n)||n<1)throw new Error(`${i} must be a positive integer`);return n}function NA(e){if(e===void 0)return{...ot,include:[...ot.include],exclude:[...ot.exclude]};let t=mo(e,"native.snapshot");return{include:Og(t.include,"native.snapshot.include",ot.include),exclude:Og(t.exclude,"native.snapshot.exclude",ot.exclude),max_files:Nf(t.max_files,ot.max_files,"native.snapshot.max_files"),max_total_bytes:Nf(t.max_total_bytes,ot.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:Nf(t.max_duration_ms,ot.max_duration_ms,"native.snapshot.max_duration_ms")}}function bA(e){if(e===void 0)return;let t=mo(e,"native.pending_root_move"),i=t.id,n=t.from_artifact_root,r=t.to_artifact_root,a=t.stage;if(typeof i!="string"||!/^[a-f0-9-]{8,}$/u.test(i))throw new Error("native.pending_root_move.id is invalid");if(typeof n!="string"||typeof r!="string")throw new Error("native.pending_root_move roots must be strings");if(a!=="copying"&&a!=="ready"&&a!=="switched")throw new Error("native.pending_root_move.stage is invalid");let o;if(t.cleanup!==void 0){let s=mo(t.cleanup,"native.pending_root_move.cleanup"),c=s.kind,l=s.state,u=s.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof u!="string"||!/^[a-f0-9]{64}$/u.test(u))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:u}}return{id:i,fromArtifactRoot:Xn(n),toArtifactRoot:Xn(r),stage:a,...o?{cleanup:o}:{}}}function kA(e,t={}){let i=mo(e,"native"),n=i.artifact_root??(t.allowMissingArtifactRoot?"docs":void 0);if(typeof n!="string")throw new Error("native.artifact_root must be a string");let r=i.clarification_mode??"sequential";if(r!=="sequential"&&r!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let a=i.archive_confirmation??"automatic";if(a!=="automatic"&&a!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=i.max_verify_failures??Hc;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=bA(i.pending_root_move);return{artifact_root:Xn(n),language:Dg(i.language,"en","native.language"),clarification_mode:r,archive_confirmation:a,max_verify_failures:o,snapshot:NA(i.snapshot),...s?{pending_root_move:s}:{}}}function SA(e){let t=mo(e,"classic"),i=t.context_compression??"off";if(i!=="off"&&i!=="beta")throw new Error("classic.context_compression must be off or beta");let n=t.review_mode??"standard";if(n!=="off"&&n!=="standard"&&n!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let r=t.auto_transition??!0;if(typeof r!="boolean")throw new Error("classic.auto_transition must be true or false");return{artifact_layout:Hg(t.artifact_layout),language:Dg(t.language,"zh-CN","classic.language"),context_compression:i,review_mode:n,auto_transition:r}}function EA(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function RA(e,t,i,n,r){let a=e.schema!==void 0;if(!(a||e.default_workflow!==void 0||e.workflows!==void 0||!r.allowPartialProject&&e.native!==void 0)||r.allowPartialProject&&!a)return null;if(e.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(e.default_workflow!=="native"&&e.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let s=e.workflows??[e.default_workflow];if(!Array.isArray(s)||s.length===0||s.some(l=>l!=="native"&&l!=="classic"))throw new Error("workflows must contain native and/or classic");let c=[...new Set(s)];if(!c.includes(e.default_workflow))throw new Error("workflows must include default_workflow");if(c.includes("native")&&!t)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:e.default_workflow,workflows:c,ambient_resume:n,...t?{native:t}:{},...i?{classic:i}:{}}}function qr(e,t={}){let i=(0,vo.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${i.errors[0].message}`);let n=i.toJS();if(n==null)return{value:{},config:null,ambient_resume:!0};if(typeof n!="object"||Array.isArray(n))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let r=n,a=EA(r.ambient_resume),o=r.native===void 0?void 0:kA(r.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),s=r.classic===void 0?void 0:SA(r.classic),c=RA(r,o,s,a,{allowPartialProject:t.allowPartialProject??!1});return{value:r,config:c,ambient_resume:a,...o?{native:o}:{},...s?{classic:s}:{}}}function Mg(e){return{id:e.id,from_artifact_root:e.fromArtifactRoot,to_artifact_root:e.toArtifactRoot,stage:e.stage,...e.cleanup?{cleanup:{kind:e.cleanup.kind,state:e.cleanup.state,manifest_hash:e.cleanup.manifestHash}}:{}}}function Fg(e){return{schema:e.schema,default_workflow:e.default_workflow,workflows:e.workflows??[e.default_workflow],ambient_resume:e.ambient_resume,...e.native?{native:{artifact_root:e.native.artifact_root,language:e.native.language,clarification_mode:e.native.clarification_mode,archive_confirmation:e.native.archive_confirmation,max_verify_failures:e.native.max_verify_failures,snapshot:e.native.snapshot,...e.native.pending_root_move?{pending_root_move:Mg(e.native.pending_root_move)}:{}}}:{},...e.classic?{classic:{artifact_layout:e.classic.artifact_layout,language:e.classic.language,context_compression:e.classic.context_compression,review_mode:e.classic.review_mode,auto_transition:e.classic.auto_transition}}:{}}}function Br(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function yo(e,t){let i=Fg(t),n=qr((0,vo.stringify)(i)).config;if(!n)throw new Error("Unsupported Comet project schema");let r={...e,schema:n.schema,default_workflow:n.default_workflow,workflows:n.workflows,ambient_resume:n.ambient_resume};if(n.native){let a=Br(e.native),o=Br(a.snapshot),s={...a,artifact_root:n.native.artifact_root,language:n.native.language,clarification_mode:n.native.clarification_mode,archive_confirmation:n.native.archive_confirmation,max_verify_failures:n.native.max_verify_failures,snapshot:{...o,...n.native.snapshot}};if(n.native.pending_root_move){let c=Br(a.pending_root_move),l=Mg(n.native.pending_root_move),u=Br(c.cleanup),d=Br(l.cleanup);s.pending_root_move={...c,...l,...l.cleanup?{cleanup:{...u,...d}}:{}}}else delete s.pending_root_move;r.native=s}return n.classic&&(r.classic={...Br(e.classic),artifact_layout:n.classic.artifact_layout,language:n.classic.language,context_compression:n.classic.context_compression,review_mode:n.classic.review_mode,auto_transition:n.classic.auto_transition}),r}function Mc(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,native:{artifact_root:Xn(e),language:t,clarification_mode:"sequential",archive_confirmation:"automatic",max_verify_failures:Hc,snapshot:{...ot,include:[...ot.include],exclude:[...ot.exclude]}}}}import{createHash as PA}from"crypto";import{promises as Bc}from"fs";import hn from"path";import{constants as Fc,promises as Qn}from"fs";var xt=class extends Error{reason;constructor(t,i,n){super(i,n),this.name="RaceSafeReadError",this.reason=t}};function kf(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function Lg(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function No(e){return{dev:e.dev,ino:e.ino,birthtime:kf(e)}}function Lc(e,t){let i=No(e),n=No(t);return Ue(i,n)?M(i,n):M(i,n)&&kf(e)===kf(t)&&Lg(e)===Lg(t)&&e.size===t.size}async function fn(e,t,i={}){if(!Number.isSafeInteger(t)||t<1)throw new Error("race-safe read byte limit must be a positive integer");let n=i.label??"file",r=i.bigint===!0,a=await Qn.lstat(e,{bigint:r});if(!a.isFile()||a.isSymbolicLink())throw new xt("not-regular-file",`${n} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new xt("too-large",`${n} exceeds ${t} bytes`);let o=await Qn.realpath(e);await i.verify?.("pre-open",{realPath:o,identity:No(a)});let s=process.platform==="win32"?Fc.O_RDONLY:Fc.O_RDONLY|Fc.O_NOFOLLOW|Fc.O_NONBLOCK,c;try{c=await Qn.open(e,s)}catch(l){throw l.code==="ELOOP"?new xt("not-regular-file",`${n} must be a regular file`,{cause:l}):l}try{let[l,u,d]=await Promise.all([c.stat({bigint:r}),Qn.lstat(e,{bigint:r}),Qn.realpath(e)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!Lc(a,l)||!Lc(a,u))throw new xt("changed",`${n} changed while opening`);await i.verify?.("post-open",{realPath:d,identity:No(l)}),await i.hooks?.afterOpen?.();let f=[],h=0,m=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let k=t+1-h,{bytesRead:N}=await c.read(m,0,Math.min(m.length,k),null);if(N===0)break;if(h+=N,h>t)throw new xt("too-large",`${n} exceeds ${t} bytes`);f.push(Buffer.from(m.subarray(0,N)))}await i.hooks?.beforeFinalCheck?.();let[p,v,S]=await Promise.all([c.stat({bigint:r}),Qn.lstat(e,{bigint:r}),Qn.realpath(e)]);if(!v.isFile()||v.isSymbolicLink()||S!==o||!Lc(a,p)||!Lc(a,v))throw new xt("changed",`${n} changed while reading`);return await i.verify?.("post-read",{realPath:S,identity:No(p)}),{bytes:Buffer.concat(f,h),stat:p,realPath:S}}finally{await c.close()}}function CA(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function Sf(e,t){let i=hn.relative(e,t);return i===""||!hn.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${hn.sep}`)}async function Bg(e,t){let i=hn.resolve(e),n=await Bc.lstat(i);if(!n.isDirectory()||n.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return Bc.realpath(i)}async function qg(e,t,i,n){let r=e;for(let a=0;a{if(!Sf(a,s.realPath))throw new Error(`${n.label} resolves outside the project root`);await qg(r.projectRoot,a,r.relative.split("/"),{label:n.label,expected:"file"})}})}var ko=".comet/config.yaml";function Ef(e,t){return e.exists===t.exists&&e.sha256===t.sha256}function xA(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function Rf(e,t={}){return(await So(e,t)).document}async function Vg(e){try{return(await Zn(e,ko,go,{label:ko})).bytes}catch(t){if(xA(t))return null;throw t}}function Wg(e){return e?{exists:!0,sha256:PA("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function qc(e){return Wg(await Vg(e))}async function So(e,t={}){let i=await Vg(e);return{document:i?qr(i.toString("utf8"),t):null,identity:Wg(i)}}var w1=16*1024;async function Cf(e,t){if(!t)return;let i=await qc(e);if(!Ef(i,t))throw new Error("Project config changed before commit; rerun the operation")}import{promises as er}from"fs";import se from"path";import IA from"os";var Co=".comet/config.yaml";async function Pf(e){try{return await er.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function jA(e){try{let t=await er.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Eo(e,t){let i=se.relative(e,t);return i===""||!se.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${se.sep}`)}async function Ro(e){let t=[],i=e;for(;!await Pf(i);){let r=se.dirname(i);if(r===i)break;t.push(se.basename(i)),i=r}let n=await er.realpath(i);return se.resolve(n,...t.reverse())}async function Jg(e){try{return(await er.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Wc(e){let t=se.resolve(e);try{(await er.stat(t)).isDirectory()||(t=se.dirname(t))}catch(r){if(r.code!=="ENOENT")throw r}let i=t,n=se.resolve(IA.homedir());for(;;){if(!(t===n&&i!==n)){let o=se.join(t,...Co.split("/")),s=t===i||await jA(o);if(await Pf(o)&&s)return t}if(await Pf(se.join(t,".git")))return t;let a=se.dirname(t);if(a===t)return i;t=a}}function pn(e){return Xn(e)}async function OA(e,t){let i=pn(t),n=se.resolve(e,...i.split("/")),r=await er.realpath(e),a=await Ro(n);if(!Eo(r,a))throw new Error("native.artifact_root resolves outside the project root");return n}async function Ne(e,t){let i=pn(t),n=await OA(e,i),r=se.join(n,"comet");if(await Jg(r))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([Ro(n),Ro(r)]);if(!Eo(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");return{projectRoot:se.resolve(e),configFile:se.join(e,...Co.split("/")),artifactRoot:n,artifactRootRef:i,nativeRoot:r,specsDir:se.join(r,"specs"),changesDir:se.join(r,"changes"),archiveDir:se.join(r,"archive"),runtimeDir:se.join(r,"runtime"),locksDir:se.join(r,"runtime","locks"),transactionsDir:se.join(r,"runtime","transactions")}}async function Jc(e){let t=[e.specsDir,e.changesDir,e.archiveDir,e.locksDir,e.transactionsDir];await Promise.all(t.map(async i=>{await x(e.nativeRoot,i),await er.mkdir(i,{recursive:!0})}))}function $(e,t){return Eo(se.resolve(e),se.resolve(t))}async function x(e,t){let i=se.resolve(e),n=se.resolve(t);if(!Eo(i,n))throw new Error(`Path is outside the Native root: ${t}`);if(await Jg(i))throw new Error(`Native root must not be a symbolic link: ${e}`);let[r,a]=await Promise.all([Ro(i),Ro(n)]);if(!Eo(r,a))throw new Error(`Path resolves outside the Native root: ${t}`);return n}var zc=ot,zg=Hc,Gc=Dc;function tr(e="docs",t="en"){return Mc(e,t)}async function re(e){let t=(await Rf(e))?.config??null;return t?.native?t:null}async function Vr(e){let t=await re(e);if(t?.native.pending_root_move)throw new Error(`Native root move ${t.native.pending_root_move.id} is incomplete; use comet native doctor --repair`)}async function li(e,t,i={}){let n=await So(e,{allowPartialProject:!0}),r=yo(n.document?.value??{},t),a=$A.join(e,...Co.split("/"));await $e(a,wo(r,t.native.language==="zh-CN"?"zh-CN":"en"),{containedRoot:e,beforeCommit:async()=>{await i.beforeCommit?.(),await Cf(e,n.identity)}})}async function Gg(e){let t=await Wc(e.startPath),i=await re(t);if(!i&&e.allowMissingConfig===!1)throw new Error(`${Co} was not found`);if(i?.native.pending_root_move)throw new Error(`Native root move ${i.native.pending_root_move.id} is incomplete; use comet native doctor --repair`);let n=e.explicitArtifactRoot?pn(e.explicitArtifactRoot):void 0;if(i&&n&&n!==i.native.artifact_root)throw new Error(`Configured Native artifact root is ${i.native.artifact_root}; refusing conflicting root ${n}`);let r=i??tr(n??"docs"),a=await Ne(t,r.native.artifact_root);return{config:r,paths:a,configured:i!==null}}import{promises as gT}from"fs";import wT from"path";import{AsyncLocalStorage as HA}from"async_hooks";import{randomUUID as Yg}from"crypto";import{promises as At}from"fs";import Xg from"os";import pe from"path";var Ug=16*1024,xf=".coordinator",DA=5e3,Kg=new HA,Uc=new Map;function MA(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function FA(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Invalid Native lock metadata: ${t}`);let i=e;if(typeof i.id!="string"||i.id.length===0||typeof i.pid!="number"||!Number.isSafeInteger(i.pid)||i.pid<1||typeof i.hostname!="string"||i.hostname.length===0||typeof i.createdAt!="string"||i.createdAt.length===0||typeof i.operation!="string"||i.operation.length===0)throw new Error(`Invalid Native lock metadata: ${t}`);return i}function Qg(e){return{device:e.dev.toString(),inode:e.ino.toString(),size:e.size.toString(),birthtimeNs:e.birthtimeNs.toString(),ctimeNs:e.ctimeNs.toString(),mtimeNs:e.mtimeNs.toString()}}function Af(e,t){let i={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},n={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return Ue(i,n)?M(i,n):M(i,n)&&e.size===t.size}function Kc(e,t){return Af(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}function LA(e,t){return e.status!==t.status?!1:!e.owner||!e.identity||!t.owner||!t.identity?e.owner===t.owner&&e.identity===t.identity:e.owner.id===t.owner.id&&Kc(e.identity,t.identity)}async function ui(e){let t,i;try{let n=await fn(e,Ug,{bigint:!0,label:"Native lock"});t=n.bytes,i=n.stat}catch(n){if(n.code==="ENOENT")return null;throw n instanceof xt?n.reason==="too-large"?new Error(`Native lock metadata exceeds ${Ug} bytes: ${e}`,{cause:n}):n.reason==="not-regular-file"?new Error(`Native lock must be a regular file: ${e}`,{cause:n}):new Error(`Native lock changed while reading: ${e}`,{cause:n}):n}return{file:e,owner:FA(JSON.parse(t.toString("utf8")),e),identity:Qg(i)}}async function BA(e){return(await ui(e))?.owner??null}function Tf(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==Xg.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=GA(e.owner.pid);return{status:t===!0?"active":t===!1?"stale":"unknown",owner:e.owner,identity:e.identity}}async function qA(e,t){try{await At.lstat(t);return}catch(i){if(i.code!=="ENOENT")throw i}try{await At.rename(e,t)}catch(i){if(i.code!=="ENOENT")throw i}}async function Yc(e,t){let i=await ui(e.file);if(!i)return"missing";if(i.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Kc(i.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await At.mkdir(t,{recursive:!0});let n=pe.join(t,`${pe.basename(e.file)}.${e.owner.id}.${Yg()}.removed`);try{await At.rename(e.file,n)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let r=await ui(n);if(!r||r.owner.id!==e.owner.id||!Af(r.identity,e.identity))throw await qA(n,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await At.rm(n,{force:!0}),"removed"}function Zg(e){return{id:Yg(),pid:process.pid,hostname:Xg.hostname(),createdAt:new Date().toISOString(),operation:e}}async function ew(e,t){let i;try{i=await At.open(e,"wx")}catch(n){if(n.code==="EEXIST"){let r=await BA(e);throw new Error(`Native lock is already held: ${e}${r?` by pid ${r.pid} for ${r.operation}`:""}`,{cause:n})}throw n}try{return await i.writeFile(JSON.stringify(t,null,2)+` +`,"utf8"),await i.sync(),Qg(await i.stat({bigint:!0}))}finally{await i.close()}}async function VA(e,t){let i=await x(e.nativeRoot,e.locksDir);await At.mkdir(i,{recursive:!0});let n=await x(e.nativeRoot,pe.join(i,xf));await At.mkdir(n,{recursive:!0});let r=Zg(t),a=pe.join(n,`.${r.id}.tmp`),o=pe.join(n,`${r.id}.claim`);try{let s=await ew(a,r);await At.rename(a,o);let c=await ui(o);if(!c||!Af(s,c.identity))throw new Error(`Native lock coordinator claim changed while publishing: ${o}`);return{file:o,nativeRoot:e.nativeRoot,locksDir:i,owner:r,identity:c.identity}}finally{await At.rm(a,{force:!0})}}async function WA(e){let t=pe.dirname(e.file),i=!1,n=pe.basename(e.file);for(let r of await At.readdir(t,{withFileTypes:!0})){if(!r.isFile()||r.isSymbolicLink()||!r.name.endsWith(".claim"))continue;let a=pe.join(t,r.name);if(pe.resolve(a)!==pe.resolve(e.file))try{let o=await ui(a),s=Tf(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await Yc(o,t);continue}r.name=i)throw new Error(`Native lock coordinator is busy: ${e.locksDir}`);await new Promise(r=>setTimeout(r,2+Math.floor(Math.random()*7)))}}async function zA(e){let t=Uc.get(e)??Promise.resolve(),i,n=new Promise(a=>{i=a}),r=t.then(()=>n);return Uc.set(e,r),await t,()=>{i(),Uc.get(e)===r&&Uc.delete(e)}}async function Xc(e,t,i){let n=pe.resolve(e.locksDir),r=Kg.getStore();if(r?.has(n))return i();let a=await zA(n);try{let o=await JA(e,t),s=new Map(r??[]);return s.set(n,o),await Kg.run(s,async()=>{try{return await i()}finally{await tw(o)}})}finally{a()}}async function Qc(e,t,i){let n=[...new Map(e.map(a=>[pe.resolve(a.locksDir),a])).values()].sort((a,o)=>pe.resolve(a.locksDir).localeCompare(pe.resolve(o.locksDir))),r=async a=>{let o=n[a];return o?Xc(o,t,()=>r(a+1)):i()};return r(0)}async function di(e,t,i){return Xc(e,`acquire ${t}`,async()=>{let n=await x(e.nativeRoot,e.locksDir);await At.mkdir(n,{recursive:!0});let r=await x(e.nativeRoot,pe.join(n,MA(t))),a=Zg(i),o=await ew(r,a);return{file:r,nativeRoot:e.nativeRoot,locksDir:n,owner:a,identity:o}})}async function fi(e){await ui(e.file)&&await Xc(e,`release ${pe.basename(e.file)}`,async()=>{let t=await ui(e.file);if(!t)return;if(t.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Kc(t.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);let i=pe.join(e.locksDir,xf);await Yc(t,i)})}function GA(e){try{return process.kill(e,0),!0}catch(t){let i=t.code;return i==="ESRCH"?!1:i==="EPERM"?!0:null}}async function Po(e){return Tf(await ui(e))}async function _f(e,t,i){return Xc(e,`take over ${pe.basename(t)}`,async()=>{let n=await x(e.nativeRoot,e.locksDir),r=await x(e.nativeRoot,t);if(pe.resolve(pe.dirname(r))!==pe.resolve(n))throw new Error(`Native lock takeover target is outside the lock directory: ${t}`);let a=await ui(r),o=Tf(a);if(o.status==="missing")return{status:"missing"};if(i&&!LA(i,o))return{status:"changed",diagnosis:o};if(o.status!=="stale"||!a)return{status:"changed",diagnosis:o};let s=pe.join(n,xf);return await Yc(a,s)==="removed"?{status:"removed",owner:a.owner}:{status:"missing"}})}import{promises as xo}from"fs";import tt from"path";import{TextDecoder as QA}from"util";import{createHash as UA}from"node:crypto";import{constants as Zc,promises as W}from"node:fs";import Q from"node:path";import{TextDecoder as KA}from"node:util";function Ye(e,t){let i=Q.relative(e,t);return i===""||!Q.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Q.sep}`)}function iw(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function Jr(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function nw(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Wr(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function mn(e,t){let i=await W.lstat(e);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await W.realpath(e),dev:i.dev,ino:i.ino,birthtimeMs:i.birthtimeMs}}async function vn(e,t,i){let n=Q.resolve(e),r=Q.resolve(t);if(!Ye(n,r))throw new Error(`${i} is outside its managed root`);let a=[await mn(n,i)],o=n;for(let s of Q.relative(n,r).split(Q.sep).filter(Boolean)){await we(a,i),o=Q.join(o,s);let c=await mn(o,i);if(!Ye(a[0].realPath,c.realPath))throw new Error(`${i} parent resolves outside its managed root: ${o}`);a.push(c)}return await we(a,i),a}async function we(e,t){for(let i of e){let n=await W.lstat(i.path);if(!n.isDirectory()||n.isSymbolicLink()||!Jr(i,n)||await W.realpath(i.path)!==i.realPath)throw new Error(`${t} parent changed during I/O: ${i.path}`)}}async function YA(e,t,i){let n=[],r=0,a=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let o=t+1-r,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(r+=s,r>t)throw new Error(`${i} exceeds ${t} bytes`);n.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(n,r)}async function ue(e){let t=iw(e.maxBytes),i=Q.resolve(e.file),n=await vn(e.root,Q.dirname(i),e.label),r=await Promise.all((e.forbiddenRoots??[]).map(u=>mn(Q.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await we(n,e.label);let a=await W.lstat(i);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);if(a.size>t)throw new Error(`${e.label} exceeds ${t} bytes`);let o=nw(a),s=await W.realpath(i);if(!Ye(n[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(r.some(u=>Ye(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?Zc.O_RDONLY:Zc.O_RDONLY|Zc.O_NOFOLLOW|Zc.O_NONBLOCK,l=await W.open(i,c);try{let u=await l.stat();await e.hooks?.afterOpen?.();let[d,f]=await Promise.all([W.lstat(i),W.realpath(i)]);if(await we(n,e.label),await we(r,e.label),!u.isFile()||!d.isFile()||d.isSymbolicLink()||f!==s||!Wr(o,u)||!Wr(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let h=await YA(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[m,p,v]=await Promise.all([l.stat(),W.lstat(i),W.realpath(i)]);if(await we(n,e.label),await we(r,e.label),!p.isFile()||p.isSymbolicLink()||v!==s||!Wr(o,m)||!Wr(o,p))throw new Error(`${e.label} changed while reading`);return{bytes:h,hash:UA("sha256").update(h).digest("hex"),size:h.length}}finally{await l.close()}}async function el(e){let t=await ue(e),i;try{i=new KA("utf-8",{fatal:!0}).decode(t.bytes)}catch(n){throw new Error(`${e.label} is not valid UTF-8`,{cause:n})}return{...t,text:i}}async function st(e){let t=await vn(e.root,e.directory,e.label),i;if(e.maxEntries===void 0)i=await W.readdir(e.directory,{withFileTypes:!0});else{let n=iw(e.maxEntries);i=[];let r=await W.opendir(e.directory);try{for await(let a of r)if(i.push(a),i.length>n)throw new Error(`${e.label} exceeds ${n} entries`)}finally{await r.close().catch(a=>{if(a.code!=="ERR_DIR_CLOSED")throw a})}}return await we(t,e.label),{entries:i,verify:()=>we(t,e.label)}}async function hi(e){let t=await vn(e.root,e.directory,e.label);return{verify:()=>we(t,e.label)}}async function XA(e){let t=Q.resolve(e.directory),i=Q.resolve(e.quarantine);if(Q.dirname(i)!==Q.dirname(t)||!Ye(Q.resolve(e.root),i)||i===t)throw new Error(`${e.label} quarantine must be a distinct sibling inside its root`);let n=await vn(e.root,Q.dirname(t),e.label),r=await mn(t,e.label);if(!Ye(n[0].realPath,r.realPath))throw new Error(`${e.label} resolves outside its managed root`);await e.beforeQuarantine?.(),await we(n,e.label);let a=await W.lstat(t);if(!a.isDirectory()||a.isSymbolicLink()||!Jr(r,a)||await W.realpath(t)!==r.realPath)throw new Error(`${e.label} changed before quarantine`);try{throw await W.lstat(i),new Error(`${e.label} quarantine path is occupied`)}catch(s){if(s.code!=="ENOENT")throw s}await W.rename(t,i),await we(n,e.label);let o=await W.lstat(i);if(!o.isDirectory()||o.isSymbolicLink()||!Jr(r,o))throw new Error(`${e.label} changed while quarantining`);await e.afterQuarantine?.(i);try{throw await W.lstat(t),new Error(`${e.label} path was recreated while quarantining`)}catch(s){if(s.code!=="ENOENT")throw s}return{quarantine:i,parentChain:n,identity:r}}async function rw(e){await XA(e)}async function tl(e){let t=Q.resolve(e.file),i=await vn(e.root,Q.dirname(t),e.label),n=await W.lstat(t);if(!n.isFile()||n.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);let r=nw(n),a=await W.realpath(t);if(!Ye(i[0].realPath,a))throw new Error(`${e.label} resolves outside its managed root`);let o=await ue({root:e.root,file:t,maxBytes:e.maxBytes,label:e.label});if(o.hash!==e.expectedHash||o.size!==e.expectedSize)throw new Error(`${e.label} changed before removal`);let[s,c]=await Promise.all([W.lstat(t),W.realpath(t)]);if(!s.isFile()||s.isSymbolicLink()||!Wr(r,s)||c!==a)throw new Error(`${e.label} changed while verifying removal`);await e.beforeRemove?.(),await we(i,e.label);let[l,u]=await Promise.all([W.lstat(t),W.realpath(t)]);if(!l.isFile()||l.isSymbolicLink()||!Wr(r,l)||u!==a)throw new Error(`${e.label} changed before removal`);await W.rm(t),await we(i,e.label)}async function If(e){let t=Q.resolve(e.directory),i=await vn(e.root,Q.dirname(t),e.label),n=await mn(t,e.label);if(!Ye(i[0].realPath,n.realPath))throw new Error(`${e.label} resolves outside its managed root`);await e.beforeRemove?.(),await we(i,e.label);let r=await W.lstat(t);if(!r.isDirectory()||r.isSymbolicLink()||!Jr(n,r)||await W.realpath(t)!==n.realPath)throw new Error(`${e.label} changed before removal`);await W.rmdir(t),await we(i,e.label)}async function pi(e){let t=Q.resolve(e.root),i=Q.resolve(e.directory);if(!Ye(t,i))throw new Error(`${e.label} is outside its managed root`);let n=[await mn(t,e.label)],r=t;for(let a of Q.relative(t,i).split(Q.sep).filter(Boolean)){await we(n,e.label),r=Q.join(r,a);try{await W.mkdir(r)}catch(s){if(s.code!=="EEXIST")throw s}let o=await mn(r,e.label);if(!Ye(n[0].realPath,o.realPath))throw new Error(`${e.label} resolves outside its managed root: ${r}`);n.push(o)}await we(n,e.label)}async function jf(e){let t=Q.resolve(e.root),i=Q.resolve(e.source),n=Q.resolve(e.target);if(i===n||!Ye(t,i)||!Ye(t,n)||Ye(i,n)||Ye(n,i))throw new Error(`${e.label} source and target must be distinct paths inside one root`);await pi({root:t,directory:Q.dirname(n),label:`${e.label} target parent`});let r=await vn(t,Q.dirname(i),e.label),a=await vn(t,Q.dirname(n),e.label),o=await mn(i,e.label);if(!Ye(r[0].realPath,o.realPath))throw new Error(`${e.label} source resolves outside its managed root`);try{throw await W.lstat(n),new Error(`${e.label} target already exists`)}catch(l){if(l.code!=="ENOENT")throw l}await e.beforeMove?.(),await Promise.all([we(r,e.label),we(a,e.label)]);let s=await W.lstat(i);if(!s.isDirectory()||s.isSymbolicLink()||!Jr(o,s)||await W.realpath(i)!==o.realPath)throw new Error(`${e.label} source changed before move`);await W.rename(i,n),await Promise.all([we(r,e.label),we(a,e.label)]);let c=await W.lstat(n);if(!c.isDirectory()||c.isSymbolicLink()||!Jr(o,c)||!Ye(r[0].realPath,await W.realpath(n)))throw new Error(`${e.label} source identity changed while moving`);try{throw await W.lstat(i),new Error(`${e.label} source was recreated while moving`)}catch(l){if(l.code!=="ENOENT")throw l}}async function Ti(e){let t=await ue({root:e.sourceRoot,file:e.source,maxBytes:e.maxBytes,label:e.label,hooks:e.hooks,forbiddenRoots:e.forbiddenRoots});if(e.expectedHash!==void 0&&t.hash!==e.expectedHash)throw new Error(`${e.label} content changed before copy`);await jg(e.target,t.bytes,{containedRoot:e.targetRoot,exclusive:e.exclusive,beforeCommit:async()=>{if(await e.hooks?.beforeTargetCommit?.(),e.expectedTargetHash===void 0)return;if(e.expectedTargetHash===null){try{await W.lstat(e.target)}catch(r){if(r.code==="ENOENT")return;throw r}throw new Error(`${e.label} target changed before commit`)}if((await ue({root:e.targetRoot,file:e.target,maxBytes:e.maxBytes,label:`${e.label} existing target`})).hash!==e.expectedTargetHash)throw new Error(`${e.label} target changed before commit`)}});let i=await ue({root:e.targetRoot,file:e.target,maxBytes:e.maxBytes,label:`${e.label} target`});if(i.hash!==t.hash||i.size!==t.size)throw new Error(`${e.label} target could not be verified`);return i}var ZA=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),eT=new Set(["id","type","source","target","staged","backup"]),tT=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),iT=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]),nT=new Set(["sequence","timestamp","type","operationId"]),cw=new Set(["prepared","applying","committed","rolling-back","rolled-back"]),lw=new Set(["prepared","operation-started","operation-completed","archive-finalization-started","archive-finalized","commit","rollback-started","rollback-completed"]),rT=256*1024,aT=1024*1024,uw=16*1024,nl=1024,Hf=64*1024*1024,oT=2e4,dw=new QA("utf-8",{fatal:!0});function Ao(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function To(e,t,i){let n=Object.keys(e).filter(r=>!t.has(r));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`)}function Gr(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function Of(e,t){if(typeof e!="string"||e.length===0||tt.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function il(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function aw(e,t){if(Of(e,t),e.includes("\\")||e!==tt.posix.normalize(e)||e.split("/").includes(".")||e.endsWith("/")||Buffer.byteLength(e,"utf8")>1024)throw new Error(`${t} must be a normalized Native-relative ref`)}function sT(e,t){let i=Ao(e,`transaction operations[${t}]`);if(To(i,eT,`transaction operations[${t}]`),typeof i.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(i.id))throw new Error(`transaction operations[${t}].id is invalid`);if(i.type!=="write"&&i.type!=="remove"&&i.type!=="move")throw new Error(`transaction operation ${i.id} has an invalid type`);Of(i.target,`transaction operation ${i.id} target`);for(let n of["source","staged","backup"])i[n]!==void 0&&Of(i[n],`transaction operation ${i.id} ${n}`);if(i.type==="write"){if(i.staged===void 0||i.source!==void 0)throw new Error(`write operation ${i.id} requires staged and forbids source`)}else if(i.type==="remove"){if(i.source!==void 0||i.staged!==void 0)throw new Error(`remove operation ${i.id} forbids source and staged`)}else if(i.source===void 0||i.staged!==void 0||i.backup!==void 0)throw new Error(`move operation ${i.id} requires source and forbids staged and backup`);return i}function _o(e){let t=Ao(e,"Native Archive transaction journal");if(To(t,tT,"Native Archive transaction journal"),t.schema!=="comet.native.transaction.v2")throw new Error("Unsupported Native Archive transaction schema");if(typeof t.id!="string"||!/^[a-f0-9-]{8,}$/u.test(t.id))throw new Error("Native Archive transaction id is invalid");if(t.kind!=="archive")throw new Error("Native v2 transaction kind must be archive");if(typeof t.status!="string"||!cw.has(t.status))throw new Error("Native Archive transaction status is invalid");if(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change))throw new Error("Native Archive transaction change name is invalid");if(!Gr(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(il(t.preflightHash,"Native Archive transaction preflightHash"),!Array.isArray(t.operations)||t.operations.length>65)throw new Error("Native Archive transaction operations must be an array");let i=t.operations.map((s,c)=>{let l=Ao(s,`Archive transaction operations[${c}]`);if(To(l,iT,`Archive transaction operations[${c}]`),typeof l.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(l.id))throw new Error(`Archive transaction operations[${c}].id is invalid`);if(l.type!=="write"&&l.type!=="remove"&&l.type!=="move")throw new Error(`Archive transaction operation ${l.id} has an invalid type`);aw(l.target,`Archive transaction operation ${l.id} target`);for(let u of["source","staged","backup"])l[u]!==void 0&&aw(l[u],`Archive transaction operation ${l.id} ${u}`);if(l.expectedTargetHash!==null&&il(l.expectedTargetHash,`Archive transaction operation ${l.id} expectedTargetHash`),l.type==="write"){if(l.staged===void 0||l.source!==void 0||l.expectedSourceHash!==void 0)throw new Error(`Archive write operation ${l.id} requires staged and forbids source`);if(il(l.stagedHash,`Archive write operation ${l.id} stagedHash`),l.expectedTargetHash===null!=(l.backup===void 0))throw new Error(`Archive write operation ${l.id} backup must match target existence`)}else if(l.type==="remove"){if(l.source!==void 0||l.staged!==void 0||l.stagedHash!==void 0||l.expectedSourceHash!==void 0||l.backup===void 0||l.expectedTargetHash===null)throw new Error(`Archive remove operation ${l.id} requires a bound target and backup`)}else{if(l.source===void 0||l.staged!==void 0||l.stagedHash!==void 0||l.backup!==void 0||l.expectedTargetHash!==null)throw new Error(`Archive move operation ${l.id} requires source and an absent target`);il(l.expectedSourceHash,`Archive move operation ${l.id} expectedSourceHash`)}return l}),n=i.map(s=>s.id);if(new Set(n).size!==n.length)throw new Error("Native Archive transaction operation ids must be unique");let r=`runtime/transactions/${t.id}`,a=i.filter(s=>s.type==="move");if(a.length!==1||a[0].id!=="archive-change"||a[0].source!==`changes/${t.change}`||!new RegExp(`^archive/\\d{4}-\\d{2}-\\d{2}-${t.change}$`,"u").test(a[0].target)||i.at(-1)!==a[0])throw new Error("Native Archive transaction must end with its exact change move");let o=new Set;for(let s of i.slice(0,-1)){if(s.type==="move"||!/^specs\/[a-z][a-z0-9]*(?:-[a-z0-9]+)*\/spec\.md$/u.test(s.target)||o.has(s.target))throw new Error(`Native Archive transaction spec target is invalid: ${s.target}`);if(o.add(s.target),s.staged!==void 0&&!s.staged.startsWith(`${r}/staged/specs/`))throw new Error(`Native Archive transaction staged ref is invalid: ${s.staged}`);if(s.backup!==void 0&&!s.backup.startsWith(`${r}/backups/specs/`))throw new Error(`Native Archive transaction backup ref is invalid: ${s.backup}`)}return{schema:"comet.native.transaction.v2",id:t.id,kind:"archive",status:t.status,change:t.change,createdAt:t.createdAt,preflightHash:t.preflightHash,operations:i}}function Df(e){let t=Ao(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return _o(t);if(To(t,ZA,"Native transaction journal"),t.schema!=="comet.native.transaction.v1")throw new Error("Unsupported Native transaction schema");if(typeof t.id!="string"||!/^[a-f0-9-]{8,}$/u.test(t.id))throw new Error("Native transaction id is invalid");if(t.kind!=="archive"&&t.kind!=="root-move")throw new Error("Native transaction kind is invalid");if(typeof t.status!="string"||!cw.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!tt.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!tt.isAbsolute(t.nativeRoot))throw new Error("Native transaction roots must be absolute paths");if(t.change!==void 0&&(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change)))throw new Error("Native transaction change name is invalid");if(!Gr(t.createdAt))throw new Error("Native transaction createdAt is invalid");if(!Array.isArray(t.operations))throw new Error("Native transaction operations must be an array");let i=t.operations.map(sT),n=i.map(r=>r.id);if(new Set(n).size!==n.length)throw new Error("Native transaction operation ids must be unique");return{schema:"comet.native.transaction.v1",id:t.id,kind:t.kind,status:t.status,projectRoot:t.projectRoot,nativeRoot:t.nativeRoot,...typeof t.change=="string"?{change:t.change}:{},createdAt:t.createdAt,operations:i}}function fw(e,t){let i=Ao(e,`Native transaction event at line ${t}`);if(To(i,nT,`Native transaction event at line ${t}`),i.sequence!==t)throw new Error(`Native transaction event sequence at line ${t} must be ${t}`);if(!Gr(i.timestamp))throw new Error(`Native transaction event timestamp at line ${t} is invalid`);if(typeof i.type!="string"||!lw.has(i.type))throw new Error(`Native transaction event type at line ${t} is invalid`);let n=i.type==="operation-started"||i.type==="operation-completed";if(n&&(typeof i.operationId!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(i.operationId)||Buffer.byteLength(i.operationId,"utf8")>256)||!n&&i.operationId!==void 0)throw new Error(`Native transaction event operationId at line ${t} is invalid`);return{sequence:i.sequence,timestamp:i.timestamp,type:i.type,...typeof i.operationId=="string"?{operationId:i.operationId}:{}}}function cT(e){if(e.length>24)return!1;let t="0000-00-00T00:00:00.000Z";for(let n=0;nString(a+u).padStart(r,"0")).some(l=>l.startsWith(s)))return!1}return e.length>=10&&!Gr(`${e.slice(0,10)}T00:00:00.000Z`)?!1:e.length<24||Gr(e)}function zr(e,t){return e.lengthuw)return!1;let i=`{"sequence":${t},"timestamp":"`;if(zr(e,i))return!0;if(!e.startsWith(i))return!1;let n=e.slice(i.length),r=n.slice(0,Math.min(24,n.length));if(!cT(r))return!1;if(n.length<24)return!0;if(!Gr(r))return!1;let a='","type":"',o=n.slice(24);if(zr(o,a))return!0;if(!o.startsWith(a))return!1;let s=o.slice(a.length);for(let c of lw){if(zr(s,c))return!0;if(!s.startsWith(c))continue;let l=s.slice(c.length);if(c==="operation-started"||c==="operation-completed"){if(lT(l))return!0}else if(zr(l,'"}'))return!0}return!1}function dT(e,t){if(e.length===0)throw new Error("Blank transaction event line");if(Buffer.byteLength(e,"utf8")>uw)throw new Error(`Native transaction event at line ${t} is too large`);return fw(JSON.parse(e),t)}function fT(e){let t=e.split(` +`),i=t.at(-1)==="";if(i&&t.pop(),t.length>nl)throw new Error(`Native transaction event log exceeds ${nl} events`);let n=[];for(let r=0;rJSON.stringify(t)).join(` `)} -`}function hT(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return tt.join(e.transactionsDir,t)}function al(e,t){let i=hT(e,t);return{directory:i,journal:tt.join(i,"transaction.json"),events:tt.join(i,"events.jsonl"),staged:tt.join(i,"staged"),backups:tt.join(i,"backups")}}async function Tt(e,t){let i=al(e,t);return await Promise.all(Object.values(i).map(n=>x(e.nativeRoot,n))),i}function pT(e,t){if(t.length===0||tt.isAbsolute(t)||/^(?:[A-Za-z]:|~|[\\/])/u.test(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Unsafe Native transaction ref: ${t}`);let i=tt.resolve(e.nativeRoot,...t.split(/[\\/]/u));if(!$(e.nativeRoot,i))throw new Error(`Unsafe Native transaction ref: ${t}`);return i}async function gn(e,t){return x(e.nativeRoot,pT(e,t))}async function ir(e){try{return await xo.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Mf(e,t,i={}){let n=await Tt(e,t);try{await xo.lstat(n.events)}catch(r){if(r.code==="ENOENT")return{exists:!1,hash:null,size:0,events:[],canonicalSource:"",needsRepair:!1};throw r}try{let r=await ue({root:e.nativeRoot,file:n.events,maxBytes:aT,label:`Native transaction event log ${t}`,hooks:i.hooks}),a;try{a=uw.decode(r.bytes)}catch(c){throw new Error(`Native transaction event log ${t} is not valid UTF-8`,{cause:c})}let o=fT(a),s=fw(o);return{exists:!0,hash:r.hash,size:r.size,events:o,canonicalSource:s,needsRepair:a!==s}}catch(r){throw r.code==="ENOENT"?new Error(`Native transaction event log ${t} changed while reading`,{cause:r}):r}}async function aw(e,t,i){let n=await Mf(e,t);if(n.exists!==i.exists||n.hash!==i.hash||n.size!==i.size)throw new Error(`Native transaction event log ${t} changed before append`)}async function Nt(e,t,i,n){let r=await Tt(e,t),a=await Mf(e,t),o=a.events.find(c=>c.type===i&&c.operationId===n);if(o)return a.needsRepair&&await $e(r.events,a.canonicalSource,{containedRoot:e.nativeRoot,beforeCommit:()=>aw(e,t,a)}),o;if(a.events.length>=nl)throw new Error(`Native transaction event log ${t} exceeds ${nl} events`);let s={sequence:a.events.length+1,timestamp:new Date().toISOString(),type:i,...n?{operationId:n}:{}};return dw(s,s.sequence),await xo.mkdir(r.directory,{recursive:!0}),await $e(r.events,fw([...a.events,s]),{containedRoot:e.nativeRoot,beforeCommit:()=>aw(e,t,a)}),s}async function Ff(e,t){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");t=Df(t);let i=await Tt(e,t.id);await xo.mkdir(i.staged,{recursive:!0}),await xo.mkdir(i.backups,{recursive:!0}),await le(i.journal,t),await Nt(e,t.id,"prepared")}async function ct(e,t,i={}){let n=await Tt(e,t),r=await ue({root:e.nativeRoot,file:n.journal,maxBytes:rT,label:`Native transaction journal ${t}`,hooks:i.hooks}),a=JSON.parse(uw.decode(r.bytes)),o=Df(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}async function wn(e,t,i={}){return(await Mf(e,t,i)).events}async function rl(e,t,i){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let n=Df({...t,status:i});return await le((await Tt(e,t.id)).journal,n),n}async function $f(e,t,i){try{return await ue({root:e.nativeRoot,file:t,maxBytes:Hf,label:i})}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Lf(e,t,i,n){let r=await $f(e,t,`${n} source`);if(!r)throw new Error(`${n} source does not exist`);let a=await $f(e,i,`${n} target`);await pi({root:e.nativeRoot,directory:tt.dirname(i),label:`${n} target parent`}),await Ti({sourceRoot:e.nativeRoot,source:t,targetRoot:e.nativeRoot,target:i,maxBytes:Hf,label:n,expectedHash:r.hash,expectedTargetHash:a?.hash??null,exclusive:a===null})}async function hw(e,t,i){let n=await $f(e,t,i);n&&await tl({root:e.nativeRoot,file:t,maxBytes:Hf,expectedHash:n.hash,expectedSize:n.size,label:i})}async function ow(e,t){if(!t.backup)return;let i=await gn(e,t.target),n=await gn(e,t.backup);!await ir(i)||await ir(n)||await Lf(e,i,n,`Legacy Native transaction backup ${t.id}`)}async function mT(e,t){let i=await gn(e,t.target);if(t.type==="write"){if(!t.staged)throw new Error(`Write operation ${t.id} has no staged ref`);await ow(e,t),await Lf(e,await gn(e,t.staged),i,`Legacy Native transaction write ${t.id}`);return}if(t.type==="remove"){await ow(e,t),await hw(e,i,`Legacy Native transaction remove ${t.id}`);return}if(!t.source)throw new Error(`Move operation ${t.id} has no source ref`);let n=await gn(e,t.source),[r,a]=await Promise.all([ir(n),ir(i)]);if(!r&&a){await(await st({root:e.nativeRoot,directory:i,label:`Legacy Native transaction move target ${t.id}`,maxEntries:oT})).verify();return}if(a)throw new Error(`Move target already exists: ${t.target}`);if(!r)throw new Error(`Move source does not exist: ${t.source}`);await jf({root:e.nativeRoot,source:n,target:i,label:`Legacy Native transaction move ${t.id}`})}async function pw(e,t,i){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let n=t.status==="prepared"?await rl(e,t,"applying"):t,r=await wn(e,t.id),a=new Set(r.filter(s=>s.type==="operation-completed").map(s=>s.operationId)),o=a.size;for(let s of n.operations)a.has(s.id)||(await Nt(e,n.id,"operation-started",s.id),await mT(e,s),await Nt(e,n.id,"operation-completed",s.id),o+=1,await i?.afterOperation?.(s,o));return n=await ct(e,n.id),n}async function vT(e,t){let i=await gn(e,t.target),n=t.backup?await gn(e,t.backup):null;if(t.type==="move"){if(!t.source)throw new Error(`Move operation ${t.id} has no source ref`);let r=await gn(e,t.source);if(await ir(i)){if(await ir(r))throw new Error(`Legacy Native rollback source already exists: ${t.source}`);await jf({root:e.nativeRoot,source:i,target:r,label:`Legacy Native transaction rollback move ${t.id}`})}return}n&&await ir(n)?await Lf(e,n,i,`Legacy Native transaction rollback restore ${t.id}`):await hw(e,i,`Legacy Native transaction rollback remove ${t.id}`)}async function ol(e,t){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let i=await wn(e,t.id);if(i.some(a=>a.type==="archive-finalization-started"||a.type==="archive-finalized"))throw new Error("An archive whose finalization started can only be recovered by continuing it");let n=await rl(e,t,"rolling-back");await Nt(e,n.id,"rollback-started");let r=new Set(i.filter(a=>a.type==="operation-started"||a.type==="operation-completed").map(a=>a.operationId));for(let a of[...n.operations].reverse())r.has(a.id)&&await vT(e,a);return await Nt(e,n.id,"rollback-completed"),n=await rl(e,n,"rolled-back"),n}async function Ur(e,t,i){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");return await Nt(e,t.id,i),i==="commit"?rl(e,t,"committed"):t}function _i(e,t){let i=tt.resolve(t);if(!$(e.nativeRoot,i))throw new Error(`Path is outside the Native root: ${t}`);return tt.relative(e.nativeRoot,i).split(tt.sep).join("/")}async function yT(e,t){let i;try{i=await gT.readdir(e.transactionsDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return!1;throw n}for(let n of i)if(!(!n.isDirectory()||n.isSymbolicLink()))try{let r=await ct(e,n.name);if(r.id!==t&&r.status!=="committed"&&r.status!=="rolled-back")return!0}catch{return!0}return!1}async function NT(e,t){let i=Date.now()+5e3,n=wT.join(e.locksDir,"root-move.lock");for(;;)try{return await di(e,"root-move",t)}catch(r){if(r.cause?.code!=="EEXIST")throw r;let o=await Po(n);if(o.status==="missing")continue;if(o.status!=="active"||Date.now()>=i)throw r;await new Promise(s=>setTimeout(s,5+Math.floor(Math.random()*11)))}}async function te(e,t,i,n){let r=await NT(e,t);try{if(await Vr(e.projectRoot),await yT(e,n?.allowedTransactionId))throw new Error("Native transaction recovery is required before another mutation");return await i()}finally{await fi(r)}}function mw(e){return Number.isSafeInteger(e)&&e>=1}async function vw(e){if(!mw(e.expectedRevision))throw new Error("Native expected revision must be a positive integer");if(e.next.revision!==e.expectedRevision+1)throw new Error("Native CAS next revision must increment the expected revision exactly once");let t=await e.read();if(!mw(t.revision))throw new Error("Native current revision must be a positive integer");let i=e.equals??((n,r)=>JSON.stringify(n)===JSON.stringify(r));if(t.revision===e.next.revision&&i(t,e.next))return t;if(t.revision!==e.expectedRevision)throw e.conflict(t.revision);return await e.write(e.next),e.next}import{createHash as dl}from"crypto";import{spawn as Cw}from"node:child_process";import{promises as fe}from"fs";import z from"path";import{createHash as gw}from"crypto";import{createReadStream as bT}from"fs";async function lt(e){let t=gw("sha256");for await(let i of bT(e))t.update(i);return t.digest("hex")}function D(e){return gw("sha256").update(e).digest("hex")}var sl={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},zf=1e3,kT=8*1024*1024,ST=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,ET=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),RT=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),CT=new Set(["schema","include","exclude","hash"]),PT=new Set(["provider","gitSelection","physicalSelection","projection"]),xT=new Set(["provider","selection"]),AT=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),TT=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),_T=new Set(["schema","status","before","after"]),IT=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),jT=new Set(["path","hash","size","type","gitObjectId"]),OT=new Set(["path","size","type","reason"]),$T=new Set(["ref","hash","count"]),HT=new Set(["change-created","legacy-migration","explicit"]),DT=new Set(["file","directory","other"]),MT=new Set(["file-size","file-count","total-size","manifest-size","changed-during-read","unreadable","gitlink-unavailable","gitlink-dirty","gitlink-changed","legacy-gitlink-boundary","git-enumeration-limit","git-selection-changed","physical-enumeration-limit","physical-selection-changed"]),fl=/^[a-f0-9]{64}$/u,Pw=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,FT=new Set(["EACCES","EPERM"]),Zr=64*1024,Wf=64*1024,LT=6e4,BT=1e3,qT=2,Gf={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},VT={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};function xw(e){let t=e.deadlineMs??LT;if(!Number.isSafeInteger(t)||t<1)throw new Error("Native snapshot execution budget must be a positive integer");return{deadlineAt:Date.now()+t,gitProcess:e.gitProcess??{command:"git"}}}function Jt(e){return Math.max(0,e.deadlineAt-Date.now())}function F(e){return Jt(e)>=1}function Bf(e){let t=e===void 0?new Error("Native snapshot deadline exceeded while waiting for Git"):new Error("Native snapshot deadline exceeded while waiting for Git",{cause:e});return Object.assign(t,{code:"GIT_SNAPSHOT_TIMEOUT"})}function Xr(e){return e.code==="GIT_SNAPSHOT_TIMEOUT"}function WT(e){let t={...VT,...e};if(!Number.isSafeInteger(t.maxNodes)||t.maxNodes<1||!Number.isSafeInteger(t.maxBytes)||t.maxBytes<1||!Number.isSafeInteger(t.maxPathBytes)||t.maxPathBytes<1||t.maxPathBytes>t.maxBytes)throw new Error("Native physical selection limits must be positive bounded integers");return t}async function JT(e,t){if(t.terminateTree){await t.terminateTree(e);return}let i=e.pid;if(i===void 0){e.kill("SIGKILL");return}if(process.platform==="win32"){let n=process.env.SystemRoot??process.env.WINDIR,r=n&&z.win32.isAbsolute(n)?z.win32.resolve(n):"C:\\Windows",a=z.win32.join(r,"System32","taskkill.exe");if(!z.win32.isAbsolute(a))throw e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy(),Object.assign(new Error("Native Git taskkill path is not trusted"),{code:"GIT_SNAPSHOT_TERMINATION_UNCONFIRMED"});let o=()=>new Promise(s=>{let c=!1,l=null,u=null,d=(f,h=!1)=>{c||(c=!0,u&&clearTimeout(u),h&&l?.kill("SIGKILL"),s(f))};try{l=Cw(a,["/pid",String(i),"/t","/f"],{stdio:"ignore",windowsHide:!0}),l.once("error",()=>d(!1)),l.once("close",f=>d(f===0)),u=setTimeout(()=>d(!1,!0),BT),u.unref()}catch{d(!1)}});for(let s=0;s{s=h});let u=new Promise(h=>{o.once("close",h)}),d=setTimeout(()=>{c=!0,l=JT(o,a).then(()=>({error:null}),h=>({error:h}))},r);d.unref();let f=u.then(async h=>{if(clearTimeout(d),c){let m=await l;throw m?.error?Bf(m.error):Bf()}return{code:h,spawnError:s}});return{child:o,completion:f}}function Aw(e){let t={...Gf,...e};if(!Number.isSafeInteger(t.maxRecords)||t.maxRecords<1||!Number.isSafeInteger(t.maxBytes)||t.maxBytes<1||!Number.isSafeInteger(t.maxRecordBytes)||t.maxRecordBytes<1||t.maxRecordBytes>t.maxBytes)throw new Error("Native Git selection limits must be positive bounded integers");return t}async function cl(e,t,i,n=Wf){let{child:r,completion:a}=Uf(e,t,i,!1),o=[],s=[],c=0,l=0,u=!1;r.stdout.on("data",h=>{let m=Math.max(0,n-l);m>0&&o.push(Buffer.from(h).subarray(0,m)),l+=h.byteLength,l>n&&(u=!0)}),r.stderr.on("data",h=>{if(c>=Zr)return;let m=Zr-c,p=Buffer.from(h).subarray(0,m);s.push(p),c+=p.byteLength});let{code:d,spawnError:f}=await a;if(d===0&&f===null&&!u)return Buffer.concat(o);throw Object.assign(new Error(`git ${i.join(" ")} failed${f?`: ${f.message}`:s.length>0?`: ${Buffer.concat(s).toString("utf8").trim()}`:""}`),{code:"GIT_SNAPSHOT_UNAVAILABLE"})}function qf(e){return{hash:e.digest,recordCount:e.recordCount,storedRecordCount:e.records.length,stdoutBytes:e.stdoutBytes,overflow:e.overflow}}function jo(e,t,i,n){if(n.outputChunkBytes!==void 0&&(!Number.isSafeInteger(n.outputChunkBytes)||n.outputChunkBytes<1))throw new Error("Native Git output chunk size must be a positive integer");return new Promise((r,a)=>{let{child:o,completion:s}=Uf(e,t,i,n.stdin!==void 0),c=[],l=dl("sha256"),u=[],d=0,f=0,h=0,m=0,p=Buffer.alloc(0),v=!1,S=!1,k=!1,N=b=>{let R=0;for(;R0&&(p.byteLength+g.byteLength>n.maxRecordBytes?(p=Buffer.alloc(0),v=!0,S=!0):p=Buffer.concat([p,g])),y<0)break;m+=1,p.byteLength===0&&!v&&(k=!0);let E=p.byteLength+1;!v&&m<=n.maxRecords&&h+E<=n.maxBytes?(c.push(p),h+=E):S=!0,p=Buffer.alloc(0),v=!1,R=y+1}};o.stdout.on("data",b=>{l.update(b),f+=b.byteLength,f>n.maxBytes&&(S=!0);let R=n.outputChunkBytes;if(R===void 0){N(b);return}for(let y=0;y{if(d>=Zr)return;let R=Zr-d,y=Buffer.from(b).subarray(0,R);u.push(y),d+=y.byteLength}),o.stdin?.on("error",()=>{}),s.then(({code:b,spawnError:R})=>{let y=n.acceptedExitCodes??[0];if(b!==null&&y.includes(b)&&R===null&&!k&&p.byteLength===0&&!v){r({records:c,digest:l.digest("hex"),overflow:S,recordCount:m,stdoutBytes:f});return}a(new Error(`git ${i.join(" ")} failed${R?`: ${R.message}`:k||p.byteLength>0||v?": malformed NUL-delimited output":u.length>0?`: ${Buffer.concat(u).toString("utf8").trim()}`:""}`))},a),n.stdin&&o.stdin?.end(n.stdin)})}function ll(e){let t=e.toString("utf8");if(!Buffer.from(t,"utf8").equals(e))throw new Error("Native Git snapshot provider returned non-UTF-8 path data");return t}async function zT(e,t,i){if(i.length===0)return new Set;let n=await jo(e,t,["check-ignore","--no-index","-z","--stdin"],{...Gf,maxRecords:Math.max(1,i.length),acceptedExitCodes:[0,1],stdin:Buffer.from(`${i.join("\0")}\0`,"utf8")});if(n.overflow)throw new Error("Native Git check-ignore output exceeded its safety budget");return new Set(n.records.map(r=>{let a=ll(r);return a.endsWith("/")?a.slice(0,-1):a}))}async function GT(e,t,i){let{child:n,completion:r}=Uf(e,t,i,!1),a=[],o=0,s=!1;n.stdout.on("data",u=>{u.byteLength>0&&(s=!0)}),n.stderr.on("data",u=>{if(o>=Zr)return;let d=Zr-o,f=Buffer.from(u).subarray(0,d);a.push(f),o+=f.byteLength});let{code:c,spawnError:l}=await r;if(c===0&&l===null)return s;throw new Error(`git ${i.join(" ")} failed${l?`: ${l.message}`:a.length>0?`: ${Buffer.concat(a).toString("utf8").trim()}`:""}`)}function Qr(e){let t=e.endsWith("/")?e.slice(0,-1):e;return t.length===0||t.includes("\\")||z.posix.isAbsolute(t)||/^[A-Za-z]:/u.test(t)||z.posix.normalize(t)!==t||t===".."||t.startsWith("../")||t.includes("\0")?null:t}function UT(e,t){return e.map(i=>{let n=Qr(i);if(n===null)throw new Error(`Native Git snapshot provider returned an unsafe ${t} path`);return n})}async function KT(e){let t=z.resolve(e);for(;;){try{return await fe.lstat(z.join(t,".git")),!0}catch(n){if(n.code!=="ENOENT")throw n}let i=z.dirname(t);if(i===t)return!1;t=i}}async function Tw(e,t,i,n={}){let r=z.resolve(t.projectRoot),a=z.join(r,".comet","current-change.json"),s=["--",".",...[t.nativeRoot,t.configFile,a].map(f=>{let h=z.relative(r,z.resolve(f)).replaceAll("\\","/"),m=Qr(h);if(m===null)throw new Error("Native Git snapshot exclusion escaped the project root");return m}).flatMap(f=>[`:(exclude)${f}`,`:(exclude)${f}/**`])],c={...i,...n.outputChunkBytes===void 0?{}:{outputChunkBytes:n.outputChunkBytes}},l=await jo(e,r,["ls-files","--stage","-z",...s],c);await n.afterStageBefore?.();let u=await jo(e,r,["ls-files","--cached","--others","--exclude-standard","-z",...s],c);await n.afterCombined?.();let d=await jo(e,r,["ls-files","--stage","-z",...s],c);return{stagedBefore:l,combined:u,stagedAfter:d}}function _w(e){return{stageBefore:qf(e.stagedBefore),combined:qf(e.combined),stageAfter:qf(e.stagedAfter)}}async function Iw(e,t,i=Gf,n={}){let r=z.resolve(t.projectRoot);if(!await KT(r))return null;let a;try{a=await cl(e,r,["rev-parse","--is-inside-work-tree"])}catch(k){throw Xr(k)?k:new Error("Native Git snapshot provider could not inspect the repository boundary",{cause:k})}if(a.toString("utf8").trim()!=="true")throw new Error("Native Git snapshot provider found .git metadata outside a working tree");let o;try{o=await Tw(e,t,i,n)}catch(k){throw Xr(k)?k:new Error("Native Git snapshot provider failed after repository detection",{cause:k})}let{stagedBefore:s,combined:c,stagedAfter:l}=o,u=new Set,d=new Map,f=new Set,h=k=>{for(let N of k){let b=ll(N),R=b.indexOf(" ");if(R<0)throw new Error("Native Git snapshot provider returned a malformed staged record");let y=/^(?[0-7]{6}) (?[a-f0-9]{40}|[a-f0-9]{64}) (?[0-3])$/u.exec(b.slice(0,R))?.groups;if(!y)throw new Error("Native Git snapshot provider returned a malformed staged header");let w=Qr(b.slice(R+1));if(w===null)throw new Error("Native Git snapshot provider returned an unsafe staged path");u.add(w),y.stage==="0"&&d.set(w,y.objectId),y.mode==="160000"&&y.stage==="0"&&f.add(w)}};h(s.records),h(l.records);let m=c.records.map(ll),p=UT(m,"combined"),v=new Set(p.filter(k=>!u.has(k))),S=new Set(p.filter((k,N)=>!u.has(k)&&m[N].endsWith("/")));for(let k of f)S.delete(k);return{tracked:u,trackedObjectIds:d,untracked:v,gitlinks:f,nestedRepositories:S,omissions:[],overflow:null,evidence:null,initialFence:_w(o)}}function Nn(e,t){return e.hash===t.hash&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.stdoutBytes===t.stdoutBytes&&e.overflow===t.overflow}function ww(e){return e.stageBefore.overflow||e.combined.overflow||e.stageAfter.overflow}function YT(e,t){return!Nn(e.stageBefore,e.stageAfter)||!Nn(e.stageAfter,t.stageBefore)||!Nn(e.combined,t.combined)||!Nn(t.stageBefore,t.stageAfter)}async function jw(e,t,i,n,r){let a;try{a=await Tw(e,t,i,{...r===void 0?{}:{outputChunkBytes:r}})}catch(u){throw Xr(u)?u:new Error("Native Git snapshot provider failed during its final selection fence",{cause:u})}let o=n.initialFence,s=_w(a),c=ww(o)||ww(s),l=YT(o,s);c&&n.omissions.push({path:".",size:null,type:"directory",reason:"git-enumeration-limit"}),l&&n.omissions.push({path:".",size:null,type:"directory",reason:"git-selection-changed"}),n.evidence=c||l?{schema:"comet.native.git-selection.v1",status:c&&l?"overflow-and-changed":c?"overflow":"changed",...o,finalStageBefore:s.stageBefore,finalCombined:s.combined,finalStageAfter:s.stageAfter}:null,(o.combined.overflow||s.combined.overflow)&&(n.overflow={count:Math.max(1,o.combined.recordCount-o.combined.storedRecordCount,s.combined.recordCount-s.combined.storedRecordCount),hash:D(`comet.native.git-selection-overflow.v2 -${JSON.stringify({initial:o.combined,final:s.combined})}`)})}var XT=(1n<<256n)-1n;function QT(e){return e.isFile()?"file":e.isDirectory()?"directory":e.isSymbolicLink()?"symlink":"other"}async function yw(e){let t=z.resolve(e.paths.projectRoot),i=z.resolve(e.paths.nativeRoot),n=z.resolve(e.paths.configFile),r=z.join(t,".comet","current-change.json"),a=[],o=[],s=Buffer.alloc(32),c=0n,l=0,u=0,d=0,f=!1,h=!1,m=!1,p=()=>Jt(e.execution)>=1?!0:(f=!0,m=!0,!1),v=N=>{let b=Buffer.from(`${N.type}\0${N.path}`,"utf8"),R=dl("sha256").update("comet.native.physical-selection-record.v1\0").update(b).digest();for(let y=0;ye.limits.maxPathBytes||d>e.limits.maxBytes){f=!0,m=!0;return}a.push(N)},S=async N=>{if(m||!p())return;let b;try{b=await fe.opendir(N)}catch(E){if(!p())return;if(!Pe(E)&&!Ce(E)||N===t&&Pe(E))throw E;h||=Ce(E),f||=Pe(E),m=!0;return}if(!p()){try{await b.close()}catch(E){if(E.code!=="ERR_DIR_CLOSED")throw E}return}let R=!1,y;try{for(;!m&&p();){let E;try{E=await b.read()}catch(oe){if(!p())break;if(!Pe(oe)&&!Ce(oe)||N===t&&Pe(oe))throw oe;h||=Ce(oe),f||=Pe(oe),m=!0;break}if(!p()||E===null)break;if(l+=1,l>e.limits.maxNodes){f=!0,m=!0;break}let O=z.join(N,E.name),B=e_(t,O);if(O===n||O===r||bn(i,O)||e.denylist.some(oe=>bn(oe,O))||ci(B)!==null)continue;if(!p())break;let q;try{q=await fe.lstat(O)}catch(oe){if(!p())break;if(!Pe(oe)&&!Ce(oe))throw oe;if(h=!0,v({path:B,type:"other"}),o.push({path:B,size:null,type:"file",reason:Pe(oe)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.(B),m||!p())break;continue}if(!p())break;let U=QT(q);if(U==="directory"){if(r_(e.policy,B))continue;if(!p())break;let oe;try{oe=await fe.realpath(O)}catch(ri){if(!p())break;if(!Pe(ri)&&!Ce(ri))throw ri;if(h=!0,v({path:B,type:U}),o.push({path:B,size:null,type:"directory",reason:Pe(ri)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.(B),m||!p())break;continue}if(!p())break;if(!$(e.physicalProjectRoot,oe)||bn(e.physicalNativeRoot,oe))continue;if(v({path:B,type:U}),await e.hooks?.afterNode?.(B),!p()||(await S(O),m))break;continue}if(v({path:B,type:U}),await e.hooks?.afterNode?.(B),!p()||m)break}}catch(E){R=!0,y=E}let w;try{await b.close()}catch(E){w=E}let g=p();if(R)throw y;if(g&&w!==void 0&&w.code!=="ERR_DIR_CLOSED")throw w};await S(t),p(),f?(a.length=0,u=0,d=0):(a.sort((N,b)=>N.path.localeCompare(b.path,"en")),o.sort((N,b)=>N.path.localeCompare(b.path,"en")));let k=f?D(`comet.native.physical-selection-incomplete.v1 +`}function hT(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return tt.join(e.transactionsDir,t)}function al(e,t){let i=hT(e,t);return{directory:i,journal:tt.join(i,"transaction.json"),events:tt.join(i,"events.jsonl"),staged:tt.join(i,"staged"),backups:tt.join(i,"backups")}}async function Tt(e,t){let i=al(e,t);return await Promise.all(Object.values(i).map(n=>x(e.nativeRoot,n))),i}function pT(e,t){if(t.length===0||tt.isAbsolute(t)||/^(?:[A-Za-z]:|~|[\\/])/u.test(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Unsafe Native transaction ref: ${t}`);let i=tt.resolve(e.nativeRoot,...t.split(/[\\/]/u));if(!$(e.nativeRoot,i))throw new Error(`Unsafe Native transaction ref: ${t}`);return i}async function gn(e,t){return x(e.nativeRoot,pT(e,t))}async function ir(e){try{return await xo.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Mf(e,t,i={}){let n=await Tt(e,t);try{await xo.lstat(n.events)}catch(r){if(r.code==="ENOENT")return{exists:!1,hash:null,size:0,events:[],canonicalSource:"",needsRepair:!1};throw r}try{let r=await ue({root:e.nativeRoot,file:n.events,maxBytes:aT,label:`Native transaction event log ${t}`,hooks:i.hooks}),a;try{a=dw.decode(r.bytes)}catch(c){throw new Error(`Native transaction event log ${t} is not valid UTF-8`,{cause:c})}let o=fT(a),s=hw(o);return{exists:!0,hash:r.hash,size:r.size,events:o,canonicalSource:s,needsRepair:a!==s}}catch(r){throw r.code==="ENOENT"?new Error(`Native transaction event log ${t} changed while reading`,{cause:r}):r}}async function ow(e,t,i){let n=await Mf(e,t);if(n.exists!==i.exists||n.hash!==i.hash||n.size!==i.size)throw new Error(`Native transaction event log ${t} changed before append`)}async function Nt(e,t,i,n){let r=await Tt(e,t),a=await Mf(e,t),o=a.events.find(c=>c.type===i&&c.operationId===n);if(o)return a.needsRepair&&await $e(r.events,a.canonicalSource,{containedRoot:e.nativeRoot,beforeCommit:()=>ow(e,t,a)}),o;if(a.events.length>=nl)throw new Error(`Native transaction event log ${t} exceeds ${nl} events`);let s={sequence:a.events.length+1,timestamp:new Date().toISOString(),type:i,...n?{operationId:n}:{}};return fw(s,s.sequence),await xo.mkdir(r.directory,{recursive:!0}),await $e(r.events,hw([...a.events,s]),{containedRoot:e.nativeRoot,beforeCommit:()=>ow(e,t,a)}),s}async function Ff(e,t){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");t=Df(t);let i=await Tt(e,t.id);await xo.mkdir(i.staged,{recursive:!0}),await xo.mkdir(i.backups,{recursive:!0}),await le(i.journal,t),await Nt(e,t.id,"prepared")}async function ct(e,t,i={}){let n=await Tt(e,t),r=await ue({root:e.nativeRoot,file:n.journal,maxBytes:rT,label:`Native transaction journal ${t}`,hooks:i.hooks}),a=JSON.parse(dw.decode(r.bytes)),o=Df(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}async function wn(e,t,i={}){return(await Mf(e,t,i)).events}async function rl(e,t,i){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let n=Df({...t,status:i});return await le((await Tt(e,t.id)).journal,n),n}async function $f(e,t,i){try{return await ue({root:e.nativeRoot,file:t,maxBytes:Hf,label:i})}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Lf(e,t,i,n){let r=await $f(e,t,`${n} source`);if(!r)throw new Error(`${n} source does not exist`);let a=await $f(e,i,`${n} target`);await pi({root:e.nativeRoot,directory:tt.dirname(i),label:`${n} target parent`}),await Ti({sourceRoot:e.nativeRoot,source:t,targetRoot:e.nativeRoot,target:i,maxBytes:Hf,label:n,expectedHash:r.hash,expectedTargetHash:a?.hash??null,exclusive:a===null})}async function pw(e,t,i){let n=await $f(e,t,i);n&&await tl({root:e.nativeRoot,file:t,maxBytes:Hf,expectedHash:n.hash,expectedSize:n.size,label:i})}async function sw(e,t){if(!t.backup)return;let i=await gn(e,t.target),n=await gn(e,t.backup);!await ir(i)||await ir(n)||await Lf(e,i,n,`Legacy Native transaction backup ${t.id}`)}async function mT(e,t){let i=await gn(e,t.target);if(t.type==="write"){if(!t.staged)throw new Error(`Write operation ${t.id} has no staged ref`);await sw(e,t),await Lf(e,await gn(e,t.staged),i,`Legacy Native transaction write ${t.id}`);return}if(t.type==="remove"){await sw(e,t),await pw(e,i,`Legacy Native transaction remove ${t.id}`);return}if(!t.source)throw new Error(`Move operation ${t.id} has no source ref`);let n=await gn(e,t.source),[r,a]=await Promise.all([ir(n),ir(i)]);if(!r&&a){await(await st({root:e.nativeRoot,directory:i,label:`Legacy Native transaction move target ${t.id}`,maxEntries:oT})).verify();return}if(a)throw new Error(`Move target already exists: ${t.target}`);if(!r)throw new Error(`Move source does not exist: ${t.source}`);await jf({root:e.nativeRoot,source:n,target:i,label:`Legacy Native transaction move ${t.id}`})}async function mw(e,t,i){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let n=t.status==="prepared"?await rl(e,t,"applying"):t,r=await wn(e,t.id),a=new Set(r.filter(s=>s.type==="operation-completed").map(s=>s.operationId)),o=a.size;for(let s of n.operations)a.has(s.id)||(await Nt(e,n.id,"operation-started",s.id),await mT(e,s),await Nt(e,n.id,"operation-completed",s.id),o+=1,await i?.afterOperation?.(s,o));return n=await ct(e,n.id),n}async function vT(e,t){let i=await gn(e,t.target),n=t.backup?await gn(e,t.backup):null;if(t.type==="move"){if(!t.source)throw new Error(`Move operation ${t.id} has no source ref`);let r=await gn(e,t.source);if(await ir(i)){if(await ir(r))throw new Error(`Legacy Native rollback source already exists: ${t.source}`);await jf({root:e.nativeRoot,source:i,target:r,label:`Legacy Native transaction rollback move ${t.id}`})}return}n&&await ir(n)?await Lf(e,n,i,`Legacy Native transaction rollback restore ${t.id}`):await pw(e,i,`Legacy Native transaction rollback remove ${t.id}`)}async function ol(e,t){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let i=await wn(e,t.id);if(i.some(a=>a.type==="archive-finalization-started"||a.type==="archive-finalized"))throw new Error("An archive whose finalization started can only be recovered by continuing it");let n=await rl(e,t,"rolling-back");await Nt(e,n.id,"rollback-started");let r=new Set(i.filter(a=>a.type==="operation-started"||a.type==="operation-completed").map(a=>a.operationId));for(let a of[...n.operations].reverse())r.has(a.id)&&await vT(e,a);return await Nt(e,n.id,"rollback-completed"),n=await rl(e,n,"rolled-back"),n}async function Ur(e,t,i){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");return await Nt(e,t.id,i),i==="commit"?rl(e,t,"committed"):t}function _i(e,t){let i=tt.resolve(t);if(!$(e.nativeRoot,i))throw new Error(`Path is outside the Native root: ${t}`);return tt.relative(e.nativeRoot,i).split(tt.sep).join("/")}async function yT(e,t){let i;try{i=await gT.readdir(e.transactionsDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return!1;throw n}for(let n of i)if(!(!n.isDirectory()||n.isSymbolicLink()))try{let r=await ct(e,n.name);if(r.id!==t&&r.status!=="committed"&&r.status!=="rolled-back")return!0}catch{return!0}return!1}async function NT(e,t){let i=Date.now()+5e3,n=wT.join(e.locksDir,"root-move.lock");for(;;)try{return await di(e,"root-move",t)}catch(r){if(r.cause?.code!=="EEXIST")throw r;let o=await Po(n);if(o.status==="missing")continue;if(o.status!=="active"||Date.now()>=i)throw r;await new Promise(s=>setTimeout(s,5+Math.floor(Math.random()*11)))}}async function te(e,t,i,n){let r=await NT(e,t);try{if(await Vr(e.projectRoot),await yT(e,n?.allowedTransactionId))throw new Error("Native transaction recovery is required before another mutation");return await i()}finally{await fi(r)}}function vw(e){return Number.isSafeInteger(e)&&e>=1}async function gw(e){if(!vw(e.expectedRevision))throw new Error("Native expected revision must be a positive integer");if(e.next.revision!==e.expectedRevision+1)throw new Error("Native CAS next revision must increment the expected revision exactly once");let t=await e.read();if(!vw(t.revision))throw new Error("Native current revision must be a positive integer");let i=e.equals??((n,r)=>JSON.stringify(n)===JSON.stringify(r));if(t.revision===e.next.revision&&i(t,e.next))return t;if(t.revision!==e.expectedRevision)throw e.conflict(t.revision);return await e.write(e.next),e.next}import{createHash as dl}from"crypto";import{spawn as Pw}from"node:child_process";import{promises as fe}from"fs";import z from"path";import{createHash as ww}from"crypto";import{createReadStream as bT}from"fs";async function lt(e){let t=ww("sha256");for await(let i of bT(e))t.update(i);return t.digest("hex")}function D(e){return ww("sha256").update(e).digest("hex")}var sl={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},zf=1e3,kT=8*1024*1024,ST=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,ET=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),RT=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),CT=new Set(["schema","include","exclude","hash"]),PT=new Set(["provider","gitSelection","physicalSelection","projection"]),xT=new Set(["provider","selection"]),AT=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),TT=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),_T=new Set(["schema","status","before","after"]),IT=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),jT=new Set(["path","hash","size","type","gitObjectId"]),OT=new Set(["path","size","type","reason"]),$T=new Set(["ref","hash","count"]),HT=new Set(["change-created","legacy-migration","explicit"]),DT=new Set(["file","directory","other"]),MT=new Set(["file-size","file-count","total-size","manifest-size","changed-during-read","unreadable","gitlink-unavailable","gitlink-dirty","gitlink-changed","legacy-gitlink-boundary","git-enumeration-limit","git-selection-changed","physical-enumeration-limit","physical-selection-changed"]),fl=/^[a-f0-9]{64}$/u,xw=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,FT=new Set(["EACCES","EPERM"]),Zr=64*1024,Wf=64*1024,LT=6e4,BT=1e3,qT=2,Gf={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},VT={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};function Aw(e){let t=e.deadlineMs??LT;if(!Number.isSafeInteger(t)||t<1)throw new Error("Native snapshot execution budget must be a positive integer");return{deadlineAt:Date.now()+t,gitProcess:e.gitProcess??{command:"git"}}}function Jt(e){return Math.max(0,e.deadlineAt-Date.now())}function F(e){return Jt(e)>=1}function Bf(e){let t=e===void 0?new Error("Native snapshot deadline exceeded while waiting for Git"):new Error("Native snapshot deadline exceeded while waiting for Git",{cause:e});return Object.assign(t,{code:"GIT_SNAPSHOT_TIMEOUT"})}function Xr(e){return e.code==="GIT_SNAPSHOT_TIMEOUT"}function WT(e){let t={...VT,...e};if(!Number.isSafeInteger(t.maxNodes)||t.maxNodes<1||!Number.isSafeInteger(t.maxBytes)||t.maxBytes<1||!Number.isSafeInteger(t.maxPathBytes)||t.maxPathBytes<1||t.maxPathBytes>t.maxBytes)throw new Error("Native physical selection limits must be positive bounded integers");return t}async function JT(e,t){if(t.terminateTree){await t.terminateTree(e);return}let i=e.pid;if(i===void 0){e.kill("SIGKILL");return}if(process.platform==="win32"){let n=process.env.SystemRoot??process.env.WINDIR,r=n&&z.win32.isAbsolute(n)?z.win32.resolve(n):"C:\\Windows",a=z.win32.join(r,"System32","taskkill.exe");if(!z.win32.isAbsolute(a))throw e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy(),Object.assign(new Error("Native Git taskkill path is not trusted"),{code:"GIT_SNAPSHOT_TERMINATION_UNCONFIRMED"});let o=()=>new Promise(s=>{let c=!1,l=null,u=null,d=(f,h=!1)=>{c||(c=!0,u&&clearTimeout(u),h&&l?.kill("SIGKILL"),s(f))};try{l=Pw(a,["/pid",String(i),"/t","/f"],{stdio:"ignore",windowsHide:!0}),l.once("error",()=>d(!1)),l.once("close",f=>d(f===0)),u=setTimeout(()=>d(!1,!0),BT),u.unref()}catch{d(!1)}});for(let s=0;s{s=h});let u=new Promise(h=>{o.once("close",h)}),d=setTimeout(()=>{c=!0,l=JT(o,a).then(()=>({error:null}),h=>({error:h}))},r);d.unref();let f=u.then(async h=>{if(clearTimeout(d),c){let m=await l;throw m?.error?Bf(m.error):Bf()}return{code:h,spawnError:s}});return{child:o,completion:f}}function Tw(e){let t={...Gf,...e};if(!Number.isSafeInteger(t.maxRecords)||t.maxRecords<1||!Number.isSafeInteger(t.maxBytes)||t.maxBytes<1||!Number.isSafeInteger(t.maxRecordBytes)||t.maxRecordBytes<1||t.maxRecordBytes>t.maxBytes)throw new Error("Native Git selection limits must be positive bounded integers");return t}async function cl(e,t,i,n=Wf){let{child:r,completion:a}=Uf(e,t,i,!1),o=[],s=[],c=0,l=0,u=!1;r.stdout.on("data",h=>{let m=Math.max(0,n-l);m>0&&o.push(Buffer.from(h).subarray(0,m)),l+=h.byteLength,l>n&&(u=!0)}),r.stderr.on("data",h=>{if(c>=Zr)return;let m=Zr-c,p=Buffer.from(h).subarray(0,m);s.push(p),c+=p.byteLength});let{code:d,spawnError:f}=await a;if(d===0&&f===null&&!u)return Buffer.concat(o);throw Object.assign(new Error(`git ${i.join(" ")} failed${f?`: ${f.message}`:s.length>0?`: ${Buffer.concat(s).toString("utf8").trim()}`:""}`),{code:"GIT_SNAPSHOT_UNAVAILABLE"})}function qf(e){return{hash:e.digest,recordCount:e.recordCount,storedRecordCount:e.records.length,stdoutBytes:e.stdoutBytes,overflow:e.overflow}}function jo(e,t,i,n){if(n.outputChunkBytes!==void 0&&(!Number.isSafeInteger(n.outputChunkBytes)||n.outputChunkBytes<1))throw new Error("Native Git output chunk size must be a positive integer");return new Promise((r,a)=>{let{child:o,completion:s}=Uf(e,t,i,n.stdin!==void 0),c=[],l=dl("sha256"),u=[],d=0,f=0,h=0,m=0,p=Buffer.alloc(0),v=!1,S=!1,k=!1,N=b=>{let R=0;for(;R0&&(p.byteLength+g.byteLength>n.maxRecordBytes?(p=Buffer.alloc(0),v=!0,S=!0):p=Buffer.concat([p,g])),y<0)break;m+=1,p.byteLength===0&&!v&&(k=!0);let E=p.byteLength+1;!v&&m<=n.maxRecords&&h+E<=n.maxBytes?(c.push(p),h+=E):S=!0,p=Buffer.alloc(0),v=!1,R=y+1}};o.stdout.on("data",b=>{l.update(b),f+=b.byteLength,f>n.maxBytes&&(S=!0);let R=n.outputChunkBytes;if(R===void 0){N(b);return}for(let y=0;y{if(d>=Zr)return;let R=Zr-d,y=Buffer.from(b).subarray(0,R);u.push(y),d+=y.byteLength}),o.stdin?.on("error",()=>{}),s.then(({code:b,spawnError:R})=>{let y=n.acceptedExitCodes??[0];if(b!==null&&y.includes(b)&&R===null&&!k&&p.byteLength===0&&!v){r({records:c,digest:l.digest("hex"),overflow:S,recordCount:m,stdoutBytes:f});return}a(new Error(`git ${i.join(" ")} failed${R?`: ${R.message}`:k||p.byteLength>0||v?": malformed NUL-delimited output":u.length>0?`: ${Buffer.concat(u).toString("utf8").trim()}`:""}`))},a),n.stdin&&o.stdin?.end(n.stdin)})}function ll(e){let t=e.toString("utf8");if(!Buffer.from(t,"utf8").equals(e))throw new Error("Native Git snapshot provider returned non-UTF-8 path data");return t}async function zT(e,t,i){if(i.length===0)return new Set;let n=await jo(e,t,["check-ignore","--no-index","-z","--stdin"],{...Gf,maxRecords:Math.max(1,i.length),acceptedExitCodes:[0,1],stdin:Buffer.from(`${i.join("\0")}\0`,"utf8")});if(n.overflow)throw new Error("Native Git check-ignore output exceeded its safety budget");return new Set(n.records.map(r=>{let a=ll(r);return a.endsWith("/")?a.slice(0,-1):a}))}async function GT(e,t,i){let{child:n,completion:r}=Uf(e,t,i,!1),a=[],o=0,s=!1;n.stdout.on("data",u=>{u.byteLength>0&&(s=!0)}),n.stderr.on("data",u=>{if(o>=Zr)return;let d=Zr-o,f=Buffer.from(u).subarray(0,d);a.push(f),o+=f.byteLength});let{code:c,spawnError:l}=await r;if(c===0&&l===null)return s;throw new Error(`git ${i.join(" ")} failed${l?`: ${l.message}`:a.length>0?`: ${Buffer.concat(a).toString("utf8").trim()}`:""}`)}function Qr(e){let t=e.endsWith("/")?e.slice(0,-1):e;return t.length===0||t.includes("\\")||z.posix.isAbsolute(t)||/^[A-Za-z]:/u.test(t)||z.posix.normalize(t)!==t||t===".."||t.startsWith("../")||t.includes("\0")?null:t}function UT(e,t){return e.map(i=>{let n=Qr(i);if(n===null)throw new Error(`Native Git snapshot provider returned an unsafe ${t} path`);return n})}async function KT(e){let t=z.resolve(e);for(;;){try{return await fe.lstat(z.join(t,".git")),!0}catch(n){if(n.code!=="ENOENT")throw n}let i=z.dirname(t);if(i===t)return!1;t=i}}async function _w(e,t,i,n={}){let r=z.resolve(t.projectRoot),a=z.join(r,".comet","current-change.json"),s=["--",".",...[t.nativeRoot,t.configFile,a].map(f=>{let h=z.relative(r,z.resolve(f)).replaceAll("\\","/"),m=Qr(h);if(m===null)throw new Error("Native Git snapshot exclusion escaped the project root");return m}).flatMap(f=>[`:(exclude)${f}`,`:(exclude)${f}/**`])],c={...i,...n.outputChunkBytes===void 0?{}:{outputChunkBytes:n.outputChunkBytes}},l=await jo(e,r,["ls-files","--stage","-z",...s],c);await n.afterStageBefore?.();let u=await jo(e,r,["ls-files","--cached","--others","--exclude-standard","-z",...s],c);await n.afterCombined?.();let d=await jo(e,r,["ls-files","--stage","-z",...s],c);return{stagedBefore:l,combined:u,stagedAfter:d}}function Iw(e){return{stageBefore:qf(e.stagedBefore),combined:qf(e.combined),stageAfter:qf(e.stagedAfter)}}async function jw(e,t,i=Gf,n={}){let r=z.resolve(t.projectRoot);if(!await KT(r))return null;let a;try{a=await cl(e,r,["rev-parse","--is-inside-work-tree"])}catch(k){throw Xr(k)?k:new Error("Native Git snapshot provider could not inspect the repository boundary",{cause:k})}if(a.toString("utf8").trim()!=="true")throw new Error("Native Git snapshot provider found .git metadata outside a working tree");let o;try{o=await _w(e,t,i,n)}catch(k){throw Xr(k)?k:new Error("Native Git snapshot provider failed after repository detection",{cause:k})}let{stagedBefore:s,combined:c,stagedAfter:l}=o,u=new Set,d=new Map,f=new Set,h=k=>{for(let N of k){let b=ll(N),R=b.indexOf(" ");if(R<0)throw new Error("Native Git snapshot provider returned a malformed staged record");let y=/^(?[0-7]{6}) (?[a-f0-9]{40}|[a-f0-9]{64}) (?[0-3])$/u.exec(b.slice(0,R))?.groups;if(!y)throw new Error("Native Git snapshot provider returned a malformed staged header");let w=Qr(b.slice(R+1));if(w===null)throw new Error("Native Git snapshot provider returned an unsafe staged path");u.add(w),y.stage==="0"&&d.set(w,y.objectId),y.mode==="160000"&&y.stage==="0"&&f.add(w)}};h(s.records),h(l.records);let m=c.records.map(ll),p=UT(m,"combined"),v=new Set(p.filter(k=>!u.has(k))),S=new Set(p.filter((k,N)=>!u.has(k)&&m[N].endsWith("/")));for(let k of f)S.delete(k);return{tracked:u,trackedObjectIds:d,untracked:v,gitlinks:f,nestedRepositories:S,omissions:[],overflow:null,evidence:null,initialFence:Iw(o)}}function Nn(e,t){return e.hash===t.hash&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.stdoutBytes===t.stdoutBytes&&e.overflow===t.overflow}function yw(e){return e.stageBefore.overflow||e.combined.overflow||e.stageAfter.overflow}function YT(e,t){return!Nn(e.stageBefore,e.stageAfter)||!Nn(e.stageAfter,t.stageBefore)||!Nn(e.combined,t.combined)||!Nn(t.stageBefore,t.stageAfter)}async function Ow(e,t,i,n,r){let a;try{a=await _w(e,t,i,{...r===void 0?{}:{outputChunkBytes:r}})}catch(u){throw Xr(u)?u:new Error("Native Git snapshot provider failed during its final selection fence",{cause:u})}let o=n.initialFence,s=Iw(a),c=yw(o)||yw(s),l=YT(o,s);c&&n.omissions.push({path:".",size:null,type:"directory",reason:"git-enumeration-limit"}),l&&n.omissions.push({path:".",size:null,type:"directory",reason:"git-selection-changed"}),n.evidence=c||l?{schema:"comet.native.git-selection.v1",status:c&&l?"overflow-and-changed":c?"overflow":"changed",...o,finalStageBefore:s.stageBefore,finalCombined:s.combined,finalStageAfter:s.stageAfter}:null,(o.combined.overflow||s.combined.overflow)&&(n.overflow={count:Math.max(1,o.combined.recordCount-o.combined.storedRecordCount,s.combined.recordCount-s.combined.storedRecordCount),hash:D(`comet.native.git-selection-overflow.v2 +${JSON.stringify({initial:o.combined,final:s.combined})}`)})}var XT=(1n<<256n)-1n;function QT(e){return e.isFile()?"file":e.isDirectory()?"directory":e.isSymbolicLink()?"symlink":"other"}async function Nw(e){let t=z.resolve(e.paths.projectRoot),i=z.resolve(e.paths.nativeRoot),n=z.resolve(e.paths.configFile),r=z.join(t,".comet","current-change.json"),a=[],o=[],s=Buffer.alloc(32),c=0n,l=0,u=0,d=0,f=!1,h=!1,m=!1,p=()=>Jt(e.execution)>=1?!0:(f=!0,m=!0,!1),v=N=>{let b=Buffer.from(`${N.type}\0${N.path}`,"utf8"),R=dl("sha256").update("comet.native.physical-selection-record.v1\0").update(b).digest();for(let y=0;ye.limits.maxPathBytes||d>e.limits.maxBytes){f=!0,m=!0;return}a.push(N)},S=async N=>{if(m||!p())return;let b;try{b=await fe.opendir(N)}catch(E){if(!p())return;if(!Pe(E)&&!Ce(E)||N===t&&Pe(E))throw E;h||=Ce(E),f||=Pe(E),m=!0;return}if(!p()){try{await b.close()}catch(E){if(E.code!=="ERR_DIR_CLOSED")throw E}return}let R=!1,y;try{for(;!m&&p();){let E;try{E=await b.read()}catch(oe){if(!p())break;if(!Pe(oe)&&!Ce(oe)||N===t&&Pe(oe))throw oe;h||=Ce(oe),f||=Pe(oe),m=!0;break}if(!p()||E===null)break;if(l+=1,l>e.limits.maxNodes){f=!0,m=!0;break}let O=z.join(N,E.name),B=e_(t,O);if(O===n||O===r||bn(i,O)||e.denylist.some(oe=>bn(oe,O))||ci(B)!==null)continue;if(!p())break;let q;try{q=await fe.lstat(O)}catch(oe){if(!p())break;if(!Pe(oe)&&!Ce(oe))throw oe;if(h=!0,v({path:B,type:"other"}),o.push({path:B,size:null,type:"file",reason:Pe(oe)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.(B),m||!p())break;continue}if(!p())break;let U=QT(q);if(U==="directory"){if(r_(e.policy,B))continue;if(!p())break;let oe;try{oe=await fe.realpath(O)}catch(ri){if(!p())break;if(!Pe(ri)&&!Ce(ri))throw ri;if(h=!0,v({path:B,type:U}),o.push({path:B,size:null,type:"directory",reason:Pe(ri)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.(B),m||!p())break;continue}if(!p())break;if(!$(e.physicalProjectRoot,oe)||bn(e.physicalNativeRoot,oe))continue;if(v({path:B,type:U}),await e.hooks?.afterNode?.(B),!p()||(await S(O),m))break;continue}if(v({path:B,type:U}),await e.hooks?.afterNode?.(B),!p()||m)break}}catch(E){R=!0,y=E}let w;try{await b.close()}catch(E){w=E}let g=p();if(R)throw y;if(g&&w!==void 0&&w.code!=="ERR_DIR_CLOSED")throw w};await S(t),p(),f?(a.length=0,u=0,d=0):(a.sort((N,b)=>N.path.localeCompare(b.path,"en")),o.sort((N,b)=>N.path.localeCompare(b.path,"en")));let k=f?D(`comet.native.physical-selection-incomplete.v1 ${JSON.stringify({maxNodes:e.limits.maxNodes,maxBytes:e.limits.maxBytes,maxPathBytes:e.limits.maxPathBytes})}`):D(`comet.native.physical-selection.v1 -${JSON.stringify({visitedNodeCount:l,recordCount:u,encodedBytes:d,xor:s.toString("hex"),sum:c.toString(16).padStart(64,"0")})}`);return{records:a,omissions:o,evidence:{hash:k,visitedNodeCount:l,recordCount:u,storedRecordCount:a.length,encodedBytes:d,overflow:f,unstable:h}}}function Ow(e,t){return e.hash===t.hash&&e.visitedNodeCount===t.visitedNodeCount&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.encodedBytes===t.encodedBytes&&e.overflow===t.overflow&&e.unstable===t.unstable}function ZT(e,t){let i=e.overflow||t.overflow,n=e.unstable||t.unstable||!Ow(e,t),r=[];return i&&r.push({path:".",size:null,type:"directory",reason:"physical-enumeration-limit"}),n&&r.push({path:".",size:null,type:"directory",reason:"physical-selection-changed"}),{omissions:r,evidence:i||n?{schema:"comet.native.physical-selection.v1",status:i&&n?"overflow-and-changed":i?"overflow":"changed",before:e,after:t}:null}}function $w(e){return[...new Set([...e.tracked,...e.untracked])].sort((t,i)=>t.localeCompare(i,"en"))}async function Nw(e,t){let n=(await cl(e,t,["rev-parse","--verify","HEAD"])).toString("utf8").trim().toLowerCase();if(!Pw.test(n))throw new Error("Native Git snapshot provider received an invalid submodule HEAD");return D(`gitlink:${n}`)}async function bw(e,t){let i=await Nw(e,t),n=await GT(e,t,["status","--porcelain=v1","-z","--untracked-files=normal"]),r=await Nw(e,t);if(r!==i)throw new Error("Native Git snapshot provider observed a changing submodule HEAD");return{hash:r,dirty:n}}function Io(e,t){if(ci(t)!==null)return!1;let i=z.resolve(e.projectRoot,...t.split("/"));return!bn(z.resolve(e.nativeRoot),i)}function hl(e,t={}){let i=Ii(e),n=t.maxRecordedPaths??20;if(!Number.isSafeInteger(n)||n<0)throw new Error("Native snapshot health maxRecordedPaths must be a non-negative integer");let r=i.omitted.slice(0,n).map(a=>a.path);return{complete:i.complete,omittedCount:i.omittedCount,recordedOmissionCount:i.omitted.length,overflowCount:i.omissionOverflow?.count??0,samplePaths:r,sampleTruncated:r.lengthz.resolve(e,...i.split(/[\\/]/u)))}function bn(e,t){let i=z.resolve(e),n=z.resolve(t);return n===i||$(i,n)}function Pe(e){return FT.has(e.code??"")}function Ce(e){return e.code==="ENOENT"}function Kf(e){return Buffer.byteLength(JSON.stringify(e,null,2)+` +${JSON.stringify({visitedNodeCount:l,recordCount:u,encodedBytes:d,xor:s.toString("hex"),sum:c.toString(16).padStart(64,"0")})}`);return{records:a,omissions:o,evidence:{hash:k,visitedNodeCount:l,recordCount:u,storedRecordCount:a.length,encodedBytes:d,overflow:f,unstable:h}}}function $w(e,t){return e.hash===t.hash&&e.visitedNodeCount===t.visitedNodeCount&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.encodedBytes===t.encodedBytes&&e.overflow===t.overflow&&e.unstable===t.unstable}function ZT(e,t){let i=e.overflow||t.overflow,n=e.unstable||t.unstable||!$w(e,t),r=[];return i&&r.push({path:".",size:null,type:"directory",reason:"physical-enumeration-limit"}),n&&r.push({path:".",size:null,type:"directory",reason:"physical-selection-changed"}),{omissions:r,evidence:i||n?{schema:"comet.native.physical-selection.v1",status:i&&n?"overflow-and-changed":i?"overflow":"changed",before:e,after:t}:null}}function Hw(e){return[...new Set([...e.tracked,...e.untracked])].sort((t,i)=>t.localeCompare(i,"en"))}async function bw(e,t){let n=(await cl(e,t,["rev-parse","--verify","HEAD"])).toString("utf8").trim().toLowerCase();if(!xw.test(n))throw new Error("Native Git snapshot provider received an invalid submodule HEAD");return D(`gitlink:${n}`)}async function kw(e,t){let i=await bw(e,t),n=await GT(e,t,["status","--porcelain=v1","-z","--untracked-files=normal"]),r=await bw(e,t);if(r!==i)throw new Error("Native Git snapshot provider observed a changing submodule HEAD");return{hash:r,dirty:n}}function Io(e,t){if(ci(t)!==null)return!1;let i=z.resolve(e.projectRoot,...t.split("/"));return!bn(z.resolve(e.nativeRoot),i)}function hl(e,t={}){let i=Ii(e),n=t.maxRecordedPaths??20;if(!Number.isSafeInteger(n)||n<0)throw new Error("Native snapshot health maxRecordedPaths must be a non-negative integer");let r=i.omitted.slice(0,n).map(a=>a.path);return{complete:i.complete,omittedCount:i.omittedCount,recordedOmissionCount:i.omitted.length,overflowCount:i.omissionOverflow?.count??0,samplePaths:r,sampleTruncated:r.lengthz.resolve(e,...i.split(/[\\/]/u)))}function bn(e,t){let i=z.resolve(e),n=z.resolve(t);return n===i||$(i,n)}function Pe(e){return FT.has(e.code??"")}function Ce(e){return e.code==="ENOENT"}function Kf(e){return Buffer.byteLength(JSON.stringify(e,null,2)+` `)}function i_(e,t){return D(`comet.native.snapshot-policy.v1 -${JSON.stringify({include:e,exclude:t,hash:"sha256"})}`)}function Vf(e,t,i){let n=new Set(t),r=[...t];for(;r.length>0;){if(i&&!i())return null;let a=r.pop(),o=e[a];o&&(o.kind==="star"||o.kind==="globstar"||o.kind==="globstar-slash")&&!n.has(a+1)&&(n.add(a+1),r.push(a+1))}return n}function n_(e){let t=0;return()=>t>0?(t-=1,!0):e()?(t=63,!0):!1}function kw(e){let t=Gc(e,"Native snapshot pattern"),i=[];for(let n=0;n{let a=r?n_(r):void 0;if(a&&!a())return!1;let o=Vf(i,new Set([0]),a);if(o===null)return!1;for(let s of n){if(a&&!a())return!1;let c=new Set;for(let l of o){if(a&&!a())return!1;let u=i[l];u&&(u.kind==="literal"&&u.value===s||u.kind==="question"&&s!=="/"?c.add(l+1):u.kind==="star"&&s!=="/"||u.kind==="globstar"?c.add(l):u.kind==="globstar-slash"&&(c.add(l),s==="/"&&c.add(l+1)))}if(o=Vf(i,c,a),o===null||o.size===0)return!1}return Vf(i,o,a)?.has(i.length)??!1}}function Hw(e){if(e===void 0)return;let t=[...new Set(e.include.map(r=>Gc(r,"include")))].sort((r,a)=>r.localeCompare(a,"en")),i=[...new Set(e.exclude.map(r=>Gc(r,"exclude")))].sort((r,a)=>r.localeCompare(a,"en"));if(t.length===0)throw new Error("Native snapshot policy include must not be empty");let n=i_(t,i);if("hash"in e&&e.hash!==n)throw new Error("Native snapshot policy hash is invalid");return{manifest:{schema:"comet.native.snapshot-policy.v1",include:t,exclude:i,hash:n},includeMatchers:t.map(kw),excludeMatchers:i.map(kw),excludedDirectoryPrefixes:i.flatMap(r=>{if(!r.endsWith("/**"))return[];let a=r.slice(0,-3);return/[*?]/u.test(a)?[]:[a]}).sort((r,a)=>r.localeCompare(a,"en"))}}function r_(e,t){return e?.excludedDirectoryPrefixes.includes(t)??!1}function Sw(e,t,i){if(!e)return!0;let n=()=>F(i),r=!1;for(let a of e.includeMatchers){if(!n())return!1;if(a(t,n)){r=!0;break}}if(!r)return!1;for(let a of e.excludeMatchers)if(!n()||a(t,n))return!1;return!0}function Oo(e,t,i){let n=JSON.stringify(i);return D(`${e} +${JSON.stringify({include:e,exclude:t,hash:"sha256"})}`)}function Vf(e,t,i){let n=new Set(t),r=[...t];for(;r.length>0;){if(i&&!i())return null;let a=r.pop(),o=e[a];o&&(o.kind==="star"||o.kind==="globstar"||o.kind==="globstar-slash")&&!n.has(a+1)&&(n.add(a+1),r.push(a+1))}return n}function n_(e){let t=0;return()=>t>0?(t-=1,!0):e()?(t=63,!0):!1}function Sw(e){let t=Gc(e,"Native snapshot pattern"),i=[];for(let n=0;n{let a=r?n_(r):void 0;if(a&&!a())return!1;let o=Vf(i,new Set([0]),a);if(o===null)return!1;for(let s of n){if(a&&!a())return!1;let c=new Set;for(let l of o){if(a&&!a())return!1;let u=i[l];u&&(u.kind==="literal"&&u.value===s||u.kind==="question"&&s!=="/"?c.add(l+1):u.kind==="star"&&s!=="/"||u.kind==="globstar"?c.add(l):u.kind==="globstar-slash"&&(c.add(l),s==="/"&&c.add(l+1)))}if(o=Vf(i,c,a),o===null||o.size===0)return!1}return Vf(i,o,a)?.has(i.length)??!1}}function Dw(e){if(e===void 0)return;let t=[...new Set(e.include.map(r=>Gc(r,"include")))].sort((r,a)=>r.localeCompare(a,"en")),i=[...new Set(e.exclude.map(r=>Gc(r,"exclude")))].sort((r,a)=>r.localeCompare(a,"en"));if(t.length===0)throw new Error("Native snapshot policy include must not be empty");let n=i_(t,i);if("hash"in e&&e.hash!==n)throw new Error("Native snapshot policy hash is invalid");return{manifest:{schema:"comet.native.snapshot-policy.v1",include:t,exclude:i,hash:n},includeMatchers:t.map(Sw),excludeMatchers:i.map(Sw),excludedDirectoryPrefixes:i.flatMap(r=>{if(!r.endsWith("/**"))return[];let a=r.slice(0,-3);return/[*?]/u.test(a)?[]:[a]}).sort((r,a)=>r.localeCompare(a,"en"))}}function r_(e,t){return e?.excludedDirectoryPrefixes.includes(t)??!1}function Ew(e,t,i){if(!e)return!0;let n=()=>F(i),r=!1;for(let a of e.includeMatchers){if(!n())return!1;if(a(t,n)){r=!0;break}}if(!r)return!1;for(let a of e.excludeMatchers)if(!n()||a(t,n))return!1;return!0}function Oo(e,t,i){let n=JSON.stringify(i);return D(`${e} ${Buffer.byteLength(t)}:${t} -${Buffer.byteLength(n)}:${n}`)}function Jf(e){return e.reason==="git-enumeration-limit"||e.reason==="git-selection-changed"||e.reason==="physical-enumeration-limit"||e.reason==="physical-selection-changed"}function ul(e){for(let t=e.length-1;t>=0;t-=1){let i=e[t];if(!Jf(i))return e.splice(t,1),i}return null}function yn(e,t){let i={...e,birthtime:e.birthtimeMs},n={...t,birthtime:t.birthtimeMs};return Ue(i,n)?M(i,n):M(i,n)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function a_(e,t,i,n){if(!F(n))return{status:"budget-exhausted"};let r;try{r=await fe.open(e,"r")}catch(c){if(!F(n))return{status:"budget-exhausted"};throw c}if(!F(n))return await r.close(),{status:"budget-exhausted"};let a=dl("sha256"),o=Buffer.allocUnsafe(Math.min(64*1024,t+1)),s=0;try{if(!F(n))return{status:"budget-exhausted"};let c=await r.stat();if(!F(n))return{status:"budget-exhausted"};if(!c.isFile()||!yn(i,c))return{status:"changed"};for(;;){if(!F(n))return{status:"budget-exhausted"};let l=t+1-s;if(l<1)return{status:"changed"};let u=await r.read(o,0,Math.min(o.length,l),null);if(!F(n))return{status:"budget-exhausted"};if(u.bytesRead===0){if(!F(n))return{status:"budget-exhausted"};let d=await r.stat();return F(n)?!d.isFile()||!yn(c,d)?{status:"changed"}:{status:"complete",hash:a.digest("hex"),bytes:s,finalStat:d}:{status:"budget-exhausted"}}if(s+u.bytesRead>t)return{status:"changed"};a.update(o.subarray(0,u.bytesRead)),s+=u.bytesRead}}finally{await r.close()}}function _t(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function It(e,t,i){let n=Object.keys(e).find(r=>!t.has(r));if(n)throw new Error(`${i} contains unknown field: ${n}`)}function Yr(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function mi(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function Dw(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0"))throw new Error(`${t} must be a normalized project-relative path`);let i=z.posix.normalize(e);if(i!==e||z.posix.isAbsolute(e)||i===".."||i.startsWith("../"))throw new Error(`${t} must stay inside the project root`);return e}function o_(e,t){let i=_t(e,`Native snapshot entry ${t}`);It(i,jT,`Native snapshot entry ${t}`);let n=Dw(i.path,`Native snapshot entry ${t} path`);if(typeof i.hash!="string"||!fl.test(i.hash))throw new Error(`Native snapshot entry ${t} hash is invalid`);if(i.type!=="file")throw new Error(`Native snapshot entry ${t} type is invalid`);let r={path:n,hash:i.hash,size:mi(i.size,`Native snapshot entry ${t} size`),type:"file"};if(i.gitObjectId!==void 0){if(typeof i.gitObjectId!="string"||!Pw.test(i.gitObjectId))throw new Error(`Native snapshot entry ${t} gitObjectId is invalid`);r.gitObjectId=i.gitObjectId}return r}function s_(e,t){let i=_t(e,`Native snapshot omission ${t}`);if(It(i,OT,`Native snapshot omission ${t}`),!DT.has(i.type))throw new Error(`Native snapshot omission ${t} type is invalid`);if(!MT.has(i.reason))throw new Error(`Native snapshot omission ${t} reason is invalid`);return{path:Dw(i.path,`Native snapshot omission ${t} path`),size:i.size===null?null:mi(i.size,`Native snapshot omission ${t} size`),type:i.type,reason:i.reason}}function c_(e){let t=_t(e,"Native snapshot omission overflow");if(It(t,$T,"Native snapshot omission overflow"),typeof t.hash!="string"||!fl.test(t.hash))throw new Error("Native snapshot omission overflow hash is invalid");let i=`native-snapshot://omitted-overflow/${t.hash}`;if(t.ref!==i)throw new Error("Native snapshot omission overflow ref is invalid");return{ref:i,hash:t.hash,count:Yr(t.count,"Native snapshot omission overflow count")}}function Kr(e,t){let i=_t(e,t);if(It(i,TT,t),typeof i.hash!="string"||!fl.test(i.hash))throw new Error(`${t} hash is invalid`);if(typeof i.overflow!="boolean")throw new Error(`${t} overflow flag is invalid`);let n=mi(i.recordCount,`${t} recordCount`),r=mi(i.storedRecordCount,`${t} storedRecordCount`),a=mi(i.stdoutBytes,`${t} stdoutBytes`);if(r>n||!i.overflow&&r!==n)throw new Error(`${t} stored record count is inconsistent`);return{hash:i.hash,recordCount:n,storedRecordCount:r,stdoutBytes:a,overflow:i.overflow}}function Ew(e){let t=_t(e,"Native Git selection evidence");if(It(t,AT,"Native Git selection evidence"),t.schema!=="comet.native.git-selection.v1")throw new Error("Native Git selection evidence schema is invalid");if(t.status!=="overflow"&&t.status!=="changed"&&t.status!=="overflow-and-changed")throw new Error("Native Git selection evidence status is invalid");let i=Kr(t.stageBefore,"Native Git selection stageBefore"),n=Kr(t.combined,"Native Git selection combined"),r=Kr(t.stageAfter,"Native Git selection stageAfter"),a=Kr(t.finalStageBefore,"Native Git selection finalStageBefore"),o=Kr(t.finalCombined,"Native Git selection finalCombined"),s=Kr(t.finalStageAfter,"Native Git selection finalStageAfter"),c=[i,n,r,a,o,s].some(d=>d.overflow),l=!Nn(i,r)||!Nn(r,a)||!Nn(n,o)||!Nn(a,s),u=c&&l?"overflow-and-changed":c?"overflow":"changed";if(!c&&!l)throw new Error("Native Git selection evidence must describe an exceptional selection");if(t.status!==u)throw new Error("Native Git selection evidence status is inconsistent");return{schema:"comet.native.git-selection.v1",status:u,stageBefore:i,combined:n,stageAfter:r,finalStageBefore:a,finalCombined:o,finalStageAfter:s}}function Rw(e,t){let i=_t(e,t);if(It(i,IT,t),typeof i.hash!="string"||!fl.test(i.hash))throw new Error(`${t} hash is invalid`);if(typeof i.overflow!="boolean"||typeof i.unstable!="boolean")throw new Error(`${t} flags are invalid`);let n=mi(i.visitedNodeCount,`${t} visitedNodeCount`),r=mi(i.recordCount,`${t} recordCount`),a=mi(i.storedRecordCount,`${t} storedRecordCount`),o=mi(i.encodedBytes,`${t} encodedBytes`);if(a>r||!i.overflow&&a!==r)throw new Error(`${t} stored record count is inconsistent`);return{hash:i.hash,visitedNodeCount:n,recordCount:r,storedRecordCount:a,encodedBytes:o,overflow:i.overflow,unstable:i.unstable}}function l_(e){let t=_t(e,"Native physical selection evidence");if(It(t,_T,"Native physical selection evidence"),t.schema!=="comet.native.physical-selection.v1")throw new Error("Native physical selection evidence schema is invalid");if(t.status!=="overflow"&&t.status!=="changed"&&t.status!=="overflow-and-changed")throw new Error("Native physical selection evidence status is invalid");let i=Rw(t.before,"Native physical selection before"),n=Rw(t.after,"Native physical selection after"),r=i.overflow||n.overflow,a=i.unstable||n.unstable||!Ow(i,n);if(!r&&!a)throw new Error("Native physical selection evidence must describe an exceptional selection");let o=r&&a?"overflow-and-changed":r?"overflow":"changed";if(t.status!==o)throw new Error("Native physical selection evidence status is inconsistent");return{schema:"comet.native.physical-selection.v1",status:o,before:i,after:n}}function Ii(e){let t=_t(e,"Native content snapshot manifest");if(It(t,ET,"Native content snapshot manifest"),t.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!HT.has(t.origin))throw new Error("Native content snapshot origin is invalid");let i;if(t.capture!==void 0){let y=_t(t.capture,"Native content snapshot capture");if(It(y,PT,"Native content snapshot capture"),y.provider!=="git"&&y.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let w=y.gitSelection===void 0?void 0:Ew(y.gitSelection),g=y.physicalSelection===void 0?void 0:l_(y.physicalSelection),E=null;if(y.projection!==void 0){let O=_t(y.projection,"Native content snapshot projection");if(It(O,xT,"Native content snapshot projection"),O.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");E={provider:"git",...O.selection===void 0?{}:{selection:Ew(O.selection)}}}if(y.provider==="git"){if(g||E)throw new Error("Native Git capture cannot include physical or projection evidence");i={provider:"git",...w?{gitSelection:w}:{}}}else{if(w)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(g&&E)throw new Error("Native physical-tree capture cannot combine selection and projection");i=E?{provider:"physical-tree",projection:E}:{provider:"physical-tree",...g?{physicalSelection:g}:{}}}}if(typeof t.createdAt!="string"||Number.isNaN(Date.parse(t.createdAt)))throw new Error("Native content snapshot timestamp is invalid");if(typeof t.complete!="boolean")throw new Error("Native content snapshot complete flag is invalid");let n=_t(t.limits,"Native content snapshot limits");It(n,RT,"Native content snapshot limits");let r={maxFiles:Yr(n.maxFiles,"Native snapshot maxFiles"),maxFileBytes:Yr(n.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:Yr(n.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:Yr(n.maxManifestBytes,"Native snapshot maxManifestBytes"),...n.maxDurationMs===void 0?{}:{maxDurationMs:Yr(n.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(t.policy!==void 0){let y=_t(t.policy,"Native snapshot policy");if(It(y,CT,"Native snapshot policy"),y.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(y.include)||!Array.isArray(y.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=Hw({include:y.include,exclude:y.exclude,hash:y.hash,schema:"comet.native.snapshot-policy.v1"}).manifest}if(!Array.isArray(t.entries)||!Array.isArray(t.omitted))throw new Error("Native content snapshot entries and omissions must be arrays");let o=t.entries.map(o_),s=t.omitted.map(s_),c=mi(t.omittedCount,"Native content snapshot omittedCount"),l=t.omissionOverflow===void 0?void 0:c_(t.omissionOverflow);if(o.length>r.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(y=>y.size>r.maxFileBytes)||o.reduce((y,w)=>y+w.size,0)>r.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(y=>y.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>zf||c0&&l?.count!==u)throw new Error("Native content snapshot omission overflow is inconsistent");if(t.complete!==(c===0))throw new Error("Native content snapshot completeness is inconsistent");let d=s.filter(y=>y.reason==="git-enumeration-limit"),f=s.filter(y=>y.reason==="git-selection-changed");for(let y of[...d,...f])if(y.path!=="."||y.size!==null||y.type!=="directory")throw new Error("Native Git selection omission must use the project-root sentinel");if(d.length>1||f.length>1)throw new Error("Native Git selection omissions must not be duplicated");let h=i?.provider==="git"?i.gitSelection:i?.projection?.selection,m=h?.status==="overflow"||h?.status==="overflow-and-changed",p=h?.status==="changed"||h?.status==="overflow-and-changed";if(m!==(d.length===1))throw new Error("Native Git enumeration omission and selection evidence are inconsistent");if(p!==(f.length===1))throw new Error("Native Git selection-change omission and selection evidence are inconsistent");let v=s.filter(y=>y.reason==="physical-enumeration-limit"),S=s.filter(y=>y.reason==="physical-selection-changed");for(let y of[...v,...S])if(y.path!=="."||y.size!==null||y.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(v.length>1||S.length>1)throw new Error("Native physical selection omissions must not be duplicated");let k=i?.physicalSelection,N=k?.status==="overflow"||k?.status==="overflow-and-changed",b=k?.status==="changed"||k?.status==="overflow-and-changed";if(N!==(v.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(b!==(S.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");let R={schema:"comet.native.content-snapshot.v1",origin:t.origin,...i?{capture:i}:{},createdAt:t.createdAt,complete:t.complete,limits:r,...a?{policy:a}:{},entries:o,omitted:s,omittedCount:c,...l?{omissionOverflow:l}:{}};if(Kf(R)>r.maxManifestBytes)throw new Error("Native content snapshot exceeds its manifest byte limit");return R}async function kn(e,t,i={}){let n=Ii(t);if(n.capture?.provider==="git"||n.capture?.projection||n.capture?.physicalSelection)return n;let r=z.resolve(e.projectRoot),a=xw(i),o=Aw(i.gitSelectionLimits),s=await Iw(a,e,o,i.gitSelectionHooks);if(s===null)return n;let c=new Set($w(s).filter(g=>Io(e,g))),l=[...s.gitlinks].filter(g=>c.has(g)),u=[...s.nestedRepositories].filter(g=>Io(e,g)),d=(g,E)=>E.some(O=>g===O||g.startsWith(`${O}/`)),f=g=>d(g,l),h=g=>d(g,u),m=[...n.entries.map(g=>g.path),...n.omitted.flatMap(g=>g.type==="directory"?[g.path,`${g.path}/`]:[g.path])].filter(g=>!c.has(g)&&!f(g)&&!h(g)),p=await zT(a,r,m),v=n.entries.filter(g=>!f(g.path)&&!h(g.path)&&Io(e,g.path)&&(c.has(g.path)||!p.has(g.path)));await jw(a,e,o,s,i.gitSelectionHooks?.outputChunkBytes);let S=[...s.omissions];for(let g of l)S.push({path:g,size:null,type:"directory",reason:"legacy-gitlink-boundary"});v.sort((g,E)=>g.path.localeCompare(E.path,"en"));let k=n.omitted.filter(g=>f(g.path)||h(g.path)||!Io(e,g.path)?!1:p.has(g.path)?c.has(g.path)||[...c].some(E=>E.startsWith(`${g.path}/`)):!0);for(let g of S)k.some(E=>E.path===g.path&&E.reason===g.reason)||k.push(g);k.sort((g,E)=>g.path.localeCompare(E.path,"en"));let N=n.omissionOverflow?.count??0,b=n.omissionOverflow?.hash??D("comet.native.snapshot-omission-overflow.v1");s.overflow&&(N+=s.overflow.count,b=Oo(b,"git-selection",{source:"git-selection",...s.overflow}));let R=g=>{N+=1,b=Oo(b,"omission",g)};for(;k.length>zf;){let g=ul(k);if(g===null)throw new Error("Projected Native snapshot has too many required selection-integrity omissions");R(g)}let y=()=>({...n,capture:{provider:"physical-tree",projection:{provider:"git",...s.evidence?{selection:s.evidence}:{}}},complete:k.length+N===0,entries:v,omitted:k,omittedCount:k.length+N,...N>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${b}`,hash:b,count:N}}:{}}),w=y();for(;Kf(w)>n.limits.maxManifestBytes;){let g=ul(k);if(g===null)throw new Error("Projected Native snapshot cannot fit its manifest byte limit");R(g),w=y()}return Ii(w)}function Mw(e,t){if(!ST.test(t))throw new Error(`Invalid Native change name: ${t}`);let i=z.join(e.changesDir,t);if(!$(e.changesDir,i))throw new Error("Native change path escaped");return z.join(i,"runtime","baseline-manifest.json")}async function $o(e,t={}){let i={maxFiles:t.limits?.maxFiles??sl.maxFiles,maxFileBytes:t.limits?.maxFileBytes??sl.maxFileBytes,maxTotalBytes:t.limits?.maxTotalBytes??sl.maxTotalBytes,maxManifestBytes:t.limits?.maxManifestBytes??sl.maxManifestBytes,...t.limits?.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},n=Hw(t.policy),r=xw({...t,deadlineMs:t.deadlineMs??i.maxDurationMs}),a=Aw(t.gitSelectionLimits),o=WT(t.physicalSelectionLimits);if(i.maxFiles<1||i.maxFileBytes<1||i.maxTotalBytes<1||i.maxManifestBytes<1)throw new Error("Native snapshot limits must be positive");let s=z.resolve(e.projectRoot),c=await fe.realpath(s),l=z.resolve(e.nativeRoot),u=await fe.realpath(l),d=z.resolve(e.configFile),f=z.join(s,".comet","current-change.json"),h=t_(s,t.denylist??[]),m=[],p=[],v=new Map,S=new Map,k=0,N=0,b=D("comet.native.snapshot-omission-overflow.v1"),R=0,y=!1,w=null,g=_=>{N+=1,b=Oo(b,"omission",_)},E=_=>{if(k+=1,p.length{k+=_.count,N+=_.count,b=Oo(b,"git-selection",{source:"git-selection",..._})},B=_=>{N+=1,b=Oo(b,"manifest-entry",{reason:"manifest-size",entry:_})},q=async(_,T)=>{m.push(_),R+=_.size,v.set(_.path,T),y||(y=!0,await t.gitSelectionHooks?.afterFirstEntryCaptured?.(_.path))},U=(_,T)=>{let j=m.findIndex(de=>de.path===_);if(j<0)return;let[V]=m.splice(j,1);R-=V.size,v.delete(_),E(T)},oe=async(_,T,j,V)=>{if(!j.isFile()||j.isSymbolicLink()||!F(r))return;let de;try{de=await fe.realpath(_)}catch(A){if(!F(r))return;if(!Pe(A)&&!Ce(A))throw A;E({path:T,size:j.size,type:"file",reason:Ce(A)?"changed-during-read":"unreadable"});return}if(!F(r)||!$(c,de)||bn(u,de))return;if(m.length>=i.maxFiles){E({path:T,size:j.size,type:"file",reason:"file-count"});return}if(j.size>i.maxFileBytes){E({path:T,size:j.size,type:"file",reason:"file-size"});return}if(R+j.size>i.maxTotalBytes){E({path:T,size:j.size,type:"file",reason:"total-size"});return}let X,L,me;try{if(X=await a_(de,j.size,j,r),X.status==="budget-exhausted"||!F(r))return;if(X.status==="changed"){E({path:T,size:null,type:"file",reason:"changed-during-read"});return}if(!F(r)||(me=await fe.realpath(_),!F(r)))return;L=await fe.lstat(_)}catch(A){if(!F(r))return;if(!Pe(A)&&!Ce(A))throw A;E({path:T,size:j.size,type:"file",reason:Ce(A)?"changed-during-read":"unreadable"});return}if(F(r)){if(X.bytes!==j.size||me!==de||!yn(j,X.finalStat)||!yn(X.finalStat,L)||!L.isFile()||L.isSymbolicLink()||L.size!==j.size||L.mtimeMs!==j.mtimeMs||L.ctimeMs!==j.ctimeMs){E({path:T,size:L.isFile()?L.size:null,type:L.isFile()?"file":"other",reason:"changed-during-read"});return}F(r)&&await q({path:T,hash:X.hash,size:L.size,type:"file",...V===void 0?{}:{gitObjectId:V}},{kind:"file",target:_,realTarget:de,stat:L})}},ri=async(_,T,j)=>{if(!F(r))return;let V,de,X;try{if(V=await fe.readlink(_,{encoding:"buffer"}),!F(r)||(X=await fe.lstat(_),!F(r)))return;de=await fe.readlink(_,{encoding:"buffer"})}catch(A){if(!F(r))return;if(!Pe(A)&&!Ce(A))throw A;E({path:T,size:null,type:"other",reason:Ce(A)?"changed-during-read":"unreadable"});return}if(!F(r))return;if(!X.isSymbolicLink()||!yn(j,X)||X.mtimeMs!==j.mtimeMs||X.ctimeMs!==j.ctimeMs||!V.equals(de)){E({path:T,size:null,type:"other",reason:"changed-during-read"});return}let L=V.byteLength;if(m.length>=i.maxFiles){E({path:T,size:L,type:"other",reason:"file-count"});return}if(L>i.maxFileBytes){E({path:T,size:L,type:"other",reason:"file-size"});return}if(R+L>i.maxTotalBytes){E({path:T,size:L,type:"other",reason:"total-size"});return}let me=dl("sha256").update("symlink\0").update(V).digest("hex");F(r)&&await q({path:T,hash:me,size:L,type:"file"},{kind:"symlink",target:_,rawTarget:V,stat:X})},ai=async()=>{for(let[_,T]of[...v]){if(!F(r))return;if(T.kind==="file"){let L,me;try{if(L=await fe.realpath(T.target),!F(r))return;me=await fe.lstat(T.target)}catch(A){if(!F(r))return;if(!Pe(A)&&!Ce(A))throw A;U(_,{path:_,size:null,type:"file",reason:Pe(A)?"unreadable":"changed-during-read"});continue}if(!F(r))return;(L!==T.realTarget||!me.isFile()||me.isSymbolicLink()||!yn(T.stat,me)||me.size!==T.stat.size||me.mtimeMs!==T.stat.mtimeMs||me.ctimeMs!==T.stat.ctimeMs)&&U(_,{path:_,size:me.isFile()?me.size:null,type:me.isFile()?"file":"other",reason:"changed-during-read"});continue}if(T.kind==="symlink"){let L,me;try{if(L=await fe.lstat(T.target),!F(r))return;me=await fe.readlink(T.target,{encoding:"buffer"})}catch(A){if(!F(r))return;if(!Pe(A)&&!Ce(A))throw A;U(_,{path:_,size:null,type:"other",reason:Pe(A)?"unreadable":"changed-during-read"});continue}if(!F(r))return;(!L.isSymbolicLink()||!yn(T.stat,L)||L.mtimeMs!==T.stat.mtimeMs||L.ctimeMs!==T.stat.ctimeMs||!T.rawTarget.equals(me))&&U(_,{path:_,size:null,type:"other",reason:"changed-during-read"});continue}let j,V;try{if(j=await fe.realpath(T.target),!F(r))return;V=await fe.lstat(T.target)}catch{if(!F(r))return;U(_,{path:_,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!F(r))return;if(!(j===T.realTarget&&V.isDirectory()&&!V.isSymbolicLink()&&yn(T.stat,V)&&$(c,j)&&!bn(u,j))){U(_,{path:_,size:null,type:"directory",reason:"gitlink-changed"});continue}let X;try{if(!F(r))return;X=await bw(r,j)}catch(L){if(Xr(L))throw L;U(_,{path:_,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!F(r))return;X.dirty?U(_,{path:_,size:null,type:"directory",reason:"gitlink-dirty"}):X.hash!==T.hash&&U(_,{path:_,size:null,type:"directory",reason:"gitlink-changed"})}for(let[_,T]of S){if(!F(r))return;try{let j=await fe.lstat(T);if(!F(r))return;E({path:_,size:j.isFile()?j.size:null,type:j.isFile()?"file":j.isDirectory()?"directory":"other",reason:"changed-during-read"})}catch(j){if(!F(r))return;if(Ce(j))continue;if(!Pe(j))throw j;E({path:_,size:null,type:"file",reason:"unreadable"})}}},wt=await Iw(r,e,a,t.gitSelectionHooks);if(wt===null){let _=await yw({execution:r,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:h,policy:n,limits:o,hooks:t.physicalSelectionHooks});await t.physicalSelectionHooks?.afterInitialSelection?.();for(let V of _.records){if(V.type!=="file"&&V.type!=="symlink"||v.has(V.path))continue;if(Jt(r)<1)break;if(!Sw(n,V.path,r))continue;if(Jt(r)<1)break;let de=z.resolve(s,...V.path.split("/")),X;try{X=await fe.lstat(de)}catch(L){if(!F(r))break;if(!Pe(L)&&!Ce(L))throw L;E({path:V.path,size:null,type:"file",reason:Ce(L)?"changed-during-read":"unreadable"});continue}if(Jt(r)<1)break;if(V.type==="symlink"&&X.isSymbolicLink()){if(await ri(de,V.path,X),Jt(r)<1)break;continue}if(V.type!=="file"||!X.isFile()||X.isSymbolicLink()){E({path:V.path,size:X.isFile()?X.size:null,type:X.isDirectory()?"directory":X.isFile()?"file":"other",reason:"changed-during-read"});continue}if(await oe(de,V.path,X),Jt(r)<1)break}Jt(r)>=1&&await ai();let T=await yw({execution:r,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:h,policy:n,limits:o}),j=ZT(_.evidence,T.evidence);w=j.evidence;for(let V of[..._.omissions,...T.omissions,...j.omissions])p.some(de=>de.path===V.path&&de.reason===V.reason)||E(V)}else{await t.gitSelectionHooks?.afterInitialSelection?.();let _=t.incrementalBaseline,T=new Map,j=!1;if(_){let A=Ii(_);for(let ve of A.entries)ve.gitObjectId!==void 0&&T.set(ve.path,ve);j=T.size>0}let V=new Set,de=!0;try{let A=await jo(r,s,["ls-files","-v","-z"],{...a,...t.gitSelectionHooks?.outputChunkBytes===void 0?{}:{outputChunkBytes:t.gitSelectionHooks.outputChunkBytes}});if(A.overflow)j=!1,de=!1,T.clear();else for(let ve of A.records){let ge=ll(ve),et=ge.indexOf(" "),Ge=et<0?null:Qr(ge.slice(et+1));if(et!==1||Ge===null)throw new Error("Native Git snapshot provider returned a malformed tagged record");ge[0]!=="H"&&V.add(Ge)}}catch(A){if(Xr(A))throw A;j=!1,de=!1,T.clear()}let X=new Set;try{let A=await cl(r,s,["ls-files","--modified","-z"],Wf);for(let ve of A.toString("utf8").split("\0")){let ge=Qr(ve);ge!==null&&X.add(ge)}}catch{j=!1,de=!1,T.clear()}let L=new Set,me=new Set;for(let A of $w(wt)){if(v.has(A)||!Io(e,A))continue;if(Jt(r)<1)break;if(!Sw(n,A,r))continue;if(Jt(r)<1)break;let ve=z.resolve(s,...A.split("/"));if(ve===d||ve===f||h.some(yt=>bn(yt,ve)))continue;if(wt.gitlinks.has(A)){if(m.length>=i.maxFiles){E({path:A,size:0,type:"file",reason:"file-count"});continue}let yt,xs;try{[yt,xs]=await Promise.all([fe.realpath(ve),fe.lstat(ve)])}catch{E({path:A,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(xs.isSymbolicLink()||!xs.isDirectory()||!$(c,yt)||bn(u,yt)){E({path:A,size:null,type:"directory",reason:"gitlink-unavailable"});continue}try{let Ar=await bw(r,yt);if(Ar.dirty){E({path:A,size:null,type:"directory",reason:"gitlink-dirty"});continue}await q({path:A,hash:Ar.hash,size:0,type:"file"},{kind:"gitlink",target:ve,realTarget:yt,stat:xs,hash:Ar.hash})}catch(Ar){if(Xr(Ar))throw Ar;E({path:A,size:null,type:"directory",reason:"gitlink-unavailable"})}continue}let ge;try{ge=await fe.lstat(ve)}catch(yt){if(Ce(yt)&&wt.tracked.has(A)){S.set(A,ve);continue}if(!Pe(yt)&&!Ce(yt))throw yt;E({path:A,size:null,type:"file",reason:Ce(yt)?"changed-during-read":"unreadable"});continue}if(ge.isSymbolicLink()){await ri(ve,A,ge);continue}if(!ge.isFile()){wt.nestedRepositories.has(A)||E({path:A,size:null,type:"other",reason:"changed-during-read"});continue}let et=wt.trackedObjectIds.get(A),Ge=et?T.get(A):void 0;if(j&&Ge?.gitObjectId!==void 0&&Ge.gitObjectId===et&&!V.has(A)&&!X.has(A)){if(m.length>=i.maxFiles){E({path:A,size:Ge.size,type:"file",reason:"file-count"});continue}if(Ge.size>i.maxFileBytes){E({path:A,size:Ge.size,type:"file",reason:"file-size"});continue}if(R+Ge.size>i.maxTotalBytes){E({path:A,size:Ge.size,type:"file",reason:"total-size"});continue}m.push({...Ge}),R+=Ge.size,L.add(A);continue}let $p=de&&!V.has(A)&&!X.has(A)?et:void 0;await oe(ve,A,ge,$p),$p!==void 0&&me.add(A)}if(await ai(),await t.gitSelectionHooks?.afterContentRevalidation?.(),await jw(r,e,a,wt,t.gitSelectionHooks?.outputChunkBytes),L.size>0||j&&me.size>0){let A=await cl(r,s,["ls-files","--modified","-z"],Wf),ve=new Set;for(let ge of A.toString("utf8").split("\0")){let et=Qr(ge);et!==null&&ve.add(et)}for(let ge of L){if(!ve.has(ge))continue;let et=m.find(Ge=>Ge.path===ge);U(ge,{path:ge,size:et?.size??null,type:"file",reason:"changed-during-read"})}for(let ge of me){if(!ve.has(ge))continue;let et=m.find(Ge=>Ge.path===ge);et&&delete et.gitObjectId}}for(let A of wt.omissions)E(A);wt.overflow&&O(wt.overflow)}m.sort((_,T)=>_.path.localeCompare(T.path,"en")),p.sort((_,T)=>_.path.localeCompare(T.path,"en"));let bE=wt===null?{provider:"physical-tree",...w?{physicalSelection:w}:{}}:{provider:"git",...wt.evidence?{gitSelection:wt.evidence}:{}},Op=()=>({schema:"comet.native.content-snapshot.v1",origin:t.origin??"explicit",capture:bE,createdAt:(t.now??new Date).toISOString(),complete:k===0,limits:i,...n?{policy:n.manifest}:{},entries:m,omitted:p,omittedCount:k,...N>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${b}`,hash:b,count:N}}:{}}),Iu=Op();for(;Kf(Iu)>i.maxManifestBytes;){if(p.filter(T=>!Jf(T)).length>0){let T=Math.max(1,Math.ceil(p.length/4));for(let j=0;j0){let T=Math.max(1,Math.ceil(m.length/4));for(let j of m.splice(-T))k+=1,B(j)}else throw new Error("Native snapshot manifest byte limit is too small for its metadata");Iu=Op()}return Iu}async function Sn(e,t,i={}){let r=(await re(e.projectRoot))?.native.snapshot??zc;return $o(e,{...i,policy:t.policy,incrementalBaseline:t,limits:{maxFiles:r.max_files,maxFileBytes:r.max_total_bytes,maxTotalBytes:r.max_total_bytes,maxDurationMs:r.max_duration_ms},deadlineMs:r.max_duration_ms})}async function pl(e,t,i){let n=Mw(e,t);await x(e.nativeRoot,n),await le(n,Ii(i))}async function vi(e,t){let i=Mw(e,t);await x(e.nativeRoot,i);try{let n=await el({root:e.nativeRoot,file:i,maxBytes:kT,label:"Native baseline snapshot manifest"});return Ii(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}import{createHash as A_}from"crypto";import yl from"path";import u_ from"path";var ut=Object.freeze({stateRef:"runtime/run-state.json",pendingRef:"runtime/pending-action.json",trajectoryRef:"runtime/trajectory.jsonl",contextRef:"runtime/context.md",artifactsRef:"runtime/artifacts.json",checkpointRef:"runtime/checkpoints/latest.json",snapshotsRef:"runtime/skill-snapshots"});function d_(e){if(e.length===0||u_.isAbsolute(e)||/^(?:[A-Za-z]:|[\\/]|~)/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error("Run storage ref must stay inside the Run root")}function Fw(e){for(let t of Object.values(e))d_(t)}import{createHash as S_}from"node:crypto";import{constants as vl,promises as it}from"node:fs";import bt from"node:path";import{TextDecoder as E_}from"node:util";import y_ from"path";var g_=Ts(uo(),1);var Lw=(e,t)=>{let i=e[t];return i==null?null:String(i)};function Do(e,t){let i=e[t];if(typeof i!="string"||i.length===0)throw new Error(`Invalid Run state: ${t} must be a non-empty string`);return i}function Ho(e,t){let i=Do(e,t);if(y_.isAbsolute(i)||/^(?:[A-Za-z]:|[\\/]|~)/u.test(i)||i.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Run state: ${t} must stay inside the change directory`);return i}function N_(e){let t=e.run_retries??"{}",i;try{i=typeof t=="string"?JSON.parse(t):t}catch(n){throw new Error("Invalid Run state: run_retries must be a JSON object",{cause:n})}if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Invalid Run state: run_retries must be a JSON object");for(let n of Object.values(i))if(!Number.isInteger(n)||Number(n)<0)throw new Error("Invalid Run state: retry counts must be non-negative integers");return i}function Bw(e){if(!e.run_id)return null;let t=Do(e,"run_id"),i=Do(e,"skill"),n=Do(e,"skill_version"),r=Do(e,"skill_hash"),a=Ho(e,"pending_ref"),o=Ho(e,"trajectory_ref"),s=Ho(e,"context_ref"),c=Ho(e,"artifacts_ref"),l=Ho(e,"checkpoint_ref"),u=Number(e.iteration);if(!Number.isInteger(u)||u<0)throw new Error("Invalid Run state: iteration must be a non-negative integer");if(e.orchestration!=="deterministic"&&e.orchestration!=="adaptive")throw new Error("Invalid Run state: orchestration must be deterministic or adaptive");if(e.run_status!=="running"&&e.run_status!=="waiting"&&e.run_status!=="completed"&&e.run_status!=="failed")throw new Error("Invalid Run state: run_status is invalid");return{runId:t,skill:i,skillVersion:n,skillHash:r,orchestration:e.orchestration,currentStep:Lw(e,"current_step"),iteration:u,pending:Lw(e,"pending"),pendingRef:a,trajectoryRef:o,contextRef:s,artifactsRef:c,checkpointRef:l,status:e.run_status,retries:N_(e)}}var _B=256*1024;var b_=new Set(["runId","skill","skillVersion","skillHash","orchestration","currentStep","iteration","pending","pendingRef","trajectoryRef","contextRef","artifactsRef","checkpointRef","status","retries"]);function k_(e){let t={run_id:e.runId,skill:e.skill,skill_version:e.skillVersion,skill_hash:e.skillHash,orchestration:e.orchestration,current_step:e.currentStep,iteration:e.iteration,pending:e.pending,pending_ref:e.pendingRef,trajectory_ref:e.trajectoryRef,context_ref:e.contextRef,artifacts_ref:e.artifactsRef,checkpoint_ref:e.checkpointRef,run_status:e.status,run_retries:JSON.stringify(e.retries)},i=Bw(t);if(!i)throw new Error("Invalid Run state: runId must be a non-empty string");return i}function ml(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid Run state: stored value must be an object");let t=e,i=Object.keys(t).find(n=>!b_.has(n));if(i)throw new Error(`Invalid Run state: unknown field ${i}`);if(t.currentStep!==null&&(typeof t.currentStep!="string"||t.currentStep.length===0))throw new Error("Invalid Run state: currentStep must be a non-empty string or null");if(t.pending!==null&&(typeof t.pending!="string"||t.pending.length===0))throw new Error("Invalid Run state: pending must be a non-empty string or null");if(!t.retries||typeof t.retries!="object"||Array.isArray(t.retries))throw new Error("Invalid Run state: retries must be an object");return k_(t)}function qw(e,t,i,n){return Fw(n),{runId:t,skill:e.definition.metadata.name,skillVersion:e.definition.metadata.version,skillHash:i,orchestration:e.definition.orchestration.mode,currentStep:e.definition.orchestration.entry??null,iteration:0,pending:null,pendingRef:n.pendingRef,trajectoryRef:n.trajectoryRef,contextRef:n.contextRef,artifactsRef:n.artifactsRef,checkpointRef:n.checkpointRef,status:"running",retries:{}}}var Xe={runStateBytes:256*1024,trajectoryBytes:8*1024*1024,trajectoryEvents:4096,trajectoryEventBytes:256*1024,checkpointBytes:256*1024,pendingActionBytes:256*1024,contextBytes:1024*1024,artifactsBytes:1024*1024};function Fo(e,t){let i=bt.relative(e,t);return i===""||!bt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${bt.sep}`)}function Ww(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Mo(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function R_(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function En(e,t,i){let n=ut[t];if(i!==void 0&&i!==n)throw new Error(`Native Run ${t} ref must be ${n}`);let r=bt.resolve(e),a=bt.resolve(r,...n.split("/"));if(!Fo(r,a))throw new Error("Native Run path must stay inside its change");return a}async function Vw(e){let t=await it.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native Run parent must be a real directory: ${e}`);return{path:e,realPath:await it.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Yf(e,t){let i=bt.resolve(e),n=bt.resolve(t);if(!Fo(i,n))throw new Error("Native Run path is outside its change");let r=[await Vw(i)],a=i;for(let o of bt.relative(i,n).split(bt.sep).filter(Boolean)){a=bt.join(a,o);let s;try{s=await Vw(a)}catch(c){if(c.code==="ENOENT")return null;throw c}if(!Fo(r[0].realPath,s.realPath))throw new Error(`Native Run parent resolves outside its change: ${a}`);r.push(s)}return r}async function gl(e){for(let t of e){let i=await it.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!R_(t,i)||await it.realpath(t.path)!==t.realPath)throw new Error(`Native Run parent changed during I/O: ${t.path}`)}}async function C_(e,t,i){let n=[],r=0,a=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let o=t+1-r,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(r+=s,r>t)throw new Error(`${i} exceeds ${t} bytes`);n.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(n,r)}async function nr(e,t,i,n,r){let a=await Yf(e,bt.dirname(t));if(!a)return null;await r?.afterParentChainCaptured?.();let o;try{o=await it.lstat(t)}catch(d){if(d.code==="ENOENT")return null;throw d}if(!o.isFile()||o.isSymbolicLink())throw new Error(`${n} must be a regular file`);if(o.size>i)throw new Error(`${n} exceeds ${i} bytes`);let s=Ww(o),c=await it.realpath(t);if(!Fo(a[0].realPath,c))throw new Error(`${n} resolves outside its change`);let l=process.platform==="win32"?vl.O_RDONLY:vl.O_RDONLY|vl.O_NOFOLLOW|vl.O_NONBLOCK,u;try{u=await it.open(t,l)}catch(d){throw new Error(`${n} changed while opening`,{cause:d})}try{let[d,f,h]=await Promise.all([u.stat(),it.lstat(t),it.realpath(t)]);if(await gl(a),!d.isFile()||!f.isFile()||f.isSymbolicLink()||h!==c||!Mo(s,d)||!Mo(s,f))throw new Error(`${n} changed while opening`);await r?.afterOpen?.();let m=await C_(u,i,n);await r?.beforeFinalCheck?.();let[p,v,S]=await Promise.all([u.stat(),it.lstat(t),it.realpath(t)]);if(await gl(a),!v.isFile()||v.isSymbolicLink()||S!==c||!Mo(s,p)||!Mo(s,v))throw new Error(`${n} changed while reading`);let k;try{k=new E_("utf-8",{fatal:!0}).decode(m)}catch(N){throw new Error(`${n} is not valid UTF-8`,{cause:N})}return{text:k,target:{exists:!0,identity:s,realPath:c}}}finally{await u.close()}}async function P_(e,t,i){let n=await Yf(e,bt.dirname(t));if(!n)return{exists:!1};let r;try{r=await it.lstat(t)}catch(o){if(o.code==="ENOENT")return{exists:!1};throw o}if(!r.isFile()||r.isSymbolicLink())throw new Error(`${i} must be a regular file`);let a=await it.realpath(t);if(!Fo(n[0].realPath,a))throw new Error(`${i} resolves outside its change`);return await gl(n),{exists:!0,identity:Ww(r),realPath:a}}async function x_(e,t,i,n){let r=await Yf(e,bt.dirname(t));if(!r){if(!i.exists)return;throw new Error(`${n} parent changed before commit`)}let a;try{a=await it.lstat(t)}catch(o){if(o.code==="ENOENT"&&!i.exists)return;throw new Error(`${n} changed before commit`,{cause:o})}if(!i.exists||!a.isFile()||a.isSymbolicLink()||!Mo(i.identity,a)||await it.realpath(t)!==i.realPath)throw new Error(`${n} changed before commit`);await gl(r)}async function wl(e){if(Buffer.byteLength(e.content,"utf8")>e.maxBytes)throw new Error(`${e.label} exceeds ${e.maxBytes} bytes`);let i=e.expected??await P_(e.changeDir,e.file,e.label);if(i.exists&&i.identity.size>e.maxBytes)throw new Error(`${e.label} exceeds ${e.maxBytes} bytes`);await $e(e.file,e.content,{containedRoot:e.changeDir,beforeCommit:async()=>{await e.hooks?.beforeCommit?.(),await x_(e.changeDir,e.file,i,e.label)}});let n=await nr(e.changeDir,e.file,e.maxBytes,e.label);if(!n||n.text!==e.content)throw new Error(`${e.label} commit could not be verified`)}function Jw(e,t){try{return JSON.parse(e)}catch(i){throw new Error(`${t} contains invalid JSON`,{cause:i})}}function zw(e){return`${JSON.stringify(e,null,2)} -`}function Rn(e){return ml(e)}function Gw(e,t,i){return qw(e,t,i,ut)}async function be(e,t){let i=En(e,"stateRef"),n=await nr(e,i,Xe.runStateBytes,"Native Run state",t);return n?ml(Jw(n.text,"Native Run state")):null}async function rr(e,t,i){let n=ml(t);await wl({changeDir:e,file:En(e,"stateRef"),content:zw(n),maxBytes:Xe.runStateBytes,label:"Native Run state",hooks:i})}async function qe(e,t,i){let n=En(e,"trajectoryRef",t),r=await nr(e,n,Xe.trajectoryBytes,"Native Run trajectory",i);if(!r)return[];let a=r.text.split(/\r?\n/u).map((o,s)=>({line:o,number:s+1})).filter(({line:o})=>o.length>0);if(a.length>Xe.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${Xe.trajectoryEvents} events`);return a.map(({line:o,number:s})=>{try{return JSON.parse(o)}catch(c){throw new Error(`Invalid Native Run trajectory event at line ${s}`,{cause:c})}})}async function Uw(e,t,i){return(await nr(e,En(e,"trajectoryRef",t),Xe.trajectoryBytes,"Native Run trajectory",i))?.text??null}async function Kw(e,t,i,n,r){if(!/^[a-f0-9]{64}$/u.test(n))throw new Error("Native Run trajectory expected hash is invalid");let a=En(e,"trajectoryRef",t),o=await nr(e,a,Xe.trajectoryBytes,"Native Run trajectory");if(!o)throw new Error("Native Run trajectory disappeared before repair");if(S_("sha256").update(o.text,"utf8").digest("hex")!==n)throw new Error("Native Run trajectory changed before repair");await wl({changeDir:e,file:a,content:i,maxBytes:Xe.trajectoryBytes,label:"Native Run trajectory",expected:o.target,hooks:r})}async function Yw(e,t,i,n){let r=En(e,"trajectoryRef",t),a=`${JSON.stringify(i)} -`;if(Buffer.byteLength(a,"utf8")>Xe.trajectoryEventBytes)throw new Error(`Native Run trajectory event exceeds ${Xe.trajectoryEventBytes} bytes`);let o=await nr(e,r,Xe.trajectoryBytes,"Native Run trajectory");if((o?o.text.split(/\r?\n/u).filter(c=>c.length>0).length:0)>=Xe.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${Xe.trajectoryEvents} events`);await wl({changeDir:e,file:r,content:`${o?.text??""}${a}`,maxBytes:Xe.trajectoryBytes,label:"Native Run trajectory",expected:o?.target??{exists:!1},hooks:n})}async function ea(e,t,i){let n=await nr(e,En(e,"checkpointRef",t),Xe.checkpointBytes,"Native Run checkpoint",i);return n?Jw(n.text,"Native Run checkpoint"):null}async function Xw(e,t,i,n){await wl({changeDir:e,file:En(e,"checkpointRef",t),content:zw(i),maxBytes:Xe.checkpointBytes,label:"Native Run checkpoint",hooks:n})}var T_=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Nl=class extends Error{constructor(i){super(i.status==="repairable"?`Native trajectory has an incomplete final line at ${i.file}:${i.line}; run doctor --repair`:`Native trajectory is invalid at ${i.file}:${i.line}: ${i.message}`);this.inspection=i;this.name="NativeTrajectoryRepairRequiredError"}inspection;code="native-trajectory-tail-repair-required"};function Xf(e){return A_("sha256").update(e).digest("hex")}function __(e,t){if(!T_.test(t))throw new Error(`Invalid Native change name: ${t}`);let i=yl.join(e.changesDir,t);if(!$(e.changesDir,i))throw new Error("Native change path escaped");return yl.join(i,"runtime","trajectory.jsonl")}function I_(e){let t=e.split(/\n/u),i=0;for(let n=0;n=Math.max(0,t.length-1)}function O_(e,t){let i=t.lastIndexOf(10),n=t.subarray(0,i+1),r=I_(n.toString("utf8"));if(r.status==="invalid")return{status:"invalid",file:e,line:r.line,message:r.message};if(i===t.length-1)return{status:"clean",file:e};let a=t.subarray(i+1),o=a.toString("utf8"),s=r.count+1,c,l;try{JSON.parse(o.endsWith("\r")?o.slice(0,-1):o),c="missing-newline",l=Buffer.concat([t,Buffer.from(` -`)])}catch(d){if(!j_(d,o))return{status:"invalid",file:e,line:s,message:d.message};c="incomplete-json",l=n}return{inspection:{status:"repairable",file:e,reason:c,line:s,originalHash:Xf(t),targetHash:Xf(l),tailHash:Xf(a),discardedBytes:c==="incomplete-json"?a.length:0},targetContent:l.toString("utf8")}}async function Qw(e,t){let i=__(e,t);await x(e.nativeRoot,i);let n=yl.join(e.changesDir,t),r=await Uw(n,ut.trajectoryRef);return r===null?{status:"clean",file:i}:O_(i,Buffer.from(r))}async function ta(e,t){let i=await Qw(e,t);return"inspection"in i?i.inspection:i}async function Lo(e,t){let i=await ta(e,t);if(i.status!=="clean")throw new Nl(i)}async function Zw(e,t,i){return te(e,`repair trajectory tail for ${t}`,async()=>{let n=await Qw(e,t);if(!("inspection"in n)){if(n.status==="clean")return null;throw new Nl(n)}try{await Kw(yl.join(e.changesDir,t),ut.trajectoryRef,n.targetContent,n.inspection.originalHash,{beforeCommit:i?.beforeCommit})}catch(a){throw/changed (?:before|while)/iu.test(a.message)?new Error(`Native trajectory changed while preparing tail repair for ${t}; inspect it again before retrying`,{cause:a}):a}if((await ta(e,t)).status!=="clean")throw new Error(`Native trajectory tail repair did not produce a clean file for ${t}`);return n.inspection})}import{createHash as D_}from"node:crypto";import{promises as kl}from"node:fs";import Cn from"node:path";import{execFileSync as $_}from"child_process";import bl from"path";function Bo(e,t){return $_("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function H_(e,t){let i=bl.normalize(e),n=bl.normalize(t);return process.platform==="win32"?i.toLowerCase()===n.toLowerCase():i===n}function Qf(e){try{let t=bl.resolve(Bo(e,["rev-parse","--show-toplevel"])),n=Bo(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),r=n?bl.resolve(n.slice(9)):t,a=null;try{a=Bo(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!H_(t,r),currentWorktreeRoot:t,primaryWorktreeRoot:r,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function ey(e,t){try{return Bo(e,["check-ref-format","--branch",t]),Bo(e,["show-ref","--verify",`refs/heads/${t}`]),!0}catch{return!1}}var qo=/^[a-f0-9]{64}$/u,M_=16*1024,Zf=process.platform,F_=new Set(["workspace-root-changed","workspace-inspection-unavailable"]);function ia(e){return F_.has(e)}function ry(e,t){let i=Cn.relative(e,t);return Cn.isAbsolute(i)||i===".."||i.startsWith(`..${Cn.sep}`)?null:i.replaceAll("\\","/")||"."}function ay(e){return Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127})}function oy(e,t){if(e.length===0||ay(e)||e.includes("\\")||Cn.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes(".."))throw new Error(`${t} must be a portable project-relative path`);let i=Cn.posix.normalize(e);if(i!==e||i===".."||i.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return i}function eh(e,t){return D_("sha256").update(`${e} -${t}`).digest("hex")}async function ty(e,t){let i=await kl.realpath(t),n=await kl.lstat(i);if(!n.isDirectory()||n.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let r=Zf==="win32"?Cn.normalize(i).toLowerCase():i;return eh(e,`${r} +${Buffer.byteLength(n)}:${n}`)}function Jf(e){return e.reason==="git-enumeration-limit"||e.reason==="git-selection-changed"||e.reason==="physical-enumeration-limit"||e.reason==="physical-selection-changed"}function ul(e){for(let t=e.length-1;t>=0;t-=1){let i=e[t];if(!Jf(i))return e.splice(t,1),i}return null}function yn(e,t){let i={...e,birthtime:e.birthtimeMs},n={...t,birthtime:t.birthtimeMs};return Ue(i,n)?M(i,n):M(i,n)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function a_(e,t,i,n){if(!F(n))return{status:"budget-exhausted"};let r;try{r=await fe.open(e,"r")}catch(c){if(!F(n))return{status:"budget-exhausted"};throw c}if(!F(n))return await r.close(),{status:"budget-exhausted"};let a=dl("sha256"),o=Buffer.allocUnsafe(Math.min(64*1024,t+1)),s=0;try{if(!F(n))return{status:"budget-exhausted"};let c=await r.stat();if(!F(n))return{status:"budget-exhausted"};if(!c.isFile()||!yn(i,c))return{status:"changed"};for(;;){if(!F(n))return{status:"budget-exhausted"};let l=t+1-s;if(l<1)return{status:"changed"};let u=await r.read(o,0,Math.min(o.length,l),null);if(!F(n))return{status:"budget-exhausted"};if(u.bytesRead===0){if(!F(n))return{status:"budget-exhausted"};let d=await r.stat();return F(n)?!d.isFile()||!yn(c,d)?{status:"changed"}:{status:"complete",hash:a.digest("hex"),bytes:s,finalStat:d}:{status:"budget-exhausted"}}if(s+u.bytesRead>t)return{status:"changed"};a.update(o.subarray(0,u.bytesRead)),s+=u.bytesRead}}finally{await r.close()}}function _t(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function It(e,t,i){let n=Object.keys(e).find(r=>!t.has(r));if(n)throw new Error(`${i} contains unknown field: ${n}`)}function Yr(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function mi(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function Mw(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0"))throw new Error(`${t} must be a normalized project-relative path`);let i=z.posix.normalize(e);if(i!==e||z.posix.isAbsolute(e)||i===".."||i.startsWith("../"))throw new Error(`${t} must stay inside the project root`);return e}function o_(e,t){let i=_t(e,`Native snapshot entry ${t}`);It(i,jT,`Native snapshot entry ${t}`);let n=Mw(i.path,`Native snapshot entry ${t} path`);if(typeof i.hash!="string"||!fl.test(i.hash))throw new Error(`Native snapshot entry ${t} hash is invalid`);if(i.type!=="file")throw new Error(`Native snapshot entry ${t} type is invalid`);let r={path:n,hash:i.hash,size:mi(i.size,`Native snapshot entry ${t} size`),type:"file"};if(i.gitObjectId!==void 0){if(typeof i.gitObjectId!="string"||!xw.test(i.gitObjectId))throw new Error(`Native snapshot entry ${t} gitObjectId is invalid`);r.gitObjectId=i.gitObjectId}return r}function s_(e,t){let i=_t(e,`Native snapshot omission ${t}`);if(It(i,OT,`Native snapshot omission ${t}`),!DT.has(i.type))throw new Error(`Native snapshot omission ${t} type is invalid`);if(!MT.has(i.reason))throw new Error(`Native snapshot omission ${t} reason is invalid`);return{path:Mw(i.path,`Native snapshot omission ${t} path`),size:i.size===null?null:mi(i.size,`Native snapshot omission ${t} size`),type:i.type,reason:i.reason}}function c_(e){let t=_t(e,"Native snapshot omission overflow");if(It(t,$T,"Native snapshot omission overflow"),typeof t.hash!="string"||!fl.test(t.hash))throw new Error("Native snapshot omission overflow hash is invalid");let i=`native-snapshot://omitted-overflow/${t.hash}`;if(t.ref!==i)throw new Error("Native snapshot omission overflow ref is invalid");return{ref:i,hash:t.hash,count:Yr(t.count,"Native snapshot omission overflow count")}}function Kr(e,t){let i=_t(e,t);if(It(i,TT,t),typeof i.hash!="string"||!fl.test(i.hash))throw new Error(`${t} hash is invalid`);if(typeof i.overflow!="boolean")throw new Error(`${t} overflow flag is invalid`);let n=mi(i.recordCount,`${t} recordCount`),r=mi(i.storedRecordCount,`${t} storedRecordCount`),a=mi(i.stdoutBytes,`${t} stdoutBytes`);if(r>n||!i.overflow&&r!==n)throw new Error(`${t} stored record count is inconsistent`);return{hash:i.hash,recordCount:n,storedRecordCount:r,stdoutBytes:a,overflow:i.overflow}}function Rw(e){let t=_t(e,"Native Git selection evidence");if(It(t,AT,"Native Git selection evidence"),t.schema!=="comet.native.git-selection.v1")throw new Error("Native Git selection evidence schema is invalid");if(t.status!=="overflow"&&t.status!=="changed"&&t.status!=="overflow-and-changed")throw new Error("Native Git selection evidence status is invalid");let i=Kr(t.stageBefore,"Native Git selection stageBefore"),n=Kr(t.combined,"Native Git selection combined"),r=Kr(t.stageAfter,"Native Git selection stageAfter"),a=Kr(t.finalStageBefore,"Native Git selection finalStageBefore"),o=Kr(t.finalCombined,"Native Git selection finalCombined"),s=Kr(t.finalStageAfter,"Native Git selection finalStageAfter"),c=[i,n,r,a,o,s].some(d=>d.overflow),l=!Nn(i,r)||!Nn(r,a)||!Nn(n,o)||!Nn(a,s),u=c&&l?"overflow-and-changed":c?"overflow":"changed";if(!c&&!l)throw new Error("Native Git selection evidence must describe an exceptional selection");if(t.status!==u)throw new Error("Native Git selection evidence status is inconsistent");return{schema:"comet.native.git-selection.v1",status:u,stageBefore:i,combined:n,stageAfter:r,finalStageBefore:a,finalCombined:o,finalStageAfter:s}}function Cw(e,t){let i=_t(e,t);if(It(i,IT,t),typeof i.hash!="string"||!fl.test(i.hash))throw new Error(`${t} hash is invalid`);if(typeof i.overflow!="boolean"||typeof i.unstable!="boolean")throw new Error(`${t} flags are invalid`);let n=mi(i.visitedNodeCount,`${t} visitedNodeCount`),r=mi(i.recordCount,`${t} recordCount`),a=mi(i.storedRecordCount,`${t} storedRecordCount`),o=mi(i.encodedBytes,`${t} encodedBytes`);if(a>r||!i.overflow&&a!==r)throw new Error(`${t} stored record count is inconsistent`);return{hash:i.hash,visitedNodeCount:n,recordCount:r,storedRecordCount:a,encodedBytes:o,overflow:i.overflow,unstable:i.unstable}}function l_(e){let t=_t(e,"Native physical selection evidence");if(It(t,_T,"Native physical selection evidence"),t.schema!=="comet.native.physical-selection.v1")throw new Error("Native physical selection evidence schema is invalid");if(t.status!=="overflow"&&t.status!=="changed"&&t.status!=="overflow-and-changed")throw new Error("Native physical selection evidence status is invalid");let i=Cw(t.before,"Native physical selection before"),n=Cw(t.after,"Native physical selection after"),r=i.overflow||n.overflow,a=i.unstable||n.unstable||!$w(i,n);if(!r&&!a)throw new Error("Native physical selection evidence must describe an exceptional selection");let o=r&&a?"overflow-and-changed":r?"overflow":"changed";if(t.status!==o)throw new Error("Native physical selection evidence status is inconsistent");return{schema:"comet.native.physical-selection.v1",status:o,before:i,after:n}}function Ii(e){let t=_t(e,"Native content snapshot manifest");if(It(t,ET,"Native content snapshot manifest"),t.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!HT.has(t.origin))throw new Error("Native content snapshot origin is invalid");let i;if(t.capture!==void 0){let y=_t(t.capture,"Native content snapshot capture");if(It(y,PT,"Native content snapshot capture"),y.provider!=="git"&&y.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let w=y.gitSelection===void 0?void 0:Rw(y.gitSelection),g=y.physicalSelection===void 0?void 0:l_(y.physicalSelection),E=null;if(y.projection!==void 0){let O=_t(y.projection,"Native content snapshot projection");if(It(O,xT,"Native content snapshot projection"),O.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");E={provider:"git",...O.selection===void 0?{}:{selection:Rw(O.selection)}}}if(y.provider==="git"){if(g||E)throw new Error("Native Git capture cannot include physical or projection evidence");i={provider:"git",...w?{gitSelection:w}:{}}}else{if(w)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(g&&E)throw new Error("Native physical-tree capture cannot combine selection and projection");i=E?{provider:"physical-tree",projection:E}:{provider:"physical-tree",...g?{physicalSelection:g}:{}}}}if(typeof t.createdAt!="string"||Number.isNaN(Date.parse(t.createdAt)))throw new Error("Native content snapshot timestamp is invalid");if(typeof t.complete!="boolean")throw new Error("Native content snapshot complete flag is invalid");let n=_t(t.limits,"Native content snapshot limits");It(n,RT,"Native content snapshot limits");let r={maxFiles:Yr(n.maxFiles,"Native snapshot maxFiles"),maxFileBytes:Yr(n.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:Yr(n.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:Yr(n.maxManifestBytes,"Native snapshot maxManifestBytes"),...n.maxDurationMs===void 0?{}:{maxDurationMs:Yr(n.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(t.policy!==void 0){let y=_t(t.policy,"Native snapshot policy");if(It(y,CT,"Native snapshot policy"),y.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(y.include)||!Array.isArray(y.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=Dw({include:y.include,exclude:y.exclude,hash:y.hash,schema:"comet.native.snapshot-policy.v1"}).manifest}if(!Array.isArray(t.entries)||!Array.isArray(t.omitted))throw new Error("Native content snapshot entries and omissions must be arrays");let o=t.entries.map(o_),s=t.omitted.map(s_),c=mi(t.omittedCount,"Native content snapshot omittedCount"),l=t.omissionOverflow===void 0?void 0:c_(t.omissionOverflow);if(o.length>r.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(y=>y.size>r.maxFileBytes)||o.reduce((y,w)=>y+w.size,0)>r.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(y=>y.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>zf||c0&&l?.count!==u)throw new Error("Native content snapshot omission overflow is inconsistent");if(t.complete!==(c===0))throw new Error("Native content snapshot completeness is inconsistent");let d=s.filter(y=>y.reason==="git-enumeration-limit"),f=s.filter(y=>y.reason==="git-selection-changed");for(let y of[...d,...f])if(y.path!=="."||y.size!==null||y.type!=="directory")throw new Error("Native Git selection omission must use the project-root sentinel");if(d.length>1||f.length>1)throw new Error("Native Git selection omissions must not be duplicated");let h=i?.provider==="git"?i.gitSelection:i?.projection?.selection,m=h?.status==="overflow"||h?.status==="overflow-and-changed",p=h?.status==="changed"||h?.status==="overflow-and-changed";if(m!==(d.length===1))throw new Error("Native Git enumeration omission and selection evidence are inconsistent");if(p!==(f.length===1))throw new Error("Native Git selection-change omission and selection evidence are inconsistent");let v=s.filter(y=>y.reason==="physical-enumeration-limit"),S=s.filter(y=>y.reason==="physical-selection-changed");for(let y of[...v,...S])if(y.path!=="."||y.size!==null||y.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(v.length>1||S.length>1)throw new Error("Native physical selection omissions must not be duplicated");let k=i?.physicalSelection,N=k?.status==="overflow"||k?.status==="overflow-and-changed",b=k?.status==="changed"||k?.status==="overflow-and-changed";if(N!==(v.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(b!==(S.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");let R={schema:"comet.native.content-snapshot.v1",origin:t.origin,...i?{capture:i}:{},createdAt:t.createdAt,complete:t.complete,limits:r,...a?{policy:a}:{},entries:o,omitted:s,omittedCount:c,...l?{omissionOverflow:l}:{}};if(Kf(R)>r.maxManifestBytes)throw new Error("Native content snapshot exceeds its manifest byte limit");return R}async function kn(e,t,i={}){let n=Ii(t);if(n.capture?.provider==="git"||n.capture?.projection||n.capture?.physicalSelection)return n;let r=z.resolve(e.projectRoot),a=Aw(i),o=Tw(i.gitSelectionLimits),s=await jw(a,e,o,i.gitSelectionHooks);if(s===null)return n;let c=new Set(Hw(s).filter(g=>Io(e,g))),l=[...s.gitlinks].filter(g=>c.has(g)),u=[...s.nestedRepositories].filter(g=>Io(e,g)),d=(g,E)=>E.some(O=>g===O||g.startsWith(`${O}/`)),f=g=>d(g,l),h=g=>d(g,u),m=[...n.entries.map(g=>g.path),...n.omitted.flatMap(g=>g.type==="directory"?[g.path,`${g.path}/`]:[g.path])].filter(g=>!c.has(g)&&!f(g)&&!h(g)),p=await zT(a,r,m),v=n.entries.filter(g=>!f(g.path)&&!h(g.path)&&Io(e,g.path)&&(c.has(g.path)||!p.has(g.path)));await Ow(a,e,o,s,i.gitSelectionHooks?.outputChunkBytes);let S=[...s.omissions];for(let g of l)S.push({path:g,size:null,type:"directory",reason:"legacy-gitlink-boundary"});v.sort((g,E)=>g.path.localeCompare(E.path,"en"));let k=n.omitted.filter(g=>f(g.path)||h(g.path)||!Io(e,g.path)?!1:p.has(g.path)?c.has(g.path)||[...c].some(E=>E.startsWith(`${g.path}/`)):!0);for(let g of S)k.some(E=>E.path===g.path&&E.reason===g.reason)||k.push(g);k.sort((g,E)=>g.path.localeCompare(E.path,"en"));let N=n.omissionOverflow?.count??0,b=n.omissionOverflow?.hash??D("comet.native.snapshot-omission-overflow.v1");s.overflow&&(N+=s.overflow.count,b=Oo(b,"git-selection",{source:"git-selection",...s.overflow}));let R=g=>{N+=1,b=Oo(b,"omission",g)};for(;k.length>zf;){let g=ul(k);if(g===null)throw new Error("Projected Native snapshot has too many required selection-integrity omissions");R(g)}let y=()=>({...n,capture:{provider:"physical-tree",projection:{provider:"git",...s.evidence?{selection:s.evidence}:{}}},complete:k.length+N===0,entries:v,omitted:k,omittedCount:k.length+N,...N>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${b}`,hash:b,count:N}}:{}}),w=y();for(;Kf(w)>n.limits.maxManifestBytes;){let g=ul(k);if(g===null)throw new Error("Projected Native snapshot cannot fit its manifest byte limit");R(g),w=y()}return Ii(w)}function Fw(e,t){if(!ST.test(t))throw new Error(`Invalid Native change name: ${t}`);let i=z.join(e.changesDir,t);if(!$(e.changesDir,i))throw new Error("Native change path escaped");return z.join(i,"runtime","baseline-manifest.json")}async function $o(e,t={}){let i={maxFiles:t.limits?.maxFiles??sl.maxFiles,maxFileBytes:t.limits?.maxFileBytes??sl.maxFileBytes,maxTotalBytes:t.limits?.maxTotalBytes??sl.maxTotalBytes,maxManifestBytes:t.limits?.maxManifestBytes??sl.maxManifestBytes,...t.limits?.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},n=Dw(t.policy),r=Aw({...t,deadlineMs:t.deadlineMs??i.maxDurationMs}),a=Tw(t.gitSelectionLimits),o=WT(t.physicalSelectionLimits);if(i.maxFiles<1||i.maxFileBytes<1||i.maxTotalBytes<1||i.maxManifestBytes<1)throw new Error("Native snapshot limits must be positive");let s=z.resolve(e.projectRoot),c=await fe.realpath(s),l=z.resolve(e.nativeRoot),u=await fe.realpath(l),d=z.resolve(e.configFile),f=z.join(s,".comet","current-change.json"),h=t_(s,t.denylist??[]),m=[],p=[],v=new Map,S=new Map,k=0,N=0,b=D("comet.native.snapshot-omission-overflow.v1"),R=0,y=!1,w=null,g=_=>{N+=1,b=Oo(b,"omission",_)},E=_=>{if(k+=1,p.length{k+=_.count,N+=_.count,b=Oo(b,"git-selection",{source:"git-selection",..._})},B=_=>{N+=1,b=Oo(b,"manifest-entry",{reason:"manifest-size",entry:_})},q=async(_,T)=>{m.push(_),R+=_.size,v.set(_.path,T),y||(y=!0,await t.gitSelectionHooks?.afterFirstEntryCaptured?.(_.path))},U=(_,T)=>{let j=m.findIndex(de=>de.path===_);if(j<0)return;let[V]=m.splice(j,1);R-=V.size,v.delete(_),E(T)},oe=async(_,T,j,V)=>{if(!j.isFile()||j.isSymbolicLink()||!F(r))return;let de;try{de=await fe.realpath(_)}catch(A){if(!F(r))return;if(!Pe(A)&&!Ce(A))throw A;E({path:T,size:j.size,type:"file",reason:Ce(A)?"changed-during-read":"unreadable"});return}if(!F(r)||!$(c,de)||bn(u,de))return;if(m.length>=i.maxFiles){E({path:T,size:j.size,type:"file",reason:"file-count"});return}if(j.size>i.maxFileBytes){E({path:T,size:j.size,type:"file",reason:"file-size"});return}if(R+j.size>i.maxTotalBytes){E({path:T,size:j.size,type:"file",reason:"total-size"});return}let X,L,me;try{if(X=await a_(de,j.size,j,r),X.status==="budget-exhausted"||!F(r))return;if(X.status==="changed"){E({path:T,size:null,type:"file",reason:"changed-during-read"});return}if(!F(r)||(me=await fe.realpath(_),!F(r)))return;L=await fe.lstat(_)}catch(A){if(!F(r))return;if(!Pe(A)&&!Ce(A))throw A;E({path:T,size:j.size,type:"file",reason:Ce(A)?"changed-during-read":"unreadable"});return}if(F(r)){if(X.bytes!==j.size||me!==de||!yn(j,X.finalStat)||!yn(X.finalStat,L)||!L.isFile()||L.isSymbolicLink()||L.size!==j.size||L.mtimeMs!==j.mtimeMs||L.ctimeMs!==j.ctimeMs){E({path:T,size:L.isFile()?L.size:null,type:L.isFile()?"file":"other",reason:"changed-during-read"});return}F(r)&&await q({path:T,hash:X.hash,size:L.size,type:"file",...V===void 0?{}:{gitObjectId:V}},{kind:"file",target:_,realTarget:de,stat:L})}},ri=async(_,T,j)=>{if(!F(r))return;let V,de,X;try{if(V=await fe.readlink(_,{encoding:"buffer"}),!F(r)||(X=await fe.lstat(_),!F(r)))return;de=await fe.readlink(_,{encoding:"buffer"})}catch(A){if(!F(r))return;if(!Pe(A)&&!Ce(A))throw A;E({path:T,size:null,type:"other",reason:Ce(A)?"changed-during-read":"unreadable"});return}if(!F(r))return;if(!X.isSymbolicLink()||!yn(j,X)||X.mtimeMs!==j.mtimeMs||X.ctimeMs!==j.ctimeMs||!V.equals(de)){E({path:T,size:null,type:"other",reason:"changed-during-read"});return}let L=V.byteLength;if(m.length>=i.maxFiles){E({path:T,size:L,type:"other",reason:"file-count"});return}if(L>i.maxFileBytes){E({path:T,size:L,type:"other",reason:"file-size"});return}if(R+L>i.maxTotalBytes){E({path:T,size:L,type:"other",reason:"total-size"});return}let me=dl("sha256").update("symlink\0").update(V).digest("hex");F(r)&&await q({path:T,hash:me,size:L,type:"file"},{kind:"symlink",target:_,rawTarget:V,stat:X})},ai=async()=>{for(let[_,T]of[...v]){if(!F(r))return;if(T.kind==="file"){let L,me;try{if(L=await fe.realpath(T.target),!F(r))return;me=await fe.lstat(T.target)}catch(A){if(!F(r))return;if(!Pe(A)&&!Ce(A))throw A;U(_,{path:_,size:null,type:"file",reason:Pe(A)?"unreadable":"changed-during-read"});continue}if(!F(r))return;(L!==T.realTarget||!me.isFile()||me.isSymbolicLink()||!yn(T.stat,me)||me.size!==T.stat.size||me.mtimeMs!==T.stat.mtimeMs||me.ctimeMs!==T.stat.ctimeMs)&&U(_,{path:_,size:me.isFile()?me.size:null,type:me.isFile()?"file":"other",reason:"changed-during-read"});continue}if(T.kind==="symlink"){let L,me;try{if(L=await fe.lstat(T.target),!F(r))return;me=await fe.readlink(T.target,{encoding:"buffer"})}catch(A){if(!F(r))return;if(!Pe(A)&&!Ce(A))throw A;U(_,{path:_,size:null,type:"other",reason:Pe(A)?"unreadable":"changed-during-read"});continue}if(!F(r))return;(!L.isSymbolicLink()||!yn(T.stat,L)||L.mtimeMs!==T.stat.mtimeMs||L.ctimeMs!==T.stat.ctimeMs||!T.rawTarget.equals(me))&&U(_,{path:_,size:null,type:"other",reason:"changed-during-read"});continue}let j,V;try{if(j=await fe.realpath(T.target),!F(r))return;V=await fe.lstat(T.target)}catch{if(!F(r))return;U(_,{path:_,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!F(r))return;if(!(j===T.realTarget&&V.isDirectory()&&!V.isSymbolicLink()&&yn(T.stat,V)&&$(c,j)&&!bn(u,j))){U(_,{path:_,size:null,type:"directory",reason:"gitlink-changed"});continue}let X;try{if(!F(r))return;X=await kw(r,j)}catch(L){if(Xr(L))throw L;U(_,{path:_,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!F(r))return;X.dirty?U(_,{path:_,size:null,type:"directory",reason:"gitlink-dirty"}):X.hash!==T.hash&&U(_,{path:_,size:null,type:"directory",reason:"gitlink-changed"})}for(let[_,T]of S){if(!F(r))return;try{let j=await fe.lstat(T);if(!F(r))return;E({path:_,size:j.isFile()?j.size:null,type:j.isFile()?"file":j.isDirectory()?"directory":"other",reason:"changed-during-read"})}catch(j){if(!F(r))return;if(Ce(j))continue;if(!Pe(j))throw j;E({path:_,size:null,type:"file",reason:"unreadable"})}}},wt=await jw(r,e,a,t.gitSelectionHooks);if(wt===null){let _=await Nw({execution:r,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:h,policy:n,limits:o,hooks:t.physicalSelectionHooks});await t.physicalSelectionHooks?.afterInitialSelection?.();for(let V of _.records){if(V.type!=="file"&&V.type!=="symlink"||v.has(V.path))continue;if(Jt(r)<1)break;if(!Ew(n,V.path,r))continue;if(Jt(r)<1)break;let de=z.resolve(s,...V.path.split("/")),X;try{X=await fe.lstat(de)}catch(L){if(!F(r))break;if(!Pe(L)&&!Ce(L))throw L;E({path:V.path,size:null,type:"file",reason:Ce(L)?"changed-during-read":"unreadable"});continue}if(Jt(r)<1)break;if(V.type==="symlink"&&X.isSymbolicLink()){if(await ri(de,V.path,X),Jt(r)<1)break;continue}if(V.type!=="file"||!X.isFile()||X.isSymbolicLink()){E({path:V.path,size:X.isFile()?X.size:null,type:X.isDirectory()?"directory":X.isFile()?"file":"other",reason:"changed-during-read"});continue}if(await oe(de,V.path,X),Jt(r)<1)break}Jt(r)>=1&&await ai();let T=await Nw({execution:r,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:h,policy:n,limits:o}),j=ZT(_.evidence,T.evidence);w=j.evidence;for(let V of[..._.omissions,...T.omissions,...j.omissions])p.some(de=>de.path===V.path&&de.reason===V.reason)||E(V)}else{await t.gitSelectionHooks?.afterInitialSelection?.();let _=t.incrementalBaseline,T=new Map,j=!1;if(_){let A=Ii(_);for(let ve of A.entries)ve.gitObjectId!==void 0&&T.set(ve.path,ve);j=T.size>0}let V=new Set,de=!0;try{let A=await jo(r,s,["ls-files","-v","-z"],{...a,...t.gitSelectionHooks?.outputChunkBytes===void 0?{}:{outputChunkBytes:t.gitSelectionHooks.outputChunkBytes}});if(A.overflow)j=!1,de=!1,T.clear();else for(let ve of A.records){let ge=ll(ve),et=ge.indexOf(" "),Ge=et<0?null:Qr(ge.slice(et+1));if(et!==1||Ge===null)throw new Error("Native Git snapshot provider returned a malformed tagged record");ge[0]!=="H"&&V.add(Ge)}}catch(A){if(Xr(A))throw A;j=!1,de=!1,T.clear()}let X=new Set;try{let A=await cl(r,s,["ls-files","--modified","-z"],Wf);for(let ve of A.toString("utf8").split("\0")){let ge=Qr(ve);ge!==null&&X.add(ge)}}catch{j=!1,de=!1,T.clear()}let L=new Set,me=new Set;for(let A of Hw(wt)){if(v.has(A)||!Io(e,A))continue;if(Jt(r)<1)break;if(!Ew(n,A,r))continue;if(Jt(r)<1)break;let ve=z.resolve(s,...A.split("/"));if(ve===d||ve===f||h.some(yt=>bn(yt,ve)))continue;if(wt.gitlinks.has(A)){if(m.length>=i.maxFiles){E({path:A,size:0,type:"file",reason:"file-count"});continue}let yt,xs;try{[yt,xs]=await Promise.all([fe.realpath(ve),fe.lstat(ve)])}catch{E({path:A,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(xs.isSymbolicLink()||!xs.isDirectory()||!$(c,yt)||bn(u,yt)){E({path:A,size:null,type:"directory",reason:"gitlink-unavailable"});continue}try{let Ar=await kw(r,yt);if(Ar.dirty){E({path:A,size:null,type:"directory",reason:"gitlink-dirty"});continue}await q({path:A,hash:Ar.hash,size:0,type:"file"},{kind:"gitlink",target:ve,realTarget:yt,stat:xs,hash:Ar.hash})}catch(Ar){if(Xr(Ar))throw Ar;E({path:A,size:null,type:"directory",reason:"gitlink-unavailable"})}continue}let ge;try{ge=await fe.lstat(ve)}catch(yt){if(Ce(yt)&&wt.tracked.has(A)){S.set(A,ve);continue}if(!Pe(yt)&&!Ce(yt))throw yt;E({path:A,size:null,type:"file",reason:Ce(yt)?"changed-during-read":"unreadable"});continue}if(ge.isSymbolicLink()){await ri(ve,A,ge);continue}if(!ge.isFile()){wt.nestedRepositories.has(A)||E({path:A,size:null,type:"other",reason:"changed-during-read"});continue}let et=wt.trackedObjectIds.get(A),Ge=et?T.get(A):void 0;if(j&&Ge?.gitObjectId!==void 0&&Ge.gitObjectId===et&&!V.has(A)&&!X.has(A)){if(m.length>=i.maxFiles){E({path:A,size:Ge.size,type:"file",reason:"file-count"});continue}if(Ge.size>i.maxFileBytes){E({path:A,size:Ge.size,type:"file",reason:"file-size"});continue}if(R+Ge.size>i.maxTotalBytes){E({path:A,size:Ge.size,type:"file",reason:"total-size"});continue}m.push({...Ge}),R+=Ge.size,L.add(A);continue}let Hp=de&&!V.has(A)&&!X.has(A)?et:void 0;await oe(ve,A,ge,Hp),Hp!==void 0&&me.add(A)}if(await ai(),await t.gitSelectionHooks?.afterContentRevalidation?.(),await Ow(r,e,a,wt,t.gitSelectionHooks?.outputChunkBytes),L.size>0||j&&me.size>0){let A=await cl(r,s,["ls-files","--modified","-z"],Wf),ve=new Set;for(let ge of A.toString("utf8").split("\0")){let et=Qr(ge);et!==null&&ve.add(et)}for(let ge of L){if(!ve.has(ge))continue;let et=m.find(Ge=>Ge.path===ge);U(ge,{path:ge,size:et?.size??null,type:"file",reason:"changed-during-read"})}for(let ge of me){if(!ve.has(ge))continue;let et=m.find(Ge=>Ge.path===ge);et&&delete et.gitObjectId}}for(let A of wt.omissions)E(A);wt.overflow&&O(wt.overflow)}m.sort((_,T)=>_.path.localeCompare(T.path,"en")),p.sort((_,T)=>_.path.localeCompare(T.path,"en"));let bE=wt===null?{provider:"physical-tree",...w?{physicalSelection:w}:{}}:{provider:"git",...wt.evidence?{gitSelection:wt.evidence}:{}},$p=()=>({schema:"comet.native.content-snapshot.v1",origin:t.origin??"explicit",capture:bE,createdAt:(t.now??new Date).toISOString(),complete:k===0,limits:i,...n?{policy:n.manifest}:{},entries:m,omitted:p,omittedCount:k,...N>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${b}`,hash:b,count:N}}:{}}),Iu=$p();for(;Kf(Iu)>i.maxManifestBytes;){if(p.filter(T=>!Jf(T)).length>0){let T=Math.max(1,Math.ceil(p.length/4));for(let j=0;j0){let T=Math.max(1,Math.ceil(m.length/4));for(let j of m.splice(-T))k+=1,B(j)}else throw new Error("Native snapshot manifest byte limit is too small for its metadata");Iu=$p()}return Iu}async function Sn(e,t,i={}){let r=(await re(e.projectRoot))?.native.snapshot??zc;return $o(e,{...i,policy:t.policy,incrementalBaseline:t,limits:{maxFiles:r.max_files,maxFileBytes:r.max_total_bytes,maxTotalBytes:r.max_total_bytes,maxDurationMs:r.max_duration_ms},deadlineMs:r.max_duration_ms})}async function pl(e,t,i){let n=Fw(e,t);await x(e.nativeRoot,n),await le(n,Ii(i))}async function vi(e,t){let i=Fw(e,t);await x(e.nativeRoot,i);try{let n=await el({root:e.nativeRoot,file:i,maxBytes:kT,label:"Native baseline snapshot manifest"});return Ii(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}import{createHash as A_}from"crypto";import yl from"path";import u_ from"path";var ut=Object.freeze({stateRef:"runtime/run-state.json",pendingRef:"runtime/pending-action.json",trajectoryRef:"runtime/trajectory.jsonl",contextRef:"runtime/context.md",artifactsRef:"runtime/artifacts.json",checkpointRef:"runtime/checkpoints/latest.json",snapshotsRef:"runtime/skill-snapshots"});function d_(e){if(e.length===0||u_.isAbsolute(e)||/^(?:[A-Za-z]:|[\\/]|~)/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error("Run storage ref must stay inside the Run root")}function Lw(e){for(let t of Object.values(e))d_(t)}import{createHash as S_}from"node:crypto";import{constants as vl,promises as it}from"node:fs";import bt from"node:path";import{TextDecoder as E_}from"node:util";import y_ from"path";var g_=Ts(uo(),1);var Bw=(e,t)=>{let i=e[t];return i==null?null:String(i)};function Do(e,t){let i=e[t];if(typeof i!="string"||i.length===0)throw new Error(`Invalid Run state: ${t} must be a non-empty string`);return i}function Ho(e,t){let i=Do(e,t);if(y_.isAbsolute(i)||/^(?:[A-Za-z]:|[\\/]|~)/u.test(i)||i.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Run state: ${t} must stay inside the change directory`);return i}function N_(e){let t=e.run_retries??"{}",i;try{i=typeof t=="string"?JSON.parse(t):t}catch(n){throw new Error("Invalid Run state: run_retries must be a JSON object",{cause:n})}if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Invalid Run state: run_retries must be a JSON object");for(let n of Object.values(i))if(!Number.isInteger(n)||Number(n)<0)throw new Error("Invalid Run state: retry counts must be non-negative integers");return i}function qw(e){if(!e.run_id)return null;let t=Do(e,"run_id"),i=Do(e,"skill"),n=Do(e,"skill_version"),r=Do(e,"skill_hash"),a=Ho(e,"pending_ref"),o=Ho(e,"trajectory_ref"),s=Ho(e,"context_ref"),c=Ho(e,"artifacts_ref"),l=Ho(e,"checkpoint_ref"),u=Number(e.iteration);if(!Number.isInteger(u)||u<0)throw new Error("Invalid Run state: iteration must be a non-negative integer");if(e.orchestration!=="deterministic"&&e.orchestration!=="adaptive")throw new Error("Invalid Run state: orchestration must be deterministic or adaptive");if(e.run_status!=="running"&&e.run_status!=="waiting"&&e.run_status!=="completed"&&e.run_status!=="failed")throw new Error("Invalid Run state: run_status is invalid");return{runId:t,skill:i,skillVersion:n,skillHash:r,orchestration:e.orchestration,currentStep:Bw(e,"current_step"),iteration:u,pending:Bw(e,"pending"),pendingRef:a,trajectoryRef:o,contextRef:s,artifactsRef:c,checkpointRef:l,status:e.run_status,retries:N_(e)}}var _B=256*1024;var b_=new Set(["runId","skill","skillVersion","skillHash","orchestration","currentStep","iteration","pending","pendingRef","trajectoryRef","contextRef","artifactsRef","checkpointRef","status","retries"]);function k_(e){let t={run_id:e.runId,skill:e.skill,skill_version:e.skillVersion,skill_hash:e.skillHash,orchestration:e.orchestration,current_step:e.currentStep,iteration:e.iteration,pending:e.pending,pending_ref:e.pendingRef,trajectory_ref:e.trajectoryRef,context_ref:e.contextRef,artifacts_ref:e.artifactsRef,checkpoint_ref:e.checkpointRef,run_status:e.status,run_retries:JSON.stringify(e.retries)},i=qw(t);if(!i)throw new Error("Invalid Run state: runId must be a non-empty string");return i}function ml(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid Run state: stored value must be an object");let t=e,i=Object.keys(t).find(n=>!b_.has(n));if(i)throw new Error(`Invalid Run state: unknown field ${i}`);if(t.currentStep!==null&&(typeof t.currentStep!="string"||t.currentStep.length===0))throw new Error("Invalid Run state: currentStep must be a non-empty string or null");if(t.pending!==null&&(typeof t.pending!="string"||t.pending.length===0))throw new Error("Invalid Run state: pending must be a non-empty string or null");if(!t.retries||typeof t.retries!="object"||Array.isArray(t.retries))throw new Error("Invalid Run state: retries must be an object");return k_(t)}function Vw(e,t,i,n){return Lw(n),{runId:t,skill:e.definition.metadata.name,skillVersion:e.definition.metadata.version,skillHash:i,orchestration:e.definition.orchestration.mode,currentStep:e.definition.orchestration.entry??null,iteration:0,pending:null,pendingRef:n.pendingRef,trajectoryRef:n.trajectoryRef,contextRef:n.contextRef,artifactsRef:n.artifactsRef,checkpointRef:n.checkpointRef,status:"running",retries:{}}}var Xe={runStateBytes:256*1024,trajectoryBytes:8*1024*1024,trajectoryEvents:4096,trajectoryEventBytes:256*1024,checkpointBytes:256*1024,pendingActionBytes:256*1024,contextBytes:1024*1024,artifactsBytes:1024*1024};function Fo(e,t){let i=bt.relative(e,t);return i===""||!bt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${bt.sep}`)}function Jw(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Mo(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function R_(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function En(e,t,i){let n=ut[t];if(i!==void 0&&i!==n)throw new Error(`Native Run ${t} ref must be ${n}`);let r=bt.resolve(e),a=bt.resolve(r,...n.split("/"));if(!Fo(r,a))throw new Error("Native Run path must stay inside its change");return a}async function Ww(e){let t=await it.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native Run parent must be a real directory: ${e}`);return{path:e,realPath:await it.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Yf(e,t){let i=bt.resolve(e),n=bt.resolve(t);if(!Fo(i,n))throw new Error("Native Run path is outside its change");let r=[await Ww(i)],a=i;for(let o of bt.relative(i,n).split(bt.sep).filter(Boolean)){a=bt.join(a,o);let s;try{s=await Ww(a)}catch(c){if(c.code==="ENOENT")return null;throw c}if(!Fo(r[0].realPath,s.realPath))throw new Error(`Native Run parent resolves outside its change: ${a}`);r.push(s)}return r}async function gl(e){for(let t of e){let i=await it.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!R_(t,i)||await it.realpath(t.path)!==t.realPath)throw new Error(`Native Run parent changed during I/O: ${t.path}`)}}async function C_(e,t,i){let n=[],r=0,a=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let o=t+1-r,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(r+=s,r>t)throw new Error(`${i} exceeds ${t} bytes`);n.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(n,r)}async function nr(e,t,i,n,r){let a=await Yf(e,bt.dirname(t));if(!a)return null;await r?.afterParentChainCaptured?.();let o;try{o=await it.lstat(t)}catch(d){if(d.code==="ENOENT")return null;throw d}if(!o.isFile()||o.isSymbolicLink())throw new Error(`${n} must be a regular file`);if(o.size>i)throw new Error(`${n} exceeds ${i} bytes`);let s=Jw(o),c=await it.realpath(t);if(!Fo(a[0].realPath,c))throw new Error(`${n} resolves outside its change`);let l=process.platform==="win32"?vl.O_RDONLY:vl.O_RDONLY|vl.O_NOFOLLOW|vl.O_NONBLOCK,u;try{u=await it.open(t,l)}catch(d){throw new Error(`${n} changed while opening`,{cause:d})}try{let[d,f,h]=await Promise.all([u.stat(),it.lstat(t),it.realpath(t)]);if(await gl(a),!d.isFile()||!f.isFile()||f.isSymbolicLink()||h!==c||!Mo(s,d)||!Mo(s,f))throw new Error(`${n} changed while opening`);await r?.afterOpen?.();let m=await C_(u,i,n);await r?.beforeFinalCheck?.();let[p,v,S]=await Promise.all([u.stat(),it.lstat(t),it.realpath(t)]);if(await gl(a),!v.isFile()||v.isSymbolicLink()||S!==c||!Mo(s,p)||!Mo(s,v))throw new Error(`${n} changed while reading`);let k;try{k=new E_("utf-8",{fatal:!0}).decode(m)}catch(N){throw new Error(`${n} is not valid UTF-8`,{cause:N})}return{text:k,target:{exists:!0,identity:s,realPath:c}}}finally{await u.close()}}async function P_(e,t,i){let n=await Yf(e,bt.dirname(t));if(!n)return{exists:!1};let r;try{r=await it.lstat(t)}catch(o){if(o.code==="ENOENT")return{exists:!1};throw o}if(!r.isFile()||r.isSymbolicLink())throw new Error(`${i} must be a regular file`);let a=await it.realpath(t);if(!Fo(n[0].realPath,a))throw new Error(`${i} resolves outside its change`);return await gl(n),{exists:!0,identity:Jw(r),realPath:a}}async function x_(e,t,i,n){let r=await Yf(e,bt.dirname(t));if(!r){if(!i.exists)return;throw new Error(`${n} parent changed before commit`)}let a;try{a=await it.lstat(t)}catch(o){if(o.code==="ENOENT"&&!i.exists)return;throw new Error(`${n} changed before commit`,{cause:o})}if(!i.exists||!a.isFile()||a.isSymbolicLink()||!Mo(i.identity,a)||await it.realpath(t)!==i.realPath)throw new Error(`${n} changed before commit`);await gl(r)}async function wl(e){if(Buffer.byteLength(e.content,"utf8")>e.maxBytes)throw new Error(`${e.label} exceeds ${e.maxBytes} bytes`);let i=e.expected??await P_(e.changeDir,e.file,e.label);if(i.exists&&i.identity.size>e.maxBytes)throw new Error(`${e.label} exceeds ${e.maxBytes} bytes`);await $e(e.file,e.content,{containedRoot:e.changeDir,beforeCommit:async()=>{await e.hooks?.beforeCommit?.(),await x_(e.changeDir,e.file,i,e.label)}});let n=await nr(e.changeDir,e.file,e.maxBytes,e.label);if(!n||n.text!==e.content)throw new Error(`${e.label} commit could not be verified`)}function zw(e,t){try{return JSON.parse(e)}catch(i){throw new Error(`${t} contains invalid JSON`,{cause:i})}}function Gw(e){return`${JSON.stringify(e,null,2)} +`}function Rn(e){return ml(e)}function Uw(e,t,i){return Vw(e,t,i,ut)}async function be(e,t){let i=En(e,"stateRef"),n=await nr(e,i,Xe.runStateBytes,"Native Run state",t);return n?ml(zw(n.text,"Native Run state")):null}async function rr(e,t,i){let n=ml(t);await wl({changeDir:e,file:En(e,"stateRef"),content:Gw(n),maxBytes:Xe.runStateBytes,label:"Native Run state",hooks:i})}async function qe(e,t,i){let n=En(e,"trajectoryRef",t),r=await nr(e,n,Xe.trajectoryBytes,"Native Run trajectory",i);if(!r)return[];let a=r.text.split(/\r?\n/u).map((o,s)=>({line:o,number:s+1})).filter(({line:o})=>o.length>0);if(a.length>Xe.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${Xe.trajectoryEvents} events`);return a.map(({line:o,number:s})=>{try{return JSON.parse(o)}catch(c){throw new Error(`Invalid Native Run trajectory event at line ${s}`,{cause:c})}})}async function Kw(e,t,i){return(await nr(e,En(e,"trajectoryRef",t),Xe.trajectoryBytes,"Native Run trajectory",i))?.text??null}async function Yw(e,t,i,n,r){if(!/^[a-f0-9]{64}$/u.test(n))throw new Error("Native Run trajectory expected hash is invalid");let a=En(e,"trajectoryRef",t),o=await nr(e,a,Xe.trajectoryBytes,"Native Run trajectory");if(!o)throw new Error("Native Run trajectory disappeared before repair");if(S_("sha256").update(o.text,"utf8").digest("hex")!==n)throw new Error("Native Run trajectory changed before repair");await wl({changeDir:e,file:a,content:i,maxBytes:Xe.trajectoryBytes,label:"Native Run trajectory",expected:o.target,hooks:r})}async function Xw(e,t,i,n){let r=En(e,"trajectoryRef",t),a=`${JSON.stringify(i)} +`;if(Buffer.byteLength(a,"utf8")>Xe.trajectoryEventBytes)throw new Error(`Native Run trajectory event exceeds ${Xe.trajectoryEventBytes} bytes`);let o=await nr(e,r,Xe.trajectoryBytes,"Native Run trajectory");if((o?o.text.split(/\r?\n/u).filter(c=>c.length>0).length:0)>=Xe.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${Xe.trajectoryEvents} events`);await wl({changeDir:e,file:r,content:`${o?.text??""}${a}`,maxBytes:Xe.trajectoryBytes,label:"Native Run trajectory",expected:o?.target??{exists:!1},hooks:n})}async function ea(e,t,i){let n=await nr(e,En(e,"checkpointRef",t),Xe.checkpointBytes,"Native Run checkpoint",i);return n?zw(n.text,"Native Run checkpoint"):null}async function Qw(e,t,i,n){await wl({changeDir:e,file:En(e,"checkpointRef",t),content:Gw(i),maxBytes:Xe.checkpointBytes,label:"Native Run checkpoint",hooks:n})}var T_=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Nl=class extends Error{constructor(i){super(i.status==="repairable"?`Native trajectory has an incomplete final line at ${i.file}:${i.line}; run doctor --repair`:`Native trajectory is invalid at ${i.file}:${i.line}: ${i.message}`);this.inspection=i;this.name="NativeTrajectoryRepairRequiredError"}inspection;code="native-trajectory-tail-repair-required"};function Xf(e){return A_("sha256").update(e).digest("hex")}function __(e,t){if(!T_.test(t))throw new Error(`Invalid Native change name: ${t}`);let i=yl.join(e.changesDir,t);if(!$(e.changesDir,i))throw new Error("Native change path escaped");return yl.join(i,"runtime","trajectory.jsonl")}function I_(e){let t=e.split(/\n/u),i=0;for(let n=0;n=Math.max(0,t.length-1)}function O_(e,t){let i=t.lastIndexOf(10),n=t.subarray(0,i+1),r=I_(n.toString("utf8"));if(r.status==="invalid")return{status:"invalid",file:e,line:r.line,message:r.message};if(i===t.length-1)return{status:"clean",file:e};let a=t.subarray(i+1),o=a.toString("utf8"),s=r.count+1,c,l;try{JSON.parse(o.endsWith("\r")?o.slice(0,-1):o),c="missing-newline",l=Buffer.concat([t,Buffer.from(` +`)])}catch(d){if(!j_(d,o))return{status:"invalid",file:e,line:s,message:d.message};c="incomplete-json",l=n}return{inspection:{status:"repairable",file:e,reason:c,line:s,originalHash:Xf(t),targetHash:Xf(l),tailHash:Xf(a),discardedBytes:c==="incomplete-json"?a.length:0},targetContent:l.toString("utf8")}}async function Zw(e,t){let i=__(e,t);await x(e.nativeRoot,i);let n=yl.join(e.changesDir,t),r=await Kw(n,ut.trajectoryRef);return r===null?{status:"clean",file:i}:O_(i,Buffer.from(r))}async function ta(e,t){let i=await Zw(e,t);return"inspection"in i?i.inspection:i}async function Lo(e,t){let i=await ta(e,t);if(i.status!=="clean")throw new Nl(i)}async function ey(e,t,i){return te(e,`repair trajectory tail for ${t}`,async()=>{let n=await Zw(e,t);if(!("inspection"in n)){if(n.status==="clean")return null;throw new Nl(n)}try{await Yw(yl.join(e.changesDir,t),ut.trajectoryRef,n.targetContent,n.inspection.originalHash,{beforeCommit:i?.beforeCommit})}catch(a){throw/changed (?:before|while)/iu.test(a.message)?new Error(`Native trajectory changed while preparing tail repair for ${t}; inspect it again before retrying`,{cause:a}):a}if((await ta(e,t)).status!=="clean")throw new Error(`Native trajectory tail repair did not produce a clean file for ${t}`);return n.inspection})}import{createHash as D_}from"node:crypto";import{promises as kl}from"node:fs";import Cn from"node:path";import{execFileSync as $_}from"child_process";import bl from"path";function Bo(e,t){return $_("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function H_(e,t){let i=bl.normalize(e),n=bl.normalize(t);return process.platform==="win32"?i.toLowerCase()===n.toLowerCase():i===n}function Qf(e){try{let t=bl.resolve(Bo(e,["rev-parse","--show-toplevel"])),n=Bo(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),r=n?bl.resolve(n.slice(9)):t,a=null;try{a=Bo(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!H_(t,r),currentWorktreeRoot:t,primaryWorktreeRoot:r,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function ty(e,t){try{return Bo(e,["check-ref-format","--branch",t]),Bo(e,["show-ref","--verify",`refs/heads/${t}`]),!0}catch{return!1}}var qo=/^[a-f0-9]{64}$/u,M_=16*1024,Zf=process.platform,F_=new Set(["workspace-root-changed","workspace-inspection-unavailable"]);function ia(e){return F_.has(e)}function ay(e,t){let i=Cn.relative(e,t);return Cn.isAbsolute(i)||i===".."||i.startsWith(`..${Cn.sep}`)?null:i.replaceAll("\\","/")||"."}function oy(e){return Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127})}function sy(e,t){if(e.length===0||oy(e)||e.includes("\\")||Cn.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes(".."))throw new Error(`${t} must be a portable project-relative path`);let i=Cn.posix.normalize(e);if(i!==e||i===".."||i.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return i}function eh(e,t){return D_("sha256").update(`${e} +${t}`).digest("hex")}async function iy(e,t){let i=await kl.realpath(t),n=await kl.lstat(i);if(!n.isDirectory()||n.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let r=Zf==="win32"?Cn.normalize(i).toLowerCase():i;return eh(e,`${r} ${n.dev} ${n.ino} -${n.birthtimeMs}`)}async function iy(e,t){let i=await kl.realpath(t),n=await kl.lstat(i);if(!n.isDirectory()||n.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let r=Zf==="win32"?Cn.normalize(i).toLowerCase():i;return eh(e,r)}function L_(e){if(typeof e!="string")throw new Error("Native workspace capturedAt is invalid");let t=new Date(e);if(!Number.isFinite(t.getTime())||t.toISOString()!==e)throw new Error("Native workspace capturedAt is invalid");return e}function ny(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||ay(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function th(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(ny(e.changeBranch,"Native workspace change branch"),ny(e.targetBranch,"Native workspace target branch"),(e.isolation==="branch"||e.isolation==="worktree")&&(e.changeBranch===null||e.targetBranch===null))throw new Error("Native isolated workspace requires change and target branches")}function na(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace identity must be an object");let t=e,i=new Set(["schema","capturedAt","capturedRevision","nativeRootRef","projectRootId","nativeRootId","projectRootPathId","nativeRootPathId","sessionHash","isolation","changeBranch","targetBranch","finish"]),n=Object.keys(t).filter(o=>!i.has(o));if(n.length>0)throw new Error(`Native workspace identity has unknown field(s): ${n.join(", ")}`);if(t.schema!=="comet.native.workspace.v2"&&t.schema!=="comet.native.workspace.v3")throw new Error("Unsupported Native workspace identity");if(!Number.isSafeInteger(t.capturedRevision)||t.capturedRevision<1||typeof t.nativeRootRef!="string"||!qo.test(String(t.projectRootId))||!qo.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");L_(t.capturedAt),oy(t.nativeRootRef,"Native workspace root ref");let r=t.projectRootPathId!==void 0,a=t.nativeRootPathId!==void 0;if(r!==a)throw new Error("Native workspace path identities must be provided together");if(r&&!qo.test(String(t.projectRootPathId))||a&&!qo.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!qo.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.schema==="comet.native.workspace.v2"){if(t.isolation!==void 0||t.changeBranch!==void 0||t.targetBranch!==void 0||t.finish!==void 0)throw new Error("Native workspace v2 identity cannot contain a workspace binding");return}if(typeof t.isolation!="string"||t.changeBranch===void 0||t.targetBranch===void 0||t.finish===void 0)throw new Error("Native workspace v3 identity requires a workspace binding");if(th(t),t.finish!==null&&!new Set(["merge","push","pull-request","keep"]).has(t.finish))throw new Error("Native workspace finish must be merge, push, pull-request, keep, or null")}function ih(e){let t=Qf(e.projectRoot);if(!t.isGitWorktree){if(e.isolation!=="current"||e.changeBranch!==void 0||e.targetBranch!==void 0)throw new Error("Native branch and worktree isolation require a Git working directory");return{isolation:"current",changeBranch:null,targetBranch:null}}if(t.currentBranch===null)throw new Error("Native workspace binding requires a branch; detached HEAD is not supported");if(e.changeBranch!==void 0&&e.changeBranch!==t.currentBranch)throw new Error(`Native change branch ${e.changeBranch} does not match the current branch ${t.currentBranch}`);if(e.isolation==="worktree"&&!t.isSecondaryWorktree)throw new Error("Native worktree isolation must be created in a linked Git worktree");if((e.isolation==="branch"||e.isolation==="worktree")&&e.targetBranch===void 0)throw new Error(`Native ${e.isolation} isolation requires --target-branch`);if(e.targetBranch!==void 0&&!ey(e.projectRoot,e.targetBranch))throw new Error(`Native target branch is not a verified local branch: ${e.targetBranch}`);let i={isolation:e.isolation,changeBranch:t.currentBranch,targetBranch:e.targetBranch??t.currentBranch};return th(i),i}function sy(e,t){let i=ih({projectRoot:e,isolation:t.isolation,...t.changeBranch!==null?{changeBranch:t.changeBranch}:{},...t.isolation!=="current"&&t.targetBranch!==null?{targetBranch:t.targetBranch}:{}});if(i.isolation!==t.isolation||i.changeBranch!==t.changeBranch||i.targetBranch!==t.targetBranch)throw new Error("Native workspace binding changed before change creation")}function ar(e,t){return Cn.join(e.changesDir,t,"runtime","workspace.json")}function B_(e,t){let i=ry(e.nativeRoot,ar(e,t));if(!i||i===".")throw new Error("Native workspace file escaped its root");return oy(i,"Native workspace file ref")}async function cy(e,t){try{let i=await ye({root:e.nativeRoot,ref:B_(e,t),maxBytes:M_});return JSON.parse(i.text)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function nh(e,t){let i=await cy(e,t);if(i===null)return!1;if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Native workspace identity must be an object");return i.schema==="comet.native.workspace.v1"?!0:(na(i),i.schema==="comet.native.workspace.v3"?!1:i.projectRootPathId===void 0||i.nativeRootPathId===void 0)}async function ly(e){if(!Number.isSafeInteger(e.revision)||e.revision<1)throw new Error("Native workspace revision must be a positive integer");let t=ry(e.paths.projectRoot,e.paths.nativeRoot);if(!t)throw new Error("Native root is outside the project root");let[i,n,r,a]=await Promise.all([ty("comet.native.workspace-project-root.v2",e.paths.projectRoot),ty("comet.native.workspace-native-root.v2",e.paths.nativeRoot),iy("comet.native.workspace-project-root-path.v2",e.paths.projectRoot),iy("comet.native.workspace-native-root-path.v2",e.paths.nativeRoot)]),o=(e.now??new Date).toISOString();if(e.finish&&!e.binding)throw new Error("Native workspace finish requires a workspace binding");e.binding&&th(e.binding);let s={capturedAt:o,capturedRevision:e.revision,nativeRootRef:t,projectRootId:i,nativeRootId:n,projectRootPathId:r,nativeRootPathId:a,...e.sessionId?{sessionHash:eh("comet.native.workspace-session.v2",`${i} +${n.birthtimeMs}`)}async function ny(e,t){let i=await kl.realpath(t),n=await kl.lstat(i);if(!n.isDirectory()||n.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let r=Zf==="win32"?Cn.normalize(i).toLowerCase():i;return eh(e,r)}function L_(e){if(typeof e!="string")throw new Error("Native workspace capturedAt is invalid");let t=new Date(e);if(!Number.isFinite(t.getTime())||t.toISOString()!==e)throw new Error("Native workspace capturedAt is invalid");return e}function ry(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||oy(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function th(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(ry(e.changeBranch,"Native workspace change branch"),ry(e.targetBranch,"Native workspace target branch"),(e.isolation==="branch"||e.isolation==="worktree")&&(e.changeBranch===null||e.targetBranch===null))throw new Error("Native isolated workspace requires change and target branches")}function na(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace identity must be an object");let t=e,i=new Set(["schema","capturedAt","capturedRevision","nativeRootRef","projectRootId","nativeRootId","projectRootPathId","nativeRootPathId","sessionHash","isolation","changeBranch","targetBranch","finish"]),n=Object.keys(t).filter(o=>!i.has(o));if(n.length>0)throw new Error(`Native workspace identity has unknown field(s): ${n.join(", ")}`);if(t.schema!=="comet.native.workspace.v2"&&t.schema!=="comet.native.workspace.v3")throw new Error("Unsupported Native workspace identity");if(!Number.isSafeInteger(t.capturedRevision)||t.capturedRevision<1||typeof t.nativeRootRef!="string"||!qo.test(String(t.projectRootId))||!qo.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");L_(t.capturedAt),sy(t.nativeRootRef,"Native workspace root ref");let r=t.projectRootPathId!==void 0,a=t.nativeRootPathId!==void 0;if(r!==a)throw new Error("Native workspace path identities must be provided together");if(r&&!qo.test(String(t.projectRootPathId))||a&&!qo.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!qo.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.schema==="comet.native.workspace.v2"){if(t.isolation!==void 0||t.changeBranch!==void 0||t.targetBranch!==void 0||t.finish!==void 0)throw new Error("Native workspace v2 identity cannot contain a workspace binding");return}if(typeof t.isolation!="string"||t.changeBranch===void 0||t.targetBranch===void 0||t.finish===void 0)throw new Error("Native workspace v3 identity requires a workspace binding");if(th(t),t.finish!==null&&!new Set(["merge","push","pull-request","keep"]).has(t.finish))throw new Error("Native workspace finish must be merge, push, pull-request, keep, or null")}function ih(e){let t=Qf(e.projectRoot);if(!t.isGitWorktree){if(e.isolation!=="current"||e.changeBranch!==void 0||e.targetBranch!==void 0)throw new Error("Native branch and worktree isolation require a Git working directory");return{isolation:"current",changeBranch:null,targetBranch:null}}if(t.currentBranch===null)throw new Error("Native workspace binding requires a branch; detached HEAD is not supported");if(e.changeBranch!==void 0&&e.changeBranch!==t.currentBranch)throw new Error(`Native change branch ${e.changeBranch} does not match the current branch ${t.currentBranch}`);if(e.isolation==="worktree"&&!t.isSecondaryWorktree)throw new Error("Native worktree isolation must be created in a linked Git worktree");if((e.isolation==="branch"||e.isolation==="worktree")&&e.targetBranch===void 0)throw new Error(`Native ${e.isolation} isolation requires --target-branch`);if(e.targetBranch!==void 0&&!ty(e.projectRoot,e.targetBranch))throw new Error(`Native target branch is not a verified local branch: ${e.targetBranch}`);let i={isolation:e.isolation,changeBranch:t.currentBranch,targetBranch:e.targetBranch??t.currentBranch};return th(i),i}function cy(e,t){let i=ih({projectRoot:e,isolation:t.isolation,...t.changeBranch!==null?{changeBranch:t.changeBranch}:{},...t.isolation!=="current"&&t.targetBranch!==null?{targetBranch:t.targetBranch}:{}});if(i.isolation!==t.isolation||i.changeBranch!==t.changeBranch||i.targetBranch!==t.targetBranch)throw new Error("Native workspace binding changed before change creation")}function ar(e,t){return Cn.join(e.changesDir,t,"runtime","workspace.json")}function B_(e,t){let i=ay(e.nativeRoot,ar(e,t));if(!i||i===".")throw new Error("Native workspace file escaped its root");return sy(i,"Native workspace file ref")}async function ly(e,t){try{let i=await ye({root:e.nativeRoot,ref:B_(e,t),maxBytes:M_});return JSON.parse(i.text)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function nh(e,t){let i=await ly(e,t);if(i===null)return!1;if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Native workspace identity must be an object");return i.schema==="comet.native.workspace.v1"?!0:(na(i),i.schema==="comet.native.workspace.v3"?!1:i.projectRootPathId===void 0||i.nativeRootPathId===void 0)}async function uy(e){if(!Number.isSafeInteger(e.revision)||e.revision<1)throw new Error("Native workspace revision must be a positive integer");let t=ay(e.paths.projectRoot,e.paths.nativeRoot);if(!t)throw new Error("Native root is outside the project root");let[i,n,r,a]=await Promise.all([iy("comet.native.workspace-project-root.v2",e.paths.projectRoot),iy("comet.native.workspace-native-root.v2",e.paths.nativeRoot),ny("comet.native.workspace-project-root-path.v2",e.paths.projectRoot),ny("comet.native.workspace-native-root-path.v2",e.paths.nativeRoot)]),o=(e.now??new Date).toISOString();if(e.finish&&!e.binding)throw new Error("Native workspace finish requires a workspace binding");e.binding&&th(e.binding);let s={capturedAt:o,capturedRevision:e.revision,nativeRootRef:t,projectRootId:i,nativeRootId:n,projectRootPathId:r,nativeRootPathId:a,...e.sessionId?{sessionHash:eh("comet.native.workspace-session.v2",`${i} ${n} -${e.sessionId}`)}:{}},c=e.binding?{schema:"comet.native.workspace.v3",...s,...e.binding,finish:e.finish??null}:{schema:"comet.native.workspace.v2",...s};return na(c),c}async function ra(e){let t=await ly(e),i=ar(e.paths,e.name);return await x(e.paths.nativeRoot,i),await le(i,t,{containedRoot:e.paths.nativeRoot}),t}async function uy(e,t,i){return te(e,`set workspace finish for ${t}`,async()=>{let n=await rh(e,t);if(n===null||n.schema!=="comet.native.workspace.v3")throw new Error(`Native change ${t} has no workspace finishing contract`);if(n.isolation==="current")throw new Error("Native current isolation does not use a workspace finishing action");let r={...n,finish:i};na(r);let a=ar(e,t);return await x(e.nativeRoot,a),await le(a,r,{containedRoot:e.nativeRoot}),r})}async function Ve(e,t){let i=await cy(e,t);return i===null||i&&typeof i=="object"&&!Array.isArray(i)&&i.schema==="comet.native.workspace.v1"?null:(na(i),i)}async function dy(e){return await nh(e.paths,e.name)?ra(e):null}async function or(e){na(e.identity);let t=await ly({paths:e.paths,name:"workspace-advisory",revision:e.identity.capturedRevision}),i=[],n=[];return t.nativeRootRef!==e.identity.nativeRootRef&&i.push("native-root-ref"),e.identity.projectRootPathId&&e.identity.nativeRootPathId?(t.projectRootPathId!==e.identity.projectRootPathId&&i.push("project-root-path"),t.nativeRootPathId!==e.identity.nativeRootPathId&&i.push("native-root-path")):(t.projectRootId!==e.identity.projectRootId&&i.push("project-root-legacy-identity"),t.nativeRootId!==e.identity.nativeRootId&&i.push("native-root-legacy-identity")),Zf==="win32"&&i.length>0&&i.every(a=>a==="project-root-legacy-identity"||a==="native-root-legacy-identity")?n.push("workspace-inspection-unavailable"):i.length>0&&n.push("workspace-root-changed"),{state:n.length===0?"aligned":n.includes("workspace-root-changed")?"drifted":"unknown",findingCodes:n,driftComponents:i}}async function sr(e){if(na(e.identity),e.identity.schema==="comet.native.workspace.v2")return{state:"legacy",code:"workspace-binding-legacy",message:"Legacy Native workspace metadata has no isolation binding"};if((await or(e)).state==="drifted")return{state:"drifted",code:"workspace-binding-root-changed",message:"Native change is being accessed from a different working directory"};let i=Qf(e.paths.projectRoot);return e.identity.changeBranch===null?i.isGitWorktree?{state:"drifted",code:"workspace-branch-changed",message:"Native change was created outside Git but is now being accessed inside Git"}:{state:"aligned",code:null,message:null}:i.isGitWorktree?i.currentBranch!==e.identity.changeBranch?{state:"drifted",code:"workspace-branch-changed",message:`Native change is bound to branch ${e.identity.changeBranch}, but the current branch is ${i.currentBranch??"detached HEAD"}`}:e.identity.isolation==="worktree"&&!i.isSecondaryWorktree?{state:"drifted",code:"workspace-kind-changed",message:"Native change is bound to a linked Git worktree"}:{state:"aligned",code:null,message:null}:{state:"drifted",code:"workspace-vcs-unavailable",message:"Native change requires its bound Git working directory"}}async function rh(e,t){let i=await Ve(e,t);if(i===null)return null;let n=await sr({paths:e,identity:i});if(n.state==="drifted")throw new Error(`${n.code}: ${n.message}`);return i}var xe="comet.native.v3",He="comet.native.v2",jt="comet.native.v1",ji="comet.native.transition.v3",Oi="comet.native.transition.v2",cr="comet.native.transition.v1";var fy=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],q_=new Set(fy),hy=new Set([...fy,"minimum_runtime_version","revision"]),V_=new Set([...hy,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),W_=new Set(["capability","operation","source","base_hash"]),J_=new Set(["shape","build","verify","archive"]),z_=new Set(["implicit","confirmed"]),G_=new Set(["pending","pass","fail"]),je="comet-state.yaml",oh=/^[a-f0-9]{64}$/u,py=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,U_=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,Vo=class extends Error{constructor(i,n){super(`Native change ${i} uses ${n}; run comet native doctor ${i} --repair before mutating it`);this.change=i;this.schema=n;this.name="NativeSchemaMigrationRequiredError"}change;schema;code="native-schema-migration-required"},Hi=class extends Error{constructor(i,n){super(i!==xe||n===null?`Unsupported Native change schema ${i} for runtime protocol ${3}`:`Native change ${i} requires runtime protocol ${n}; current protocol is ${3}`);this.schema=i;this.minimumRuntimeVersion=n;this.name="NativeRuntimeCompatibilityError"}schema;minimumRuntimeVersion;code="native-runtime-incompatible"},xn=class extends Error{constructor(i,n,r){super(`Native change ${i} revision conflict: expected ${n}, actual ${r}`);this.change=i;this.expectedRevision=n;this.actualRevision=r;this.name="NativeChangeRevisionConflictError"}change;expectedRevision;actualRevision;code="native-change-revision-conflict"},Wo=class extends Error{constructor(i,n){super(`Native working directory already contains active change${n.length===1?"":"s"} ${n.join(", ")}; create the new change in a separate worktree`);this.requestedIsolation=i;this.activeChanges=n;this.name="NativeWorkspaceIsolationRequiredError"}requestedIsolation;activeChanges;code="native-workspace-isolation-required"},gi=class extends Error{constructor(i,n,r,a,o,s=null,c=null){super(`Native change ${i} baseline is incomplete (${n} omitted entr${n===1?"y":"ies"}). Adjust native.snapshot scope or resource budgets in .comet/config.yaml, then retry.`);this.change=i;this.omittedCount=n;this.omittedByReason=r;this.samplePaths=a;this.sampleTruncated=o;this.effectiveLimits=s;this.policyHash=c;this.name="NativeBaselineIncompleteError"}change;omittedCount;omittedByReason;samplePaths;sampleTruncated;effectiveLimits;policyHash;code="native-baseline-incomplete"},K_=["# Outcome","","# Scope","","# Non-goals","","# Acceptance examples","","# Constraints and invariants","","# Decisions","","# Open questions","","# Verification expectations",""].join(` -`);function Go(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function my(e,t,i){let n=Object.keys(e).filter(r=>!t.has(r));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`)}function zt(e){if(!py.test(e))throw new Error(`Invalid Native change name: ${e}`)}function Y_(e){if(!py.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function vy(e,t){if(e.length===0||dt.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function X_(e,t){let i=Go(e,`spec_changes[${t}]`);if(my(i,W_,`spec_changes[${t}]`),typeof i.capability!="string")throw new Error("spec change capability is required");if(Y_(i.capability),i.operation!=="create"&&i.operation!=="replace"&&i.operation!=="remove")throw new Error(`Invalid spec operation for ${i.capability}`);let n=i.source,r=i.base_hash;if(n!==void 0&&typeof n!="string")throw new Error(`Spec source for ${i.capability} must be a string`);if(typeof n=="string"&&vy(n,`Spec source for ${i.capability}`),i.operation==="create"){if(!n)throw new Error(`Create spec ${i.capability} requires source`);if(r!==null)throw new Error(`Create spec ${i.capability} requires null base_hash`)}else if(i.operation==="replace"){if(!n)throw new Error(`Replace spec ${i.capability} requires source`);if(typeof r!="string"||!oh.test(r))throw new Error(`Replace spec ${i.capability} requires a SHA-256 base_hash`)}else{if(n!==void 0)throw new Error(`Remove spec ${i.capability} forbids source`);if(typeof r!="string"||!oh.test(r))throw new Error(`Remove spec ${i.capability} requires a SHA-256 base_hash`)}return{capability:i.capability,operation:i.operation,...typeof n=="string"?{source:n}:{},base_hash:r}}function Q_(e){return/^\d{4}-\d{2}-\d{2}$/u.test(e)?new Date(`${e}T00:00:00.000Z`).toISOString().slice(0,10)===e:!1}function sh(e,t){if(my(e,t,je),typeof e.name!="string")throw new Error("Native change name is required");if(zt(e.name),e.language!=="en"&&e.language!=="zh-CN")throw new Error("Native change language must be en or zh-CN");if(typeof e.phase!="string"||!J_.has(e.phase))throw new Error("Native change phase is invalid");if(e.brief!=="brief.md")throw new Error("Native change brief must be brief.md");if(e.approval!==null&&!z_.has(e.approval))throw new Error("Native change approval is invalid");if(!Array.isArray(e.spec_changes))throw new Error("Native spec_changes must be an array");let i=e.spec_changes.map(X_),n=i.map(r=>r.capability).filter((r,a,o)=>o.indexOf(r)!==a);if(n.length>0)throw new Error(`Duplicate Native capability operation: ${[...new Set(n)].join(", ")}`);if(typeof e.verification_result!="string"||!G_.has(e.verification_result))throw new Error("Native verification_result is invalid");if(e.verification_report!==null&&typeof e.verification_report!="string")throw new Error("Native verification_report must be a string or null");if(typeof e.verification_report=="string"&&vy(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!Q_(e.created_at))throw new Error("Native created_at must be a valid YYYY-MM-DD date");if(e.run_id!==null&&(typeof e.run_id!="string"||e.run_id.length===0))throw new Error("Native run_id must be a non-empty string or null");return{name:e.name,language:e.language,phase:e.phase,brief:"brief.md",approval:e.approval,spec_changes:i,verification_result:e.verification_result,verification_report:e.verification_report,archived:e.archived,created_at:e.created_at,run_id:e.run_id}}function Uo(e){let t=Go(e,je);if(t.schema!==jt)throw new Error(`Expected ${jt}`);return{schema:jt,...sh(t,q_)}}function Jo(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function ah(e,t,i){if(e===null)return null;let n=typeof e=="string"?U_.exec(e):null;if(!n||n[1]!==i)throw new Error(`${t} must be null or runtime/evidence/${i}/.json relative to the Native change`);return e}function Z_(e){if(e==null)return null;if(typeof e!="string"||!oh.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function eI(e){if(e===void 0)return"legacy-v1";if(e!=="legacy-v1")throw new Error("Native verification_protocol must be legacy-v1");return e}function An(e){let t=Go(e,je);if(t.schema!==He)throw new Error(`Expected ${He}`);if(Jo(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${He} minimum_runtime_version must be 2`);return{schema:He,minimum_runtime_version:2,revision:Jo(t.revision,"Native v2 revision"),...sh(t,hy)}}function Ot(e){let t=Go(e,je);if(t.schema!==xe){if(t.schema===jt||t.schema===He){let o=t.schema===jt?Uo(t):An(t);throw new Vo(o.name,o.schema)}throw new Hi(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let i=Jo(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)throw new Hi(t.schema,i);if(i!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let n=Jo(t.revision,"Native revision"),r=sh(t,V_),a=Z_(t.approved_contract_hash);if(r.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:xe,minimum_runtime_version:3,revision:n,verification_protocol:eI(t.verification_protocol),...r,approved_contract_hash:a,implementation_scope:ah(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:ah(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:ah(t.partial_allowance,"Native partial_allowance","allowances")}}function gy(e){let t=Go(e,je);if(t.schema===jt){let r=Uo(t);return{status:"migration-required",schema:r.schema,minimumRuntimeVersion:1,state:r,message:`Native change ${r.name} requires migration to ${xe}`}}if(t.schema===He){let r=An(t);return{status:"migration-required",schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,state:r,message:`Native change ${r.name} requires migration to ${xe}`}}if(t.schema!==xe){let r=typeof t.minimum_runtime_version=="number"&&Number.isSafeInteger(t.minimum_runtime_version)?t.minimum_runtime_version:null;return{status:"runtime-incompatible",schema:typeof t.schema=="string"?t.schema:"(missing)",minimumRuntimeVersion:r,state:null,message:new Hi(typeof t.schema=="string"?t.schema:"(missing)",r).message}}let i=Jo(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:i,state:null,message:new Hi(t.schema,i).message};let n=Ot(t);return{status:"current",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n}}function Pn(e){let t=Ot(e);return{schema:t.schema,minimum_runtime_version:t.minimum_runtime_version,revision:t.revision,verification_protocol:t.verification_protocol,name:t.name,language:t.language,phase:t.phase,brief:t.brief,approval:t.approval,approved_contract_hash:t.approved_contract_hash??null,spec_changes:t.spec_changes.map(i=>({capability:i.capability,operation:i.operation,...i.source?{source:i.source}:{},base_hash:i.base_hash})),verification_result:t.verification_result,verification_report:t.verification_report,implementation_scope:t.implementation_scope,verification_evidence:t.verification_evidence,partial_allowance:t.partial_allowance,archived:t.archived,created_at:t.created_at,run_id:t.run_id}}function Sl(e){let t=An(e);return{schema:t.schema,minimum_runtime_version:t.minimum_runtime_version,revision:t.revision,name:t.name,language:t.language,phase:t.phase,brief:t.brief,approval:t.approval,spec_changes:t.spec_changes.map(i=>({capability:i.capability,operation:i.operation,...i.source?{source:i.source}:{},base_hash:i.base_hash})),verification_result:t.verification_result,verification_report:t.verification_report,archived:t.archived,created_at:t.created_at,run_id:t.run_id}}function C(e,t){zt(t);let i=dt.join(e.changesDir,t);if(!$(e.changesDir,i))throw new Error("Native change path escaped");return i}async function lr(e,t){let i=dt.join(C(e,t),"runtime","schema-migration.json");await x(e.nativeRoot,i);try{return await $i.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function aa(e,t){let i=dt.join(C(e,t),"runtime","checkpoint-journal.json");await x(e.nativeRoot,i);try{return await $i.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function wy(e){return te(e.paths,`create change ${e.name}`,()=>tI(e))}async function tI(e){if(zt(e.name),e.initialProjectConfig&&await re(e.paths.projectRoot)===null&&await li(e.paths.projectRoot,e.initialProjectConfig),e.workspaceBinding){sy(e.paths.projectRoot,e.workspaceBinding);let r=await sI(e.paths);if(r.length>0)throw new Wo(e.workspaceBinding.isolation,r)}let t=e.verificationProtocol??"legacy-v1",i=C(e.paths,e.name);await x(e.paths.nativeRoot,i);let n=!1;try{try{await $i.mkdir(i,{recursive:!1}),n=!0}catch(c){if(c.code==="ENOENT"){await $i.mkdir(e.paths.changesDir,{recursive:!0});try{await $i.mkdir(i,{recursive:!1}),n=!0}catch(l){throw l.code==="EEXIST"?new Error(`Native change already exists: ${e.name}`,{cause:l}):l}}else throw c.code==="EEXIST"?new Error(`Native change already exists: ${e.name}`,{cause:c}):c}let r={schema:xe,minimum_runtime_version:3,revision:1,verification_protocol:t,name:e.name,language:e.language,phase:"shape",brief:"brief.md",approval:null,approved_contract_hash:null,spec_changes:[],verification_result:"pending",verification_report:null,implementation_scope:null,verification_evidence:null,partial_allowance:null,archived:!1,created_at:(e.now??new Date).toISOString().slice(0,10),run_id:null};await Promise.all([$i.mkdir(dt.join(i,"specs"),{recursive:!0}),$i.mkdir(dt.join(i,"runtime","checkpoints"),{recursive:!0}),$e(dt.join(i,"brief.md"),K_)]);let o=(await re(e.paths.projectRoot))?.native.snapshot??zc,s=await $o(e.paths,{now:e.now,origin:"change-created",policy:o,limits:{maxFiles:o.max_files,maxFileBytes:o.max_total_bytes,maxTotalBytes:o.max_total_bytes,maxDurationMs:o.max_duration_ms},deadlineMs:o.max_duration_ms});if(!s.complete){let c=hl(s),l=s.omitted.reduce((d,f)=>(d[f.reason]=(d[f.reason]??0)+1,d),{}),u=s.omissionOverflow?.count??0;throw u>0&&(l.overflow=u),new gi(r.name,s.omittedCount,l,c.samplePaths,c.sampleTruncated,s.limits,s.policy?.hash??null)}return await pl(e.paths,r.name,s),await aI(e.paths,r),await ra({paths:e.paths,name:r.name,revision:r.revision,now:e.now,...e.workspaceBinding?{binding:e.workspaceBinding}:{}}),r}catch(r){throw n&&await $i.rm(i,{recursive:!0,force:!0}),r}}var iI=256*1024;async function El(e,t=dt.dirname(e)){let i=dt.relative(t,e).split(dt.sep).join("/"),n=await ye({root:t,ref:i,maxBytes:iI}),r=(0,zo.parseDocument)(n.text,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`Invalid Native change file ${e}: ${r.errors[0].message}`);return r.toJS()}async function ft(e,t){let i=dt.join(C(e,t),je);await x(e.nativeRoot,i);let n=gy(await El(i,e.nativeRoot));if(n.state&&n.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return await lr(e,t)?{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimumRuntimeVersion,state:n.state,message:`Native schema migration is incomplete for ${t}; run doctor --repair`}:(n.status==="current"&&n.state&&await rI(e,n.state),n)}async function nI(e,t){let i=dt.join(C(e,t),je);await x(e.nativeRoot,i);let n=gy(await El(i,e.nativeRoot));if(n.state&&n.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return n}async function rI(e,t){if(await vi(e,t.name)!==null&&t.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${t.verification_protocol}`)}async function G(e,t){let i=await ft(e,t);if(i.status==="migration-required")throw new Vo(t,i.schema);if(i.status==="runtime-incompatible"||!i.state)throw new Hi(i.schema,i.minimumRuntimeVersion);return await rh(e,t),i.state}async function aI(e,t){let i=dt.join(C(e,t.name),je);await x(e.nativeRoot,i);try{throw await $i.access(i),new Error(`Native change state already exists: ${t.name}`)}catch(n){if(n.code!=="ENOENT")throw n}if(t.revision!==1)throw new Error("New Native change must start at revision 1");await $e(i,(0,zo.stringify)(Pn(t)))}async function yy(e,t,i){let n={...t,schema:xe,minimum_runtime_version:3,revision:i+1},r=await vw({expectedRevision:i,next:n,read:async()=>{let a=Ot(await El(e));if(a.name!==t.name)throw new Error(`Native change file/name mismatch: ${t.name}`);return a},write:a=>$e(e,(0,zo.stringify)(Pn(a))),equals:(a,o)=>JSON.stringify(Pn(a))===JSON.stringify(Pn(o)),conflict:a=>new xn(t.name,i,a)});return Object.assign(t,r),r}async function oa(e,t,i,n){if(await Vr(e.projectRoot),await lr(e,t.name))throw new Vo(t.name,t.schema);if(!n?.allowPendingCheckpointRecovery&&await aa(e,t.name))throw new Error(`Native progress checkpoint recovery is required for ${t.name} before another state write`);if((await G(e,t.name)).verification_protocol!==t.verification_protocol)throw new Error("Native verification protocol changed outside a revisioned state transition");await Lo(e,t.name);let a=dt.join(C(e,t.name),je);return await x(e.nativeRoot,a),yy(a,t,i)}async function Ny(e,t){return yy(e,t,t.revision)}async function by(e){return Ot(await El(e))}async function oI(e){let t;try{let n=await st({root:e.nativeRoot,directory:e.changesDir,label:"Native changes directory",maxEntries:4096});await n.verify(),t=n.entries}catch(n){if(n.code==="ENOENT")return[];throw n}return t.filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort()}async function sI(e){let t=[];for(let i of await oI(e)){let n=await nI(e,i);if(!n.state){t.push(i);continue}if(n.state.archived)continue;let r=await Ve(e,i);if(r?.schema==="comet.native.workspace.v3"){if((await sr({paths:e,identity:r})).code==="workspace-binding-root-changed")continue}else if(r&&(await or({paths:e,identity:r})).state==="drifted")continue;t.push(i)}return t}var Sy=["Outcome","Scope","Non-goals","Acceptance examples"],cI=[...Sy,"Constraints and invariants","Decisions","Open questions","Verification expectations"],lI=["Acceptance evidence","Commands and results","Skipped checks","Spec consistency","Known limitations and risks","Conclusion"],Ey={maxFileBytes:ho};function Ry(e){let t=new Map,i=null,n=[],r=()=>{i!==null&&t.set(i,n.join(` -`).trim())};for(let a of e.split(/\r?\n/u)){let o=/^# ([^#].*)$/u.exec(a);o?(r(),i=o[1].trim(),n=[]):i!==null&&n.push(a)}return r(),t}async function Cy(e,t){let i=ky.resolve(e,...t.split(/[\\/]/u));if(!$(e,i))throw new Error(`Artifact escapes Native change: ${t}`);let n=await ch.realpath(e),r=await ch.realpath(i);if(!$(n,r))throw new Error(`Artifact symlink escapes Native change: ${t}`);if(!(await ch.stat(r)).isFile())throw new Error(`Artifact is not a file: ${t}`);return r}function Ko(e){return{valid:e.length===0,findings:e}}async function ur(e,t){let i=[],n;try{n=(await ye({root:e,ref:t,maxBytes:Ey.maxFileBytes})).text}catch(o){return Ko([{code:"brief-missing",message:o.message,path:t}])}let r=Ry(n);for(let o of cI)r.has(o)||i.push({code:"brief-section-missing",message:`Missing brief section: ${o}`,path:t});for(let o of Sy)(r.get(o)??"").length===0&&i.push({code:"brief-section-empty",message:`Brief section is empty: ${o}`,path:t});let a=r.get("Open questions")??"";return/^\s*-\s*\[blocking\]/imu.test(a)&&i.push({code:"brief-blocking-question",message:"Brief has a blocking open question",path:t}),Ko(i)}async function sa(e,t){let i=[],n;try{n=(await ye({root:e,ref:t,maxBytes:Ey.maxFileBytes})).text}catch(a){return Ko([{code:"verification-missing",message:a.message,path:t}])}let r=Ry(n);for(let a of lI)r.has(a)?(r.get(a)??"").length===0&&i.push({code:"verification-section-empty",message:`Verification section is empty: ${a}`,path:t}):i.push({code:"verification-section-missing",message:`Missing verification section: ${a}`,path:t});return Ko(i)}function Gt(e,t){return ky.join(e.specsDir,t,"spec.md")}async function ca(e,t){let i=[],n=C(e,t.name);for(let r of t.spec_changes){let a=Gt(e,r.capability),o=null;try{await x(e.nativeRoot,a),o=await lt(a)}catch(s){if(s.code!=="ENOENT"){i.push({code:"spec-canonical-unsafe",message:s.message,path:a});continue}}if(r.operation==="create"&&o!==null&&i.push({code:"spec-create-exists",message:`Canonical spec already exists: ${r.capability}`,path:a}),r.operation!=="create"&&o===null&&i.push({code:"spec-base-missing",message:`Canonical spec is missing: ${r.capability}`,path:a}),r.operation!=="create"&&o!==null&&o!==r.base_hash&&i.push({code:"spec-base-conflict",message:`Canonical spec changed for ${r.capability}: expected ${r.base_hash}, actual ${o}`,path:a}),r.source)try{await Cy(n,r.source)}catch(s){i.push({code:"spec-source-invalid",message:s.message,path:r.source})}}return Ko(i)}async function Py(e,t){return Cy(e,t)}import{promises as q$}from"node:fs";import ek from"node:path";import xy from"node:path";import{createHash as uI}from"crypto";function Ut(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function dI(e,t){t.has(e)&&Ut("cyclic structures are not supported"),t.add(e);try{let i=Object.keys(e);for(let n=0;nn!==String(r)))&&Ut("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&Ut("symbol properties are not supported"),`[${e.map(n=>lh(n,t)).join(",")}]`}finally{t.delete(e)}}function fI(e,t){let i=Object.getPrototypeOf(e);i!==Object.prototype&&i!==null&&Ut("only plain objects are supported"),t.has(e)&&Ut("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&Ut("symbol properties are not supported"),t.add(e);try{let n=Object.getOwnPropertyDescriptors(e);return`{${Object.keys(e).sort().map(o=>{let s=n[o];return(!s||!("value"in s))&&Ut("accessor properties are not supported"),`${JSON.stringify(o)}:${lh(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function lh(e,t){if(e===null)return"null";switch(typeof e){case"boolean":return e?"true":"false";case"string":return JSON.stringify(e);case"number":return Number.isFinite(e)||Ut("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?dI(e,t):fI(e,t);case"bigint":case"function":case"symbol":case"undefined":return Ut(`${typeof e} values are not supported`)}return Ut("unsupported value type")}function Yo(e){return lh(e,new Set)}function H(e,t){if(e.length===0)throw new TypeError("Canonical hash tag must be non-empty");if(/[\r\n]/u.test(e))throw new TypeError("Canonical hash tag must not contain a line break");return uI("sha256").update(`${e} -${Yo(t)}`).digest("hex")}var hI="comet.native.archive-preflight.v1",pI="comet.native.archive-preflight.v1",mI="comet.native.archive-operation.v1",vI=/^[a-f0-9]{64}$/u,Ay=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,gI=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function Rl(e,t){return et?1:0}function wI(e,t){if(typeof e!="string"||!vI.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Di(e,t){return e===null?null:wI(e,t)}function yI(e,t){let i=xy.posix.normalize(e);if(typeof e!="string"||e.length===0||e!==e.trim()||e.includes("\\")||xy.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||i!==e||i==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized Native-relative ref`);return e}function NI(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native archive preflight revision must be a positive integer");return e}function bI(e){if(e==null)return null;if(e.schema!=="comet.native.workspace.v3")throw new Error("Native archive workspace schema is invalid");if(e.isolation!=="current"&&e.isolation!=="branch"&&e.isolation!=="worktree")throw new Error("Native archive workspace isolation is invalid");for(let[t,i]of[["change",e.changeBranch],["target",e.targetBranch]])if(i!==null&&(i.length===0||i.trim()!==i||Array.from(i).some(n=>{let r=n.codePointAt(0)??0;return r<=31||r===127})))throw new Error(`Native archive workspace ${t} branch is invalid`);if(e.finish!==null&&e.finish!=="merge"&&e.finish!=="push"&&e.finish!=="pull-request"&&e.finish!=="keep")throw new Error("Native archive workspace finish is invalid");if((e.isolation==="branch"||e.isolation==="worktree")&&(e.changeBranch===null||e.targetBranch===null||e.finish===null))throw new Error("Native isolated archive workspace requires branches and a finish action");if(e.isolation==="current"&&e.finish!==null)throw new Error("Native current archive workspace cannot have a finish action");return{...e}}function kI(e,t){if(!Ay.test(e.capability))throw new Error(`Native archive spec ${t} capability is invalid`);if(e.operation!=="create"&&e.operation!=="replace"&&e.operation!=="remove")throw new Error(`Native archive spec ${e.capability} operation is invalid`);let i=Di(e.expectedBaseHash,`Native archive spec ${e.capability} expected base`),n=Di(e.actualBaseHash,`Native archive spec ${e.capability} actual base`),r=Di(e.proposedHash,`Native archive spec ${e.capability} proposed content`);if(e.operation==="create"&&i!==null)throw new Error(`Native archive create ${e.capability} must expect no canonical base`);if(e.operation!=="create"&&i===null)throw new Error(`Native archive ${e.operation} ${e.capability} requires a base hash`);if(e.operation==="remove"!=(r===null))throw new Error(`Native archive ${e.operation} ${e.capability} proposed hash is invalid`);return{capability:e.capability,operation:e.operation,expectedBaseHash:i,actualBaseHash:n,proposedHash:r}}function SI(e){if(e.result!=="pending"&&e.result!=="pass"&&e.result!=="fail")throw new Error("Native archive verification result is invalid");if(!["missing","invalid","stale","complete","partial"].includes(e.freshness))throw new Error("Native archive verification freshness is invalid");if(!Number.isSafeInteger(e.skippedAcceptanceCount)||e.skippedAcceptanceCount<0)throw new Error("Native archive skipped acceptance count is invalid");let t={result:e.result,freshness:e.freshness,contractHash:Di(e.contractHash,"Native archive contract hash"),acceptanceHash:Di(e.acceptanceHash,"Native archive acceptance hash"),implementationScopeHash:Di(e.implementationScopeHash,"Native archive implementation scope hash"),reportHash:Di(e.reportHash,"Native archive report hash"),envelopeHash:Di(e.envelopeHash,"Native archive envelope hash"),partialAllowanceHash:Di(e.partialAllowanceHash,"Native archive partial allowance hash"),skippedAcceptanceCount:e.skippedAcceptanceCount};if((e.freshness==="complete"||e.freshness==="partial")&&[t.contractHash,t.acceptanceHash,t.implementationScopeHash,t.reportHash,t.envelopeHash].some(i=>i===null))throw new Error("Fresh Native archive evidence requires every bound content hash");if(e.freshness==="partial"&&t.partialAllowanceHash===null||e.freshness==="complete"&&t.partialAllowanceHash!==null)throw new Error("Native archive partial evidence allowance state is invalid");return t}function EI(e){if(e.length>64)throw new Error("Native archive preflight has too many findings");let t=e.map(n=>{if(typeof n!="string"||!gI.test(n))throw new Error(`Native archive preflight finding code is invalid: ${String(n)}`);return n}),i=[...new Set(t)].sort(Rl);if(i.length!==t.length)throw new Error("Native archive preflight has duplicate finding codes");return i}function RI(e){let t=[];e.phase!=="archive"&&t.push("archive-phase-required"),e.archived&&t.push("change-already-archived"),e.pendingJournal&&t.push("pending-journal"),e.targetExists&&t.push("archive-target-exists"),e.evidence.result!=="pass"&&t.push("verification-not-passed"),e.evidence.freshness==="missing"&&t.push("verification-evidence-missing"),e.evidence.freshness==="invalid"&&t.push("verification-evidence-invalid"),e.evidence.freshness==="stale"&&t.push("verification-evidence-stale"),e.evidence.skippedAcceptanceCount>0&&t.push("verification-acceptance-skipped");for(let i of e.specs)i.actualBaseHash!==i.expectedBaseHash&&t.push("spec-base-conflict");return[...new Set(t)].sort(Rl)}function Ty(e){if(!Ay.test(e.change))throw new Error("Native archive change name is invalid");if(typeof e.stateSchema!="string"||e.stateSchema.length===0)throw new Error("Native archive state schema is invalid");if(!Array.isArray(e.specs)||e.specs.length>64)throw new Error("Native archive preflight exceeds its spec budget");let t=e.specs.map(kI).sort((l,u)=>Rl(l.capability,u.capability));if(new Set(t.map(l=>l.capability)).size!==t.length)throw new Error("Native archive preflight contains duplicate capabilities");let i=t.map(l=>({...l,operationHash:H(mI,l)})),n=SI(e.evidence),r=bI(e.workspace),a=[...new Set([...EI(e.findingCodes??[]),...RI({phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetExists:e.targetExists,specs:t,evidence:n})])].sort(Rl),o=NI(e.revision),s=yI(e.targetRef,"Native archive target");if(e.archiveConfirmation!=="automatic"&&e.archiveConfirmation!=="required")throw new Error("Native archive confirmation must be automatic or required");let c={stateSchema:e.stateSchema,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:o,phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetRef:s,targetExists:e.targetExists,operations:i,evidence:n,workspace:r,findingCodes:a};return{schema:hI,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:o,targetRef:s,ready:a.length===0,evidenceFreshness:n.freshness,operationCount:i.length,operations:i,workspace:r,findingCodes:a,preflightHash:H(pI,c)}}import{createHash as CI}from"node:crypto";import _y from"node:path";var PI="comet.native.conflict-radar.v1",ht=Object.freeze({maxChanges:32,maxSpecsPerChange:64,maxArtifactsPerChange:128,maxTotalSpecs:512,maxTotalArtifacts:1024,maxSignalsPerRelationship:8,maxRelationships:256,maxSerializedBytes:64*1024,maxNameBytes:128,maxCapabilityBytes:128,maxArtifactPathBytes:512}),xI="comet.native.conflict-radar.v1",AI="comet.native.conflict-radar-signals.v1",TI=/^[a-f0-9]{64}$/u,Oy=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,_I=new Set(["name","revision","specs","declaredArtifacts","workspaceIdentityHash"]),II=new Set(["capability","operation","baseHash"]),jI=new Set(["path","kind"]);function la(e,t){return et?1:0}function uh(e){return Buffer.byteLength(e,"utf8")}function dh(e,t,i){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${i} must be an object`);let n=e,r=Object.keys(n).filter(a=>!t.has(a));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`);return n}function fh(e,t,i){if(typeof e!="string"||e.length===0||e!==e.trim())throw new Error(`${t} must be a non-empty trimmed string`);if(uh(e)>i)throw new Error(`${t} exceeds its byte budget`);return e}function OI(e,t){let i=fh(e,t,ht.maxArtifactPathBytes),n=_y.posix.normalize(i);if(i.includes("\\")||Array.from(i).some(r=>{let a=r.codePointAt(0)??0;return a<=31||a===127})||/^(?:[A-Za-z]:|~)/u.test(i)||_y.posix.isAbsolute(n)||i.split("/").includes("..")||n!==i||n==="."||i.endsWith("/"))throw new Error(`${t} must be a normalized project-relative path`);return i}function $y(e,t){if(typeof e!="string"||!TI.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function $I(e,t){let i=dh(e,II,t),n=fh(i.capability,`${t} capability`,ht.maxCapabilityBytes);if(!Oy.test(n))throw new Error(`${t} capability is invalid`);if(i.operation!=="create"&&i.operation!=="replace"&&i.operation!=="remove")throw new Error(`${t} operation is invalid`);let r=i.baseHash===null?null:$y(i.baseHash,`${t} canonical base hash`);if(i.operation==="create"&&r!==null)throw new Error(`${t} create operation requires a null canonical base hash`);if(i.operation!=="create"&&r===null)throw new Error(`${t} ${i.operation} operation requires a canonical base hash`);return{capability:n,operation:i.operation,baseHash:r}}function HI(e,t){let i=dh(e,jI,t);if(i.kind!=="file"&&i.kind!=="directory")throw new Error(`${t} kind is invalid`);return{path:OI(i.path,`${t} path`),kind:i.kind}}function DI(e,t){let i=dh(e,_I,`Conflict radar change ${t}`),n=fh(i.name,`Conflict radar change ${t} name`,ht.maxNameBytes);if(!Oy.test(n))throw new Error(`Conflict radar change ${t} name is invalid`);if(!Number.isSafeInteger(i.revision)||i.revision<1)throw new Error(`Conflict radar change ${n} revision must be a positive safe integer`);if(!Array.isArray(i.specs))throw new Error(`Conflict radar change ${n} specs must be an array`);if(i.specs.length>ht.maxSpecsPerChange)throw new Error(`Conflict radar change ${n} exceeds the spec budget`);if(!Array.isArray(i.declaredArtifacts))throw new Error(`Conflict radar change ${n} declared artifacts must be an array`);if(i.declaredArtifacts.length>ht.maxArtifactsPerChange)throw new Error(`Conflict radar change ${n} exceeds the declared artifact budget`);let r=i.specs.map((c,l)=>$I(c,`Conflict radar change ${n} spec ${l}`)).sort((c,l)=>la(c.capability,l.capability));if(new Set(r.map(c=>c.capability)).size!==r.length)throw new Error(`Conflict radar change ${n} has duplicate capabilities`);let a=i.declaredArtifacts.map((c,l)=>HI(c,`Conflict radar change ${n} artifact ${l}`)).sort((c,l)=>la(c.path,l.path)||la(c.kind,l.kind)),o=a.map(c=>c.path);if(new Set(o).size!==o.length)throw new Error(`Conflict radar change ${n} has duplicate or conflicting artifact paths`);let s=i.workspaceIdentityHash===void 0||i.workspaceIdentityHash===null?null:$y(i.workspaceIdentityHash,`Conflict radar change ${n} workspace identity hash`);return{name:n,revision:i.revision,specs:r,declaredArtifacts:a,workspaceIdentityHash:s}}function MI(e){if(!Array.isArray(e))throw new Error("Native conflict radar input must be an array");if(e.length>ht.maxChanges)throw new Error("Native conflict radar exceeds the change budget");let t=e.map(DI).sort((r,a)=>la(r.name,a.name));if(new Set(t.map(r=>r.name)).size!==t.length)throw new Error("Native conflict radar contains duplicate change names");if(t.reduce((r,a)=>r+a.specs.length,0)>ht.maxTotalSpecs)throw new Error("Native conflict radar exceeds the total spec budget");if(t.reduce((r,a)=>r+a.declaredArtifacts.length,0)>ht.maxTotalArtifacts)throw new Error("Native conflict radar exceeds the total declared artifact budget");return t}function FI(e,t){let i=e.baseHash!==null&&e.baseHash===t.baseHash;return{kind:"capability",certainty:e.operation==="create"||t.operation==="create"||i?"definite-conflict":"possible-overlap",capability:e.capability,leftOperation:e.operation,rightOperation:t.operation,leftBaseHash:e.baseHash,rightBaseHash:t.baseHash}}function LI(e,t){let i=e.kind==="directory"&&(t.path===e.path||t.path.startsWith(`${e.path}/`)),n=t.kind==="directory"&&(e.path===t.path||e.path.startsWith(`${t.path}/`)),r=e.kind==="file"&&t.kind==="file"&&e.path===t.path;return!i&&!n&&!r?null:{kind:"artifact",certainty:r?"definite-conflict":"possible-overlap",leftArtifact:e,rightArtifact:t}}function BI(e,t){return e.workspaceIdentityHash===null||t.workspaceIdentityHash===null?"unknown":e.workspaceIdentityHash===t.workspaceIdentityHash?"same":"different"}function qI(e,t){let i=[],n=CI("sha256").update(`${AI} -[`),r=0,a=!1,o=l=>{r>0&&n.update(","),n.update(Yo(l)),r+=1,l.certainty==="definite-conflict"&&(a=!0),i.length[l.capability,l]));for(let l of e.specs){let u=s.get(l.capability);u&&o(FI(l,u))}for(let l of e.declaredArtifacts)for(let u of t.declaredArtifacts){let d=LI(l,u);d&&o(d)}let c=a?"definite-conflict":r>0?"possible-overlap":"disjoint";return n.update("]"),{left:e.name,right:t.name,classification:c,workspaceRelationship:BI(e,t),signalCount:r,signalHash:n.digest("hex"),signals:i,signalsTruncated:i.length!==r}}function Iy(e){return e==="definite-conflict"?0:e==="possible-overlap"?1:2}function VI(e,t){return Iy(e.classification)-Iy(t.classification)||la(e.left,t.left)||la(e.right,t.right)}function jy(e,t,i,n){let r={definiteConflict:t.filter(({classification:a})=>a==="definite-conflict").length,possibleOverlap:t.filter(({classification:a})=>a==="possible-overlap").length,disjoint:t.filter(({classification:a})=>a==="disjoint").length};return{schema:PI,workspaceIdentityAdvisoryOnly:!0,changeCount:e.length,relationshipCount:t.length,counts:r,relationships:i,relationshipsTruncated:i.length!==t.length,omittedRelationshipCount:t.length-i.length,radarHash:n}}function Hy(e){let t=MI(e),i=[];for(let s=0;s({left:s.left,right:s.right,classification:s.classification,workspaceRelationship:s.workspaceRelationship,signalCount:s.signalCount,signalHash:s.signalHash})),r=H(xI,{changes:t,relationships:n}),a=i.slice(0,ht.maxRelationships).map(s=>({...s,signals:[...s.signals]})),o=jy(t,i,a,r);for(;a.length>0&&uh(JSON.stringify(o))>ht.maxSerializedBytes;)a=a.slice(0,-1),o=jy(t,i,a,r);if(uh(JSON.stringify(o))>ht.maxSerializedBytes)throw new Error("Native conflict radar summary exceeds its serialized output budget");return o}import{createHash as EN}from"node:crypto";import{promises as Dt}from"node:fs";import Xt from"node:path";import{createHash as Vy}from"node:crypto";import Dy from"path";var hh="comet.native.implementation-scope.v2",Wy="comet.native.content-snapshot-projection.v1",Xo="comet.native.content-snapshot-projection.v1",Jy="comet.native.implementation-scope.v2",WI="comet.native.unresolved-scope-id.v1",JI="comet.native.scope-detail-overflow.v1",zI="comet.native.snapshot-projection-overflow.v2",gh=/^[a-f0-9]{64}$/u,wi=1024*1024,GI=128,UI=128;function Qe(e,t){return et?1:0}function ph(e){if(!gh.test(e))throw new Error("Native snapshot projection hash must be a SHA-256 hash");return`runtime/evidence/snapshots/${e}.json`}function KI(e,t){return e===t?0:e===null?-1:t===null?1:Qe(e,t)}function _n(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||e.endsWith("/")||/^[a-zA-Z]:/u.test(e))throw new Error(`${t} must be a normalized project-relative path`);let i=Dy.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||Dy.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function zy(e,t){return e==="."?e:_n(e,t)}function ua(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative safe integer`);return e}function YI(e,t){if(e.type!=="file")throw new Error(`${t} must describe a file`);if(typeof e.hash!="string"||e.hash.length===0)throw new Error(`${t} hash must be non-empty`);return{path:_n(e.path,`${t} path`),hash:e.hash,size:ua(e.size,`${t} size`),type:"file"}}function XI(e,t){return{path:zy(e.path,`${t} path`),size:e.size===null?null:ua(e.size,`${t} size`),type:e.type,reason:e.reason}}function QI(e,t){return Qe(e.path,t.path)||Qe(e.hash,t.hash)||e.size-t.size}function ZI(e,t){return Qe(e.path,t.path)||Qe(e.reason,t.reason)||Qe(e.type,t.type)||(e.size??-1)-(t.size??-1)}function Qo(e){return Buffer.byteLength(JSON.stringify(e,null,2)+` +${e.sessionId}`)}:{}},c=e.binding?{schema:"comet.native.workspace.v3",...s,...e.binding,finish:e.finish??null}:{schema:"comet.native.workspace.v2",...s};return na(c),c}async function ra(e){let t=await uy(e),i=ar(e.paths,e.name);return await x(e.paths.nativeRoot,i),await le(i,t,{containedRoot:e.paths.nativeRoot}),t}async function dy(e,t,i){return te(e,`set workspace finish for ${t}`,async()=>{let n=await rh(e,t);if(n===null||n.schema!=="comet.native.workspace.v3")throw new Error(`Native change ${t} has no workspace finishing contract`);if(n.isolation==="current")throw new Error("Native current isolation does not use a workspace finishing action");let r={...n,finish:i};na(r);let a=ar(e,t);return await x(e.nativeRoot,a),await le(a,r,{containedRoot:e.nativeRoot}),r})}async function Ve(e,t){let i=await ly(e,t);return i===null||i&&typeof i=="object"&&!Array.isArray(i)&&i.schema==="comet.native.workspace.v1"?null:(na(i),i)}async function fy(e){return await nh(e.paths,e.name)?ra(e):null}async function or(e){na(e.identity);let t=await uy({paths:e.paths,name:"workspace-advisory",revision:e.identity.capturedRevision}),i=[],n=[];return t.nativeRootRef!==e.identity.nativeRootRef&&i.push("native-root-ref"),e.identity.projectRootPathId&&e.identity.nativeRootPathId?(t.projectRootPathId!==e.identity.projectRootPathId&&i.push("project-root-path"),t.nativeRootPathId!==e.identity.nativeRootPathId&&i.push("native-root-path")):(t.projectRootId!==e.identity.projectRootId&&i.push("project-root-legacy-identity"),t.nativeRootId!==e.identity.nativeRootId&&i.push("native-root-legacy-identity")),Zf==="win32"&&i.length>0&&i.every(a=>a==="project-root-legacy-identity"||a==="native-root-legacy-identity")?n.push("workspace-inspection-unavailable"):i.length>0&&n.push("workspace-root-changed"),{state:n.length===0?"aligned":n.includes("workspace-root-changed")?"drifted":"unknown",findingCodes:n,driftComponents:i}}async function sr(e){if(na(e.identity),e.identity.schema==="comet.native.workspace.v2")return{state:"legacy",code:"workspace-binding-legacy",message:"Legacy Native workspace metadata has no isolation binding"};if((await or(e)).state==="drifted")return{state:"drifted",code:"workspace-binding-root-changed",message:"Native change is being accessed from a different working directory"};let i=Qf(e.paths.projectRoot);return e.identity.changeBranch===null?i.isGitWorktree?{state:"drifted",code:"workspace-branch-changed",message:"Native change was created outside Git but is now being accessed inside Git"}:{state:"aligned",code:null,message:null}:i.isGitWorktree?i.currentBranch!==e.identity.changeBranch?{state:"drifted",code:"workspace-branch-changed",message:`Native change is bound to branch ${e.identity.changeBranch}, but the current branch is ${i.currentBranch??"detached HEAD"}`}:e.identity.isolation==="worktree"&&!i.isSecondaryWorktree?{state:"drifted",code:"workspace-kind-changed",message:"Native change is bound to a linked Git worktree"}:{state:"aligned",code:null,message:null}:{state:"drifted",code:"workspace-vcs-unavailable",message:"Native change requires its bound Git working directory"}}async function rh(e,t){let i=await Ve(e,t);if(i===null)return null;let n=await sr({paths:e,identity:i});if(n.state==="drifted")throw new Error(`${n.code}: ${n.message}`);return i}var xe="comet.native.v3",He="comet.native.v2",jt="comet.native.v1",ji="comet.native.transition.v3",Oi="comet.native.transition.v2",cr="comet.native.transition.v1";var hy=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],q_=new Set(hy),py=new Set([...hy,"minimum_runtime_version","revision"]),V_=new Set([...py,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),W_=new Set(["capability","operation","source","base_hash"]),J_=new Set(["shape","build","verify","archive"]),z_=new Set(["implicit","confirmed"]),G_=new Set(["pending","pass","fail"]),je="comet-state.yaml",oh=/^[a-f0-9]{64}$/u,my=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,U_=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,Vo=class extends Error{constructor(i,n){super(`Native change ${i} uses ${n}; run comet native doctor ${i} --repair before mutating it`);this.change=i;this.schema=n;this.name="NativeSchemaMigrationRequiredError"}change;schema;code="native-schema-migration-required"},Hi=class extends Error{constructor(i,n){super(i!==xe||n===null?`Unsupported Native change schema ${i} for runtime protocol ${3}`:`Native change ${i} requires runtime protocol ${n}; current protocol is ${3}`);this.schema=i;this.minimumRuntimeVersion=n;this.name="NativeRuntimeCompatibilityError"}schema;minimumRuntimeVersion;code="native-runtime-incompatible"},xn=class extends Error{constructor(i,n,r){super(`Native change ${i} revision conflict: expected ${n}, actual ${r}`);this.change=i;this.expectedRevision=n;this.actualRevision=r;this.name="NativeChangeRevisionConflictError"}change;expectedRevision;actualRevision;code="native-change-revision-conflict"},Wo=class extends Error{constructor(i,n){super(`Native working directory already contains active change${n.length===1?"":"s"} ${n.join(", ")}; create the new change in a separate worktree`);this.requestedIsolation=i;this.activeChanges=n;this.name="NativeWorkspaceIsolationRequiredError"}requestedIsolation;activeChanges;code="native-workspace-isolation-required"},gi=class extends Error{constructor(i,n,r,a,o,s=null,c=null){super(`Native change ${i} baseline is incomplete (${n} omitted entr${n===1?"y":"ies"}). Adjust native.snapshot scope or resource budgets in .comet/config.yaml, then retry.`);this.change=i;this.omittedCount=n;this.omittedByReason=r;this.samplePaths=a;this.sampleTruncated=o;this.effectiveLimits=s;this.policyHash=c;this.name="NativeBaselineIncompleteError"}change;omittedCount;omittedByReason;samplePaths;sampleTruncated;effectiveLimits;policyHash;code="native-baseline-incomplete"},K_=["# Outcome","","# Scope","","# Non-goals","","# Acceptance examples","","# Constraints and invariants","","# Decisions","","# Open questions","","# Verification expectations",""].join(` +`);function Go(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function vy(e,t,i){let n=Object.keys(e).filter(r=>!t.has(r));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`)}function zt(e){if(!my.test(e))throw new Error(`Invalid Native change name: ${e}`)}function Y_(e){if(!my.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function gy(e,t){if(e.length===0||dt.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function X_(e,t){let i=Go(e,`spec_changes[${t}]`);if(vy(i,W_,`spec_changes[${t}]`),typeof i.capability!="string")throw new Error("spec change capability is required");if(Y_(i.capability),i.operation!=="create"&&i.operation!=="replace"&&i.operation!=="remove")throw new Error(`Invalid spec operation for ${i.capability}`);let n=i.source,r=i.base_hash;if(n!==void 0&&typeof n!="string")throw new Error(`Spec source for ${i.capability} must be a string`);if(typeof n=="string"&&gy(n,`Spec source for ${i.capability}`),i.operation==="create"){if(!n)throw new Error(`Create spec ${i.capability} requires source`);if(r!==null)throw new Error(`Create spec ${i.capability} requires null base_hash`)}else if(i.operation==="replace"){if(!n)throw new Error(`Replace spec ${i.capability} requires source`);if(typeof r!="string"||!oh.test(r))throw new Error(`Replace spec ${i.capability} requires a SHA-256 base_hash`)}else{if(n!==void 0)throw new Error(`Remove spec ${i.capability} forbids source`);if(typeof r!="string"||!oh.test(r))throw new Error(`Remove spec ${i.capability} requires a SHA-256 base_hash`)}return{capability:i.capability,operation:i.operation,...typeof n=="string"?{source:n}:{},base_hash:r}}function Q_(e){return/^\d{4}-\d{2}-\d{2}$/u.test(e)?new Date(`${e}T00:00:00.000Z`).toISOString().slice(0,10)===e:!1}function sh(e,t){if(vy(e,t,je),typeof e.name!="string")throw new Error("Native change name is required");if(zt(e.name),e.language!=="en"&&e.language!=="zh-CN")throw new Error("Native change language must be en or zh-CN");if(typeof e.phase!="string"||!J_.has(e.phase))throw new Error("Native change phase is invalid");if(e.brief!=="brief.md")throw new Error("Native change brief must be brief.md");if(e.approval!==null&&!z_.has(e.approval))throw new Error("Native change approval is invalid");if(!Array.isArray(e.spec_changes))throw new Error("Native spec_changes must be an array");let i=e.spec_changes.map(X_),n=i.map(r=>r.capability).filter((r,a,o)=>o.indexOf(r)!==a);if(n.length>0)throw new Error(`Duplicate Native capability operation: ${[...new Set(n)].join(", ")}`);if(typeof e.verification_result!="string"||!G_.has(e.verification_result))throw new Error("Native verification_result is invalid");if(e.verification_report!==null&&typeof e.verification_report!="string")throw new Error("Native verification_report must be a string or null");if(typeof e.verification_report=="string"&&gy(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!Q_(e.created_at))throw new Error("Native created_at must be a valid YYYY-MM-DD date");if(e.run_id!==null&&(typeof e.run_id!="string"||e.run_id.length===0))throw new Error("Native run_id must be a non-empty string or null");return{name:e.name,language:e.language,phase:e.phase,brief:"brief.md",approval:e.approval,spec_changes:i,verification_result:e.verification_result,verification_report:e.verification_report,archived:e.archived,created_at:e.created_at,run_id:e.run_id}}function Uo(e){let t=Go(e,je);if(t.schema!==jt)throw new Error(`Expected ${jt}`);return{schema:jt,...sh(t,q_)}}function Jo(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function ah(e,t,i){if(e===null)return null;let n=typeof e=="string"?U_.exec(e):null;if(!n||n[1]!==i)throw new Error(`${t} must be null or runtime/evidence/${i}/.json relative to the Native change`);return e}function Z_(e){if(e==null)return null;if(typeof e!="string"||!oh.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function eI(e){if(e===void 0)return"legacy-v1";if(e!=="legacy-v1")throw new Error("Native verification_protocol must be legacy-v1");return e}function An(e){let t=Go(e,je);if(t.schema!==He)throw new Error(`Expected ${He}`);if(Jo(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${He} minimum_runtime_version must be 2`);return{schema:He,minimum_runtime_version:2,revision:Jo(t.revision,"Native v2 revision"),...sh(t,py)}}function Ot(e){let t=Go(e,je);if(t.schema!==xe){if(t.schema===jt||t.schema===He){let o=t.schema===jt?Uo(t):An(t);throw new Vo(o.name,o.schema)}throw new Hi(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let i=Jo(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)throw new Hi(t.schema,i);if(i!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let n=Jo(t.revision,"Native revision"),r=sh(t,V_),a=Z_(t.approved_contract_hash);if(r.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:xe,minimum_runtime_version:3,revision:n,verification_protocol:eI(t.verification_protocol),...r,approved_contract_hash:a,implementation_scope:ah(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:ah(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:ah(t.partial_allowance,"Native partial_allowance","allowances")}}function wy(e){let t=Go(e,je);if(t.schema===jt){let r=Uo(t);return{status:"migration-required",schema:r.schema,minimumRuntimeVersion:1,state:r,message:`Native change ${r.name} requires migration to ${xe}`}}if(t.schema===He){let r=An(t);return{status:"migration-required",schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,state:r,message:`Native change ${r.name} requires migration to ${xe}`}}if(t.schema!==xe){let r=typeof t.minimum_runtime_version=="number"&&Number.isSafeInteger(t.minimum_runtime_version)?t.minimum_runtime_version:null;return{status:"runtime-incompatible",schema:typeof t.schema=="string"?t.schema:"(missing)",minimumRuntimeVersion:r,state:null,message:new Hi(typeof t.schema=="string"?t.schema:"(missing)",r).message}}let i=Jo(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:i,state:null,message:new Hi(t.schema,i).message};let n=Ot(t);return{status:"current",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n}}function Pn(e){let t=Ot(e);return{schema:t.schema,minimum_runtime_version:t.minimum_runtime_version,revision:t.revision,verification_protocol:t.verification_protocol,name:t.name,language:t.language,phase:t.phase,brief:t.brief,approval:t.approval,approved_contract_hash:t.approved_contract_hash??null,spec_changes:t.spec_changes.map(i=>({capability:i.capability,operation:i.operation,...i.source?{source:i.source}:{},base_hash:i.base_hash})),verification_result:t.verification_result,verification_report:t.verification_report,implementation_scope:t.implementation_scope,verification_evidence:t.verification_evidence,partial_allowance:t.partial_allowance,archived:t.archived,created_at:t.created_at,run_id:t.run_id}}function Sl(e){let t=An(e);return{schema:t.schema,minimum_runtime_version:t.minimum_runtime_version,revision:t.revision,name:t.name,language:t.language,phase:t.phase,brief:t.brief,approval:t.approval,spec_changes:t.spec_changes.map(i=>({capability:i.capability,operation:i.operation,...i.source?{source:i.source}:{},base_hash:i.base_hash})),verification_result:t.verification_result,verification_report:t.verification_report,archived:t.archived,created_at:t.created_at,run_id:t.run_id}}function C(e,t){zt(t);let i=dt.join(e.changesDir,t);if(!$(e.changesDir,i))throw new Error("Native change path escaped");return i}async function lr(e,t){let i=dt.join(C(e,t),"runtime","schema-migration.json");await x(e.nativeRoot,i);try{return await $i.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function aa(e,t){let i=dt.join(C(e,t),"runtime","checkpoint-journal.json");await x(e.nativeRoot,i);try{return await $i.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function yy(e){return te(e.paths,`create change ${e.name}`,()=>tI(e))}async function tI(e){if(zt(e.name),e.initialProjectConfig&&await re(e.paths.projectRoot)===null&&await li(e.paths.projectRoot,e.initialProjectConfig),e.workspaceBinding){cy(e.paths.projectRoot,e.workspaceBinding);let r=await sI(e.paths);if(r.length>0)throw new Wo(e.workspaceBinding.isolation,r)}let t=e.verificationProtocol??"legacy-v1",i=C(e.paths,e.name);await x(e.paths.nativeRoot,i);let n=!1;try{try{await $i.mkdir(i,{recursive:!1}),n=!0}catch(c){if(c.code==="ENOENT"){await $i.mkdir(e.paths.changesDir,{recursive:!0});try{await $i.mkdir(i,{recursive:!1}),n=!0}catch(l){throw l.code==="EEXIST"?new Error(`Native change already exists: ${e.name}`,{cause:l}):l}}else throw c.code==="EEXIST"?new Error(`Native change already exists: ${e.name}`,{cause:c}):c}let r={schema:xe,minimum_runtime_version:3,revision:1,verification_protocol:t,name:e.name,language:e.language,phase:"shape",brief:"brief.md",approval:null,approved_contract_hash:null,spec_changes:[],verification_result:"pending",verification_report:null,implementation_scope:null,verification_evidence:null,partial_allowance:null,archived:!1,created_at:(e.now??new Date).toISOString().slice(0,10),run_id:null};await Promise.all([$i.mkdir(dt.join(i,"specs"),{recursive:!0}),$i.mkdir(dt.join(i,"runtime","checkpoints"),{recursive:!0}),$e(dt.join(i,"brief.md"),K_)]);let o=(await re(e.paths.projectRoot))?.native.snapshot??zc,s=await $o(e.paths,{now:e.now,origin:"change-created",policy:o,limits:{maxFiles:o.max_files,maxFileBytes:o.max_total_bytes,maxTotalBytes:o.max_total_bytes,maxDurationMs:o.max_duration_ms},deadlineMs:o.max_duration_ms});if(!s.complete){let c=hl(s),l=s.omitted.reduce((d,f)=>(d[f.reason]=(d[f.reason]??0)+1,d),{}),u=s.omissionOverflow?.count??0;throw u>0&&(l.overflow=u),new gi(r.name,s.omittedCount,l,c.samplePaths,c.sampleTruncated,s.limits,s.policy?.hash??null)}return await pl(e.paths,r.name,s),await aI(e.paths,r),await ra({paths:e.paths,name:r.name,revision:r.revision,now:e.now,...e.workspaceBinding?{binding:e.workspaceBinding}:{}}),r}catch(r){throw n&&await $i.rm(i,{recursive:!0,force:!0}),r}}var iI=256*1024;async function El(e,t=dt.dirname(e)){let i=dt.relative(t,e).split(dt.sep).join("/"),n=await ye({root:t,ref:i,maxBytes:iI}),r=(0,zo.parseDocument)(n.text,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`Invalid Native change file ${e}: ${r.errors[0].message}`);return r.toJS()}async function ft(e,t){let i=dt.join(C(e,t),je);await x(e.nativeRoot,i);let n=wy(await El(i,e.nativeRoot));if(n.state&&n.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return await lr(e,t)?{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimumRuntimeVersion,state:n.state,message:`Native schema migration is incomplete for ${t}; run doctor --repair`}:(n.status==="current"&&n.state&&await rI(e,n.state),n)}async function nI(e,t){let i=dt.join(C(e,t),je);await x(e.nativeRoot,i);let n=wy(await El(i,e.nativeRoot));if(n.state&&n.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return n}async function rI(e,t){if(await vi(e,t.name)!==null&&t.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${t.verification_protocol}`)}async function G(e,t){let i=await ft(e,t);if(i.status==="migration-required")throw new Vo(t,i.schema);if(i.status==="runtime-incompatible"||!i.state)throw new Hi(i.schema,i.minimumRuntimeVersion);return await rh(e,t),i.state}async function aI(e,t){let i=dt.join(C(e,t.name),je);await x(e.nativeRoot,i);try{throw await $i.access(i),new Error(`Native change state already exists: ${t.name}`)}catch(n){if(n.code!=="ENOENT")throw n}if(t.revision!==1)throw new Error("New Native change must start at revision 1");await $e(i,(0,zo.stringify)(Pn(t)))}async function Ny(e,t,i){let n={...t,schema:xe,minimum_runtime_version:3,revision:i+1},r=await gw({expectedRevision:i,next:n,read:async()=>{let a=Ot(await El(e));if(a.name!==t.name)throw new Error(`Native change file/name mismatch: ${t.name}`);return a},write:a=>$e(e,(0,zo.stringify)(Pn(a))),equals:(a,o)=>JSON.stringify(Pn(a))===JSON.stringify(Pn(o)),conflict:a=>new xn(t.name,i,a)});return Object.assign(t,r),r}async function oa(e,t,i,n){if(await Vr(e.projectRoot),await lr(e,t.name))throw new Vo(t.name,t.schema);if(!n?.allowPendingCheckpointRecovery&&await aa(e,t.name))throw new Error(`Native progress checkpoint recovery is required for ${t.name} before another state write`);if((await G(e,t.name)).verification_protocol!==t.verification_protocol)throw new Error("Native verification protocol changed outside a revisioned state transition");await Lo(e,t.name);let a=dt.join(C(e,t.name),je);return await x(e.nativeRoot,a),Ny(a,t,i)}async function by(e,t){return Ny(e,t,t.revision)}async function ky(e){return Ot(await El(e))}async function oI(e){let t;try{let n=await st({root:e.nativeRoot,directory:e.changesDir,label:"Native changes directory",maxEntries:4096});await n.verify(),t=n.entries}catch(n){if(n.code==="ENOENT")return[];throw n}return t.filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort()}async function sI(e){let t=[];for(let i of await oI(e)){let n=await nI(e,i);if(!n.state){t.push(i);continue}if(n.state.archived)continue;let r=await Ve(e,i);if(r?.schema==="comet.native.workspace.v3"){if((await sr({paths:e,identity:r})).code==="workspace-binding-root-changed")continue}else if(r&&(await or({paths:e,identity:r})).state==="drifted")continue;t.push(i)}return t}var Ey=["Outcome","Scope","Non-goals","Acceptance examples"],cI=[...Ey,"Constraints and invariants","Decisions","Open questions","Verification expectations"],lI=["Acceptance evidence","Commands and results","Skipped checks","Spec consistency","Known limitations and risks","Conclusion"],Ry={maxFileBytes:ho};function Cy(e){let t=new Map,i=null,n=[],r=()=>{i!==null&&t.set(i,n.join(` +`).trim())};for(let a of e.split(/\r?\n/u)){let o=/^# ([^#].*)$/u.exec(a);o?(r(),i=o[1].trim(),n=[]):i!==null&&n.push(a)}return r(),t}async function Py(e,t){let i=Sy.resolve(e,...t.split(/[\\/]/u));if(!$(e,i))throw new Error(`Artifact escapes Native change: ${t}`);let n=await ch.realpath(e),r=await ch.realpath(i);if(!$(n,r))throw new Error(`Artifact symlink escapes Native change: ${t}`);if(!(await ch.stat(r)).isFile())throw new Error(`Artifact is not a file: ${t}`);return r}function Ko(e){return{valid:e.length===0,findings:e}}async function ur(e,t){let i=[],n;try{n=(await ye({root:e,ref:t,maxBytes:Ry.maxFileBytes})).text}catch(o){return Ko([{code:"brief-missing",message:o.message,path:t}])}let r=Cy(n);for(let o of cI)r.has(o)||i.push({code:"brief-section-missing",message:`Missing brief section: ${o}`,path:t});for(let o of Ey)(r.get(o)??"").length===0&&i.push({code:"brief-section-empty",message:`Brief section is empty: ${o}`,path:t});let a=r.get("Open questions")??"";return/^\s*-\s*\[blocking\]/imu.test(a)&&i.push({code:"brief-blocking-question",message:"Brief has a blocking open question",path:t}),Ko(i)}async function sa(e,t){let i=[],n;try{n=(await ye({root:e,ref:t,maxBytes:Ry.maxFileBytes})).text}catch(a){return Ko([{code:"verification-missing",message:a.message,path:t}])}let r=Cy(n);for(let a of lI)r.has(a)?(r.get(a)??"").length===0&&i.push({code:"verification-section-empty",message:`Verification section is empty: ${a}`,path:t}):i.push({code:"verification-section-missing",message:`Missing verification section: ${a}`,path:t});return Ko(i)}function Gt(e,t){return Sy.join(e.specsDir,t,"spec.md")}async function ca(e,t){let i=[],n=C(e,t.name);for(let r of t.spec_changes){let a=Gt(e,r.capability),o=null;try{await x(e.nativeRoot,a),o=await lt(a)}catch(s){if(s.code!=="ENOENT"){i.push({code:"spec-canonical-unsafe",message:s.message,path:a});continue}}if(r.operation==="create"&&o!==null&&i.push({code:"spec-create-exists",message:`Canonical spec already exists: ${r.capability}`,path:a}),r.operation!=="create"&&o===null&&i.push({code:"spec-base-missing",message:`Canonical spec is missing: ${r.capability}`,path:a}),r.operation!=="create"&&o!==null&&o!==r.base_hash&&i.push({code:"spec-base-conflict",message:`Canonical spec changed for ${r.capability}: expected ${r.base_hash}, actual ${o}`,path:a}),r.source)try{await Py(n,r.source)}catch(s){i.push({code:"spec-source-invalid",message:s.message,path:r.source})}}return Ko(i)}async function xy(e,t){return Py(e,t)}import{promises as q$}from"node:fs";import tk from"node:path";import Ay from"node:path";import{createHash as uI}from"crypto";function Ut(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function dI(e,t){t.has(e)&&Ut("cyclic structures are not supported"),t.add(e);try{let i=Object.keys(e);for(let n=0;nn!==String(r)))&&Ut("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&Ut("symbol properties are not supported"),`[${e.map(n=>lh(n,t)).join(",")}]`}finally{t.delete(e)}}function fI(e,t){let i=Object.getPrototypeOf(e);i!==Object.prototype&&i!==null&&Ut("only plain objects are supported"),t.has(e)&&Ut("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&Ut("symbol properties are not supported"),t.add(e);try{let n=Object.getOwnPropertyDescriptors(e);return`{${Object.keys(e).sort().map(o=>{let s=n[o];return(!s||!("value"in s))&&Ut("accessor properties are not supported"),`${JSON.stringify(o)}:${lh(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function lh(e,t){if(e===null)return"null";switch(typeof e){case"boolean":return e?"true":"false";case"string":return JSON.stringify(e);case"number":return Number.isFinite(e)||Ut("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?dI(e,t):fI(e,t);case"bigint":case"function":case"symbol":case"undefined":return Ut(`${typeof e} values are not supported`)}return Ut("unsupported value type")}function Yo(e){return lh(e,new Set)}function H(e,t){if(e.length===0)throw new TypeError("Canonical hash tag must be non-empty");if(/[\r\n]/u.test(e))throw new TypeError("Canonical hash tag must not contain a line break");return uI("sha256").update(`${e} +${Yo(t)}`).digest("hex")}var hI="comet.native.archive-preflight.v1",pI="comet.native.archive-preflight.v1",mI="comet.native.archive-operation.v1",vI=/^[a-f0-9]{64}$/u,Ty=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,gI=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function Rl(e,t){return et?1:0}function wI(e,t){if(typeof e!="string"||!vI.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Di(e,t){return e===null?null:wI(e,t)}function yI(e,t){let i=Ay.posix.normalize(e);if(typeof e!="string"||e.length===0||e!==e.trim()||e.includes("\\")||Ay.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||i!==e||i==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized Native-relative ref`);return e}function NI(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native archive preflight revision must be a positive integer");return e}function bI(e){if(e==null)return null;if(e.schema!=="comet.native.workspace.v3")throw new Error("Native archive workspace schema is invalid");if(e.isolation!=="current"&&e.isolation!=="branch"&&e.isolation!=="worktree")throw new Error("Native archive workspace isolation is invalid");for(let[t,i]of[["change",e.changeBranch],["target",e.targetBranch]])if(i!==null&&(i.length===0||i.trim()!==i||Array.from(i).some(n=>{let r=n.codePointAt(0)??0;return r<=31||r===127})))throw new Error(`Native archive workspace ${t} branch is invalid`);if(e.finish!==null&&e.finish!=="merge"&&e.finish!=="push"&&e.finish!=="pull-request"&&e.finish!=="keep")throw new Error("Native archive workspace finish is invalid");if((e.isolation==="branch"||e.isolation==="worktree")&&(e.changeBranch===null||e.targetBranch===null||e.finish===null))throw new Error("Native isolated archive workspace requires branches and a finish action");if(e.isolation==="current"&&e.finish!==null)throw new Error("Native current archive workspace cannot have a finish action");return{...e}}function kI(e,t){if(!Ty.test(e.capability))throw new Error(`Native archive spec ${t} capability is invalid`);if(e.operation!=="create"&&e.operation!=="replace"&&e.operation!=="remove")throw new Error(`Native archive spec ${e.capability} operation is invalid`);let i=Di(e.expectedBaseHash,`Native archive spec ${e.capability} expected base`),n=Di(e.actualBaseHash,`Native archive spec ${e.capability} actual base`),r=Di(e.proposedHash,`Native archive spec ${e.capability} proposed content`);if(e.operation==="create"&&i!==null)throw new Error(`Native archive create ${e.capability} must expect no canonical base`);if(e.operation!=="create"&&i===null)throw new Error(`Native archive ${e.operation} ${e.capability} requires a base hash`);if(e.operation==="remove"!=(r===null))throw new Error(`Native archive ${e.operation} ${e.capability} proposed hash is invalid`);return{capability:e.capability,operation:e.operation,expectedBaseHash:i,actualBaseHash:n,proposedHash:r}}function SI(e){if(e.result!=="pending"&&e.result!=="pass"&&e.result!=="fail")throw new Error("Native archive verification result is invalid");if(!["missing","invalid","stale","complete","partial"].includes(e.freshness))throw new Error("Native archive verification freshness is invalid");if(!Number.isSafeInteger(e.skippedAcceptanceCount)||e.skippedAcceptanceCount<0)throw new Error("Native archive skipped acceptance count is invalid");let t={result:e.result,freshness:e.freshness,contractHash:Di(e.contractHash,"Native archive contract hash"),acceptanceHash:Di(e.acceptanceHash,"Native archive acceptance hash"),implementationScopeHash:Di(e.implementationScopeHash,"Native archive implementation scope hash"),reportHash:Di(e.reportHash,"Native archive report hash"),envelopeHash:Di(e.envelopeHash,"Native archive envelope hash"),partialAllowanceHash:Di(e.partialAllowanceHash,"Native archive partial allowance hash"),skippedAcceptanceCount:e.skippedAcceptanceCount};if((e.freshness==="complete"||e.freshness==="partial")&&[t.contractHash,t.acceptanceHash,t.implementationScopeHash,t.reportHash,t.envelopeHash].some(i=>i===null))throw new Error("Fresh Native archive evidence requires every bound content hash");if(e.freshness==="partial"&&t.partialAllowanceHash===null||e.freshness==="complete"&&t.partialAllowanceHash!==null)throw new Error("Native archive partial evidence allowance state is invalid");return t}function EI(e){if(e.length>64)throw new Error("Native archive preflight has too many findings");let t=e.map(n=>{if(typeof n!="string"||!gI.test(n))throw new Error(`Native archive preflight finding code is invalid: ${String(n)}`);return n}),i=[...new Set(t)].sort(Rl);if(i.length!==t.length)throw new Error("Native archive preflight has duplicate finding codes");return i}function RI(e){let t=[];e.phase!=="archive"&&t.push("archive-phase-required"),e.archived&&t.push("change-already-archived"),e.pendingJournal&&t.push("pending-journal"),e.targetExists&&t.push("archive-target-exists"),e.evidence.result!=="pass"&&t.push("verification-not-passed"),e.evidence.freshness==="missing"&&t.push("verification-evidence-missing"),e.evidence.freshness==="invalid"&&t.push("verification-evidence-invalid"),e.evidence.freshness==="stale"&&t.push("verification-evidence-stale"),e.evidence.skippedAcceptanceCount>0&&t.push("verification-acceptance-skipped");for(let i of e.specs)i.actualBaseHash!==i.expectedBaseHash&&t.push("spec-base-conflict");return[...new Set(t)].sort(Rl)}function _y(e){if(!Ty.test(e.change))throw new Error("Native archive change name is invalid");if(typeof e.stateSchema!="string"||e.stateSchema.length===0)throw new Error("Native archive state schema is invalid");if(!Array.isArray(e.specs)||e.specs.length>64)throw new Error("Native archive preflight exceeds its spec budget");let t=e.specs.map(kI).sort((l,u)=>Rl(l.capability,u.capability));if(new Set(t.map(l=>l.capability)).size!==t.length)throw new Error("Native archive preflight contains duplicate capabilities");let i=t.map(l=>({...l,operationHash:H(mI,l)})),n=SI(e.evidence),r=bI(e.workspace),a=[...new Set([...EI(e.findingCodes??[]),...RI({phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetExists:e.targetExists,specs:t,evidence:n})])].sort(Rl),o=NI(e.revision),s=yI(e.targetRef,"Native archive target");if(e.archiveConfirmation!=="automatic"&&e.archiveConfirmation!=="required")throw new Error("Native archive confirmation must be automatic or required");let c={stateSchema:e.stateSchema,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:o,phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetRef:s,targetExists:e.targetExists,operations:i,evidence:n,workspace:r,findingCodes:a};return{schema:hI,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:o,targetRef:s,ready:a.length===0,evidenceFreshness:n.freshness,operationCount:i.length,operations:i,workspace:r,findingCodes:a,preflightHash:H(pI,c)}}import{createHash as CI}from"node:crypto";import Iy from"node:path";var PI="comet.native.conflict-radar.v1",ht=Object.freeze({maxChanges:32,maxSpecsPerChange:64,maxArtifactsPerChange:128,maxTotalSpecs:512,maxTotalArtifacts:1024,maxSignalsPerRelationship:8,maxRelationships:256,maxSerializedBytes:64*1024,maxNameBytes:128,maxCapabilityBytes:128,maxArtifactPathBytes:512}),xI="comet.native.conflict-radar.v1",AI="comet.native.conflict-radar-signals.v1",TI=/^[a-f0-9]{64}$/u,$y=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,_I=new Set(["name","revision","specs","declaredArtifacts","workspaceIdentityHash"]),II=new Set(["capability","operation","baseHash"]),jI=new Set(["path","kind"]);function la(e,t){return et?1:0}function uh(e){return Buffer.byteLength(e,"utf8")}function dh(e,t,i){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${i} must be an object`);let n=e,r=Object.keys(n).filter(a=>!t.has(a));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`);return n}function fh(e,t,i){if(typeof e!="string"||e.length===0||e!==e.trim())throw new Error(`${t} must be a non-empty trimmed string`);if(uh(e)>i)throw new Error(`${t} exceeds its byte budget`);return e}function OI(e,t){let i=fh(e,t,ht.maxArtifactPathBytes),n=Iy.posix.normalize(i);if(i.includes("\\")||Array.from(i).some(r=>{let a=r.codePointAt(0)??0;return a<=31||a===127})||/^(?:[A-Za-z]:|~)/u.test(i)||Iy.posix.isAbsolute(n)||i.split("/").includes("..")||n!==i||n==="."||i.endsWith("/"))throw new Error(`${t} must be a normalized project-relative path`);return i}function Hy(e,t){if(typeof e!="string"||!TI.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function $I(e,t){let i=dh(e,II,t),n=fh(i.capability,`${t} capability`,ht.maxCapabilityBytes);if(!$y.test(n))throw new Error(`${t} capability is invalid`);if(i.operation!=="create"&&i.operation!=="replace"&&i.operation!=="remove")throw new Error(`${t} operation is invalid`);let r=i.baseHash===null?null:Hy(i.baseHash,`${t} canonical base hash`);if(i.operation==="create"&&r!==null)throw new Error(`${t} create operation requires a null canonical base hash`);if(i.operation!=="create"&&r===null)throw new Error(`${t} ${i.operation} operation requires a canonical base hash`);return{capability:n,operation:i.operation,baseHash:r}}function HI(e,t){let i=dh(e,jI,t);if(i.kind!=="file"&&i.kind!=="directory")throw new Error(`${t} kind is invalid`);return{path:OI(i.path,`${t} path`),kind:i.kind}}function DI(e,t){let i=dh(e,_I,`Conflict radar change ${t}`),n=fh(i.name,`Conflict radar change ${t} name`,ht.maxNameBytes);if(!$y.test(n))throw new Error(`Conflict radar change ${t} name is invalid`);if(!Number.isSafeInteger(i.revision)||i.revision<1)throw new Error(`Conflict radar change ${n} revision must be a positive safe integer`);if(!Array.isArray(i.specs))throw new Error(`Conflict radar change ${n} specs must be an array`);if(i.specs.length>ht.maxSpecsPerChange)throw new Error(`Conflict radar change ${n} exceeds the spec budget`);if(!Array.isArray(i.declaredArtifacts))throw new Error(`Conflict radar change ${n} declared artifacts must be an array`);if(i.declaredArtifacts.length>ht.maxArtifactsPerChange)throw new Error(`Conflict radar change ${n} exceeds the declared artifact budget`);let r=i.specs.map((c,l)=>$I(c,`Conflict radar change ${n} spec ${l}`)).sort((c,l)=>la(c.capability,l.capability));if(new Set(r.map(c=>c.capability)).size!==r.length)throw new Error(`Conflict radar change ${n} has duplicate capabilities`);let a=i.declaredArtifacts.map((c,l)=>HI(c,`Conflict radar change ${n} artifact ${l}`)).sort((c,l)=>la(c.path,l.path)||la(c.kind,l.kind)),o=a.map(c=>c.path);if(new Set(o).size!==o.length)throw new Error(`Conflict radar change ${n} has duplicate or conflicting artifact paths`);let s=i.workspaceIdentityHash===void 0||i.workspaceIdentityHash===null?null:Hy(i.workspaceIdentityHash,`Conflict radar change ${n} workspace identity hash`);return{name:n,revision:i.revision,specs:r,declaredArtifacts:a,workspaceIdentityHash:s}}function MI(e){if(!Array.isArray(e))throw new Error("Native conflict radar input must be an array");if(e.length>ht.maxChanges)throw new Error("Native conflict radar exceeds the change budget");let t=e.map(DI).sort((r,a)=>la(r.name,a.name));if(new Set(t.map(r=>r.name)).size!==t.length)throw new Error("Native conflict radar contains duplicate change names");if(t.reduce((r,a)=>r+a.specs.length,0)>ht.maxTotalSpecs)throw new Error("Native conflict radar exceeds the total spec budget");if(t.reduce((r,a)=>r+a.declaredArtifacts.length,0)>ht.maxTotalArtifacts)throw new Error("Native conflict radar exceeds the total declared artifact budget");return t}function FI(e,t){let i=e.baseHash!==null&&e.baseHash===t.baseHash;return{kind:"capability",certainty:e.operation==="create"||t.operation==="create"||i?"definite-conflict":"possible-overlap",capability:e.capability,leftOperation:e.operation,rightOperation:t.operation,leftBaseHash:e.baseHash,rightBaseHash:t.baseHash}}function LI(e,t){let i=e.kind==="directory"&&(t.path===e.path||t.path.startsWith(`${e.path}/`)),n=t.kind==="directory"&&(e.path===t.path||e.path.startsWith(`${t.path}/`)),r=e.kind==="file"&&t.kind==="file"&&e.path===t.path;return!i&&!n&&!r?null:{kind:"artifact",certainty:r?"definite-conflict":"possible-overlap",leftArtifact:e,rightArtifact:t}}function BI(e,t){return e.workspaceIdentityHash===null||t.workspaceIdentityHash===null?"unknown":e.workspaceIdentityHash===t.workspaceIdentityHash?"same":"different"}function qI(e,t){let i=[],n=CI("sha256").update(`${AI} +[`),r=0,a=!1,o=l=>{r>0&&n.update(","),n.update(Yo(l)),r+=1,l.certainty==="definite-conflict"&&(a=!0),i.length[l.capability,l]));for(let l of e.specs){let u=s.get(l.capability);u&&o(FI(l,u))}for(let l of e.declaredArtifacts)for(let u of t.declaredArtifacts){let d=LI(l,u);d&&o(d)}let c=a?"definite-conflict":r>0?"possible-overlap":"disjoint";return n.update("]"),{left:e.name,right:t.name,classification:c,workspaceRelationship:BI(e,t),signalCount:r,signalHash:n.digest("hex"),signals:i,signalsTruncated:i.length!==r}}function jy(e){return e==="definite-conflict"?0:e==="possible-overlap"?1:2}function VI(e,t){return jy(e.classification)-jy(t.classification)||la(e.left,t.left)||la(e.right,t.right)}function Oy(e,t,i,n){let r={definiteConflict:t.filter(({classification:a})=>a==="definite-conflict").length,possibleOverlap:t.filter(({classification:a})=>a==="possible-overlap").length,disjoint:t.filter(({classification:a})=>a==="disjoint").length};return{schema:PI,workspaceIdentityAdvisoryOnly:!0,changeCount:e.length,relationshipCount:t.length,counts:r,relationships:i,relationshipsTruncated:i.length!==t.length,omittedRelationshipCount:t.length-i.length,radarHash:n}}function Dy(e){let t=MI(e),i=[];for(let s=0;s({left:s.left,right:s.right,classification:s.classification,workspaceRelationship:s.workspaceRelationship,signalCount:s.signalCount,signalHash:s.signalHash})),r=H(xI,{changes:t,relationships:n}),a=i.slice(0,ht.maxRelationships).map(s=>({...s,signals:[...s.signals]})),o=Oy(t,i,a,r);for(;a.length>0&&uh(JSON.stringify(o))>ht.maxSerializedBytes;)a=a.slice(0,-1),o=Oy(t,i,a,r);if(uh(JSON.stringify(o))>ht.maxSerializedBytes)throw new Error("Native conflict radar summary exceeds its serialized output budget");return o}import{createHash as RN}from"node:crypto";import{promises as Dt}from"node:fs";import Xt from"node:path";import{createHash as Wy}from"node:crypto";import My from"path";var hh="comet.native.implementation-scope.v2",Jy="comet.native.content-snapshot-projection.v1",Xo="comet.native.content-snapshot-projection.v1",zy="comet.native.implementation-scope.v2",WI="comet.native.unresolved-scope-id.v1",JI="comet.native.scope-detail-overflow.v1",zI="comet.native.snapshot-projection-overflow.v2",gh=/^[a-f0-9]{64}$/u,wi=1024*1024,GI=128,UI=128;function Qe(e,t){return et?1:0}function ph(e){if(!gh.test(e))throw new Error("Native snapshot projection hash must be a SHA-256 hash");return`runtime/evidence/snapshots/${e}.json`}function KI(e,t){return e===t?0:e===null?-1:t===null?1:Qe(e,t)}function _n(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||e.endsWith("/")||/^[a-zA-Z]:/u.test(e))throw new Error(`${t} must be a normalized project-relative path`);let i=My.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||My.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function Gy(e,t){return e==="."?e:_n(e,t)}function ua(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative safe integer`);return e}function YI(e,t){if(e.type!=="file")throw new Error(`${t} must describe a file`);if(typeof e.hash!="string"||e.hash.length===0)throw new Error(`${t} hash must be non-empty`);return{path:_n(e.path,`${t} path`),hash:e.hash,size:ua(e.size,`${t} size`),type:"file"}}function XI(e,t){return{path:Gy(e.path,`${t} path`),size:e.size===null?null:ua(e.size,`${t} size`),type:e.type,reason:e.reason}}function QI(e,t){return Qe(e.path,t.path)||Qe(e.hash,t.hash)||e.size-t.size}function ZI(e,t){return Qe(e.path,t.path)||Qe(e.reason,t.reason)||Qe(e.type,t.type)||(e.size??-1)-(t.size??-1)}function Qo(e){return Buffer.byteLength(JSON.stringify(e,null,2)+` `,"utf8")}function Tn(e,t,i){let n=`${t} -${Yo(i)}`;e.update(`${Buffer.byteLength(n,"utf8")}:`),e.update(n)}function ej(e){if(Qo(e)<=wi)return e;let t=[...e.entries],i=[...e.omitted],n=e.omittedCount,r=e.omissionOverflow?.count??0,a=Vy("sha256");a.update(`${zI} -`),e.omissionOverflow&&Tn(a,"existing-overflow",e.omissionOverflow);let o=(f,h)=>{h||(n+=1),r+=1,Tn(a,"omission",f)},s=f=>{n+=1,r+=1,Tn(a,"entry",f)},c=()=>{for(let f=i.length-1;f>=0;f-=1){let h=i[f];if(!(h.reason==="git-enumeration-limit"||h.reason==="git-selection-changed"||h.reason==="physical-enumeration-limit"||h.reason==="physical-selection-changed"))return i.splice(f,1),h}return null},l=()=>({...e,complete:n===0,entries:t,omitted:i,omittedCount:n,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${"0".repeat(64)}`,hash:"0".repeat(64),count:r}}),u=l();for(;Qo(u)>wi;){if(i.filter(h=>h.reason!=="git-enumeration-limit"&&h.reason!=="git-selection-changed"&&h.reason!=="physical-enumeration-limit"&&h.reason!=="physical-selection-changed").length>0){let h=Math.max(1,Math.ceil(i.length/4));for(let m=0;m0){let h=Math.max(1,Math.ceil(t.length/4));for(let m of t.splice(-h))s(m)}else throw new Error("Native snapshot projection metadata exceeds its evidence byte budget");u=l()}let d=a.digest("hex");return{...u,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${d}`,hash:d,count:r}}}function mh(e){let t=Ii(e),i=t.entries.map((r,a)=>YI(r,`Snapshot entry ${a}`));if(i.sort(QI),new Set(i.map(r=>r.path)).size!==i.length)throw new Error("Snapshot entries must not contain duplicate paths");let n=t.omitted.map((r,a)=>XI(r,`Snapshot omission ${a}`));return n.sort(ZI),ej({schema:Wy,origin:t.origin,...t.capture?{capture:t.capture}:{},complete:t.complete,limits:{maxFiles:t.limits.maxFiles,maxFileBytes:t.limits.maxFileBytes,maxTotalBytes:t.limits.maxTotalBytes,maxManifestBytes:t.limits.maxManifestBytes,...t.limits.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},...t.policy?{policy:t.policy}:{},entries:i,omitted:n,omittedCount:t.omittedCount,...t.omissionOverflow?{omissionOverflow:{ref:t.omissionOverflow.ref,hash:t.omissionOverflow.hash,count:t.omissionOverflow.count}}:{}})}function Pl(e){let t=new Map;for(let[i,n]of e.entries()){if(n.kind!=="file"&&n.kind!=="directory")throw new Error(`Declared artifact ${i} kind is invalid`);let r={path:_n(n.path,`Declared artifact ${i} path`),kind:n.kind},a=t.get(r.path);if(a&&a.kind!==r.kind)throw new Error(`Declared artifact path has conflicting kinds: ${r.path}`);t.set(r.path,r)}return[...t.values()].sort((i,n)=>Qe(i.path,n.path)||Qe(i.kind,n.kind))}function xl(e,t){return e.kind==="file"?e.path===t:t===e.path||t.startsWith(`${e.path}/`)}function My(e){return e?{hash:e.hash,size:e.size}:null}function Gy(e,t,i){let n=0,r=0;for(;n=0?o:void 0;if(s<=0&&(n+=1),s>=0&&(r+=1),c&&l&&c.hash===l.hash&&c.size===l.size||c&&!l&&!t.complete)continue;let u=c?.path??l?.path;u!==void 0&&i({path:u,kind:c?l?"modified":"removed":"added",before:My(c),after:My(l)})}}function tj(e,t){return{...e,attributedTo:t.filter(i=>xl(i,e.path))}}function Mi(e,t){return{id:`scope:${H(WI,e)}`,kind:e.kind,source:e.source,path:e.path,reason:t}}function ij(e,t){let i=t.omitted.map(n=>Mi({kind:"snapshot-omission",source:e,path:n.path,evidence:{reason:n.reason,size:n.size,type:n.type}},`${e} snapshot omitted ${n.path}: ${n.reason}`));return t.complete||i.push(Mi({kind:"snapshot-incomplete",source:e,path:null,evidence:{omittedCount:t.omittedCount}},`${e} snapshot is incomplete`)),t.omissionOverflow&&i.push(Mi({kind:"snapshot-omission-overflow",source:e,path:null,evidence:{count:t.omissionOverflow.count,hash:t.omissionOverflow.hash,ref:t.omissionOverflow.ref}},`${e} snapshot has ${t.omissionOverflow.count} unlisted omissions`)),i}function Fy(e,t){return ij(e,{...t,omitted:[]}).filter(i=>i.kind!=="snapshot-omission")}function vh(e,t){return Qe(e.kind,t.kind)||Qe(e.source,t.source)||KI(e.path,t.path)||Qe(e.id,t.id)}function nj(e){return[...new Map(e.map(i=>[i.id,i])).values()].sort(vh)}function rj(e){return[...new Set(e.map((t,i)=>_n(t,`Git path ${i}`)))].sort(Qe)}function Uy(e){if(typeof e.contractHash!="string"||!gh.test(e.contractHash))throw new Error("Contract hash must be a SHA-256 hash");return{contractHash:e.contractHash,declaredArtifacts:Pl(e.declaredArtifacts),noCodeReason:e.noCodeReason?.trim()||null,...e.gitChangedPaths===void 0?{}:{gitChangedPaths:rj(e.gitChangedPaths)}}}function aj(e,t,i,n){let r=[],a=n===void 0?null:new Set(n),o=[],s=0,c=!1,l=0,u=0;return Gy(e,t,d=>{let f=i.some(h=>xl(h,d.path));if(l+=1,f||(u+=1),a?.has(d.path)&&o.push(d.path),!c&&r.length{if(i>=e.detailedChangeCount){Tn(t,"change",r);let a=0;for(let o of e.declaredArtifacts)xl(o,r.path)&&(a+=1,Tn(t,"change-attribution",o));Tn(t,"change-end",{attributionCount:a}),a===0&&Tn(t,"unattributed-change",{after:r.after,before:r.before,changeKind:r.kind,path:r.path})}i+=1});let n=0;for(let[r,a]of[["baseline",e.baseline],["current",e.current]])for(let o of a.omitted)n>=e.detailedOmissionCount&&Tn(t,"snapshot-omission",{source:r,...o}),n+=1;return t.digest("hex")}function Yy(e,t,i){let{contractHash:n,declaredArtifacts:r,noCodeReason:a}=i,o=aj(e,t,r,i.gitChangedPaths),s=H(Xo,e),c=H(Xo,t),l=[];for(let[y,w]of[["baseline",e],["current",t]])for(let g of w.omitted){if(l.length>=UI)break;l.push(Mi({kind:"snapshot-omission",source:y,path:g.path,evidence:{reason:g.reason,size:g.size,type:g.type}},`${y} snapshot omitted ${g.path}: ${g.reason}`))}let u=e.omitted.length+t.omitted.length,d=[...Fy("baseline",e),...Fy("current",t),...o.totalChanges===0&&a===null?[Mi({kind:"missing-no-code-reason",source:"implementation-scope",path:null,evidence:{baselineProjectionHash:s,currentProjectionHash:c}},"A non-empty no-code reason is required when the snapshots contain no changes")]:[]],f=()=>{if(i.gitChangedPaths===void 0)return;let y=new Set(o.gitPathsPresentInChanges);return{advisoryOnly:!0,changedPaths:i.gitChangedPaths,pathsPresentInSnapshotChanges:i.gitChangedPaths.filter(w=>y.has(w)),pathsAbsentFromSnapshotChanges:i.gitChangedPaths.filter(w=>!y.has(w))}},h=y=>{let w=o.candidates.slice(0,y.detailedChangeCount),g=w.filter(ai=>ai.attributedTo.length===0),E=o.totalChanges-w.length,O=o.totalUnattributed-g.length,B=u-y.detailedOmissionCount,q=O+B,U=[...g.map(ai=>Mi({kind:"unattributed-change",source:"implementation-scope",path:ai.path,evidence:{after:ai.after,before:ai.before,changeKind:ai.kind}},`Changed path is not covered by a declared artifact: ${ai.path}`)),...l.slice(0,y.detailedOmissionCount),...d,...E>0||q>0?[Ky(y.overflowHash,{changes:E,unattributed:O,unresolved:q})]:[]],oe=nj(U),ri=y.includeGitAdvisory?f():void 0;return{schema:hh,contractHash:n,baselineProjectionRef:ph(s),baselineProjectionHash:s,currentProjectionRef:ph(c),currentProjectionHash:c,complete:oe.length===0,declaredArtifacts:r,changes:w,unattributed:g,unresolvedScopes:oe,noCodeReason:a,...ri?{gitAdvisory:ri}:{}}},m=o.candidates.length,p=l.length,v=i.gitChangedPaths!==void 0,S="0".repeat(64);for(;;){let y=h({detailedChangeCount:m,detailedOmissionCount:p,includeGitAdvisory:v,overflowHash:S});if(Qo({...y,scopeHash:S})<=wi)break;if(v){v=!1;continue}if(p>0){p-=Math.max(1,Math.ceil(p/4));continue}if(m>0){m-=Math.max(1,Math.ceil(m/4));continue}throw new Error("Native implementation scope metadata exceeds its evidence byte budget")}let N=o.totalChanges>m||u>p?sj({baseline:e,current:t,declaredArtifacts:r,detailedChangeCount:m,detailedOmissionCount:p}):S,b=h({detailedChangeCount:m,detailedOmissionCount:p,includeGitAdvisory:v,overflowHash:N}),R={...b,scopeHash:H(Jy,b)};if(Qo(R)>wi)throw new Error("Native implementation scope exceeded its evidence byte budget after fitting");return R}function In(e){let t=mh(e.baseline),i=mh(e.current),n=Uy(e);return{authority:n,baseline:t,current:i,scope:Yy(t,i,n)}}var cj=new Set(["schema","contractHash","baselineProjectionRef","baselineProjectionHash","currentProjectionRef","currentProjectionHash","complete","declaredArtifacts","changes","unattributed","unresolvedScopes","noCodeReason","gitAdvisory","scopeHash"]);function Fi(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Li(e,t,i,n){let r=new Set([...t,...i]),a=Object.keys(e).filter(s=>!r.has(s)),o=t.filter(s=>!(s in e));if(a.length>0)throw new Error(`${n} has unknown field(s): ${a.join(", ")}`);if(o.length>0)throw new Error(`${n} is missing field(s): ${o.join(", ")}`)}function dr(e,t){if(typeof e!="string"||!gh.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Ly(e,t,i){let n=ph(t);if(e!==n)throw new Error(`${i} ref/hash mismatch`);return n}function da(e,t){let i=Fi(e,"Native snapshot projection");if(Li(i,["schema","origin","complete","limits","entries","omitted","omittedCount"],["capture","omissionOverflow","policy"],"Native snapshot projection"),i.schema!==Wy)throw new Error("Native snapshot projection schema is invalid");let n=Ii({schema:"comet.native.content-snapshot.v1",origin:i.origin,...i.capture===void 0?{}:{capture:i.capture},createdAt:"1970-01-01T00:00:00.000Z",complete:i.complete,limits:i.limits,...i.policy===void 0?{}:{policy:i.policy},entries:i.entries,omitted:i.omitted,omittedCount:i.omittedCount,...i.omissionOverflow===void 0?{}:{omissionOverflow:i.omissionOverflow}}),r=mh(n);if(H(Xo,i)!==H(Xo,r))throw new Error("Native snapshot projection is not canonical");let a=H(Xo,r);if(t!==void 0&&dr(t,"Snapshot projection hash")!==a)throw new Error("Native snapshot projection content hash mismatch");return r}function wh(e,t){let i=Fi(e,`Declared artifact ${t}`);if(Li(i,["path","kind"],[],`Declared artifact ${t}`),i.kind!=="file"&&i.kind!=="directory")throw new Error(`Declared artifact ${t} kind is invalid`);return{path:_n(i.path,`Declared artifact ${t} path`),kind:i.kind}}function By(e,t){if(e===null)return null;let i=Fi(e,t);return Li(i,["hash","size"],[],t),{hash:dr(i.hash,`${t} hash`),size:ua(i.size,`${t} size`)}}function qy(e,t){let i=Fi(e,`Implementation change ${t}`);if(Li(i,["path","kind","before","after","attributedTo"],[],`Implementation change ${t}`),i.kind!=="added"&&i.kind!=="modified"&&i.kind!=="removed")throw new Error(`Implementation change ${t} kind is invalid`);if(!Array.isArray(i.attributedTo))throw new Error(`Implementation change ${t} attributedTo must be an array`);let n=i.attributedTo.map(wh),r=Pl(n);if(JSON.stringify(n)!==JSON.stringify(r))throw new Error(`Implementation change ${t} attribution must be sorted and unique`);let a=By(i.before,`Implementation change ${t} before`),o=By(i.after,`Implementation change ${t} after`);if(i.kind==="added"&&(a!==null||o===null)||i.kind==="removed"&&(a===null||o!==null)||i.kind==="modified"&&(a===null||o===null||JSON.stringify(a)===JSON.stringify(o)))throw new Error(`Implementation change ${t} before/after state is invalid`);return{path:_n(i.path,`Implementation change ${t} path`),kind:i.kind,before:a,after:o,attributedTo:n}}function lj(e,t){let i=Fi(e,`Unresolved scope ${t}`);Li(i,["id","kind","source","path","reason"],[],`Unresolved scope ${t}`);let n=new Set(["unattributed-change","snapshot-omission","snapshot-incomplete","snapshot-omission-overflow","scope-detail-overflow","missing-no-code-reason"]);if(typeof i.kind!="string"||!n.has(i.kind))throw new Error(`Unresolved scope ${t} kind is invalid`);if(i.source!=="baseline"&&i.source!=="current"&&i.source!=="implementation-scope")throw new Error(`Unresolved scope ${t} source is invalid`);if(typeof i.id!="string"||!/^scope:[a-f0-9]{64}$/u.test(i.id))throw new Error(`Unresolved scope ${t} id is invalid`);if(i.path!==null&&typeof i.path!="string")throw new Error(`Unresolved scope ${t} path is invalid`);if(typeof i.reason!="string"||i.reason.length===0||i.reason.trim()!==i.reason)throw new Error(`Unresolved scope ${t} reason is invalid`);return{id:i.id,kind:i.kind,source:i.source,path:i.path===null?null:i.kind==="snapshot-omission"?zy(i.path,`Unresolved scope ${t} path`):_n(i.path,`Unresolved scope ${t} path`),reason:i.reason}}function Cl(e,t){if(!Array.isArray(e)||e.some(r=>typeof r!="string"))throw new Error(`${t} must be an array of paths`);let i=e.map((r,a)=>_n(r,`${t} ${a}`)),n=[...new Set(i)].sort(Qe);if(JSON.stringify(i)!==JSON.stringify(n))throw new Error(`${t} must be sorted and unique`);return i}function fa(e){let t=Fi(e,"Native implementation scope"),i=[...cj].filter(w=>w!=="gitAdvisory");if(Li(t,i,["gitAdvisory"],"Native implementation scope"),t.schema!==hh)throw new Error("Native implementation scope schema is invalid");let n=dr(t.contractHash,"Implementation scope contractHash"),r=dr(t.baselineProjectionHash,"Implementation scope baselineProjectionHash"),a=Ly(t.baselineProjectionRef,r,"Implementation scope baseline projection"),o=dr(t.currentProjectionHash,"Implementation scope currentProjectionHash"),s=Ly(t.currentProjectionRef,o,"Implementation scope current projection");if(typeof t.complete!="boolean")throw new Error("Implementation scope complete flag is invalid");if(!Array.isArray(t.declaredArtifacts)||!Array.isArray(t.changes)||!Array.isArray(t.unattributed)||!Array.isArray(t.unresolvedScopes))throw new Error("Implementation scope collections are invalid");let c=t.declaredArtifacts.map(wh);if(JSON.stringify(c)!==JSON.stringify(Pl(c)))throw new Error("Implementation scope declared artifacts must be sorted and unique");let l=t.changes.map(qy),u=[...l].sort((w,g)=>Qe(w.path,g.path));if(JSON.stringify(l)!==JSON.stringify(u)||new Set(l.map(w=>w.path)).size!==l.length)throw new Error("Implementation scope changes must be sorted and unique");let d=new Set(c.map(w=>`${w.kind}:${w.path}`));if(l.some(w=>w.attributedTo.some(g=>!d.has(`${g.kind}:${g.path}`))))throw new Error("Implementation scope change references an undeclared artifact");if(l.some(w=>JSON.stringify(w.attributedTo)!==JSON.stringify(c.filter(g=>xl(g,w.path)))))throw new Error("Implementation scope change attribution is inconsistent");let f=t.unattributed.map(qy),h=l.filter(w=>w.attributedTo.length===0);if(JSON.stringify(f)!==JSON.stringify(h))throw new Error("Implementation scope unattributed changes are inconsistent");let m=t.unresolvedScopes.map(lj),p=m.filter(w=>w.kind==="scope-detail-overflow");if(p.length>1)throw new Error("Implementation scope has multiple detail overflow records");let v=p[0]===void 0?null:oj(p[0]);if(v&&(v.changes+v.unresolved===0||v.unattributed>v.changes||v.unattributed>v.unresolved))throw new Error("Implementation scope detail overflow counts are inconsistent");let S=t.noCodeReason,k=[...h.map(w=>Mi({kind:"unattributed-change",source:"implementation-scope",path:w.path,evidence:{after:w.after,before:w.before,changeKind:w.kind}},`Changed path is not covered by a declared artifact: ${w.path}`)),...l.length+(v?.changes??0)===0&&S===null?[Mi({kind:"missing-no-code-reason",source:"implementation-scope",path:null,evidence:{baselineProjectionHash:r,currentProjectionHash:o}},"A non-empty no-code reason is required when the snapshots contain no changes")]:[]],N=m.filter(w=>w.kind==="unattributed-change"||w.kind==="missing-no-code-reason");if(JSON.stringify(m)!==JSON.stringify([...m].sort(vh))||new Set(m.map(w=>w.id)).size!==m.length||JSON.stringify(N)!==JSON.stringify(k.sort(vh))||t.complete!==(m.length===0))throw new Error("Implementation scope unresolved scopes are inconsistent");if(t.noCodeReason!==null&&(typeof t.noCodeReason!="string"||t.noCodeReason.length===0||t.noCodeReason.trim()!==t.noCodeReason))throw new Error("Implementation scope no-code reason is invalid");let b;if(t.gitAdvisory!==void 0){let w=Fi(t.gitAdvisory,"Implementation scope Git advisory");if(Li(w,["advisoryOnly","changedPaths","pathsPresentInSnapshotChanges","pathsAbsentFromSnapshotChanges"],[],"Implementation scope Git advisory"),w.advisoryOnly!==!0)throw new Error("Implementation scope Git advisory must remain advisory-only");let g=Cl(w.changedPaths,"Git changed paths"),E=Cl(w.pathsPresentInSnapshotChanges,"Git present paths"),O=Cl(w.pathsAbsentFromSnapshotChanges,"Git absent paths"),B=[...E,...O].sort(Qe),q=new Set(l.map(U=>U.path));if(JSON.stringify(B)!==JSON.stringify(g)||(v?.changes??0)===0&&E.some(U=>!q.has(U))||O.some(U=>q.has(U)))throw new Error("Implementation scope Git advisory partition is invalid");b={advisoryOnly:!0,changedPaths:g,pathsPresentInSnapshotChanges:E,pathsAbsentFromSnapshotChanges:O}}let R={schema:hh,contractHash:n,baselineProjectionRef:a,baselineProjectionHash:r,currentProjectionRef:s,currentProjectionHash:o,complete:t.complete,declaredArtifacts:c,changes:l,unattributed:f,unresolvedScopes:m,noCodeReason:S,...b?{gitAdvisory:b}:{}},y=dr(t.scopeHash,"Implementation scope scopeHash");if(H(Jy,R)!==y)throw new Error("Implementation scope content hash mismatch");return{...R,scopeHash:y}}function uj(e){let t=Fi(e,"Native implementation scope authority");if(Li(t,["contractHash","declaredArtifacts","noCodeReason"],["gitChangedPaths"],"Native implementation scope authority"),!Array.isArray(t.declaredArtifacts))throw new Error("Native implementation scope authority declarations must be an array");let i=t.declaredArtifacts.map(wh);if(JSON.stringify(i)!==JSON.stringify(Pl(i)))throw new Error("Native implementation scope authority declarations must be canonical");if(t.noCodeReason!==null&&(typeof t.noCodeReason!="string"||t.noCodeReason.length===0||t.noCodeReason.trim()!==t.noCodeReason))throw new Error("Native implementation scope authority no-code reason is invalid");let n;t.gitChangedPaths!==void 0&&(n=Cl(t.gitChangedPaths,"Native implementation scope authority Git paths"));let r=Uy({contractHash:t.contractHash,declaredArtifacts:i,noCodeReason:t.noCodeReason,...n===void 0?{}:{gitChangedPaths:n}});if(r.contractHash!==t.contractHash)throw new Error("Native implementation scope authority contract hash is not canonical");return r}function Kt(e){let t=Fi(e,"Native implementation scope bundle");Li(t,["authority","baseline","current","scope"],[],"Native implementation scope bundle");let i=uj(t.authority),n=da(t.baseline),r=da(t.current),a=fa(t.scope),o=Yy(n,r,i);if(JSON.stringify(a)!==JSON.stringify(o))throw new Error("Native implementation scope does not match its authoritative bundle");return{authority:i,baseline:n,current:r,scope:o}}function Xy(e){let t=fa(e.scope);return Kt({authority:{contractHash:t.contractHash,declaredArtifacts:t.declaredArtifacts,noCodeReason:t.noCodeReason,...t.gitAdvisory?{gitChangedPaths:t.gitAdvisory.changedPaths}:{}},baseline:e.baseline,current:e.current,scope:t})}import Qy from"node:path";var dj=/\b(Bearer|Basic)\s+[^\s"']+/giu,fj=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,hj=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,pj=/\b(?:sk-(?:proj-)?[A-Za-z0-9_-]{16,}|gh[pousr]_[A-Za-z0-9_]{16,}|github_pat_[A-Za-z0-9_]{16,}|AKIA[A-Z0-9]{16}|AIza[A-Za-z0-9_-]{20,})\b/gu,mj=/("(?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie)"\s*:\s*)"(?:\\[\s\S]|[^"\\\r\n])*"/giu,vj=/(["'])((?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie))\1(\s*:\s*)(["'])[^\r\n]*?\4/giu,gj=/\b((?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie))\b(\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;"']+)/giu;function ke(e){return e.replace(dj,"$1 [REDACTED]").replace(fj,"[REDACTED PRIVATE KEY]").replace(hj,"$1[REDACTED]@").replace(pj,"[REDACTED TOKEN]").replace(mj,'$1"[REDACTED]"').replace(vj,"$1$2$1$3$4[REDACTED]$4").replace(gj,"$1$2[REDACTED]")}var Zy=/^[a-f0-9]{64}$/u,wj=8,eN="comet.native.acceptance-trace.v2",tN="comet.native.partial-allowance.v1",iN="comet.native.verification-evidence.v2";function $t(e,t){if(!Zy.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Il(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native evidence source revision must be a positive integer");return e}function jl(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error(`Invalid Native evidence change name: ${e}`);return e}function ha(e,t,i=2e3){let n=ke(e).trim();if(n.length===0||n.length>i)throw new Error(`${t} must be between 1 and ${i} characters`);return n}function jn(e,t){let i=Qy.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(n=>{let r=n.codePointAt(0)??0;return r<=31||r===127})||Qy.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||i!==e||i==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized relative ref`);return e}function nN(e,t,i){let n=jn(e,t);if(/^runtime\/evidence\/check-receipts\/[a-f0-9]{64}\.json$/u.test(n))return n;let r=ci(n),a=n.toLowerCase(),o=i?jn(i,"Native root ref").toLowerCase():null;if(r||a==="runtime"||a.startsWith("runtime/")||o!==null&&(a===o||a.startsWith(`${o}/`)))throw new Error(`${t} is excluded as sensitive (${r??"native-runtime"}): ${n}`);return n}function Zo(e){let t=jn(e,"Verification typed receipt ref");if(!/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u.test(t))throw new Error("Verification receipt ref must identify a typed v3 receipt");return t}function rN(e){let t=e.toISOString();if(Number.isNaN(Date.parse(t)))throw new Error("Native evidence timestamp is invalid");return t}function yj(e){return H("comet.native.acceptance-set.v1",[...e].sort((t,i)=>Ht(t.id,i.id)))}function Ht(e,t){return et?1:0}function aN(e,t,i){let n=jn(i.nativeRootRef,"Native root ref"),r=new Map(e.map(u=>[u.id,u]));if(r.size!==e.length)throw new Error("Native contract has duplicate acceptance IDs");let a=new Map;for(let u of t){if(!r.has(u.acceptance_id))throw new Error(`Verification references unknown acceptance ID: ${u.acceptance_id}`);if(a.has(u.acceptance_id))throw new Error(`Verification repeats acceptance ID: ${u.acceptance_id}`);a.set(u.acceptance_id,u)}let o=[...r.keys()].filter(u=>!a.has(u));if(o.length>0&&i.allowMissing!==!0){let u=o.slice(0,wj),d=o.length-u.length;throw new Error(`Verification is missing ${o.length} acceptance evidence entr${o.length===1?"y":"ies"}: ${u.join(", ")}${d>0?`, ... (${d} more)`:""}`)}let s=[...r.values()].sort((u,d)=>Ht(u.id,d.id)).map(u=>{let d=a.get(u.id);if(!d)return{acceptanceId:u.id,status:"missing",kind:u.kind,source:jn(u.source,`Acceptance source for ${u.id}`),evidenceRefs:[],skippedReason:null};let f=d.status,h=[...d.evidence_refs].map(v=>Zo(v)).sort();if(new Set(h).size!==h.length)throw new Error(`Verification repeats an evidence ref for ${u.id}`);let m=d.skipped_reason?.trim()||null,p=m===null?null:ha(m,`Skipped reason for ${u.id}`);if(f==="passed"&&(h.length===0||p!==null)||f==="failed"&&h.length===0&&p===null)throw new Error(`Acceptance ${u.id} has an invalid evidence state`);return{acceptanceId:u.id,status:f,kind:u.kind,source:jn(u.source,`Acceptance source for ${u.id}`),evidenceRefs:h,skippedReason:p}}),c=yj(e),l={schema:"comet.native.acceptance-trace.v2",nativeRootRef:n,criteriaHash:c,total:s.length,evidenced:s.filter(u=>u.evidenceRefs.length>0).length,skipped:s.filter(u=>u.skippedReason!==null).length,entries:s};return{...l,traceHash:H(eN,l)}}function oN(e){let t=Kt(e.scopeBundle).scope;if(t.complete)throw new Error("Complete implementation scope cannot be partially allowed");let i=new Set(t.unresolvedScopes.map(s=>s.id));if(new Set(e.allowedScopeIds).size!==e.allowedScopeIds.length)throw new Error("Partial allowance has duplicate allowed scope IDs");let n=[...e.allowedScopeIds].sort(Ht);if(n.length===0)throw new Error("Partial allowance requires at least one scope ID");if([...i,...n].some(s=>!/^scope:[a-f0-9]{64}$/u.test(s)))throw new Error("Partial allowance scope IDs are invalid");let r=n.filter(s=>!i.has(s)),a=[...i].filter(s=>!n.includes(s));if(r.length>0)throw new Error(`Partial allowance has unknown scope IDs: ${r}`);if(a.length>0)throw new Error(`Partial allowance is missing scope IDs: ${a}`);let o={schema:"comet.native.partial-allowance.v1",change:jl(e.change),scopeHash:t.scopeHash,scopeIds:n,reason:ha(e.reason,"Partial allowance reason"),confirmedSummary:ha(e.confirmedSummary,"Partial allowance confirmation"),sourceRevision:Il(e.sourceRevision),confirmedAt:rN(e.now??new Date)};return{...o,allowanceHash:H(tN,o)}}function sN(e){if(e.result!=="pass"&&e.result!=="fail")throw new Error("Native verification evidence result is invalid");let t=lN(e.acceptanceTrace),i=Kt(e.implementationScope.bundle).scope,n=_l(e.implementationScope.ref,"scopes",i.scopeHash);if(i.contractHash!==e.contractHash)throw new Error("Implementation scope does not match the verification contract");let r=e.partialAllowance??null,a=r?es(r.allowance):null,o=r&&a?{ref:_l(r.ref,"allowances",a.allowanceHash),allowance:a}:null;if(i.complete&&o!==null)throw new Error("Complete implementation scope must not use a partial allowance");if(!i.complete&&o===null)throw new Error("Partial implementation scope requires a confirmed allowance");let s=i.unresolvedScopes.map(f=>f.id).sort(Ht);if(o&&(o.allowance.change!==e.change||o.allowance.scopeHash!==i.scopeHash||JSON.stringify(o.allowance.scopeIds)!==JSON.stringify(s)))throw new Error("Partial allowance does not match the verification scope");if(t.criteriaHash!==e.acceptanceHash)throw new Error("Acceptance trace does not match the verification contract");if(o&&o.allowance.sourceRevision>=e.sourceRevision)throw new Error("Partial allowance must precede the verification evidence revision");let c=[...new Set(t.entries.flatMap(f=>f.evidenceRefs))].sort(Ht),l=[...new Set(e.requiredReceiptRefs.map(Zo))].sort(Ht),u=c;if(e.result==="pass"&&l.length===0)throw new Error("Passing verification requires at least one current required check receipt");let d={schema:"comet.native.verification-evidence.v2",change:jl(e.change),sourceRevision:Il(e.sourceRevision),result:e.result,freshness:i.complete?"complete":"partial",contractHash:$t(e.contractHash,"Verification contractHash"),acceptanceCriteriaHash:$t(e.acceptanceHash,"Verification acceptanceHash"),implementationScopeRef:n,implementationScopeHash:i.scopeHash,reportRef:nN(e.reportRef,"Verification report ref"),reportHash:$t(e.reportHash,"Verification report hash"),acceptanceTrace:t,partialAllowanceRef:o?.ref??null,partialAllowanceHash:o?.allowance.allowanceHash??null,requiredReceiptRefs:l,receiptRefs:u,createdAt:rN(e.now??new Date)};return{...d,envelopeHash:H(iN,d)}}function Al(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Tl(e,t,i){let n=new Set(t),r=Object.keys(e).filter(o=>!n.has(o)),a=t.filter(o=>!(o in e));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`);if(a.length>0)throw new Error(`${i} is missing field(s): ${a.join(", ")}`)}function cN(e,t){if(typeof e!="string")throw new Error(`${t} is invalid`);let i=new Date(e);if(Number.isNaN(i.valueOf())||i.toISOString()!==e)throw new Error(`${t} is invalid`);return e}function _l(e,t,i){if(typeof e!="string")throw new Error(`Native ${t} evidence ref is invalid`);let n=`runtime/evidence/${t}/${i}.json`;if(e!==n)throw new Error(`Native ${t} evidence ref/hash mismatch`);return e}function lN(e){let t=Al(e,"Native acceptance trace");if(Tl(t,["schema","nativeRootRef","criteriaHash","total","evidenced","skipped","entries","traceHash"],"Native acceptance trace"),t.schema!=="comet.native.acceptance-trace.v2"||typeof t.nativeRootRef!="string"||typeof t.criteriaHash!="string"||!Zy.test(t.criteriaHash)||!Number.isSafeInteger(t.total)||!Number.isSafeInteger(t.evidenced)||!Number.isSafeInteger(t.skipped)||!Array.isArray(t.entries))throw new Error("Native acceptance trace is invalid");let i=jn(t.nativeRootRef,"Native root ref"),n=t.entries.map((o,s)=>{let c=Al(o,`Native acceptance trace entry ${s}`);if(Tl(c,["acceptanceId","status","kind","source","evidenceRefs","skippedReason"],`Native acceptance trace entry ${s}`),typeof c.acceptanceId!="string"||!/^acceptance-[a-f0-9]{64}$/u.test(c.acceptanceId)||c.kind!=="brief-example"&&c.kind!=="spec-scenario"&&c.kind!=="spec-must"||typeof c.source!="string"||!Array.isArray(c.evidenceRefs)||c.status!=="passed"&&c.status!=="failed"&&c.status!=="missing"||c.evidenceRefs.some(d=>typeof d!="string")||c.skippedReason!==null&&(typeof c.skippedReason!="string"||c.skippedReason.length===0||c.skippedReason.trim()!==c.skippedReason))throw new Error(`Native acceptance trace entry ${s} is invalid`);let l=c.evidenceRefs.map(d=>Zo(d)),u=c.status;if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(Ht))||u==="passed"&&(l.length===0||c.skippedReason!==null)||u==="failed"&&l.length===0&&c.skippedReason===null||u==="missing"&&(l.length>0||c.skippedReason!==null))throw new Error(`Native acceptance trace entry ${s} evidence state is invalid`);return{acceptanceId:c.acceptanceId,status:u,kind:c.kind,source:jn(c.source,`Native acceptance trace entry ${s} source`),evidenceRefs:l,skippedReason:c.skippedReason===null?null:ha(c.skippedReason,`Native acceptance trace entry ${s} skipped reason`)}});if(JSON.stringify(n)!==JSON.stringify([...n].sort((o,s)=>Ht(o.acceptanceId,s.acceptanceId)))||new Set(n.map(o=>o.acceptanceId)).size!==n.length||t.total!==n.length||t.evidenced!==n.filter(o=>o.evidenceRefs.length>0).length||t.skipped!==n.filter(o=>o.skippedReason!==null).length)throw new Error("Native acceptance trace entries are inconsistent");let r={schema:"comet.native.acceptance-trace.v2",nativeRootRef:i,criteriaHash:t.criteriaHash,total:t.total,evidenced:t.evidenced,skipped:t.skipped,entries:n},a=$t(t.traceHash,"Native acceptance trace hash");if(H(eN,r)!==a)throw new Error("Native acceptance trace content hash mismatch");return{...r,traceHash:a}}function es(e){let t=Al(e,"Native partial allowance");if(Tl(t,["schema","change","scopeHash","scopeIds","reason","confirmedSummary","sourceRevision","confirmedAt","allowanceHash"],"Native partial allowance"),t.schema!=="comet.native.partial-allowance.v1"||typeof t.change!="string"||typeof t.scopeHash!="string"||!Array.isArray(t.scopeIds)||t.scopeIds.length===0||t.scopeIds.some(r=>typeof r!="string"||!/^scope:[a-f0-9]{64}$/u.test(r))||JSON.stringify(t.scopeIds)!==JSON.stringify([...new Set(t.scopeIds)].sort(Ht))||typeof t.reason!="string"||typeof t.confirmedSummary!="string")throw new Error("Native partial allowance is invalid");let i={schema:"comet.native.partial-allowance.v1",change:jl(t.change),scopeHash:$t(t.scopeHash,"Native partial allowance scopeHash"),scopeIds:t.scopeIds,reason:ha(t.reason,"Partial allowance reason"),confirmedSummary:ha(t.confirmedSummary,"Partial allowance confirmation"),sourceRevision:Il(t.sourceRevision),confirmedAt:cN(t.confirmedAt,"Native partial allowance timestamp")};if(i.reason!==t.reason||i.confirmedSummary!==t.confirmedSummary)throw new Error("Native partial allowance text is not canonical");let n=$t(t.allowanceHash,"Native partial allowance hash");if(H(tN,i)!==n)throw new Error("Native partial allowance content hash mismatch");return{...i,allowanceHash:n}}function pa(e){let t=Al(e,"Native verification evidence");if(Tl(t,["schema","change","sourceRevision","result","freshness","contractHash","acceptanceCriteriaHash","implementationScopeRef","implementationScopeHash","reportRef","reportHash","acceptanceTrace","partialAllowanceRef","partialAllowanceHash","requiredReceiptRefs","receiptRefs","createdAt","envelopeHash"],"Native verification evidence"),t.schema!=="comet.native.verification-evidence.v2"||typeof t.change!="string"||t.result!=="pass"&&t.result!=="fail"||t.freshness!=="complete"&&t.freshness!=="partial"||typeof t.implementationScopeHash!="string"||typeof t.reportRef!="string"||!Array.isArray(t.requiredReceiptRefs)||!Array.isArray(t.receiptRefs))throw new Error("Native verification evidence is invalid");let i=$t(t.implementationScopeHash,"Native verification implementation scope hash"),n=lN(t.acceptanceTrace),r=$t(t.acceptanceCriteriaHash,"Native verification acceptance criteria hash");if(n.criteriaHash!==r)throw new Error("Native verification acceptance trace does not match its criteria hash");let a=t.partialAllowanceRef!==null||t.partialAllowanceHash!==null;if(t.partialAllowanceRef===null!=(t.partialAllowanceHash===null)||t.freshness==="complete"&&a||t.freshness==="partial"&&!a)throw new Error("Native verification partial allowance state is invalid");let o=t.partialAllowanceHash===null?null:$t(t.partialAllowanceHash,"Native verification allowance hash"),s=t.receiptRefs.map(f=>Zo(f));if(JSON.stringify(s)!==JSON.stringify([...new Set(s)].sort(Ht)))throw new Error("Native verification receipt refs must be canonical");let c=[...new Set(n.entries.flatMap(f=>f.evidenceRefs))].sort(Ht);if(JSON.stringify(s)!==JSON.stringify(c))throw new Error("Native verification envelope receipt refs do not match its matrix");let l=t.requiredReceiptRefs.map(f=>Zo(f));if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(Ht)))throw new Error("Native required receipt refs must be canonical");if(t.result==="pass"&&l.length===0)throw new Error("Passing verification has no current static receipt");let u={schema:"comet.native.verification-evidence.v2",change:jl(t.change),sourceRevision:Il(t.sourceRevision),result:t.result,freshness:t.freshness,contractHash:$t(t.contractHash,"Native verification contract hash"),acceptanceCriteriaHash:r,implementationScopeRef:_l(t.implementationScopeRef,"scopes",i),implementationScopeHash:i,reportRef:nN(t.reportRef,"Native verification report ref"),reportHash:$t(t.reportHash,"Native verification report hash"),acceptanceTrace:n,partialAllowanceRef:o===null?null:_l(t.partialAllowanceRef,"allowances",o),partialAllowanceHash:o,requiredReceiptRefs:l,receiptRefs:s,createdAt:cN(t.createdAt,"Native verification timestamp")},d=$t(t.envelopeHash,"Native verification envelope hash");if(H(iN,u)!==d)throw new Error("Native verification evidence content hash mismatch");return{...u,envelopeHash:d}}import uN from"node:path";var Ol="comet.native.check-receipt.v1",hN="comet.native.check-receipt.v1",On="scoped-text-safety",ts=1,Ae=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),Nj=/^[a-f0-9]{64}$/u,bj=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,kj="comet.native.checker-policy.v1",Sj="comet.native.check-input.v1",Ej=2048,$l=H(kj,{policy:On,version:ts,limits:Ae,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),Rj=new Set(["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"]),dN=["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"],pN=["contract-before-does-not-match-scope","implementation-before-does-not-match-scope","contract-changed-during-check","implementation-changed-during-check","contract-after-does-not-match-scope","implementation-after-does-not-match-scope"],Cj=new Set(pN);function hr(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function pr(e,t,i){let n=new Set(t),r=Object.keys(e).filter(o=>!n.has(o)),a=t.filter(o=>!(o in e));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`);if(a.length>0)throw new Error(`${i} is missing field(s): ${a.join(", ")}`)}function Bi(e,t){if(typeof e!="string"||!Nj.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function fr(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function mN(e,t){let i=fr(e,t);if(i<1)throw new Error(`${t} must be a positive integer`);return i}function fN(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let i=new Date(e);if(!Number.isFinite(i.getTime())||i.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function Pj(e,t){if(typeof e!="string"||e.length===0||Buffer.byteLength(e,"utf8")>Ej||e.includes("\\")||e.includes("\0")||e.endsWith("/")||/^[a-zA-Z]:/u.test(e))throw new Error(`${t} must be a bounded normalized project-relative path`);let i=uN.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||uN.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function xj(e){let t=hr(e,"Native check receipt checker");pr(t,["policy","version","hash","limits"],"Native check receipt checker");let i=hr(t.limits,"Native check receipt limits");if(pr(i,["maxFiles","maxFileBytes","maxTotalBytes","maxIssues"],"Native check receipt limits"),t.policy!==On||t.version!==ts||t.hash!==$l||i.maxFiles!==Ae.maxFiles||i.maxFileBytes!==Ae.maxFileBytes||i.maxTotalBytes!==Ae.maxTotalBytes||i.maxIssues!==Ae.maxIssues)throw new Error("Native check receipt checker policy is unsupported");return{policy:On,version:ts,hash:$l,limits:{...Ae}}}function Aj(e){let t=hr(e,"Native check receipt contract");return pr(t,["expectedHash","beforeHash","afterHash"],"Native check receipt contract"),{expectedHash:Bi(t.expectedHash,"Native check expected contract hash"),beforeHash:Bi(t.beforeHash,"Native check before contract hash"),afterHash:Bi(t.afterHash,"Native check after contract hash")}}function Tj(e){let t=hr(e,"Native check receipt implementation");return pr(t,["scopeHash","expectedSnapshotHash","beforeSnapshotHash","afterSnapshotHash"],"Native check receipt implementation"),{scopeHash:Bi(t.scopeHash,"Native check scope hash"),expectedSnapshotHash:Bi(t.expectedSnapshotHash,"Native check expected snapshot hash"),beforeSnapshotHash:Bi(t.beforeSnapshotHash,"Native check before snapshot hash"),afterSnapshotHash:Bi(t.afterSnapshotHash,"Native check after snapshot hash")}}function _j(e){let t=hr(e,"Native check receipt counts");pr(t,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],"Native check receipt counts");let i={filesSelected:fr(t.filesSelected,"Native check filesSelected"),filesScanned:fr(t.filesScanned,"Native check filesScanned"),binaryFilesSkipped:fr(t.binaryFilesSkipped,"Native check binaryFilesSkipped"),bytesScanned:fr(t.bytesScanned,"Native check bytesScanned"),issueCount:fr(t.issueCount,"Native check issueCount"),recordedIssueCount:fr(t.recordedIssueCount,"Native check recordedIssueCount")};if(i.filesScanned+i.binaryFilesSkipped>i.filesSelected||i.filesScanned+i.binaryFilesSkipped>Ae.maxFiles||i.bytesScanned>Ae.maxTotalBytes||i.recordedIssueCount>i.issueCount||i.recordedIssueCount>Ae.maxIssues)throw new Error("Native check receipt count accounting is invalid");return i}function Ij(e,t){return e.path.localeCompare(t.path,"en")||e.line-t.line||dN.indexOf(e.kind)-dN.indexOf(t.kind)}function jj(e){if(!Array.isArray(e)||e.length>Ae.maxIssues)throw new Error("Native check receipt issues must be a bounded array");let t=e.map((n,r)=>{let a=hr(n,`Native check issue ${r}`);if(pr(a,["path","line","kind"],`Native check issue ${r}`),typeof a.kind!="string"||!Rj.has(a.kind))throw new Error(`Native check issue ${r} kind is invalid`);return{path:Pj(a.path,`Native check issue ${r} path`),line:mN(a.line,`Native check issue ${r} line`),kind:a.kind}}),i=[...t].sort(Ij);if(JSON.stringify(i)!==JSON.stringify(t))throw new Error("Native check receipt issues must be canonical");return t}function Oj(e){if(!Array.isArray(e)||e.some(n=>typeof n!="string"||!Cj.has(n)))throw new Error("Native check receipt stale reasons are invalid");let t=e,i=pN.filter(n=>t.includes(n));if(new Set(t).size!==t.length||JSON.stringify(i)!==JSON.stringify(t))throw new Error("Native check receipt stale reasons must be canonical");return[...t]}function vN(e){return H(Sj,e)}function qi(e){let t=hr(e,"Native check receipt");if(pr(t,["schema","change","sourceRevision","checker","inputHash","status","startedAt","endedAt","contract","implementation","counts","issues","issuesTruncated","stale","staleReasons","receiptHash"],"Native check receipt"),t.schema!==Ol)throw new Error("Native check receipt schema is invalid");if(typeof t.change!="string"||Buffer.byteLength(t.change,"utf8")>128||!bj.test(t.change))throw new Error("Native check receipt change name is invalid");let i=mN(t.sourceRevision,"Native check source revision"),n=xj(t.checker),r=Aj(t.contract),a=Tj(t.implementation),o=vN({change:t.change,sourceRevision:i,checkerHash:n.hash,contractHash:r.expectedHash,scopeHash:a.scopeHash,snapshotHash:a.expectedSnapshotHash});if(Bi(t.inputHash,"Native check input hash")!==o)throw new Error("Native check receipt input hash mismatch");if(t.status!=="passed"&&t.status!=="failed")throw new Error("Native check receipt status is invalid");let s=fN(t.startedAt,"Native check receipt startedAt"),c=fN(t.endedAt,"Native check receipt endedAt");if(cu.length)throw new Error("Native check receipt issue truncation flag is inconsistent");let d=Oj(t.staleReasons);if(typeof t.stale!="boolean"||t.stale!==d.length>0)throw new Error("Native check receipt stale flag is inconsistent");let f=l.issueCount===0&&!t.stale?"passed":"failed";if(t.status!==f)throw new Error("Native check receipt status is inconsistent with its evidence");if(t.status==="passed"&&(l.filesSelected>Ae.maxFiles||l.filesScanned+l.binaryFilesSkipped!==l.filesSelected))throw new Error("Passed Native check receipt must cover every selected file");if(l.filesSelected>Ae.maxFiles&&!u.some(p=>p.kind==="scan-limit"))throw new Error("Native check receipt exceeds its file budget without a scan-limit issue");let h={schema:Ol,change:t.change,sourceRevision:i,checker:n,inputHash:o,status:t.status,startedAt:s,endedAt:c,contract:r,implementation:a,counts:l,issues:u,issuesTruncated:t.issuesTruncated,stale:t.stale,staleReasons:d},m=Bi(t.receiptHash,"Native check receipt content hash");if(H(hN,h)!==m)throw new Error("Native check receipt content hash mismatch");return{...h,receiptHash:m}}function gN(e){let t={policy:On,version:ts,hash:$l,limits:{...Ae}},i={schema:Ol,...e,checker:t,inputHash:vN({change:e.change,sourceRevision:e.sourceRevision,checkerHash:t.hash,contractHash:e.contract.expectedHash,scopeHash:e.implementation.scopeHash,snapshotHash:e.implementation.expectedSnapshotHash})};return qi({...i,receiptHash:H(hN,i)})}var Hl="comet.native.verification-receipt.v3",wN=Hl,$j="comet.native.declared-artifacts.v1",Hj=/^[a-f0-9]{64}$/u,Dj=/^acceptance-[a-f0-9]{64}$/u,Mj=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Fj=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,Lj=4096,Bj=256,qj=1024;function ma(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let i=Object.getPrototypeOf(e);if(i!==Object.prototype&&i!==null)throw new Error(`${t} must be a plain object`);return e}function $n(e,t,i){let n=Object.keys(e).sort(),r=[...t].sort();if(n.length!==r.length||n.some((a,o)=>a!==r[o]))throw new Error(`${i} fields are invalid`)}function Vi(e,t){if(typeof e!="string"||!Hj.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Yt(e,t){if(typeof e!="string")throw new Error(`${t} must be text`);let i=ke(e).trim();if(!i||i.length>Lj||i!==e.trim())throw new Error(`${t} is invalid`);return i}function yh(e,t){let i=Yt(e,t),n=new Date(i);if(Number.isNaN(n.getTime())||n.toISOString()!==i)throw new Error(`${t} must be a canonical timestamp`);return i}function is(e,t,i=Yt,n=!1,r=Bj){if(!Array.isArray(e)||e.length>r||!n&&e.length===0)throw new Error(`${t} must be a bounded non-empty array`);let a=e.map((o,s)=>i(o,`${t} ${s}`));if(new Set(a).size!==a.length)throw new Error(`${t} has duplicates`);return a}function Vj(e,t){if(typeof e!="string"||!Dj.test(e))throw new Error(`${t} is invalid`);return e}function Wj(e){let t=ma(e,"Native verification receipt bindings");if($n(t,["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"],"Native verification receipt bindings"),typeof t.change!="string"||!Mj.test(t.change)||!Number.isSafeInteger(t.sourceRevision)||t.sourceRevision<1)throw new Error("Native verification receipt bindings are invalid");return{change:t.change,sourceRevision:t.sourceRevision,contractHash:Vi(t.contractHash,"Native verification receipt contract hash"),scopeHash:Vi(t.scopeHash,"Native verification receipt scope hash"),snapshotHash:Vi(t.snapshotHash,"Native verification receipt snapshot hash"),artifactHash:Vi(t.artifactHash,"Native verification receipt artifact hash")}}function Jj(e){if(typeof e!="string")throw new Error("Native static check receipt ref is invalid");let t=Fj.exec(e);if(!t)throw new Error("Native static check receipt ref is invalid");return{ref:e,hash:t[1]}}function zj(e,t,i,n){let r=ma(t,`Native ${e} evidence`);if(e==="automated-check"){if($n(r,["executable","args","cwd","exitCode","signal","timedOut","timeoutMs","startedAt","endedAt","worktree","afterFence","outputHash","outputSummary","outputTruncated"],"Native automated-check evidence"),!Number.isSafeInteger(r.exitCode)||!Number.isSafeInteger(r.timeoutMs)||r.timeoutMs<1||r.timeoutMs>3600*1e3||typeof r.timedOut!="boolean"||typeof r.outputTruncated!="boolean"||r.signal!==null&&typeof r.signal!="string")throw new Error("Native automated-check exit code is invalid");let a=yh(r.startedAt,"Native automated-check start time"),o=yh(r.endedAt,"Native automated-check end time");if(Date.parse(o)({path:t.path,kind:t.kind})).sort((t,i)=>t.path.localeCompare(i.path)||t.kind.localeCompare(i.kind)))}function NN(e){return e.kind==="static-inspection"?`static:${e.evidence.rule}`:e.kind==="automated-check"?`automated:${H("comet.native.failed-check.v1",{executable:e.evidence.executable,args:e.evidence.args,acceptanceIds:e.acceptanceIds})}`:`manual:${H("comet.native.failed-check.v1",{acceptanceIds:e.acceptanceIds})}`}var RN=/^[a-f0-9]{64}$/u,Qt=wi,vV=3*Qt;function Nh(e,t){let i=Xt.relative(e,t);return i===""||!Xt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Xt.sep}`)}function Gj(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Fl(e,t){let i={...e,birthtime:e.birthtimeMs},n={...t,birthtime:t.birthtimeMs};return Ue(i,n)?M(i,n):M(i,n)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function bN(e){let t=await Dt.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${e}`);return{path:e,realPath:await Dt.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Uj(e,t){let i=Xt.resolve(e),n=Xt.resolve(t);if(!Nh(i,n))throw new Error("Native evidence path is outside its change");let r=[await bN(i)],a=i;for(let o of Xt.relative(i,n).split(Xt.sep).filter(Boolean)){a=Xt.join(a,o);let s=await bN(a);if(!Nh(r[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);r.push(s)}return r}async function kN(e){for(let t of e){let i=await Dt.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!Gj(t,i)||await Dt.realpath(t.path)!==t.realPath)throw new Error(`Native evidence parent changed while reading: ${t.path}`)}}async function Kj(e,t,i={}){let n=await Uj(t,Xt.dirname(e));await i.afterParentChainCaptured?.();let r=await Dt.lstat(e);if(!r.isFile()||r.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await Dt.realpath(e);if(!Nh(n[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await Dt.open(e,"r");try{let[s,c,l]=await Promise.all([o.stat(),Dt.lstat(e),Dt.realpath(e)]);if(await kN(n),!s.isFile()||!c.isFile()||c.isSymbolicLink()||l!==a||!Fl(s,r)||!Fl(s,c))throw new Error("Native evidence document changed while opening");if(s.size>Qt)throw new Error(`Native evidence document exceeds ${Qt} bytes`);await i.afterOpen?.();let u=[],d=0,f=Buffer.allocUnsafe(64*1024);for(;;){let v=Qt+1-d,S=await o.read(f,0,Math.min(f.length,v),null);if(S.bytesRead===0)break;if(d+=S.bytesRead,d>Qt)throw new Error(`Native evidence document exceeds ${Qt} bytes`);u.push(Buffer.from(f.subarray(0,S.bytesRead)))}await i.beforeFinalCheck?.();let[h,m,p]=await Promise.all([o.stat(),Dt.lstat(e),Dt.realpath(e)]);if(await kN(n),!m.isFile()||m.isSymbolicLink()||p!==a||!Fl(s,h)||!Fl(s,m))throw new Error("Native evidence document changed while reading");return JSON.parse(Buffer.concat(u,d).toString("utf8"))}finally{await o.close()}}function pt(e,t){if(!RN.test(t))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${e}/${t}.json`}function CN(e){return pt("reports",e)}async function PN(e){let t=Buffer.from(e.text,"utf8");if(t.byteLength>Qt||EN("sha256").update(t).digest("hex")!==e.hash)throw new Error("Native verification report snapshot hash or size is invalid");return mr({paths:e.paths,name:e.name,kind:"reports",hash:e.hash,value:{schema:"comet.native.verification-report.v1",reportHash:e.hash,content:e.text}})}async function Yj(e,t,i,n,r){if(!RN.test(i))throw new Error("Native report evidence hash is invalid");let a=await Wi({paths:e,name:t,kind:"reports",hash:i,hooks:n,changeDir:r});if(!a||typeof a!="object"||Array.isArray(a))throw new Error("Native report evidence must be an object");let o=a;if(Object.keys(o).sort().join(",")!=="content,reportHash,schema"||o.schema!=="comet.native.verification-report.v1"||o.reportHash!==i||typeof o.content!="string"||EN("sha256").update(Buffer.from(o.content,"utf8")).digest("hex")!==i)throw new Error("Native report evidence does not match its hash");return o.content}function va(e,t){let i=/^runtime\/evidence\/(snapshots|scopes|allowances|verifications|reports|receipts)\/([a-f0-9]{64})\.json$/u.exec(e);if(!i||i[1]!==t)throw new Error(`Native evidence ref is invalid for ${t}`);return i[2]}function xN(e,t,i,n,r){return Xt.join(r??C(e,t),...pt(i,n).split("/"))}async function Wi(e){let t=e.changeDir??C(e.paths,e.name),i=xN(e.paths,e.name,e.kind,e.hash,t);return await x(e.paths.nativeRoot,i),Kj(i,t,e.hooks)}async function mr(e){Ll(e.value);let t=xN(e.paths,e.name,e.kind,e.hash);await x(e.paths.nativeRoot,t);try{let n=await Wi(e);if(JSON.stringify(n)!==JSON.stringify(e.value))throw new Error(`Native evidence hash collision for ${e.hash}`);return pt(e.kind,e.hash)}catch(n){if(n.code!=="ENOENT")throw n}await le(t,e.value,{containedRoot:e.paths.nativeRoot});let i=await Wi(e);if(JSON.stringify(i)!==JSON.stringify(e.value))throw new Error(`Native evidence changed during commit for ${e.hash}`);return pt(e.kind,e.hash)}function Ll(e){if(Xj(e)>Qt)throw new Error(`Native evidence document exceeds ${Qt} bytes`)}function Xj(e){return Buffer.byteLength(JSON.stringify(e,null,2)+` -`,"utf8")}function SN(e,t){return da(e,t)}function Qj(e,t){let i=fa(e);if(i.scopeHash!==t)throw new Error("Native implementation scope ref/hash mismatch");return i}function AN(e,t,i){let n=es(e);if(n.change!==t||n.allowanceHash!==i)throw new Error("Native partial allowance ref/hash/change mismatch");return n}function TN(e,t,i){let n=pa(e);if(n.change!==t||n.envelopeHash!==i)throw new Error("Native verification evidence ref/hash/change mismatch");return n}async function _N(e,t,i,n=!1,r){let a=await Bl(e,t,i.implementationScopeRef,void 0,r);if(n&&await Yj(e,t,i.reportHash,void 0,r),a.scopeHash!==i.implementationScopeHash||a.contractHash!==i.contractHash||(a.complete?"complete":"partial")!==i.freshness)throw new Error("Native verification evidence does not match its implementation scope");if(i.partialAllowanceRef===null)return;let o=await bh(e,t,i.partialAllowanceRef,void 0,r);if(o.allowanceHash!==i.partialAllowanceHash||o.scopeHash!==a.scopeHash||JSON.stringify(o.scopeIds)!==JSON.stringify(a.unresolvedScopes.map(s=>s.id).sort())||o.sourceRevision>=i.sourceRevision)throw new Error("Native verification evidence does not match its partial allowance")}async function IN(e){let t=Kt(e.bundle),{baseline:i,current:n,scope:r}=t;return Ll(i),Ll(n),Ll(r),await mr({paths:e.paths,name:e.name,kind:"snapshots",hash:r.baselineProjectionHash,value:i}),await mr({paths:e.paths,name:e.name,kind:"snapshots",hash:r.currentProjectionHash,value:n}),mr({paths:e.paths,name:e.name,kind:"scopes",hash:r.scopeHash,value:r})}async function yi(e,t,i,n,r){let a=va(i,"scopes"),o=Qj(await Wi({paths:e,name:t,kind:"scopes",hash:a,hooks:n,changeDir:r}),a),s=va(o.baselineProjectionRef,"snapshots"),c=va(o.currentProjectionRef,"snapshots"),[l,u]=await Promise.all([Wi({paths:e,name:t,kind:"snapshots",hash:s,changeDir:r}).then(d=>SN(d,s)),Wi({paths:e,name:t,kind:"snapshots",hash:c,changeDir:r}).then(d=>SN(d,c))]);return Xy({baseline:l,current:u,scope:o})}async function Bl(e,t,i,n,r){return(await yi(e,t,i,n,r)).scope}async function jN(e){let t=AN(e.allowance,e.name,e.allowance.allowanceHash),i=await Bl(e.paths,e.name,pt("scopes",t.scopeHash)),n=i.unresolvedScopes.map(r=>r.id).sort();if(i.complete||JSON.stringify(n)!==JSON.stringify(t.scopeIds))throw new Error("Native partial allowance does not match a persisted partial scope");return mr({...e,kind:"allowances",hash:t.allowanceHash,value:t})}async function bh(e,t,i,n,r){let a=va(i,"allowances");return AN(await Wi({paths:e,name:t,kind:"allowances",hash:a,hooks:n,changeDir:r}),t,a)}async function ql(e){let t=ns(e.receipt);if(t.bindings.change!==e.name)throw new Error("Native verification receipt change mismatch");return mr({paths:e.paths,name:e.name,kind:"receipts",hash:t.receiptHash,value:t})}async function Hn(e,t,i,n,r){let a=va(i,"receipts"),o=ns(await Wi({paths:e,name:t,kind:"receipts",hash:a,hooks:n,changeDir:r}));if(o.bindings.change!==t||o.receiptHash!==a)throw new Error("Native verification receipt ref/hash/change mismatch");return o}async function ON(e,t){let i=Xt.join(C(e,t),"runtime","evidence","receipts");await x(e.nativeRoot,i);let n;try{n=await Dt.readdir(i,{withFileTypes:!0})}catch(r){if(r.code==="ENOENT")return[];throw r}return n.filter(r=>r.isFile()).map(r=>/^([a-f0-9]{64})\.json$/u.exec(r.name)?.[1]).filter(r=>r!==void 0).sort().map(r=>pt("receipts",r))}async function $N(e){let t=TN(e.evidence,e.name,e.evidence.envelopeHash);if(t.schema!=="comet.native.verification-evidence.v2")throw new Error("Native active verification evidence must use v2");return await _N(e.paths,e.name,t,!0),mr({...e,kind:"verifications",hash:t.envelopeHash,value:t})}async function Dn(e,t,i,n,r){let a=va(i,"verifications"),o=TN(await Wi({paths:e,name:t,kind:"verifications",hash:a,hooks:n,changeDir:r}),t,a);return await _N(e,t,o,!1,r),o}var Zj=4096;async function eO(e,t=ht.maxChanges){try{let i=await st({root:e.nativeRoot,directory:e.changesDir,label:"Native conflict changes directory",maxEntries:t});return await i.verify(),i.entries}catch(i){if(i.code==="ENOENT")return[];throw i}}async function HN(e,t){let i=await G(e,t),[n,r]=await Promise.all([i.implementation_scope?Bl(e,t,i.implementation_scope):null,Ve(e,t).catch(()=>null)]);return{name:i.name,revision:i.revision,specs:i.spec_changes.map(a=>({capability:a.capability,operation:a.operation,baseHash:a.base_hash})),declaredArtifacts:n?.declaredArtifacts??[],workspaceIdentityHash:r?.nativeRootId??null}}async function Vl(e,t,i={}){let r=(await eO(e,Zj)).filter(c=>c.isDirectory()&&!c.isSymbolicLink()).map(c=>c.name).sort();if(!r.includes(t))throw new Error(`Native conflict target is not visible: ${t}`);let a=await HN(e,t),o=0,s=0;for(let c of r){if(c===t)continue;let l=await HN(e,c).catch(d=>{if(i.tolerateInvalidSiblings)return null;throw d});if(!l)continue;let u=Hy([a,l]).relationships[0];u.classification==="definite-conflict"&&(o+=1),u.classification==="possible-overlap"&&(s+=1)}return{definiteConflictCount:o,possibleOverlapCount:s,findingCodes:[...o>0?["native-change-conflict"]:[],...s>0?["native-change-overlap"]:[]]}}import{randomUUID as SO}from"crypto";import{promises as EO}from"fs";import RO from"path";import{isDeepStrictEqual as xh}from"util";var tO="comet.native.repair-signature.v1",kt={warningAtConsecutiveFailures:2,manualStopAtConsecutiveFailures:3,maxHistoryRecords:64,maxFailedAcceptanceIds:1024,maxFailedCheckIds:128,maxOverrideSummaryCharacters:2e3},iO="comet.native.repair-signature.v1",nO="comet.native.repair-override-summary.v1",rO=/^[a-f0-9]{64}$/u,aO=/^[a-z0-9][a-z0-9._:/-]{0,255}$/u;function MN(e,t){return et?1:0}function Wl(e,t){if(typeof e!="string"||!rO.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function kh(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Jl(e,t,i,n){if(!Array.isArray(e)||e.length>i||!n&&e.length===0)throw new Error(`${t} exceeds its count boundary`);let r=e.map(a=>{if(typeof a!="string"||!aO.test(a))throw new Error(`${t} contains an invalid token: ${String(a)}`);return a});return[...new Set(r)].sort(MN)}function ga(e=[]){return Jl(e,"Native repair failed check IDs",kt.maxFailedCheckIds,!0)}function FN(e){let t=ga(e.failedCheckIds),i=Jl(e.failedAcceptanceIds,"Native repair failed acceptance IDs",kt.maxFailedAcceptanceIds,!0),n={schema:tO,contractHash:Wl(e.contractHash,"Native repair contract hash"),failedAcceptanceIds:i,failedCheckIds:t};return{...n,signatureHash:H(iO,n)}}function oO(e){if(!Array.isArray(e)||e.length>kt.maxHistoryRecords)throw new Error("Native repair history exceeds its record boundary");let t=0,i=0;return e.map((n,r)=>{if(!n||n.kind!=="failure"&&n.kind!=="override")throw new Error(`Native repair history record ${r} is invalid`);let a=n.kind==="failure"?n.failedAcceptanceIds===void 0&&n.failedCheckIds===void 0?["iteration","kind","revision","signatureHash"]:["failedAcceptanceIds","failedCheckIds","iteration","kind","revision","signatureHash"]:["iteration","kind","revision","signatureHash","summaryHash"],o=Object.keys(n).sort(MN);if(o.length!==a.length||o.some((f,h)=>f!==a[h]))throw new Error(`Native repair history record ${r} fields are invalid`);let s=kh(n.iteration,`Native repair history ${r} iteration`),c=kh(n.revision,`Native repair history ${r} revision`),l=r>0?e[r-1]:null;if(!(n.kind==="override"&&l?.kind==="failure"&&s===t&&c>=i&&n.signatureHash===l.signatureHash)&&(s<=t||c<=i))throw new Error("Native repair history must be strictly ordered by revision and iteration");t=s,i=c;let d=Wl(n.signatureHash,`Native repair history ${r} signature`);return n.kind==="failure"?n.failedAcceptanceIds===void 0&&n.failedCheckIds===void 0?{kind:"failure",iteration:s,revision:c,signatureHash:d}:{kind:"failure",iteration:s,revision:c,signatureHash:d,failedAcceptanceIds:Jl(n.failedAcceptanceIds??[],`Native repair history ${r} failed acceptance IDs`,kt.maxFailedAcceptanceIds,!0),failedCheckIds:Jl(n.failedCheckIds??[],`Native repair history ${r} failed check IDs`,kt.maxFailedCheckIds,!0)}:{kind:"override",iteration:s,revision:c,signatureHash:d,summaryHash:Wl(n.summaryHash,`Native repair history ${r} summary`)}})}function DN(e,t){let i=new Set(t);return e.every(n=>i.has(n))}function sO(e,t){return e.failedAcceptanceIds===void 0||e.failedCheckIds===void 0||t.failedAcceptanceIds===void 0||t.failedCheckIds===void 0?e.signatureHash!==t.signatureHash:DN(e.failedAcceptanceIds,t.failedAcceptanceIds)&&DN(e.failedCheckIds,t.failedCheckIds)&&(e.failedAcceptanceIds.length=0;r-=1){let a=t[r];if(sO(n,a))break;i+=1,n=a}return i}function LN(e){let t=e.trim();if(t.length===0||t.length>kt.maxOverrideSummaryCharacters)throw new Error("Native repair override summary is invalid");return t}function zl(e){return H(nO,{summary:LN(e)})}function BN(e){let t=FN(e.facts),i=oO(e.history),n=i.filter(l=>l.kind==="failure"),r=n.length+1,a=kh(e.maxVerifyFailures,"Native maximum Verify failures"),o=Math.max(0,a-r),s=rs({signatureHash:t.signatureHash,failedAcceptanceIds:t.failedAcceptanceIds,failedCheckIds:t.failedCheckIds},n);if(r>=a)return{disposition:"hard-stop",reasonCode:"repair-iteration-limit",signature:t,consecutiveFailures:s,totalRepairFailures:r,remainingIterations:o,overrideAccepted:!1};if(sd.kind==="override"&&d.signatureHash===t.signatureHash);return{disposition:u?"manual-stop":"continue",reasonCode:u?"override-already-used":"override-accepted",signature:t,consecutiveFailures:s,totalRepairFailures:r,remainingIterations:o,overrideAccepted:!u}}return{disposition:"manual-stop",reasonCode:i.some(l=>l.kind==="override"&&l.signatureHash===t.signatureHash)?"override-already-used":"repeated-failure-stop",signature:t,consecutiveFailures:s,totalRepairFailures:r,remainingIterations:o,overrideAccepted:!1}}function Mn(e,t){if(typeof e!="string"||e.trim().length===0||e.length>4096)throw new Error(`${t} must be between 1 and 4096 characters`)}var qN="repairStagnation",St={maxEvents:4096,maxDataDepth:8,maxDataNodes:4096,maxTotalDataNodes:65536,maxObjectFields:64,maxArrayEntries:256,maxKeyCharacters:128,maxTextCharacters:4096,maxEventDataCharacters:65536,maxTotalDataCharacters:1048576,maxRunIdCharacters:256},lO=/^[a-f0-9]{64}$/u,VN="comet.native.repair-scope.v1",uO=new Set(["run_started","action_proposed","action_completed","eval_completed","checkpoint","state_migrated","state_transitioned","command_check_recorded","recovery_reconciled"]),dO=["data","runId","sequence","timestamp","type"],WN=["disposition","overrideSummaryHash","signatureHash"],fO=["contractHash","disposition","failedAcceptanceIds","failedCheckIds","maxVerifyFailures","overrideSummaryHash","signatureHash"],JN=12;function Gl(e,t){return et?1:0}function Eh(e,t,i){let n=Object.keys(e).sort(Gl);if(n.length!==t.length||n.some((r,a)=>r!==t[a]))throw new Error(`${i} fields are invalid`)}function as(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let i=Object.getPrototypeOf(e);if(i!==Object.prototype&&i!==null)throw new Error(`${t} must be a plain object`);return e}function wa(e,t){if(typeof e!="string"||!lO.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function hO(e){if(!Array.isArray(e)||e.length>kt.maxFailedAcceptanceIds||e.some(t=>typeof t!="string"||!/^acceptance-[a-f0-9]{64}$/u.test(t)))throw new Error("Native repair trajectory failed acceptance IDs are invalid");return[...new Set(e)].sort(Gl)}function ya(e){let t=Kt(e).scope;return H(VN,{schema:VN,contractHash:t.contractHash,artifactSnapshotHash:t.currentProjectionHash})}function zN(e){if(typeof e!="string"||e.length===0||e.length>St.maxRunIdCharacters||Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127}))throw new Error("Native repair trajectory run ID is invalid");return e}function Sh(e,t,i,n,r=!1){if(i.nodes+=1,i.nodes>St.maxDataNodes)throw new Error("Native repair trajectory event data exceeds its node boundary");if(t>St.maxDataDepth)throw new Error("Native repair trajectory event data exceeds its depth boundary");if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){if(!Number.isFinite(e))throw new Error(`${n} contains a non-finite number`);return}if(typeof e=="string"){if(e.length>St.maxTextCharacters&&(!r||e.length>St.maxEventDataCharacters))throw new Error(`${n} contains oversized text`);if(i.characters+=e.length,i.characters>St.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");return}if(typeof e!="object")throw new Error(`${n} contains a non-JSON value`);if(i.ancestors.has(e))throw new Error(`${n} contains a cycle`);i.ancestors.add(e);try{if(Array.isArray(e)){if(e.length>St.maxArrayEntries)throw new Error(`${n} contains an oversized array`);e.forEach((s,c)=>Sh(s,t+1,i,`${n}[${c}]`));return}let a=as(e,n),o=Object.keys(a);if(o.length>St.maxObjectFields)throw new Error(`${n} contains too many fields`);for(let s of o){if(s.length===0||s.length>St.maxKeyCharacters)throw new Error(`${n} contains an invalid field name`);if(i.characters+=s.length,i.characters>St.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");Sh(a[s],t+1,i,`${n}.${s}`,t===0&&(s==="summary"||s==="noCodeReason"))}}finally{i.ancestors.delete(e)}}}function pO(e){if(typeof e!="string"||e.length>64)throw new Error("Native repair trajectory timestamp is invalid");let t=new Date(e);if(!Number.isFinite(t.valueOf())||t.toISOString()!==e)throw new Error("Native repair trajectory timestamp is invalid");return e}function mO(e,t,i){let n=as(e,`Native repair trajectory event ${t+1}`);if(Eh(n,dO,`Native repair trajectory event ${t+1}`),!Number.isSafeInteger(n.sequence)||n.sequence!==t+1)throw new Error("Native repair trajectory sequence is invalid");if(pO(n.timestamp),typeof n.type!="string"||!uO.has(n.type))throw new Error("Native repair trajectory event type is invalid");if(zN(n.runId)!==i)throw new Error("Native repair trajectory run ID changed inside the committed prefix");let r={nodes:0,characters:0,ancestors:new Set};return Sh(n.data,0,r,"Native trajectory event data"),as(n.data,"Native repair trajectory event data"),{event:n,dataNodes:r.nodes,dataCharacters:r.characters}}function Rh(e){let t=as(e,"Native repair trajectory projection"),i=Object.keys(t).sort(Gl),n=i.length===WN.length&&i.every((l,u)=>l===WN[u]);n||Eh(t,fO,"Native repair trajectory projection");let r=wa(t.signatureHash,"Native repair trajectory signature hash");if(t.disposition!=="continue"&&t.disposition!=="warn"&&t.disposition!=="manual-stop"&&t.disposition!=="hard-stop")throw new Error("Native repair trajectory disposition is invalid");let a=t.overrideSummaryHash===null?null:wa(t.overrideSummaryHash,"Native repair trajectory override summary hash");if(a!==null&&t.disposition!=="continue")throw new Error("Native repair trajectory override must continue exactly once");if(n)return{signatureHash:r,disposition:t.disposition,overrideSummaryHash:a,contractHash:null,failedAcceptanceIds:[],failedCheckIds:[],maxVerifyFailures:null};let o=wa(t.contractHash,"Native repair trajectory contract hash"),s=hO(t.failedAcceptanceIds),c=ga(t.failedCheckIds);if(!Number.isSafeInteger(t.maxVerifyFailures)||t.maxVerifyFailures<1)throw new Error("Native repair trajectory maximum Verify failures is invalid");return{signatureHash:r,disposition:t.disposition,overrideSummaryHash:a,contractHash:o,failedAcceptanceIds:s,failedCheckIds:c,maxVerifyFailures:t.maxVerifyFailures}}function vO(e,t){if(t.overrideSummaryHash===null){if(e.previousPhase!=="verify"||e.nextPhase!=="build"||e.verificationResult!=="fail")throw new Error("Native repair failure projection is only valid on a failed Verify-to-Build transition");return}if(t.disposition!=="continue"||e.previousPhase!=="build"||e.nextPhase!=="verify"||e.verificationResult!==null)throw new Error("Native repair override projection is only valid on a Build-to-Verify transition")}function gO(e,t){let i=t.filter(s=>s.kind==="failure"),n=i.length+1,r=e.maxVerifyFailures??JN;if(n>r)throw new Error("Native repair trajectory commits a failure beyond the hard-stop boundary");let a=rs({signatureHash:e.signatureHash,...e.contractHash===null?{}:{failedAcceptanceIds:e.failedAcceptanceIds,failedCheckIds:e.failedCheckIds}},i),o=n>=r?"hard-stop":aa.kind==="failure"),r=i?.maxVerifyFailures??JN;if(n.length>=r)throw new Error("Native repair trajectory cannot override a hard stop");if(i?.disposition!=="manual-stop"||i.signatureHash!==e.signatureHash||n.at(-1)?.signatureHash!==e.signatureHash)throw new Error("Native repair trajectory override does not match the latest manual stop");if(t.some(a=>a.kind==="override"&&a.signatureHash===e.signatureHash))throw new Error("Native repair trajectory signature was already overridden")}function Ul(e){if(!Array.isArray(e.trajectory)||e.trajectory.length>St.maxEvents)throw new Error("Native repair trajectory exceeds its event boundary");let t=zN(e.runId);if(!Number.isSafeInteger(e.committedTrajectoryOffset)||e.committedTrajectoryOffset<0||e.committedTrajectoryOffset>e.trajectory.length)throw new Error("Native repair committed trajectory offset is invalid");let i=[],n=null,r=null,a=null,o=0,s=0,c=0;for(let l=0;lSt.maxTotalDataNodes||c>St.maxTotalDataCharacters)throw new Error("Native repair committed trajectory exceeds its aggregate data boundary");let f=d.data,h=Object.hasOwn(f,"repairScopeHash")?wa(f.repairScopeHash,"Native repair trajectory repair scope hash"):Object.hasOwn(f,"implementationScopeHash")?wa(f.implementationScopeHash,"Native repair trajectory implementation scope hash"):null;if(!Object.hasOwn(f,qN)){if(n?.contractHash===null&&d.type==="state_transitioned"&&f.previousPhase==="build"&&f.nextPhase==="verify"&&(h!==null&&r!==null&&h!==r||h===null&&(n?.disposition==="manual-stop"||n?.disposition==="hard-stop"))){i.length=0,n=null,r=h,o=0;continue}continue}if(d.type!=="state_transitioned")throw new Error("Native repair projection must belong to a state_transitioned event");let m=Rh(f[qN]);if(vO(f,m),m.overrideSummaryHash===null)m.contractHash!==null&&a!==null&&m.contractHash!==a&&(i.length=0,o=0),m.contractHash!==null&&(a=m.contractHash),m.contractHash===null&&h!==null&&r!==null&&h!==r&&(i.length=0,o=0),h!==null&&(r=h),gO(m,i),o+=1,i.push({kind:"failure",revision:d.sequence,iteration:o,signatureHash:m.signatureHash,...m.contractHash===null?{}:{failedAcceptanceIds:[...m.failedAcceptanceIds],failedCheckIds:[...m.failedCheckIds]}});else{if(n?.contractHash===null&&h!==null&&r!==null&&h!==r)throw new Error("Native repair override cannot cross implementation scope progress");wO(m,i,n);let p=i.at(-1);if(!p||p.kind!=="failure")throw new Error("Native repair trajectory override has no failure history");i.push({kind:"override",revision:d.sequence,iteration:p.iteration,signatureHash:m.signatureHash,summaryHash:m.overrideSummaryHash})}if(n=m,i.length>kt.maxHistoryRecords)throw new Error("Native repair trajectory history exceeds its record boundary")}return{history:i,latestProjection:n}}function GN(e){return Ul(e).history}function UN(e){let t=Ul(e).latestProjection;return t?{...t}:null}function KN(e){let t=Ul(e),i=as(e.override,"Native repair override request");Eh(i,["expectedSignatureHash","summary"],"Native repair override request");let n=wa(i.expectedSignatureHash,"Native repair override expected signature");if(typeof i.summary!="string")throw new Error("Native repair override summary is invalid");if(t.latestProjection?.disposition==="hard-stop")throw new Error("Native repair hard stop cannot be overridden");if(t.latestProjection?.disposition!=="manual-stop"||t.latestProjection.signatureHash!==n)throw new Error("Native repair override does not match the latest manual stop");if(t.history.some(a=>a.kind==="override"&&a.signatureHash===n))throw new Error("Native repair signature was already overridden");let r=zl(i.summary);return{history:t.history,eventProjection:{signatureHash:n,disposition:"continue",overrideSummaryHash:r,contractHash:t.latestProjection.contractHash,failedAcceptanceIds:[...t.latestProjection.failedAcceptanceIds],failedCheckIds:[...t.latestProjection.failedCheckIds],maxVerifyFailures:t.latestProjection.maxVerifyFailures}}}function yO(e){let t=pa(e.envelope),i=Kt(e.implementationScope);if(t.result!=="fail")throw new Error("Native repair stagnation requires a failed verification envelope");if(t.contractHash!==i.scope.contractHash||t.implementationScopeHash!==i.scope.scopeHash)throw new Error("Native repair evidence does not match the implementation scope authority");return{contractHash:i.scope.contractHash,implementationScopeHash:ya(i),artifactSnapshotHash:i.scope.currentProjectionHash,failedAcceptanceIds:t.acceptanceTrace.entries.filter(n=>n.status==="failed"||n.status==="missing").map(n=>n.acceptanceId).sort(Gl),failedCheckIds:ga(e.failedCheckIds)}}function NO(e,t){return{signatureHash:e.signature.signatureHash,disposition:e.disposition,overrideSummaryHash:t,contractHash:e.signature.contractHash,failedAcceptanceIds:[...e.signature.failedAcceptanceIds],failedCheckIds:[...e.signature.failedCheckIds],maxVerifyFailures:e.totalRepairFailures+e.remainingIterations}}function bO(e){let t=yO(e),i=Ul(e);return{facts:t,history:i.latestProjection?.contractHash!==null&&i.latestProjection?.contractHash!==t.contractHash?[]:i.history}}function YN(e){let t=bO(e),i=BN({...t,maxVerifyFailures:e.maxVerifyFailures});return{...t,decision:i,eventProjection:NO(i,null)}}var mt={root:"/comet/native-runtime",packageKind:"runtime",definition:{apiVersion:"comet/v1alpha1",kind:"Skill",metadata:{name:"comet-native-runtime",version:"3",description:"Comet-owned state runtime for the Native workflow."},goal:{statement:"Advance a Native change only after its current guard passes.",inputs:[],outputs:[],success:["The Native change and Run state agree on the next phase."]},orchestration:{mode:"deterministic",entry:"shape",steps:[{id:"shape",action:{type:"checkpoint"},next:"build"},{id:"build",action:{type:"checkpoint"},next:"verify"},{id:"verify",action:{type:"checkpoint"},next:"archive"},{id:"archive",action:{type:"checkpoint"}}]},skills:[],agents:[],tools:[]},guardrails:{allowedSkills:[],allowedAgents:[],allowedTools:[],maxIterations:Number.MAX_SAFE_INTEGER,maxRetriesPerAction:2,confirmationRequiredFor:[]},evals:[]},vr=D("comet-native-runtime:v3:semantic-repair-budget"),kO=[{skillVersion:"2",skillHash:D("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:D("comet-native-runtime:v1")}];function XN(e){return e.skillVersion===mt.definition.metadata.version&&e.skillHash===vr||kO.some(t=>t.skillVersion===e.skillVersion&&t.skillHash===e.skillHash)}var Na={resolveStep({pkg:e,state:t}){return e.definition.orchestration.steps?.find(i=>i.id===t.currentStep)},resolveNext({step:e,outcome:t}){return e.id==="verify"&&t.state?.verification_result==="fail"?"build":e.next??null}};async function Fn(e){let i={sequence:(await qe(e.changeDir,e.run.trajectoryRef)).length+1,timestamp:(e.now??new Date).toISOString(),type:e.type,runId:e.run.runId,data:e.data};return await Yw(e.changeDir,e.run.trajectoryRef,i),i}async function gr(e){let t={runId:e.run.runId,stateVersion:e.run.iteration,trajectoryOffset:e.trajectoryOffset,contextHash:null,artifactsHash:D(e.evidenceHash),createdAt:(e.now??new Date).toISOString()};return await Xw(e.changeDir,e.run.checkpointRef,t),t}function Kl(e){return D(JSON.stringify({summary:e.summary,confirmed:e.confirmed??!1,artifacts:[...e.artifacts??[]].sort(),noCodeReason:e.noCodeReason??null,verificationResult:e.verificationResult??null,verificationReport:e.verificationReport??null,allowPartialScopeHash:e.allowPartialScopeHash??null,partialReason:e.partialReason??null,repairOverrideSignature:e.repairOverrideSignature??null,repairOverrideSummary:e.repairOverrideSummary??null}))}var ab=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],CO=new Set(ab),ob=new Set([...ab,"minimum_runtime_version","revision"]),PO=new Set([...ob,"operation"]),xO=512*1024,Ch=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),AO=new Set([...Ch,"implementationScopeHash","repairScopeHash","repairStagnation"]),os=class extends Error{constructor(i){super(`Native transition for ${i} requires doctor migration before recovery`);this.change=i;this.name="NativeTransitionMigrationRequiredError"}change;code="native-transition-migration-required"};function We(e,t){return RO.join(C(e,t),"runtime","transition.json")}function TO(e){return`transition-${e}`}async function _O(e,t,i){let n=TO(t);return di(e,n,i)}async function De(e,t,i,n){let r=await _O(e,t,i);try{return await n()}finally{await fi(r)}}function Xl(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal must be an object");return e}function Ah(e,t){let i=Object.keys(e).find(n=>!t.has(n));if(i)throw new Error(`Native transition journal contains unknown field: ${i}`)}function Yl(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Ni(e,t){return xh(e,t)}function Ph(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal event data is invalid");let i=e,n=Object.keys(i),r=n.find(u=>!AO.has(u)),a=[...Ch].find(u=>!Object.hasOwn(i,u)),o=Ch.size+(Object.hasOwn(i,"implementationScopeHash")?1:0)+(Object.hasOwn(i,"repairScopeHash")?1:0)+(Object.hasOwn(i,"repairStagnation")?1:0);if(r||a||n.length!==o)throw new Error(`Native transition journal event data keys are invalid${r?`: ${r}`:a?`: missing ${a}`:""}`);if(!["shape","build","verify","archive"].includes(i.previousPhase)||!["shape","build","verify","archive"].includes(i.nextPhase))throw new Error("Native transition journal event phases are invalid");if(i.evidenceHash!==t)throw new Error("Native transition journal event evidence hash mismatch");if(Mn(i.summary,"Native transition journal event summary"),ke(i.summary)!==i.summary)throw new Error("Native transition journal event summary contains unredacted credentials");if(!Array.isArray(i.artifacts)||i.artifacts.length>128||i.artifacts.some(u=>typeof u!="string"||u.length===0||Buffer.byteLength(u,"utf8")>512))throw new Error("Native transition journal event artifacts are invalid");if(i.noCodeReason!==null&&(Mn(i.noCodeReason,"Native transition journal event no-code reason"),ke(i.noCodeReason)!==i.noCodeReason))throw new Error("Native transition journal event no-code reason contains unredacted credentials");if(i.verificationResult!==null&&i.verificationResult!=="pass"&&i.verificationResult!=="fail")throw new Error("Native transition journal event verification result is invalid");let s=Object.hasOwn(i,"implementationScopeHash")?i.implementationScopeHash:null;if(s!==null&&(typeof s!="string"||!/^[a-f0-9]{64}$/.test(s)||i.previousPhase!=="build"&&i.previousPhase!=="verify"))throw new Error("Native transition journal implementation scope hash is invalid");let c=Object.hasOwn(i,"repairStagnation")?Rh(i.repairStagnation):null;if(c){let u=c.overrideSummaryHash===null;if(u&&(i.previousPhase!=="verify"||i.nextPhase!=="build"||i.verificationResult!=="fail")||!u&&(i.previousPhase!=="build"||i.nextPhase!=="verify"||i.verificationResult!==null))throw new Error("Native transition journal repair projection does not match its phase")}let l=Object.hasOwn(i,"repairScopeHash")?i.repairScopeHash:null;if(l!==null&&(typeof l!="string"||!/^[a-f0-9]{64}$/.test(l)||i.previousPhase!=="build"&&i.previousPhase!=="verify"||s===null))throw new Error("Native transition journal repair scope hash is invalid");return{previousPhase:i.previousPhase,nextPhase:i.nextPhase,evidenceHash:t,summary:i.summary,artifacts:[...i.artifacts],noCodeReason:i.noCodeReason,verificationResult:i.verificationResult,...s?{implementationScopeHash:s}:{},...l?{repairScopeHash:l}:{},...c?{repairStagnation:c}:{}}}function IO(e,t){if(e&&typeof e=="object"&&!Array.isArray(e)){let i=e,n=Object.keys(i),r=new Set(["previousPhase","nextPhase","evidenceHash","summary","reason"]);if(n.length===r.size&&n.every(a=>r.has(a))&&i.reason==="spec-rebase")return Ph({previousPhase:i.previousPhase,nextPhase:i.nextPhase,evidenceHash:i.evidenceHash,summary:i.summary,artifacts:[],noCodeReason:null,verificationResult:null},t)}return Ph(e,t)}function Th(e,t,i=!1){if(e.change!==t)throw new Error("Native transition journal change mismatch");if(typeof e.id!="string"||e.id.length===0)throw new Error("Native transition journal id is invalid");if(typeof e.evidenceHash!="string"||!/^[a-f0-9]{64}$/u.test(e.evidenceHash))throw new Error("Native transition journal evidence hash is invalid");if(typeof e.createdAt!="string"||Number.isNaN(Date.parse(e.createdAt)))throw new Error("Native transition journal timestamp is invalid");let n=i?IO(e.eventData,e.evidenceHash):Ph(e.eventData,e.evidenceHash),r=Rn(e.nextRun),a=e.previousRun===null?null:Rn(e.previousRun);return{id:e.id,evidenceHash:e.evidenceHash,createdAt:e.createdAt,previousRun:a,nextRun:r,eventData:n}}function QN(e,t,i=!1){if(e.skill!==mt.definition.metadata.name||(i?!XN(e):e.skillVersion!==mt.definition.metadata.version||e.skillHash!==vr)||e.orchestration!==mt.definition.orchestration.mode||e.pendingRef!==ut.pendingRef||e.trajectoryRef!==ut.trajectoryRef||e.contextRef!==ut.contextRef||e.artifactsRef!==ut.artifactsRef||e.checkpointRef!==ut.checkpointRef)throw new Error(`Native transition journal ${t} metadata or storage refs are invalid`)}function ZN(e){return{runId:e.runId,skill:e.skill,skillVersion:e.skillVersion,skillHash:e.skillHash,orchestration:e.orchestration,pendingRef:e.pendingRef,trajectoryRef:e.trajectoryRef,contextRef:e.contextRef,artifactsRef:e.artifactsRef,checkpointRef:e.checkpointRef,retries:e.retries}}function eb(e,t){if(e.status!=="running")throw new Error(`Native transition journal ${t} status must be running`);if(e.pending!==null)throw new Error(`Native transition journal ${t} pending action must be null`)}function _h(e,t,i,n=!1){let{previousRun:r,nextRun:a}=i;if(QN(a,"next Run",n||r!==null),eb(a,"next Run"),a.runId!==t.run_id||a.currentStep!==t.phase)throw new Error("Native transition journal next Run does not match the next change state");if(r===null){if(e.run_id!==null||e.phase!=="shape"||a.iteration!==1||Object.keys(a.retries).length!==0)throw new Error("Native transition journal first Run transition is invalid");return}if(QN(r,"previous Run",!0),eb(r,"previous Run"),e.run_id!==r.runId||r.currentStep!==e.phase||t.run_id!==r.runId)throw new Error("Native transition journal previous Run does not match the change state");if(a.iteration!==r.iteration+1)throw new Error("Native transition journal next Run iteration must advance exactly once");if(!xh(ZN(r),ZN(a)))throw new Error("Native transition journal Run identity or storage invariants changed")}function jO(e,t,i){return D(JSON.stringify({operation:"spec-rebase",change:e,summary:t,specChanges:i}))}function sb(e,t,i){return e.phase!=="shape"&&t.phase==="build"&&i.verificationResult===null?"spec-rebase":"advance"}function tb(e){return"implementation_scope"in e?{implementation_scope:e.implementation_scope,verification_evidence:e.verification_evidence,partial_allowance:e.partial_allowance}:null}function Ih(e,t,i,n,r=!1){let a=i.eventData,o=tb(e),s=tb(t);if(a.previousPhase!==e.phase||a.nextPhase!==t.phase)throw new Error("Native transition journal event phases do not match its states");if(e.archived||t.archived)throw new Error("Native transition journal cannot mutate an archived change");if(n==="evidence-retreat"){let c=e.name===t.name&&e.language===t.language&&e.brief===t.brief&&e.approval===t.approval&&("approved_contract_hash"in e?"approved_contract_hash"in t&&e.approved_contract_hash===t.approved_contract_hash:!("approved_contract_hash"in t))&&e.created_at===t.created_at&&e.run_id===t.run_id&&xh(e.spec_changes,t.spec_changes),l=Kl({summary:a.summary});if(!(e.phase==="archive"&&e.verification_result==="pass"||e.phase==="verify"&&e.verification_result==="pending")||t.phase!=="build"||t.verification_result!=="pending"||t.verification_report!==null||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||i.evidenceHash!==l||!c||o===null||s===null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null)throw new Error("Native transition journal evidence retreat semantics are invalid");return}if(n==="spec-rebase"){let c=jO(e.name,a.summary,t.spec_changes),l=D(`spec-rebase:${e.name}:${a.summary}`);if(e.phase==="shape"||t.phase!=="build"||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||t.verification_result!=="pending"||t.verification_report!==null||!r&&i.evidenceHash!==c||r&&i.evidenceHash!==c&&i.evidenceHash!==l||"implementation_scope"in t&&(t.implementation_scope!==null||t.verification_evidence!==null||t.partial_allowance!==null))throw new Error("Native transition journal spec rebase semantics are invalid");return}if(e.phase==="shape"){if(t.phase!=="build"||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||e.verification_result!=="pending"||t.verification_result!=="pending"||e.verification_report!==null||t.verification_report!==null||o!==null&&s!==null&&(o.implementation_scope!==null||o.verification_evidence!==null||o.partial_allowance!==null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null))throw new Error("Native transition journal Shape to Build semantics are invalid");return}if(e.phase==="build"){if(t.phase!=="verify"||a.verificationResult!==null||a.artifacts.length===0&&a.noCodeReason===null||t.verification_result!=="pending"||t.verification_report!==null||o!==null&&s!==null&&(s.implementation_scope===null||s.verification_evidence!==null||s.implementation_scope!==o.implementation_scope&&s.partial_allowance!==null&&s.partial_allowance===o.partial_allowance))throw new Error("Native transition journal Build to Verify semantics are invalid");return}if(e.phase==="verify"){let c=a.verificationResult==="pass"?"archive":"build";if(a.verificationResult!=="pass"&&a.verificationResult!=="fail"||t.phase!==c||a.artifacts.length!==0||a.noCodeReason!==null||t.verification_result!==a.verificationResult||t.verification_report===null||o!==null&&s!==null&&(o.implementation_scope===null||s.implementation_scope!==o.implementation_scope||s.partial_allowance!==o.partial_allowance||o.verification_evidence!==null||s.verification_evidence===null))throw new Error("Native transition journal Verify outcome semantics are invalid");return}throw new Error("Native transition journal cannot advance from Archive")}function Ql(e,t){let i=Xl(e);if(Ah(i,PO),i.schema!==ji)throw new Error(`Expected Native transition schema ${ji}`);let n=Yl(i.minimum_runtime_version,"Native transition minimum_runtime_version");if(n>3)throw new Error(`Native transition requires runtime protocol ${n}; current protocol is ${3}`);if(n!==3)throw new Error(`Native transition ${ji} minimum_runtime_version must be ${3}`);let r=Yl(i.revision,"Native transition revision");if(r!==1)throw new Error("Native transition journal revision must be 1");if(i.operation!=="advance"&&i.operation!=="spec-rebase"&&i.operation!=="evidence-retreat")throw new Error("Native transition journal operation is invalid");let a=Th(i,t),o=Ot(i.previousState),s=Ot(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native transition journal state mismatch");if(Ih(o,s,a,i.operation),_h(o,s,a),s.revision!==o.revision+1)throw new Error("Native transition journal state revision must advance exactly once");return{schema:ji,minimum_runtime_version:3,revision:r,operation:i.operation,id:a.id,change:t,evidenceHash:a.evidenceHash,createdAt:a.createdAt,previousState:o,nextState:s,previousRun:a.previousRun,nextRun:a.nextRun,eventData:a.eventData}}function OO(e,t){let i=Xl(e);if(Ah(i,CO),i.schema!==cr)throw new Error(`Expected Native transition schema ${cr}`);let n=Th(i,t,!0),r=Uo(i.previousState),a=Uo(i.nextState);if(r.name!==t||a.name!==t)throw new Error("Native transition journal state mismatch");return Ih(r,a,n,sb(r,a,n.eventData),!0),_h(r,a,n,!0),{schema:cr,id:n.id,change:t,evidenceHash:n.evidenceHash,createdAt:n.createdAt,previousState:r,nextState:a,previousRun:n.previousRun,nextRun:n.nextRun,eventData:n.eventData}}function jh(e,t){let i=Xl(e);if(Ah(i,ob),i.schema!==Oi)throw new Error(`Expected Native transition schema ${Oi}`);if(Yl(i.minimum_runtime_version,"Native v2 transition minimum_runtime_version")!==2)throw new Error(`Native transition ${Oi} minimum_runtime_version must be 2`);let r=Yl(i.revision,"Native v2 transition revision");if(r!==1)throw new Error("Native v2 transition journal revision must be 1");let a=Th(i,t,!0),o=An(i.previousState),s=An(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native v2 transition journal state mismatch");if(Ih(o,s,a,sb(o,s,a.eventData),!0),_h(o,s,a,!0),s.revision!==o.revision+1)throw new Error("Native v2 transition journal state revision must advance exactly once");return{schema:Oi,minimum_runtime_version:2,revision:r,id:a.id,change:t,evidenceHash:a.evidenceHash,createdAt:a.createdAt,previousState:o,nextState:s,previousRun:a.previousRun,nextRun:a.nextRun,eventData:a.eventData}}function $O(e,t){let i=Xl(e);if(i.schema===ji)return{status:"current",journal:Ql(i,t)};if(i.schema===cr)return{status:"migration-required",journal:OO(i,t)};if(i.schema===Oi)return{status:"migration-required",journal:jh(i,t)};throw new Error(`Unsupported Native transition journal schema: ${String(i.schema)}`)}async function Oh(e,t){let i=We(e,t);await x(e.nativeRoot,i);try{let n=await ue({root:e.nativeRoot,file:i,maxBytes:xO,label:`Native transition journal ${t}`});return $O(JSON.parse(n.bytes.toString("utf8")),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function bi(e,t){let i=await Oh(e,t);if(!i)return null;if(i.status==="migration-required")throw new os(t);return i.journal}async function ss(e){if(await lr(e.paths,e.nextState.name))throw new Error(`Native schema migration is incomplete for ${e.nextState.name}; run doctor --repair`);await Lo(e.paths,e.nextState.name);let t={schema:ji,minimum_runtime_version:3,revision:1,operation:e.operation??"advance",id:e.transitionId?.()??SO(),change:e.nextState.name,evidenceHash:e.evidenceHash,createdAt:(e.now??new Date).toISOString(),previousState:e.previousState,nextState:e.nextState,previousRun:e.previousRun,nextRun:e.nextRun,eventData:e.eventData},i=Ql(t,t.change),n=We(e.paths,i.change);if(await x(e.paths.nativeRoot,n),await bi(e.paths,i.change))throw new Error(`Native transition recovery is already pending for ${i.change}`);return await le(n,i),i}function ib(e,t){if(Ni(e,t.nextRun))return"next";if(t.previousRun===null){if(e===null)return"previous"}else if(Ni(e,t.previousRun))return"previous";throw new Error(`Native transition Run content changed for ${t.change}; recovery journal was preserved`)}function nb(e,t){if(Ni(e,t.nextState))return"next";if(Ni(e,t.previousState))return"previous";throw new Error(`Native transition change content changed for ${t.change}; recovery journal was preserved`)}function HO(e){let{journal:t}=e;return cb({sequence:e.sequence,timestamp:t.createdAt,type:e.type,runId:t.nextRun.runId,data:e.type==="run_started"?{runtime:"comet-native",phase:t.previousState.phase,transitionId:t.id}:{...t.eventData,transitionId:t.id}})}function cb(e){return{sequence:e.sequence,timestamp:e.timestamp,type:e.type,runId:e.runId,data:e.data}}function rb(e,t){let i=e.map((a,o)=>({event:a,index:o})).filter(({event:a})=>a.data.transitionId===t.id),n=i.filter(({event:a})=>a.type==="run_started"),r=i.filter(({event:a})=>a.type==="state_transitioned");if(i.length!==n.length+r.length||n.length>(t.previousRun===null?1:0)||r.length>1||t.previousRun===null&&r.length===1&&(n.length!==1||n[0].index>=r[0].index))throw new Error(`Native trajectory transition id collision for ${t.change}; recovery journal was preserved`);for(let a of[...n,...r]){let o=HO({sequence:a.index+1,journal:t,type:a.event.type});if(!Ni(cb(a.event),o))throw new Error(`Native trajectory event changed for transition ${t.id}; recovery journal was preserved`)}return{started:n[0]?.event??null,transitioned:r[0]?.event??null}}async function ki(e,t,i){if(await lr(e,t))throw new Error(`Native schema migration is incomplete for ${t}; run doctor --repair`);await Lo(e,t);let n=await bi(e,t);if(!n)return null;let r=C(e,t),a=rb(await qe(r,n.nextRun.trajectoryRef),n),[o,s]=await Promise.all([be(r),G(e,t)]),c=ib(o,n),l=nb(s,n);if((a.started||a.transitioned)&&(c!=="next"||l!=="next"))throw new Error(`Native trajectory is ahead of transition state for ${n.change}; recovery journal was preserved`);if(c==="previous"&&(await rr(r,n.nextRun),await i?.afterRunStateWritten?.(n)),!Ni(await be(r),n.nextRun))throw new Error(`Native transition Run content changed while continuing ${n.change}; recovery journal was preserved`);if(l==="previous"){let v=await oa(e,n.nextState,n.previousState.revision);if(!Ni(v,n.nextState))throw new Error(`Native transition change write diverged for ${n.change}; recovery journal was preserved`);await i?.afterChangeStateWritten?.(n)}if(!Ni(await G(e,t),n.nextState))throw new Error(`Native transition change content changed while continuing ${n.change}; recovery journal was preserved`);let u=await bi(e,t);if(!u||!Ni(u,n))throw new Error(`Native transition journal changed while continuing ${n.change}; it was preserved`);let d=rb(await qe(r,n.nextRun.trajectoryRef),n);n.previousRun===null&&(d.started||await Fn({changeDir:r,run:n.nextRun,type:"run_started",data:{runtime:"comet-native",phase:n.previousState.phase,transitionId:n.id},now:new Date(n.createdAt)}));let f=d.transitioned;f||(f=await Fn({changeDir:r,run:n.nextRun,type:"state_transitioned",data:{...n.eventData,transitionId:n.id},now:new Date(n.createdAt)})),await gr({changeDir:r,run:n.nextRun,trajectoryOffset:f.sequence,evidenceHash:n.evidenceHash,now:new Date(n.createdAt)});let[h,m]=await Promise.all([be(r),G(e,t)]);ib(h,{...n,previousRun:n.nextRun}),nb(m,{...n,previousState:n.nextState});let p=await bi(e,t);if(!p||!Ni(p,n))throw new Error(`Native transition journal changed while continuing ${n.change}; it was not removed`);return await EO.rm(We(e,t),{force:!0}),n.nextState}async function lb(e,t,i){return te(e,`continue transition ${t}`,()=>De(e,t,`continue transition ${t}`,()=>ki(e,t,i)))}import Kb from"node:path";import ub from"node:path";var DO="comet.native.acceptance.v1",MO=/^acceptance-[a-f0-9]{64}$/u,FO=new Set(["acceptance_id","status","evidence_refs","skipped_reason"]),LO=/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u,BO=/^[a-f0-9]{64}$/u,qO=/^native-acceptance-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u;function VO(e,t){return et?1:0}var Ji=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),ls=Object.freeze({maxCriteria:1024}),cs="",ba="";function db(e,t){if(Buffer.byteLength(e,"utf8")<=t)return{value:e,truncated:!1};let i="",n=0;for(let r of e){let a=Buffer.byteLength(r,"utf8");if(n+a>t)break;i+=r,n+=a}return{value:i,truncated:!0}}function fb(e,t){let i=t.toString(36),n=H("comet.native.acceptance-cursor.v1",{acceptanceHash:e,offset:t});return`native-acceptance-v1.${e}.${i}.${n}`}function WO(e){if(!BO.test(e.acceptanceHash))throw new Error("Native acceptance page hash is invalid");if(e.cursor===void 0||e.cursor===null)return 0;let t=qO.exec(e.cursor);if(!t)throw new Error("Native acceptance cursor is invalid");if(t[1]!==e.acceptanceHash)throw new Error("Native acceptance cursor is stale");let i=Number.parseInt(t[2],36);if(!Number.isSafeInteger(i)||i<=0||i>=e.total||i.toString(36)!==t[2])throw new Error("Native acceptance cursor offset is invalid");if(t[3]!==H("comet.native.acceptance-cursor.v1",{acceptanceHash:e.acceptanceHash,offset:i}))throw new Error("Native acceptance cursor integrity check failed");return i}function JO(e,t){let i=db(e.text,Ji.maxTextBytes),n=e.context.slice(0,Ji.maxContextItems).map(r=>db(r,Ji.maxContextItemBytes));return{id:e.id,kind:e.kind,source:e.source,context:n.map(r=>r.value),text:i.value,contextTruncated:e.context.length>n.length||n.some(r=>r.truncated),textTruncated:i.truncated,verificationStatus:t}}function Zl(e){let t=WO({acceptanceHash:e.acceptanceHash,total:e.criteria.length,cursor:e.cursor}),i=[],n=[...new Set(e.failedCheckIds??[])].sort(VO),r=n.slice(0,Ji.maxFailedCheckIds),a=e.criteria.slice(t,t+Ji.maxItems);for(let c of a){let l=[...i,JO(c,e.verificationStatuses?.get(c.id)??"unverified")],u=t+l.length,d={schema:"comet.native.acceptance-page.v1",acceptanceHash:e.acceptanceHash,total:e.criteria.length,offset:t,items:l,failedAcceptanceIds:l.filter(f=>f.verificationStatus==="failed").map(f=>f.id),missingAcceptanceIds:l.filter(f=>f.verificationStatus==="missing").map(f=>f.id),failedCheckIds:r,failedCheckIdsTruncated:n.length>r.length,nextCursor:uJi.maxSerializedBytes){if(i.length===0)throw new Error("Native acceptance criterion exceeds the page serialization budget");break}i.push(l.at(-1))}if(e.criteria.length>0&&i.length===0)throw new Error("Native acceptance page could not project its next criterion");let o=t+i.length,s={schema:"comet.native.acceptance-page.v1",acceptanceHash:e.acceptanceHash,total:e.criteria.length,offset:t,items:i,failedAcceptanceIds:i.filter(c=>c.verificationStatus==="failed").map(c=>c.id),missingAcceptanceIds:i.filter(c=>c.verificationStatus==="missing").map(c=>c.id),failedCheckIds:r,failedCheckIdsTruncated:n.length>r.length,nextCursor:oJi.maxSerializedBytes)throw new Error("Native acceptance page exceeds its serialization budget");return s}function Dh(e){let t=/^ {0,3}(#{1,6})[ \t]+(.+?)[ \t]*$/u.exec(e);return t?{level:t[1].length,text:t[2].replace(/[ \t]+#+[ \t]*$/u,"").trim()}:null}function $h(e,t){let i=/^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(e);if(!i)return t;let n=i[1][0];return t===null?{marker:n,length:i[1].length}:n===t.marker&&i[1].length>=t.length&&i[2].trim().length===0?null:t}function hb(e){return e.includes("-->")||e.includes("--!>")}function*ka(e){let t=null,i=!1,n=null,r=new Set(["code","pre","script","style","svg","template"]),a=e.replace(/\r\n?/gu,` +${Yo(i)}`;e.update(`${Buffer.byteLength(n,"utf8")}:`),e.update(n)}function ej(e){if(Qo(e)<=wi)return e;let t=[...e.entries],i=[...e.omitted],n=e.omittedCount,r=e.omissionOverflow?.count??0,a=Wy("sha256");a.update(`${zI} +`),e.omissionOverflow&&Tn(a,"existing-overflow",e.omissionOverflow);let o=(f,h)=>{h||(n+=1),r+=1,Tn(a,"omission",f)},s=f=>{n+=1,r+=1,Tn(a,"entry",f)},c=()=>{for(let f=i.length-1;f>=0;f-=1){let h=i[f];if(!(h.reason==="git-enumeration-limit"||h.reason==="git-selection-changed"||h.reason==="physical-enumeration-limit"||h.reason==="physical-selection-changed"))return i.splice(f,1),h}return null},l=()=>({...e,complete:n===0,entries:t,omitted:i,omittedCount:n,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${"0".repeat(64)}`,hash:"0".repeat(64),count:r}}),u=l();for(;Qo(u)>wi;){if(i.filter(h=>h.reason!=="git-enumeration-limit"&&h.reason!=="git-selection-changed"&&h.reason!=="physical-enumeration-limit"&&h.reason!=="physical-selection-changed").length>0){let h=Math.max(1,Math.ceil(i.length/4));for(let m=0;m0){let h=Math.max(1,Math.ceil(t.length/4));for(let m of t.splice(-h))s(m)}else throw new Error("Native snapshot projection metadata exceeds its evidence byte budget");u=l()}let d=a.digest("hex");return{...u,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${d}`,hash:d,count:r}}}function mh(e){let t=Ii(e),i=t.entries.map((r,a)=>YI(r,`Snapshot entry ${a}`));if(i.sort(QI),new Set(i.map(r=>r.path)).size!==i.length)throw new Error("Snapshot entries must not contain duplicate paths");let n=t.omitted.map((r,a)=>XI(r,`Snapshot omission ${a}`));return n.sort(ZI),ej({schema:Jy,origin:t.origin,...t.capture?{capture:t.capture}:{},complete:t.complete,limits:{maxFiles:t.limits.maxFiles,maxFileBytes:t.limits.maxFileBytes,maxTotalBytes:t.limits.maxTotalBytes,maxManifestBytes:t.limits.maxManifestBytes,...t.limits.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},...t.policy?{policy:t.policy}:{},entries:i,omitted:n,omittedCount:t.omittedCount,...t.omissionOverflow?{omissionOverflow:{ref:t.omissionOverflow.ref,hash:t.omissionOverflow.hash,count:t.omissionOverflow.count}}:{}})}function Pl(e){let t=new Map;for(let[i,n]of e.entries()){if(n.kind!=="file"&&n.kind!=="directory")throw new Error(`Declared artifact ${i} kind is invalid`);let r={path:_n(n.path,`Declared artifact ${i} path`),kind:n.kind},a=t.get(r.path);if(a&&a.kind!==r.kind)throw new Error(`Declared artifact path has conflicting kinds: ${r.path}`);t.set(r.path,r)}return[...t.values()].sort((i,n)=>Qe(i.path,n.path)||Qe(i.kind,n.kind))}function xl(e,t){return e.kind==="file"?e.path===t:t===e.path||t.startsWith(`${e.path}/`)}function Fy(e){return e?{hash:e.hash,size:e.size}:null}function Uy(e,t,i){let n=0,r=0;for(;n=0?o:void 0;if(s<=0&&(n+=1),s>=0&&(r+=1),c&&l&&c.hash===l.hash&&c.size===l.size||c&&!l&&!t.complete)continue;let u=c?.path??l?.path;u!==void 0&&i({path:u,kind:c?l?"modified":"removed":"added",before:Fy(c),after:Fy(l)})}}function tj(e,t){return{...e,attributedTo:t.filter(i=>xl(i,e.path))}}function Mi(e,t){return{id:`scope:${H(WI,e)}`,kind:e.kind,source:e.source,path:e.path,reason:t}}function ij(e,t){let i=t.omitted.map(n=>Mi({kind:"snapshot-omission",source:e,path:n.path,evidence:{reason:n.reason,size:n.size,type:n.type}},`${e} snapshot omitted ${n.path}: ${n.reason}`));return t.complete||i.push(Mi({kind:"snapshot-incomplete",source:e,path:null,evidence:{omittedCount:t.omittedCount}},`${e} snapshot is incomplete`)),t.omissionOverflow&&i.push(Mi({kind:"snapshot-omission-overflow",source:e,path:null,evidence:{count:t.omissionOverflow.count,hash:t.omissionOverflow.hash,ref:t.omissionOverflow.ref}},`${e} snapshot has ${t.omissionOverflow.count} unlisted omissions`)),i}function Ly(e,t){return ij(e,{...t,omitted:[]}).filter(i=>i.kind!=="snapshot-omission")}function vh(e,t){return Qe(e.kind,t.kind)||Qe(e.source,t.source)||KI(e.path,t.path)||Qe(e.id,t.id)}function nj(e){return[...new Map(e.map(i=>[i.id,i])).values()].sort(vh)}function rj(e){return[...new Set(e.map((t,i)=>_n(t,`Git path ${i}`)))].sort(Qe)}function Ky(e){if(typeof e.contractHash!="string"||!gh.test(e.contractHash))throw new Error("Contract hash must be a SHA-256 hash");return{contractHash:e.contractHash,declaredArtifacts:Pl(e.declaredArtifacts),noCodeReason:e.noCodeReason?.trim()||null,...e.gitChangedPaths===void 0?{}:{gitChangedPaths:rj(e.gitChangedPaths)}}}function aj(e,t,i,n){let r=[],a=n===void 0?null:new Set(n),o=[],s=0,c=!1,l=0,u=0;return Uy(e,t,d=>{let f=i.some(h=>xl(h,d.path));if(l+=1,f||(u+=1),a?.has(d.path)&&o.push(d.path),!c&&r.length{if(i>=e.detailedChangeCount){Tn(t,"change",r);let a=0;for(let o of e.declaredArtifacts)xl(o,r.path)&&(a+=1,Tn(t,"change-attribution",o));Tn(t,"change-end",{attributionCount:a}),a===0&&Tn(t,"unattributed-change",{after:r.after,before:r.before,changeKind:r.kind,path:r.path})}i+=1});let n=0;for(let[r,a]of[["baseline",e.baseline],["current",e.current]])for(let o of a.omitted)n>=e.detailedOmissionCount&&Tn(t,"snapshot-omission",{source:r,...o}),n+=1;return t.digest("hex")}function Xy(e,t,i){let{contractHash:n,declaredArtifacts:r,noCodeReason:a}=i,o=aj(e,t,r,i.gitChangedPaths),s=H(Xo,e),c=H(Xo,t),l=[];for(let[y,w]of[["baseline",e],["current",t]])for(let g of w.omitted){if(l.length>=UI)break;l.push(Mi({kind:"snapshot-omission",source:y,path:g.path,evidence:{reason:g.reason,size:g.size,type:g.type}},`${y} snapshot omitted ${g.path}: ${g.reason}`))}let u=e.omitted.length+t.omitted.length,d=[...Ly("baseline",e),...Ly("current",t),...o.totalChanges===0&&a===null?[Mi({kind:"missing-no-code-reason",source:"implementation-scope",path:null,evidence:{baselineProjectionHash:s,currentProjectionHash:c}},"A non-empty no-code reason is required when the snapshots contain no changes")]:[]],f=()=>{if(i.gitChangedPaths===void 0)return;let y=new Set(o.gitPathsPresentInChanges);return{advisoryOnly:!0,changedPaths:i.gitChangedPaths,pathsPresentInSnapshotChanges:i.gitChangedPaths.filter(w=>y.has(w)),pathsAbsentFromSnapshotChanges:i.gitChangedPaths.filter(w=>!y.has(w))}},h=y=>{let w=o.candidates.slice(0,y.detailedChangeCount),g=w.filter(ai=>ai.attributedTo.length===0),E=o.totalChanges-w.length,O=o.totalUnattributed-g.length,B=u-y.detailedOmissionCount,q=O+B,U=[...g.map(ai=>Mi({kind:"unattributed-change",source:"implementation-scope",path:ai.path,evidence:{after:ai.after,before:ai.before,changeKind:ai.kind}},`Changed path is not covered by a declared artifact: ${ai.path}`)),...l.slice(0,y.detailedOmissionCount),...d,...E>0||q>0?[Yy(y.overflowHash,{changes:E,unattributed:O,unresolved:q})]:[]],oe=nj(U),ri=y.includeGitAdvisory?f():void 0;return{schema:hh,contractHash:n,baselineProjectionRef:ph(s),baselineProjectionHash:s,currentProjectionRef:ph(c),currentProjectionHash:c,complete:oe.length===0,declaredArtifacts:r,changes:w,unattributed:g,unresolvedScopes:oe,noCodeReason:a,...ri?{gitAdvisory:ri}:{}}},m=o.candidates.length,p=l.length,v=i.gitChangedPaths!==void 0,S="0".repeat(64);for(;;){let y=h({detailedChangeCount:m,detailedOmissionCount:p,includeGitAdvisory:v,overflowHash:S});if(Qo({...y,scopeHash:S})<=wi)break;if(v){v=!1;continue}if(p>0){p-=Math.max(1,Math.ceil(p/4));continue}if(m>0){m-=Math.max(1,Math.ceil(m/4));continue}throw new Error("Native implementation scope metadata exceeds its evidence byte budget")}let N=o.totalChanges>m||u>p?sj({baseline:e,current:t,declaredArtifacts:r,detailedChangeCount:m,detailedOmissionCount:p}):S,b=h({detailedChangeCount:m,detailedOmissionCount:p,includeGitAdvisory:v,overflowHash:N}),R={...b,scopeHash:H(zy,b)};if(Qo(R)>wi)throw new Error("Native implementation scope exceeded its evidence byte budget after fitting");return R}function In(e){let t=mh(e.baseline),i=mh(e.current),n=Ky(e);return{authority:n,baseline:t,current:i,scope:Xy(t,i,n)}}var cj=new Set(["schema","contractHash","baselineProjectionRef","baselineProjectionHash","currentProjectionRef","currentProjectionHash","complete","declaredArtifacts","changes","unattributed","unresolvedScopes","noCodeReason","gitAdvisory","scopeHash"]);function Fi(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Li(e,t,i,n){let r=new Set([...t,...i]),a=Object.keys(e).filter(s=>!r.has(s)),o=t.filter(s=>!(s in e));if(a.length>0)throw new Error(`${n} has unknown field(s): ${a.join(", ")}`);if(o.length>0)throw new Error(`${n} is missing field(s): ${o.join(", ")}`)}function dr(e,t){if(typeof e!="string"||!gh.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function By(e,t,i){let n=ph(t);if(e!==n)throw new Error(`${i} ref/hash mismatch`);return n}function da(e,t){let i=Fi(e,"Native snapshot projection");if(Li(i,["schema","origin","complete","limits","entries","omitted","omittedCount"],["capture","omissionOverflow","policy"],"Native snapshot projection"),i.schema!==Jy)throw new Error("Native snapshot projection schema is invalid");let n=Ii({schema:"comet.native.content-snapshot.v1",origin:i.origin,...i.capture===void 0?{}:{capture:i.capture},createdAt:"1970-01-01T00:00:00.000Z",complete:i.complete,limits:i.limits,...i.policy===void 0?{}:{policy:i.policy},entries:i.entries,omitted:i.omitted,omittedCount:i.omittedCount,...i.omissionOverflow===void 0?{}:{omissionOverflow:i.omissionOverflow}}),r=mh(n);if(H(Xo,i)!==H(Xo,r))throw new Error("Native snapshot projection is not canonical");let a=H(Xo,r);if(t!==void 0&&dr(t,"Snapshot projection hash")!==a)throw new Error("Native snapshot projection content hash mismatch");return r}function wh(e,t){let i=Fi(e,`Declared artifact ${t}`);if(Li(i,["path","kind"],[],`Declared artifact ${t}`),i.kind!=="file"&&i.kind!=="directory")throw new Error(`Declared artifact ${t} kind is invalid`);return{path:_n(i.path,`Declared artifact ${t} path`),kind:i.kind}}function qy(e,t){if(e===null)return null;let i=Fi(e,t);return Li(i,["hash","size"],[],t),{hash:dr(i.hash,`${t} hash`),size:ua(i.size,`${t} size`)}}function Vy(e,t){let i=Fi(e,`Implementation change ${t}`);if(Li(i,["path","kind","before","after","attributedTo"],[],`Implementation change ${t}`),i.kind!=="added"&&i.kind!=="modified"&&i.kind!=="removed")throw new Error(`Implementation change ${t} kind is invalid`);if(!Array.isArray(i.attributedTo))throw new Error(`Implementation change ${t} attributedTo must be an array`);let n=i.attributedTo.map(wh),r=Pl(n);if(JSON.stringify(n)!==JSON.stringify(r))throw new Error(`Implementation change ${t} attribution must be sorted and unique`);let a=qy(i.before,`Implementation change ${t} before`),o=qy(i.after,`Implementation change ${t} after`);if(i.kind==="added"&&(a!==null||o===null)||i.kind==="removed"&&(a===null||o!==null)||i.kind==="modified"&&(a===null||o===null||JSON.stringify(a)===JSON.stringify(o)))throw new Error(`Implementation change ${t} before/after state is invalid`);return{path:_n(i.path,`Implementation change ${t} path`),kind:i.kind,before:a,after:o,attributedTo:n}}function lj(e,t){let i=Fi(e,`Unresolved scope ${t}`);Li(i,["id","kind","source","path","reason"],[],`Unresolved scope ${t}`);let n=new Set(["unattributed-change","snapshot-omission","snapshot-incomplete","snapshot-omission-overflow","scope-detail-overflow","missing-no-code-reason"]);if(typeof i.kind!="string"||!n.has(i.kind))throw new Error(`Unresolved scope ${t} kind is invalid`);if(i.source!=="baseline"&&i.source!=="current"&&i.source!=="implementation-scope")throw new Error(`Unresolved scope ${t} source is invalid`);if(typeof i.id!="string"||!/^scope:[a-f0-9]{64}$/u.test(i.id))throw new Error(`Unresolved scope ${t} id is invalid`);if(i.path!==null&&typeof i.path!="string")throw new Error(`Unresolved scope ${t} path is invalid`);if(typeof i.reason!="string"||i.reason.length===0||i.reason.trim()!==i.reason)throw new Error(`Unresolved scope ${t} reason is invalid`);return{id:i.id,kind:i.kind,source:i.source,path:i.path===null?null:i.kind==="snapshot-omission"?Gy(i.path,`Unresolved scope ${t} path`):_n(i.path,`Unresolved scope ${t} path`),reason:i.reason}}function Cl(e,t){if(!Array.isArray(e)||e.some(r=>typeof r!="string"))throw new Error(`${t} must be an array of paths`);let i=e.map((r,a)=>_n(r,`${t} ${a}`)),n=[...new Set(i)].sort(Qe);if(JSON.stringify(i)!==JSON.stringify(n))throw new Error(`${t} must be sorted and unique`);return i}function fa(e){let t=Fi(e,"Native implementation scope"),i=[...cj].filter(w=>w!=="gitAdvisory");if(Li(t,i,["gitAdvisory"],"Native implementation scope"),t.schema!==hh)throw new Error("Native implementation scope schema is invalid");let n=dr(t.contractHash,"Implementation scope contractHash"),r=dr(t.baselineProjectionHash,"Implementation scope baselineProjectionHash"),a=By(t.baselineProjectionRef,r,"Implementation scope baseline projection"),o=dr(t.currentProjectionHash,"Implementation scope currentProjectionHash"),s=By(t.currentProjectionRef,o,"Implementation scope current projection");if(typeof t.complete!="boolean")throw new Error("Implementation scope complete flag is invalid");if(!Array.isArray(t.declaredArtifacts)||!Array.isArray(t.changes)||!Array.isArray(t.unattributed)||!Array.isArray(t.unresolvedScopes))throw new Error("Implementation scope collections are invalid");let c=t.declaredArtifacts.map(wh);if(JSON.stringify(c)!==JSON.stringify(Pl(c)))throw new Error("Implementation scope declared artifacts must be sorted and unique");let l=t.changes.map(Vy),u=[...l].sort((w,g)=>Qe(w.path,g.path));if(JSON.stringify(l)!==JSON.stringify(u)||new Set(l.map(w=>w.path)).size!==l.length)throw new Error("Implementation scope changes must be sorted and unique");let d=new Set(c.map(w=>`${w.kind}:${w.path}`));if(l.some(w=>w.attributedTo.some(g=>!d.has(`${g.kind}:${g.path}`))))throw new Error("Implementation scope change references an undeclared artifact");if(l.some(w=>JSON.stringify(w.attributedTo)!==JSON.stringify(c.filter(g=>xl(g,w.path)))))throw new Error("Implementation scope change attribution is inconsistent");let f=t.unattributed.map(Vy),h=l.filter(w=>w.attributedTo.length===0);if(JSON.stringify(f)!==JSON.stringify(h))throw new Error("Implementation scope unattributed changes are inconsistent");let m=t.unresolvedScopes.map(lj),p=m.filter(w=>w.kind==="scope-detail-overflow");if(p.length>1)throw new Error("Implementation scope has multiple detail overflow records");let v=p[0]===void 0?null:oj(p[0]);if(v&&(v.changes+v.unresolved===0||v.unattributed>v.changes||v.unattributed>v.unresolved))throw new Error("Implementation scope detail overflow counts are inconsistent");let S=t.noCodeReason,k=[...h.map(w=>Mi({kind:"unattributed-change",source:"implementation-scope",path:w.path,evidence:{after:w.after,before:w.before,changeKind:w.kind}},`Changed path is not covered by a declared artifact: ${w.path}`)),...l.length+(v?.changes??0)===0&&S===null?[Mi({kind:"missing-no-code-reason",source:"implementation-scope",path:null,evidence:{baselineProjectionHash:r,currentProjectionHash:o}},"A non-empty no-code reason is required when the snapshots contain no changes")]:[]],N=m.filter(w=>w.kind==="unattributed-change"||w.kind==="missing-no-code-reason");if(JSON.stringify(m)!==JSON.stringify([...m].sort(vh))||new Set(m.map(w=>w.id)).size!==m.length||JSON.stringify(N)!==JSON.stringify(k.sort(vh))||t.complete!==(m.length===0))throw new Error("Implementation scope unresolved scopes are inconsistent");if(t.noCodeReason!==null&&(typeof t.noCodeReason!="string"||t.noCodeReason.length===0||t.noCodeReason.trim()!==t.noCodeReason))throw new Error("Implementation scope no-code reason is invalid");let b;if(t.gitAdvisory!==void 0){let w=Fi(t.gitAdvisory,"Implementation scope Git advisory");if(Li(w,["advisoryOnly","changedPaths","pathsPresentInSnapshotChanges","pathsAbsentFromSnapshotChanges"],[],"Implementation scope Git advisory"),w.advisoryOnly!==!0)throw new Error("Implementation scope Git advisory must remain advisory-only");let g=Cl(w.changedPaths,"Git changed paths"),E=Cl(w.pathsPresentInSnapshotChanges,"Git present paths"),O=Cl(w.pathsAbsentFromSnapshotChanges,"Git absent paths"),B=[...E,...O].sort(Qe),q=new Set(l.map(U=>U.path));if(JSON.stringify(B)!==JSON.stringify(g)||(v?.changes??0)===0&&E.some(U=>!q.has(U))||O.some(U=>q.has(U)))throw new Error("Implementation scope Git advisory partition is invalid");b={advisoryOnly:!0,changedPaths:g,pathsPresentInSnapshotChanges:E,pathsAbsentFromSnapshotChanges:O}}let R={schema:hh,contractHash:n,baselineProjectionRef:a,baselineProjectionHash:r,currentProjectionRef:s,currentProjectionHash:o,complete:t.complete,declaredArtifacts:c,changes:l,unattributed:f,unresolvedScopes:m,noCodeReason:S,...b?{gitAdvisory:b}:{}},y=dr(t.scopeHash,"Implementation scope scopeHash");if(H(zy,R)!==y)throw new Error("Implementation scope content hash mismatch");return{...R,scopeHash:y}}function uj(e){let t=Fi(e,"Native implementation scope authority");if(Li(t,["contractHash","declaredArtifacts","noCodeReason"],["gitChangedPaths"],"Native implementation scope authority"),!Array.isArray(t.declaredArtifacts))throw new Error("Native implementation scope authority declarations must be an array");let i=t.declaredArtifacts.map(wh);if(JSON.stringify(i)!==JSON.stringify(Pl(i)))throw new Error("Native implementation scope authority declarations must be canonical");if(t.noCodeReason!==null&&(typeof t.noCodeReason!="string"||t.noCodeReason.length===0||t.noCodeReason.trim()!==t.noCodeReason))throw new Error("Native implementation scope authority no-code reason is invalid");let n;t.gitChangedPaths!==void 0&&(n=Cl(t.gitChangedPaths,"Native implementation scope authority Git paths"));let r=Ky({contractHash:t.contractHash,declaredArtifacts:i,noCodeReason:t.noCodeReason,...n===void 0?{}:{gitChangedPaths:n}});if(r.contractHash!==t.contractHash)throw new Error("Native implementation scope authority contract hash is not canonical");return r}function Kt(e){let t=Fi(e,"Native implementation scope bundle");Li(t,["authority","baseline","current","scope"],[],"Native implementation scope bundle");let i=uj(t.authority),n=da(t.baseline),r=da(t.current),a=fa(t.scope),o=Xy(n,r,i);if(JSON.stringify(a)!==JSON.stringify(o))throw new Error("Native implementation scope does not match its authoritative bundle");return{authority:i,baseline:n,current:r,scope:o}}function Qy(e){let t=fa(e.scope);return Kt({authority:{contractHash:t.contractHash,declaredArtifacts:t.declaredArtifacts,noCodeReason:t.noCodeReason,...t.gitAdvisory?{gitChangedPaths:t.gitAdvisory.changedPaths}:{}},baseline:e.baseline,current:e.current,scope:t})}import Zy from"node:path";var dj=/\b(Bearer|Basic)\s+[^\s"']+/giu,fj=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,hj=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,pj=/\b(?:sk-(?:proj-)?[A-Za-z0-9_-]{16,}|gh[pousr]_[A-Za-z0-9_]{16,}|github_pat_[A-Za-z0-9_]{16,}|AKIA[A-Z0-9]{16}|AIza[A-Za-z0-9_-]{20,})\b/gu,mj=/("(?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie)"\s*:\s*)"(?:\\[\s\S]|[^"\\\r\n])*"/giu,vj=/(["'])((?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie))\1(\s*:\s*)(["'])[^\r\n]*?\4/giu,gj=/\b((?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie))\b(\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;"']+)/giu;function ke(e){return e.replace(dj,"$1 [REDACTED]").replace(fj,"[REDACTED PRIVATE KEY]").replace(hj,"$1[REDACTED]@").replace(pj,"[REDACTED TOKEN]").replace(mj,'$1"[REDACTED]"').replace(vj,"$1$2$1$3$4[REDACTED]$4").replace(gj,"$1$2[REDACTED]")}var eN=/^[a-f0-9]{64}$/u,wj=8,tN="comet.native.acceptance-trace.v2",iN="comet.native.partial-allowance.v1",nN="comet.native.verification-evidence.v2";function $t(e,t){if(!eN.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Il(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native evidence source revision must be a positive integer");return e}function jl(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error(`Invalid Native evidence change name: ${e}`);return e}function ha(e,t,i=2e3){let n=ke(e).trim();if(n.length===0||n.length>i)throw new Error(`${t} must be between 1 and ${i} characters`);return n}function jn(e,t){let i=Zy.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(n=>{let r=n.codePointAt(0)??0;return r<=31||r===127})||Zy.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||i!==e||i==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized relative ref`);return e}function rN(e,t,i){let n=jn(e,t);if(/^runtime\/evidence\/check-receipts\/[a-f0-9]{64}\.json$/u.test(n))return n;let r=ci(n),a=n.toLowerCase(),o=i?jn(i,"Native root ref").toLowerCase():null;if(r||a==="runtime"||a.startsWith("runtime/")||o!==null&&(a===o||a.startsWith(`${o}/`)))throw new Error(`${t} is excluded as sensitive (${r??"native-runtime"}): ${n}`);return n}function Zo(e){let t=jn(e,"Verification typed receipt ref");if(!/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u.test(t))throw new Error("Verification receipt ref must identify a typed v3 receipt");return t}function aN(e){let t=e.toISOString();if(Number.isNaN(Date.parse(t)))throw new Error("Native evidence timestamp is invalid");return t}function yj(e){return H("comet.native.acceptance-set.v1",[...e].sort((t,i)=>Ht(t.id,i.id)))}function Ht(e,t){return et?1:0}function oN(e,t,i){let n=jn(i.nativeRootRef,"Native root ref"),r=new Map(e.map(u=>[u.id,u]));if(r.size!==e.length)throw new Error("Native contract has duplicate acceptance IDs");let a=new Map;for(let u of t){if(!r.has(u.acceptance_id))throw new Error(`Verification references unknown acceptance ID: ${u.acceptance_id}`);if(a.has(u.acceptance_id))throw new Error(`Verification repeats acceptance ID: ${u.acceptance_id}`);a.set(u.acceptance_id,u)}let o=[...r.keys()].filter(u=>!a.has(u));if(o.length>0&&i.allowMissing!==!0){let u=o.slice(0,wj),d=o.length-u.length;throw new Error(`Verification is missing ${o.length} acceptance evidence entr${o.length===1?"y":"ies"}: ${u.join(", ")}${d>0?`, ... (${d} more)`:""}`)}let s=[...r.values()].sort((u,d)=>Ht(u.id,d.id)).map(u=>{let d=a.get(u.id);if(!d)return{acceptanceId:u.id,status:"missing",kind:u.kind,source:jn(u.source,`Acceptance source for ${u.id}`),evidenceRefs:[],skippedReason:null};let f=d.status,h=[...d.evidence_refs].map(v=>Zo(v)).sort();if(new Set(h).size!==h.length)throw new Error(`Verification repeats an evidence ref for ${u.id}`);let m=d.skipped_reason?.trim()||null,p=m===null?null:ha(m,`Skipped reason for ${u.id}`);if(f==="passed"&&(h.length===0||p!==null)||f==="failed"&&h.length===0&&p===null)throw new Error(`Acceptance ${u.id} has an invalid evidence state`);return{acceptanceId:u.id,status:f,kind:u.kind,source:jn(u.source,`Acceptance source for ${u.id}`),evidenceRefs:h,skippedReason:p}}),c=yj(e),l={schema:"comet.native.acceptance-trace.v2",nativeRootRef:n,criteriaHash:c,total:s.length,evidenced:s.filter(u=>u.evidenceRefs.length>0).length,skipped:s.filter(u=>u.skippedReason!==null).length,entries:s};return{...l,traceHash:H(tN,l)}}function sN(e){let t=Kt(e.scopeBundle).scope;if(t.complete)throw new Error("Complete implementation scope cannot be partially allowed");let i=new Set(t.unresolvedScopes.map(s=>s.id));if(new Set(e.allowedScopeIds).size!==e.allowedScopeIds.length)throw new Error("Partial allowance has duplicate allowed scope IDs");let n=[...e.allowedScopeIds].sort(Ht);if(n.length===0)throw new Error("Partial allowance requires at least one scope ID");if([...i,...n].some(s=>!/^scope:[a-f0-9]{64}$/u.test(s)))throw new Error("Partial allowance scope IDs are invalid");let r=n.filter(s=>!i.has(s)),a=[...i].filter(s=>!n.includes(s));if(r.length>0)throw new Error(`Partial allowance has unknown scope IDs: ${r}`);if(a.length>0)throw new Error(`Partial allowance is missing scope IDs: ${a}`);let o={schema:"comet.native.partial-allowance.v1",change:jl(e.change),scopeHash:t.scopeHash,scopeIds:n,reason:ha(e.reason,"Partial allowance reason"),confirmedSummary:ha(e.confirmedSummary,"Partial allowance confirmation"),sourceRevision:Il(e.sourceRevision),confirmedAt:aN(e.now??new Date)};return{...o,allowanceHash:H(iN,o)}}function cN(e){if(e.result!=="pass"&&e.result!=="fail")throw new Error("Native verification evidence result is invalid");let t=uN(e.acceptanceTrace),i=Kt(e.implementationScope.bundle).scope,n=_l(e.implementationScope.ref,"scopes",i.scopeHash);if(i.contractHash!==e.contractHash)throw new Error("Implementation scope does not match the verification contract");let r=e.partialAllowance??null,a=r?es(r.allowance):null,o=r&&a?{ref:_l(r.ref,"allowances",a.allowanceHash),allowance:a}:null;if(i.complete&&o!==null)throw new Error("Complete implementation scope must not use a partial allowance");if(!i.complete&&o===null)throw new Error("Partial implementation scope requires a confirmed allowance");let s=i.unresolvedScopes.map(f=>f.id).sort(Ht);if(o&&(o.allowance.change!==e.change||o.allowance.scopeHash!==i.scopeHash||JSON.stringify(o.allowance.scopeIds)!==JSON.stringify(s)))throw new Error("Partial allowance does not match the verification scope");if(t.criteriaHash!==e.acceptanceHash)throw new Error("Acceptance trace does not match the verification contract");if(o&&o.allowance.sourceRevision>=e.sourceRevision)throw new Error("Partial allowance must precede the verification evidence revision");let c=[...new Set(t.entries.flatMap(f=>f.evidenceRefs))].sort(Ht),l=[...new Set(e.requiredReceiptRefs.map(Zo))].sort(Ht),u=c;if(e.result==="pass"&&l.length===0)throw new Error("Passing verification requires at least one current required check receipt");let d={schema:"comet.native.verification-evidence.v2",change:jl(e.change),sourceRevision:Il(e.sourceRevision),result:e.result,freshness:i.complete?"complete":"partial",contractHash:$t(e.contractHash,"Verification contractHash"),acceptanceCriteriaHash:$t(e.acceptanceHash,"Verification acceptanceHash"),implementationScopeRef:n,implementationScopeHash:i.scopeHash,reportRef:rN(e.reportRef,"Verification report ref"),reportHash:$t(e.reportHash,"Verification report hash"),acceptanceTrace:t,partialAllowanceRef:o?.ref??null,partialAllowanceHash:o?.allowance.allowanceHash??null,requiredReceiptRefs:l,receiptRefs:u,createdAt:aN(e.now??new Date)};return{...d,envelopeHash:H(nN,d)}}function Al(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Tl(e,t,i){let n=new Set(t),r=Object.keys(e).filter(o=>!n.has(o)),a=t.filter(o=>!(o in e));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`);if(a.length>0)throw new Error(`${i} is missing field(s): ${a.join(", ")}`)}function lN(e,t){if(typeof e!="string")throw new Error(`${t} is invalid`);let i=new Date(e);if(Number.isNaN(i.valueOf())||i.toISOString()!==e)throw new Error(`${t} is invalid`);return e}function _l(e,t,i){if(typeof e!="string")throw new Error(`Native ${t} evidence ref is invalid`);let n=`runtime/evidence/${t}/${i}.json`;if(e!==n)throw new Error(`Native ${t} evidence ref/hash mismatch`);return e}function uN(e){let t=Al(e,"Native acceptance trace");if(Tl(t,["schema","nativeRootRef","criteriaHash","total","evidenced","skipped","entries","traceHash"],"Native acceptance trace"),t.schema!=="comet.native.acceptance-trace.v2"||typeof t.nativeRootRef!="string"||typeof t.criteriaHash!="string"||!eN.test(t.criteriaHash)||!Number.isSafeInteger(t.total)||!Number.isSafeInteger(t.evidenced)||!Number.isSafeInteger(t.skipped)||!Array.isArray(t.entries))throw new Error("Native acceptance trace is invalid");let i=jn(t.nativeRootRef,"Native root ref"),n=t.entries.map((o,s)=>{let c=Al(o,`Native acceptance trace entry ${s}`);if(Tl(c,["acceptanceId","status","kind","source","evidenceRefs","skippedReason"],`Native acceptance trace entry ${s}`),typeof c.acceptanceId!="string"||!/^acceptance-[a-f0-9]{64}$/u.test(c.acceptanceId)||c.kind!=="brief-example"&&c.kind!=="spec-scenario"&&c.kind!=="spec-must"||typeof c.source!="string"||!Array.isArray(c.evidenceRefs)||c.status!=="passed"&&c.status!=="failed"&&c.status!=="missing"||c.evidenceRefs.some(d=>typeof d!="string")||c.skippedReason!==null&&(typeof c.skippedReason!="string"||c.skippedReason.length===0||c.skippedReason.trim()!==c.skippedReason))throw new Error(`Native acceptance trace entry ${s} is invalid`);let l=c.evidenceRefs.map(d=>Zo(d)),u=c.status;if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(Ht))||u==="passed"&&(l.length===0||c.skippedReason!==null)||u==="failed"&&l.length===0&&c.skippedReason===null||u==="missing"&&(l.length>0||c.skippedReason!==null))throw new Error(`Native acceptance trace entry ${s} evidence state is invalid`);return{acceptanceId:c.acceptanceId,status:u,kind:c.kind,source:jn(c.source,`Native acceptance trace entry ${s} source`),evidenceRefs:l,skippedReason:c.skippedReason===null?null:ha(c.skippedReason,`Native acceptance trace entry ${s} skipped reason`)}});if(JSON.stringify(n)!==JSON.stringify([...n].sort((o,s)=>Ht(o.acceptanceId,s.acceptanceId)))||new Set(n.map(o=>o.acceptanceId)).size!==n.length||t.total!==n.length||t.evidenced!==n.filter(o=>o.evidenceRefs.length>0).length||t.skipped!==n.filter(o=>o.skippedReason!==null).length)throw new Error("Native acceptance trace entries are inconsistent");let r={schema:"comet.native.acceptance-trace.v2",nativeRootRef:i,criteriaHash:t.criteriaHash,total:t.total,evidenced:t.evidenced,skipped:t.skipped,entries:n},a=$t(t.traceHash,"Native acceptance trace hash");if(H(tN,r)!==a)throw new Error("Native acceptance trace content hash mismatch");return{...r,traceHash:a}}function es(e){let t=Al(e,"Native partial allowance");if(Tl(t,["schema","change","scopeHash","scopeIds","reason","confirmedSummary","sourceRevision","confirmedAt","allowanceHash"],"Native partial allowance"),t.schema!=="comet.native.partial-allowance.v1"||typeof t.change!="string"||typeof t.scopeHash!="string"||!Array.isArray(t.scopeIds)||t.scopeIds.length===0||t.scopeIds.some(r=>typeof r!="string"||!/^scope:[a-f0-9]{64}$/u.test(r))||JSON.stringify(t.scopeIds)!==JSON.stringify([...new Set(t.scopeIds)].sort(Ht))||typeof t.reason!="string"||typeof t.confirmedSummary!="string")throw new Error("Native partial allowance is invalid");let i={schema:"comet.native.partial-allowance.v1",change:jl(t.change),scopeHash:$t(t.scopeHash,"Native partial allowance scopeHash"),scopeIds:t.scopeIds,reason:ha(t.reason,"Partial allowance reason"),confirmedSummary:ha(t.confirmedSummary,"Partial allowance confirmation"),sourceRevision:Il(t.sourceRevision),confirmedAt:lN(t.confirmedAt,"Native partial allowance timestamp")};if(i.reason!==t.reason||i.confirmedSummary!==t.confirmedSummary)throw new Error("Native partial allowance text is not canonical");let n=$t(t.allowanceHash,"Native partial allowance hash");if(H(iN,i)!==n)throw new Error("Native partial allowance content hash mismatch");return{...i,allowanceHash:n}}function pa(e){let t=Al(e,"Native verification evidence");if(Tl(t,["schema","change","sourceRevision","result","freshness","contractHash","acceptanceCriteriaHash","implementationScopeRef","implementationScopeHash","reportRef","reportHash","acceptanceTrace","partialAllowanceRef","partialAllowanceHash","requiredReceiptRefs","receiptRefs","createdAt","envelopeHash"],"Native verification evidence"),t.schema!=="comet.native.verification-evidence.v2"||typeof t.change!="string"||t.result!=="pass"&&t.result!=="fail"||t.freshness!=="complete"&&t.freshness!=="partial"||typeof t.implementationScopeHash!="string"||typeof t.reportRef!="string"||!Array.isArray(t.requiredReceiptRefs)||!Array.isArray(t.receiptRefs))throw new Error("Native verification evidence is invalid");let i=$t(t.implementationScopeHash,"Native verification implementation scope hash"),n=uN(t.acceptanceTrace),r=$t(t.acceptanceCriteriaHash,"Native verification acceptance criteria hash");if(n.criteriaHash!==r)throw new Error("Native verification acceptance trace does not match its criteria hash");let a=t.partialAllowanceRef!==null||t.partialAllowanceHash!==null;if(t.partialAllowanceRef===null!=(t.partialAllowanceHash===null)||t.freshness==="complete"&&a||t.freshness==="partial"&&!a)throw new Error("Native verification partial allowance state is invalid");let o=t.partialAllowanceHash===null?null:$t(t.partialAllowanceHash,"Native verification allowance hash"),s=t.receiptRefs.map(f=>Zo(f));if(JSON.stringify(s)!==JSON.stringify([...new Set(s)].sort(Ht)))throw new Error("Native verification receipt refs must be canonical");let c=[...new Set(n.entries.flatMap(f=>f.evidenceRefs))].sort(Ht);if(JSON.stringify(s)!==JSON.stringify(c))throw new Error("Native verification envelope receipt refs do not match its matrix");let l=t.requiredReceiptRefs.map(f=>Zo(f));if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(Ht)))throw new Error("Native required receipt refs must be canonical");if(t.result==="pass"&&l.length===0)throw new Error("Passing verification has no current static receipt");let u={schema:"comet.native.verification-evidence.v2",change:jl(t.change),sourceRevision:Il(t.sourceRevision),result:t.result,freshness:t.freshness,contractHash:$t(t.contractHash,"Native verification contract hash"),acceptanceCriteriaHash:r,implementationScopeRef:_l(t.implementationScopeRef,"scopes",i),implementationScopeHash:i,reportRef:rN(t.reportRef,"Native verification report ref"),reportHash:$t(t.reportHash,"Native verification report hash"),acceptanceTrace:n,partialAllowanceRef:o===null?null:_l(t.partialAllowanceRef,"allowances",o),partialAllowanceHash:o,requiredReceiptRefs:l,receiptRefs:s,createdAt:lN(t.createdAt,"Native verification timestamp")},d=$t(t.envelopeHash,"Native verification envelope hash");if(H(nN,u)!==d)throw new Error("Native verification evidence content hash mismatch");return{...u,envelopeHash:d}}import dN from"node:path";var Ol="comet.native.check-receipt.v1",pN="comet.native.check-receipt.v1",On="scoped-text-safety",ts=1,Ae=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),Nj=/^[a-f0-9]{64}$/u,bj=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,kj="comet.native.checker-policy.v1",Sj="comet.native.check-input.v1",Ej=2048,$l=H(kj,{policy:On,version:ts,limits:Ae,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),Rj=new Set(["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"]),fN=["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"],mN=["contract-before-does-not-match-scope","implementation-before-does-not-match-scope","contract-changed-during-check","implementation-changed-during-check","contract-after-does-not-match-scope","implementation-after-does-not-match-scope"],Cj=new Set(mN);function hr(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function pr(e,t,i){let n=new Set(t),r=Object.keys(e).filter(o=>!n.has(o)),a=t.filter(o=>!(o in e));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`);if(a.length>0)throw new Error(`${i} is missing field(s): ${a.join(", ")}`)}function Bi(e,t){if(typeof e!="string"||!Nj.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function fr(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function vN(e,t){let i=fr(e,t);if(i<1)throw new Error(`${t} must be a positive integer`);return i}function hN(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let i=new Date(e);if(!Number.isFinite(i.getTime())||i.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function Pj(e,t){if(typeof e!="string"||e.length===0||Buffer.byteLength(e,"utf8")>Ej||e.includes("\\")||e.includes("\0")||e.endsWith("/")||/^[a-zA-Z]:/u.test(e))throw new Error(`${t} must be a bounded normalized project-relative path`);let i=dN.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||dN.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function xj(e){let t=hr(e,"Native check receipt checker");pr(t,["policy","version","hash","limits"],"Native check receipt checker");let i=hr(t.limits,"Native check receipt limits");if(pr(i,["maxFiles","maxFileBytes","maxTotalBytes","maxIssues"],"Native check receipt limits"),t.policy!==On||t.version!==ts||t.hash!==$l||i.maxFiles!==Ae.maxFiles||i.maxFileBytes!==Ae.maxFileBytes||i.maxTotalBytes!==Ae.maxTotalBytes||i.maxIssues!==Ae.maxIssues)throw new Error("Native check receipt checker policy is unsupported");return{policy:On,version:ts,hash:$l,limits:{...Ae}}}function Aj(e){let t=hr(e,"Native check receipt contract");return pr(t,["expectedHash","beforeHash","afterHash"],"Native check receipt contract"),{expectedHash:Bi(t.expectedHash,"Native check expected contract hash"),beforeHash:Bi(t.beforeHash,"Native check before contract hash"),afterHash:Bi(t.afterHash,"Native check after contract hash")}}function Tj(e){let t=hr(e,"Native check receipt implementation");return pr(t,["scopeHash","expectedSnapshotHash","beforeSnapshotHash","afterSnapshotHash"],"Native check receipt implementation"),{scopeHash:Bi(t.scopeHash,"Native check scope hash"),expectedSnapshotHash:Bi(t.expectedSnapshotHash,"Native check expected snapshot hash"),beforeSnapshotHash:Bi(t.beforeSnapshotHash,"Native check before snapshot hash"),afterSnapshotHash:Bi(t.afterSnapshotHash,"Native check after snapshot hash")}}function _j(e){let t=hr(e,"Native check receipt counts");pr(t,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],"Native check receipt counts");let i={filesSelected:fr(t.filesSelected,"Native check filesSelected"),filesScanned:fr(t.filesScanned,"Native check filesScanned"),binaryFilesSkipped:fr(t.binaryFilesSkipped,"Native check binaryFilesSkipped"),bytesScanned:fr(t.bytesScanned,"Native check bytesScanned"),issueCount:fr(t.issueCount,"Native check issueCount"),recordedIssueCount:fr(t.recordedIssueCount,"Native check recordedIssueCount")};if(i.filesScanned+i.binaryFilesSkipped>i.filesSelected||i.filesScanned+i.binaryFilesSkipped>Ae.maxFiles||i.bytesScanned>Ae.maxTotalBytes||i.recordedIssueCount>i.issueCount||i.recordedIssueCount>Ae.maxIssues)throw new Error("Native check receipt count accounting is invalid");return i}function Ij(e,t){return e.path.localeCompare(t.path,"en")||e.line-t.line||fN.indexOf(e.kind)-fN.indexOf(t.kind)}function jj(e){if(!Array.isArray(e)||e.length>Ae.maxIssues)throw new Error("Native check receipt issues must be a bounded array");let t=e.map((n,r)=>{let a=hr(n,`Native check issue ${r}`);if(pr(a,["path","line","kind"],`Native check issue ${r}`),typeof a.kind!="string"||!Rj.has(a.kind))throw new Error(`Native check issue ${r} kind is invalid`);return{path:Pj(a.path,`Native check issue ${r} path`),line:vN(a.line,`Native check issue ${r} line`),kind:a.kind}}),i=[...t].sort(Ij);if(JSON.stringify(i)!==JSON.stringify(t))throw new Error("Native check receipt issues must be canonical");return t}function Oj(e){if(!Array.isArray(e)||e.some(n=>typeof n!="string"||!Cj.has(n)))throw new Error("Native check receipt stale reasons are invalid");let t=e,i=mN.filter(n=>t.includes(n));if(new Set(t).size!==t.length||JSON.stringify(i)!==JSON.stringify(t))throw new Error("Native check receipt stale reasons must be canonical");return[...t]}function gN(e){return H(Sj,e)}function qi(e){let t=hr(e,"Native check receipt");if(pr(t,["schema","change","sourceRevision","checker","inputHash","status","startedAt","endedAt","contract","implementation","counts","issues","issuesTruncated","stale","staleReasons","receiptHash"],"Native check receipt"),t.schema!==Ol)throw new Error("Native check receipt schema is invalid");if(typeof t.change!="string"||Buffer.byteLength(t.change,"utf8")>128||!bj.test(t.change))throw new Error("Native check receipt change name is invalid");let i=vN(t.sourceRevision,"Native check source revision"),n=xj(t.checker),r=Aj(t.contract),a=Tj(t.implementation),o=gN({change:t.change,sourceRevision:i,checkerHash:n.hash,contractHash:r.expectedHash,scopeHash:a.scopeHash,snapshotHash:a.expectedSnapshotHash});if(Bi(t.inputHash,"Native check input hash")!==o)throw new Error("Native check receipt input hash mismatch");if(t.status!=="passed"&&t.status!=="failed")throw new Error("Native check receipt status is invalid");let s=hN(t.startedAt,"Native check receipt startedAt"),c=hN(t.endedAt,"Native check receipt endedAt");if(cu.length)throw new Error("Native check receipt issue truncation flag is inconsistent");let d=Oj(t.staleReasons);if(typeof t.stale!="boolean"||t.stale!==d.length>0)throw new Error("Native check receipt stale flag is inconsistent");let f=l.issueCount===0&&!t.stale?"passed":"failed";if(t.status!==f)throw new Error("Native check receipt status is inconsistent with its evidence");if(t.status==="passed"&&(l.filesSelected>Ae.maxFiles||l.filesScanned+l.binaryFilesSkipped!==l.filesSelected))throw new Error("Passed Native check receipt must cover every selected file");if(l.filesSelected>Ae.maxFiles&&!u.some(p=>p.kind==="scan-limit"))throw new Error("Native check receipt exceeds its file budget without a scan-limit issue");let h={schema:Ol,change:t.change,sourceRevision:i,checker:n,inputHash:o,status:t.status,startedAt:s,endedAt:c,contract:r,implementation:a,counts:l,issues:u,issuesTruncated:t.issuesTruncated,stale:t.stale,staleReasons:d},m=Bi(t.receiptHash,"Native check receipt content hash");if(H(pN,h)!==m)throw new Error("Native check receipt content hash mismatch");return{...h,receiptHash:m}}function wN(e){let t={policy:On,version:ts,hash:$l,limits:{...Ae}},i={schema:Ol,...e,checker:t,inputHash:gN({change:e.change,sourceRevision:e.sourceRevision,checkerHash:t.hash,contractHash:e.contract.expectedHash,scopeHash:e.implementation.scopeHash,snapshotHash:e.implementation.expectedSnapshotHash})};return qi({...i,receiptHash:H(pN,i)})}var Hl="comet.native.verification-receipt.v3",yN=Hl,$j="comet.native.declared-artifacts.v1",Hj=/^[a-f0-9]{64}$/u,Dj=/^acceptance-[a-f0-9]{64}$/u,Mj=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Fj=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,Lj=4096,Bj=256,qj=1024;function ma(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let i=Object.getPrototypeOf(e);if(i!==Object.prototype&&i!==null)throw new Error(`${t} must be a plain object`);return e}function $n(e,t,i){let n=Object.keys(e).sort(),r=[...t].sort();if(n.length!==r.length||n.some((a,o)=>a!==r[o]))throw new Error(`${i} fields are invalid`)}function Vi(e,t){if(typeof e!="string"||!Hj.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Yt(e,t){if(typeof e!="string")throw new Error(`${t} must be text`);let i=ke(e).trim();if(!i||i.length>Lj||i!==e.trim())throw new Error(`${t} is invalid`);return i}function yh(e,t){let i=Yt(e,t),n=new Date(i);if(Number.isNaN(n.getTime())||n.toISOString()!==i)throw new Error(`${t} must be a canonical timestamp`);return i}function is(e,t,i=Yt,n=!1,r=Bj){if(!Array.isArray(e)||e.length>r||!n&&e.length===0)throw new Error(`${t} must be a bounded non-empty array`);let a=e.map((o,s)=>i(o,`${t} ${s}`));if(new Set(a).size!==a.length)throw new Error(`${t} has duplicates`);return a}function Vj(e,t){if(typeof e!="string"||!Dj.test(e))throw new Error(`${t} is invalid`);return e}function Wj(e){let t=ma(e,"Native verification receipt bindings");if($n(t,["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"],"Native verification receipt bindings"),typeof t.change!="string"||!Mj.test(t.change)||!Number.isSafeInteger(t.sourceRevision)||t.sourceRevision<1)throw new Error("Native verification receipt bindings are invalid");return{change:t.change,sourceRevision:t.sourceRevision,contractHash:Vi(t.contractHash,"Native verification receipt contract hash"),scopeHash:Vi(t.scopeHash,"Native verification receipt scope hash"),snapshotHash:Vi(t.snapshotHash,"Native verification receipt snapshot hash"),artifactHash:Vi(t.artifactHash,"Native verification receipt artifact hash")}}function Jj(e){if(typeof e!="string")throw new Error("Native static check receipt ref is invalid");let t=Fj.exec(e);if(!t)throw new Error("Native static check receipt ref is invalid");return{ref:e,hash:t[1]}}function zj(e,t,i,n){let r=ma(t,`Native ${e} evidence`);if(e==="automated-check"){if($n(r,["executable","args","cwd","exitCode","signal","timedOut","timeoutMs","startedAt","endedAt","worktree","afterFence","outputHash","outputSummary","outputTruncated"],"Native automated-check evidence"),!Number.isSafeInteger(r.exitCode)||!Number.isSafeInteger(r.timeoutMs)||r.timeoutMs<1||r.timeoutMs>3600*1e3||typeof r.timedOut!="boolean"||typeof r.outputTruncated!="boolean"||r.signal!==null&&typeof r.signal!="string")throw new Error("Native automated-check exit code is invalid");let a=yh(r.startedAt,"Native automated-check start time"),o=yh(r.endedAt,"Native automated-check end time");if(Date.parse(o)({path:t.path,kind:t.kind})).sort((t,i)=>t.path.localeCompare(i.path)||t.kind.localeCompare(i.kind)))}function bN(e){return e.kind==="static-inspection"?`static:${e.evidence.rule}`:e.kind==="automated-check"?`automated:${H("comet.native.failed-check.v1",{executable:e.evidence.executable,args:e.evidence.args,acceptanceIds:e.acceptanceIds})}`:`manual:${H("comet.native.failed-check.v1",{acceptanceIds:e.acceptanceIds})}`}var CN=/^[a-f0-9]{64}$/u,Qt=wi,vV=3*Qt;function Nh(e,t){let i=Xt.relative(e,t);return i===""||!Xt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Xt.sep}`)}function Gj(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Fl(e,t){let i={...e,birthtime:e.birthtimeMs},n={...t,birthtime:t.birthtimeMs};return Ue(i,n)?M(i,n):M(i,n)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function kN(e){let t=await Dt.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${e}`);return{path:e,realPath:await Dt.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Uj(e,t){let i=Xt.resolve(e),n=Xt.resolve(t);if(!Nh(i,n))throw new Error("Native evidence path is outside its change");let r=[await kN(i)],a=i;for(let o of Xt.relative(i,n).split(Xt.sep).filter(Boolean)){a=Xt.join(a,o);let s=await kN(a);if(!Nh(r[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);r.push(s)}return r}async function SN(e){for(let t of e){let i=await Dt.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!Gj(t,i)||await Dt.realpath(t.path)!==t.realPath)throw new Error(`Native evidence parent changed while reading: ${t.path}`)}}async function Kj(e,t,i={}){let n=await Uj(t,Xt.dirname(e));await i.afterParentChainCaptured?.();let r=await Dt.lstat(e);if(!r.isFile()||r.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await Dt.realpath(e);if(!Nh(n[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await Dt.open(e,"r");try{let[s,c,l]=await Promise.all([o.stat(),Dt.lstat(e),Dt.realpath(e)]);if(await SN(n),!s.isFile()||!c.isFile()||c.isSymbolicLink()||l!==a||!Fl(s,r)||!Fl(s,c))throw new Error("Native evidence document changed while opening");if(s.size>Qt)throw new Error(`Native evidence document exceeds ${Qt} bytes`);await i.afterOpen?.();let u=[],d=0,f=Buffer.allocUnsafe(64*1024);for(;;){let v=Qt+1-d,S=await o.read(f,0,Math.min(f.length,v),null);if(S.bytesRead===0)break;if(d+=S.bytesRead,d>Qt)throw new Error(`Native evidence document exceeds ${Qt} bytes`);u.push(Buffer.from(f.subarray(0,S.bytesRead)))}await i.beforeFinalCheck?.();let[h,m,p]=await Promise.all([o.stat(),Dt.lstat(e),Dt.realpath(e)]);if(await SN(n),!m.isFile()||m.isSymbolicLink()||p!==a||!Fl(s,h)||!Fl(s,m))throw new Error("Native evidence document changed while reading");return JSON.parse(Buffer.concat(u,d).toString("utf8"))}finally{await o.close()}}function pt(e,t){if(!CN.test(t))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${e}/${t}.json`}function PN(e){return pt("reports",e)}async function xN(e){let t=Buffer.from(e.text,"utf8");if(t.byteLength>Qt||RN("sha256").update(t).digest("hex")!==e.hash)throw new Error("Native verification report snapshot hash or size is invalid");return mr({paths:e.paths,name:e.name,kind:"reports",hash:e.hash,value:{schema:"comet.native.verification-report.v1",reportHash:e.hash,content:e.text}})}async function Yj(e,t,i,n,r){if(!CN.test(i))throw new Error("Native report evidence hash is invalid");let a=await Wi({paths:e,name:t,kind:"reports",hash:i,hooks:n,changeDir:r});if(!a||typeof a!="object"||Array.isArray(a))throw new Error("Native report evidence must be an object");let o=a;if(Object.keys(o).sort().join(",")!=="content,reportHash,schema"||o.schema!=="comet.native.verification-report.v1"||o.reportHash!==i||typeof o.content!="string"||RN("sha256").update(Buffer.from(o.content,"utf8")).digest("hex")!==i)throw new Error("Native report evidence does not match its hash");return o.content}function va(e,t){let i=/^runtime\/evidence\/(snapshots|scopes|allowances|verifications|reports|receipts)\/([a-f0-9]{64})\.json$/u.exec(e);if(!i||i[1]!==t)throw new Error(`Native evidence ref is invalid for ${t}`);return i[2]}function AN(e,t,i,n,r){return Xt.join(r??C(e,t),...pt(i,n).split("/"))}async function Wi(e){let t=e.changeDir??C(e.paths,e.name),i=AN(e.paths,e.name,e.kind,e.hash,t);return await x(e.paths.nativeRoot,i),Kj(i,t,e.hooks)}async function mr(e){Ll(e.value);let t=AN(e.paths,e.name,e.kind,e.hash);await x(e.paths.nativeRoot,t);try{let n=await Wi(e);if(JSON.stringify(n)!==JSON.stringify(e.value))throw new Error(`Native evidence hash collision for ${e.hash}`);return pt(e.kind,e.hash)}catch(n){if(n.code!=="ENOENT")throw n}await le(t,e.value,{containedRoot:e.paths.nativeRoot});let i=await Wi(e);if(JSON.stringify(i)!==JSON.stringify(e.value))throw new Error(`Native evidence changed during commit for ${e.hash}`);return pt(e.kind,e.hash)}function Ll(e){if(Xj(e)>Qt)throw new Error(`Native evidence document exceeds ${Qt} bytes`)}function Xj(e){return Buffer.byteLength(JSON.stringify(e,null,2)+` +`,"utf8")}function EN(e,t){return da(e,t)}function Qj(e,t){let i=fa(e);if(i.scopeHash!==t)throw new Error("Native implementation scope ref/hash mismatch");return i}function TN(e,t,i){let n=es(e);if(n.change!==t||n.allowanceHash!==i)throw new Error("Native partial allowance ref/hash/change mismatch");return n}function _N(e,t,i){let n=pa(e);if(n.change!==t||n.envelopeHash!==i)throw new Error("Native verification evidence ref/hash/change mismatch");return n}async function IN(e,t,i,n=!1,r){let a=await Bl(e,t,i.implementationScopeRef,void 0,r);if(n&&await Yj(e,t,i.reportHash,void 0,r),a.scopeHash!==i.implementationScopeHash||a.contractHash!==i.contractHash||(a.complete?"complete":"partial")!==i.freshness)throw new Error("Native verification evidence does not match its implementation scope");if(i.partialAllowanceRef===null)return;let o=await bh(e,t,i.partialAllowanceRef,void 0,r);if(o.allowanceHash!==i.partialAllowanceHash||o.scopeHash!==a.scopeHash||JSON.stringify(o.scopeIds)!==JSON.stringify(a.unresolvedScopes.map(s=>s.id).sort())||o.sourceRevision>=i.sourceRevision)throw new Error("Native verification evidence does not match its partial allowance")}async function jN(e){let t=Kt(e.bundle),{baseline:i,current:n,scope:r}=t;return Ll(i),Ll(n),Ll(r),await mr({paths:e.paths,name:e.name,kind:"snapshots",hash:r.baselineProjectionHash,value:i}),await mr({paths:e.paths,name:e.name,kind:"snapshots",hash:r.currentProjectionHash,value:n}),mr({paths:e.paths,name:e.name,kind:"scopes",hash:r.scopeHash,value:r})}async function yi(e,t,i,n,r){let a=va(i,"scopes"),o=Qj(await Wi({paths:e,name:t,kind:"scopes",hash:a,hooks:n,changeDir:r}),a),s=va(o.baselineProjectionRef,"snapshots"),c=va(o.currentProjectionRef,"snapshots"),[l,u]=await Promise.all([Wi({paths:e,name:t,kind:"snapshots",hash:s,changeDir:r}).then(d=>EN(d,s)),Wi({paths:e,name:t,kind:"snapshots",hash:c,changeDir:r}).then(d=>EN(d,c))]);return Qy({baseline:l,current:u,scope:o})}async function Bl(e,t,i,n,r){return(await yi(e,t,i,n,r)).scope}async function ON(e){let t=TN(e.allowance,e.name,e.allowance.allowanceHash),i=await Bl(e.paths,e.name,pt("scopes",t.scopeHash)),n=i.unresolvedScopes.map(r=>r.id).sort();if(i.complete||JSON.stringify(n)!==JSON.stringify(t.scopeIds))throw new Error("Native partial allowance does not match a persisted partial scope");return mr({...e,kind:"allowances",hash:t.allowanceHash,value:t})}async function bh(e,t,i,n,r){let a=va(i,"allowances");return TN(await Wi({paths:e,name:t,kind:"allowances",hash:a,hooks:n,changeDir:r}),t,a)}async function ql(e){let t=ns(e.receipt);if(t.bindings.change!==e.name)throw new Error("Native verification receipt change mismatch");return mr({paths:e.paths,name:e.name,kind:"receipts",hash:t.receiptHash,value:t})}async function Hn(e,t,i,n,r){let a=va(i,"receipts"),o=ns(await Wi({paths:e,name:t,kind:"receipts",hash:a,hooks:n,changeDir:r}));if(o.bindings.change!==t||o.receiptHash!==a)throw new Error("Native verification receipt ref/hash/change mismatch");return o}async function $N(e,t){let i=Xt.join(C(e,t),"runtime","evidence","receipts");await x(e.nativeRoot,i);let n;try{n=await Dt.readdir(i,{withFileTypes:!0})}catch(r){if(r.code==="ENOENT")return[];throw r}return n.filter(r=>r.isFile()).map(r=>/^([a-f0-9]{64})\.json$/u.exec(r.name)?.[1]).filter(r=>r!==void 0).sort().map(r=>pt("receipts",r))}async function HN(e){let t=_N(e.evidence,e.name,e.evidence.envelopeHash);if(t.schema!=="comet.native.verification-evidence.v2")throw new Error("Native active verification evidence must use v2");return await IN(e.paths,e.name,t,!0),mr({...e,kind:"verifications",hash:t.envelopeHash,value:t})}async function Dn(e,t,i,n,r){let a=va(i,"verifications"),o=_N(await Wi({paths:e,name:t,kind:"verifications",hash:a,hooks:n,changeDir:r}),t,a);return await IN(e,t,o,!1,r),o}var Zj=4096;async function eO(e,t=ht.maxChanges){try{let i=await st({root:e.nativeRoot,directory:e.changesDir,label:"Native conflict changes directory",maxEntries:t});return await i.verify(),i.entries}catch(i){if(i.code==="ENOENT")return[];throw i}}async function DN(e,t){let i=await G(e,t),[n,r]=await Promise.all([i.implementation_scope?Bl(e,t,i.implementation_scope):null,Ve(e,t).catch(()=>null)]);return{name:i.name,revision:i.revision,specs:i.spec_changes.map(a=>({capability:a.capability,operation:a.operation,baseHash:a.base_hash})),declaredArtifacts:n?.declaredArtifacts??[],workspaceIdentityHash:r?.nativeRootId??null}}async function Vl(e,t,i={}){let r=(await eO(e,Zj)).filter(c=>c.isDirectory()&&!c.isSymbolicLink()).map(c=>c.name).sort();if(!r.includes(t))throw new Error(`Native conflict target is not visible: ${t}`);let a=await DN(e,t),o=0,s=0;for(let c of r){if(c===t)continue;let l=await DN(e,c).catch(d=>{if(i.tolerateInvalidSiblings)return null;throw d});if(!l)continue;let u=Dy([a,l]).relationships[0];u.classification==="definite-conflict"&&(o+=1),u.classification==="possible-overlap"&&(s+=1)}return{definiteConflictCount:o,possibleOverlapCount:s,findingCodes:[...o>0?["native-change-conflict"]:[],...s>0?["native-change-overlap"]:[]]}}import{randomUUID as SO}from"crypto";import{promises as EO}from"fs";import RO from"path";import{isDeepStrictEqual as xh}from"util";var tO="comet.native.repair-signature.v1",kt={warningAtConsecutiveFailures:2,manualStopAtConsecutiveFailures:3,maxHistoryRecords:64,maxFailedAcceptanceIds:1024,maxFailedCheckIds:128,maxOverrideSummaryCharacters:2e3},iO="comet.native.repair-signature.v1",nO="comet.native.repair-override-summary.v1",rO=/^[a-f0-9]{64}$/u,aO=/^[a-z0-9][a-z0-9._:/-]{0,255}$/u;function FN(e,t){return et?1:0}function Wl(e,t){if(typeof e!="string"||!rO.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function kh(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Jl(e,t,i,n){if(!Array.isArray(e)||e.length>i||!n&&e.length===0)throw new Error(`${t} exceeds its count boundary`);let r=e.map(a=>{if(typeof a!="string"||!aO.test(a))throw new Error(`${t} contains an invalid token: ${String(a)}`);return a});return[...new Set(r)].sort(FN)}function ga(e=[]){return Jl(e,"Native repair failed check IDs",kt.maxFailedCheckIds,!0)}function LN(e){let t=ga(e.failedCheckIds),i=Jl(e.failedAcceptanceIds,"Native repair failed acceptance IDs",kt.maxFailedAcceptanceIds,!0),n={schema:tO,contractHash:Wl(e.contractHash,"Native repair contract hash"),failedAcceptanceIds:i,failedCheckIds:t};return{...n,signatureHash:H(iO,n)}}function oO(e){if(!Array.isArray(e)||e.length>kt.maxHistoryRecords)throw new Error("Native repair history exceeds its record boundary");let t=0,i=0;return e.map((n,r)=>{if(!n||n.kind!=="failure"&&n.kind!=="override")throw new Error(`Native repair history record ${r} is invalid`);let a=n.kind==="failure"?n.failedAcceptanceIds===void 0&&n.failedCheckIds===void 0?["iteration","kind","revision","signatureHash"]:["failedAcceptanceIds","failedCheckIds","iteration","kind","revision","signatureHash"]:["iteration","kind","revision","signatureHash","summaryHash"],o=Object.keys(n).sort(FN);if(o.length!==a.length||o.some((f,h)=>f!==a[h]))throw new Error(`Native repair history record ${r} fields are invalid`);let s=kh(n.iteration,`Native repair history ${r} iteration`),c=kh(n.revision,`Native repair history ${r} revision`),l=r>0?e[r-1]:null;if(!(n.kind==="override"&&l?.kind==="failure"&&s===t&&c>=i&&n.signatureHash===l.signatureHash)&&(s<=t||c<=i))throw new Error("Native repair history must be strictly ordered by revision and iteration");t=s,i=c;let d=Wl(n.signatureHash,`Native repair history ${r} signature`);return n.kind==="failure"?n.failedAcceptanceIds===void 0&&n.failedCheckIds===void 0?{kind:"failure",iteration:s,revision:c,signatureHash:d}:{kind:"failure",iteration:s,revision:c,signatureHash:d,failedAcceptanceIds:Jl(n.failedAcceptanceIds??[],`Native repair history ${r} failed acceptance IDs`,kt.maxFailedAcceptanceIds,!0),failedCheckIds:Jl(n.failedCheckIds??[],`Native repair history ${r} failed check IDs`,kt.maxFailedCheckIds,!0)}:{kind:"override",iteration:s,revision:c,signatureHash:d,summaryHash:Wl(n.summaryHash,`Native repair history ${r} summary`)}})}function MN(e,t){let i=new Set(t);return e.every(n=>i.has(n))}function sO(e,t){return e.failedAcceptanceIds===void 0||e.failedCheckIds===void 0||t.failedAcceptanceIds===void 0||t.failedCheckIds===void 0?e.signatureHash!==t.signatureHash:MN(e.failedAcceptanceIds,t.failedAcceptanceIds)&&MN(e.failedCheckIds,t.failedCheckIds)&&(e.failedAcceptanceIds.length=0;r-=1){let a=t[r];if(sO(n,a))break;i+=1,n=a}return i}function BN(e){let t=e.trim();if(t.length===0||t.length>kt.maxOverrideSummaryCharacters)throw new Error("Native repair override summary is invalid");return t}function zl(e){return H(nO,{summary:BN(e)})}function qN(e){let t=LN(e.facts),i=oO(e.history),n=i.filter(l=>l.kind==="failure"),r=n.length+1,a=kh(e.maxVerifyFailures,"Native maximum Verify failures"),o=Math.max(0,a-r),s=rs({signatureHash:t.signatureHash,failedAcceptanceIds:t.failedAcceptanceIds,failedCheckIds:t.failedCheckIds},n);if(r>=a)return{disposition:"hard-stop",reasonCode:"repair-iteration-limit",signature:t,consecutiveFailures:s,totalRepairFailures:r,remainingIterations:o,overrideAccepted:!1};if(sd.kind==="override"&&d.signatureHash===t.signatureHash);return{disposition:u?"manual-stop":"continue",reasonCode:u?"override-already-used":"override-accepted",signature:t,consecutiveFailures:s,totalRepairFailures:r,remainingIterations:o,overrideAccepted:!u}}return{disposition:"manual-stop",reasonCode:i.some(l=>l.kind==="override"&&l.signatureHash===t.signatureHash)?"override-already-used":"repeated-failure-stop",signature:t,consecutiveFailures:s,totalRepairFailures:r,remainingIterations:o,overrideAccepted:!1}}function Mn(e,t){if(typeof e!="string"||e.trim().length===0||e.length>4096)throw new Error(`${t} must be between 1 and 4096 characters`)}var VN="repairStagnation",St={maxEvents:4096,maxDataDepth:8,maxDataNodes:4096,maxTotalDataNodes:65536,maxObjectFields:64,maxArrayEntries:256,maxKeyCharacters:128,maxTextCharacters:4096,maxEventDataCharacters:65536,maxTotalDataCharacters:1048576,maxRunIdCharacters:256},lO=/^[a-f0-9]{64}$/u,WN="comet.native.repair-scope.v1",uO=new Set(["run_started","action_proposed","action_completed","eval_completed","checkpoint","state_migrated","state_transitioned","command_check_recorded","recovery_reconciled"]),dO=["data","runId","sequence","timestamp","type"],JN=["disposition","overrideSummaryHash","signatureHash"],fO=["contractHash","disposition","failedAcceptanceIds","failedCheckIds","maxVerifyFailures","overrideSummaryHash","signatureHash"],zN=12;function Gl(e,t){return et?1:0}function Eh(e,t,i){let n=Object.keys(e).sort(Gl);if(n.length!==t.length||n.some((r,a)=>r!==t[a]))throw new Error(`${i} fields are invalid`)}function as(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let i=Object.getPrototypeOf(e);if(i!==Object.prototype&&i!==null)throw new Error(`${t} must be a plain object`);return e}function wa(e,t){if(typeof e!="string"||!lO.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function hO(e){if(!Array.isArray(e)||e.length>kt.maxFailedAcceptanceIds||e.some(t=>typeof t!="string"||!/^acceptance-[a-f0-9]{64}$/u.test(t)))throw new Error("Native repair trajectory failed acceptance IDs are invalid");return[...new Set(e)].sort(Gl)}function ya(e){let t=Kt(e).scope;return H(WN,{schema:WN,contractHash:t.contractHash,artifactSnapshotHash:t.currentProjectionHash})}function GN(e){if(typeof e!="string"||e.length===0||e.length>St.maxRunIdCharacters||Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127}))throw new Error("Native repair trajectory run ID is invalid");return e}function Sh(e,t,i,n,r=!1){if(i.nodes+=1,i.nodes>St.maxDataNodes)throw new Error("Native repair trajectory event data exceeds its node boundary");if(t>St.maxDataDepth)throw new Error("Native repair trajectory event data exceeds its depth boundary");if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){if(!Number.isFinite(e))throw new Error(`${n} contains a non-finite number`);return}if(typeof e=="string"){if(e.length>St.maxTextCharacters&&(!r||e.length>St.maxEventDataCharacters))throw new Error(`${n} contains oversized text`);if(i.characters+=e.length,i.characters>St.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");return}if(typeof e!="object")throw new Error(`${n} contains a non-JSON value`);if(i.ancestors.has(e))throw new Error(`${n} contains a cycle`);i.ancestors.add(e);try{if(Array.isArray(e)){if(e.length>St.maxArrayEntries)throw new Error(`${n} contains an oversized array`);e.forEach((s,c)=>Sh(s,t+1,i,`${n}[${c}]`));return}let a=as(e,n),o=Object.keys(a);if(o.length>St.maxObjectFields)throw new Error(`${n} contains too many fields`);for(let s of o){if(s.length===0||s.length>St.maxKeyCharacters)throw new Error(`${n} contains an invalid field name`);if(i.characters+=s.length,i.characters>St.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");Sh(a[s],t+1,i,`${n}.${s}`,t===0&&(s==="summary"||s==="noCodeReason"))}}finally{i.ancestors.delete(e)}}}function pO(e){if(typeof e!="string"||e.length>64)throw new Error("Native repair trajectory timestamp is invalid");let t=new Date(e);if(!Number.isFinite(t.valueOf())||t.toISOString()!==e)throw new Error("Native repair trajectory timestamp is invalid");return e}function mO(e,t,i){let n=as(e,`Native repair trajectory event ${t+1}`);if(Eh(n,dO,`Native repair trajectory event ${t+1}`),!Number.isSafeInteger(n.sequence)||n.sequence!==t+1)throw new Error("Native repair trajectory sequence is invalid");if(pO(n.timestamp),typeof n.type!="string"||!uO.has(n.type))throw new Error("Native repair trajectory event type is invalid");if(GN(n.runId)!==i)throw new Error("Native repair trajectory run ID changed inside the committed prefix");let r={nodes:0,characters:0,ancestors:new Set};return Sh(n.data,0,r,"Native trajectory event data"),as(n.data,"Native repair trajectory event data"),{event:n,dataNodes:r.nodes,dataCharacters:r.characters}}function Rh(e){let t=as(e,"Native repair trajectory projection"),i=Object.keys(t).sort(Gl),n=i.length===JN.length&&i.every((l,u)=>l===JN[u]);n||Eh(t,fO,"Native repair trajectory projection");let r=wa(t.signatureHash,"Native repair trajectory signature hash");if(t.disposition!=="continue"&&t.disposition!=="warn"&&t.disposition!=="manual-stop"&&t.disposition!=="hard-stop")throw new Error("Native repair trajectory disposition is invalid");let a=t.overrideSummaryHash===null?null:wa(t.overrideSummaryHash,"Native repair trajectory override summary hash");if(a!==null&&t.disposition!=="continue")throw new Error("Native repair trajectory override must continue exactly once");if(n)return{signatureHash:r,disposition:t.disposition,overrideSummaryHash:a,contractHash:null,failedAcceptanceIds:[],failedCheckIds:[],maxVerifyFailures:null};let o=wa(t.contractHash,"Native repair trajectory contract hash"),s=hO(t.failedAcceptanceIds),c=ga(t.failedCheckIds);if(!Number.isSafeInteger(t.maxVerifyFailures)||t.maxVerifyFailures<1)throw new Error("Native repair trajectory maximum Verify failures is invalid");return{signatureHash:r,disposition:t.disposition,overrideSummaryHash:a,contractHash:o,failedAcceptanceIds:s,failedCheckIds:c,maxVerifyFailures:t.maxVerifyFailures}}function vO(e,t){if(t.overrideSummaryHash===null){if(e.previousPhase!=="verify"||e.nextPhase!=="build"||e.verificationResult!=="fail")throw new Error("Native repair failure projection is only valid on a failed Verify-to-Build transition");return}if(t.disposition!=="continue"||e.previousPhase!=="build"||e.nextPhase!=="verify"||e.verificationResult!==null)throw new Error("Native repair override projection is only valid on a Build-to-Verify transition")}function gO(e,t){let i=t.filter(s=>s.kind==="failure"),n=i.length+1,r=e.maxVerifyFailures??zN;if(n>r)throw new Error("Native repair trajectory commits a failure beyond the hard-stop boundary");let a=rs({signatureHash:e.signatureHash,...e.contractHash===null?{}:{failedAcceptanceIds:e.failedAcceptanceIds,failedCheckIds:e.failedCheckIds}},i),o=n>=r?"hard-stop":aa.kind==="failure"),r=i?.maxVerifyFailures??zN;if(n.length>=r)throw new Error("Native repair trajectory cannot override a hard stop");if(i?.disposition!=="manual-stop"||i.signatureHash!==e.signatureHash||n.at(-1)?.signatureHash!==e.signatureHash)throw new Error("Native repair trajectory override does not match the latest manual stop");if(t.some(a=>a.kind==="override"&&a.signatureHash===e.signatureHash))throw new Error("Native repair trajectory signature was already overridden")}function Ul(e){if(!Array.isArray(e.trajectory)||e.trajectory.length>St.maxEvents)throw new Error("Native repair trajectory exceeds its event boundary");let t=GN(e.runId);if(!Number.isSafeInteger(e.committedTrajectoryOffset)||e.committedTrajectoryOffset<0||e.committedTrajectoryOffset>e.trajectory.length)throw new Error("Native repair committed trajectory offset is invalid");let i=[],n=null,r=null,a=null,o=0,s=0,c=0;for(let l=0;lSt.maxTotalDataNodes||c>St.maxTotalDataCharacters)throw new Error("Native repair committed trajectory exceeds its aggregate data boundary");let f=d.data,h=Object.hasOwn(f,"repairScopeHash")?wa(f.repairScopeHash,"Native repair trajectory repair scope hash"):Object.hasOwn(f,"implementationScopeHash")?wa(f.implementationScopeHash,"Native repair trajectory implementation scope hash"):null;if(!Object.hasOwn(f,VN)){if(n?.contractHash===null&&d.type==="state_transitioned"&&f.previousPhase==="build"&&f.nextPhase==="verify"&&(h!==null&&r!==null&&h!==r||h===null&&(n?.disposition==="manual-stop"||n?.disposition==="hard-stop"))){i.length=0,n=null,r=h,o=0;continue}continue}if(d.type!=="state_transitioned")throw new Error("Native repair projection must belong to a state_transitioned event");let m=Rh(f[VN]);if(vO(f,m),m.overrideSummaryHash===null)m.contractHash!==null&&a!==null&&m.contractHash!==a&&(i.length=0,o=0),m.contractHash!==null&&(a=m.contractHash),m.contractHash===null&&h!==null&&r!==null&&h!==r&&(i.length=0,o=0),h!==null&&(r=h),gO(m,i),o+=1,i.push({kind:"failure",revision:d.sequence,iteration:o,signatureHash:m.signatureHash,...m.contractHash===null?{}:{failedAcceptanceIds:[...m.failedAcceptanceIds],failedCheckIds:[...m.failedCheckIds]}});else{if(n?.contractHash===null&&h!==null&&r!==null&&h!==r)throw new Error("Native repair override cannot cross implementation scope progress");wO(m,i,n);let p=i.at(-1);if(!p||p.kind!=="failure")throw new Error("Native repair trajectory override has no failure history");i.push({kind:"override",revision:d.sequence,iteration:p.iteration,signatureHash:m.signatureHash,summaryHash:m.overrideSummaryHash})}if(n=m,i.length>kt.maxHistoryRecords)throw new Error("Native repair trajectory history exceeds its record boundary")}return{history:i,latestProjection:n}}function UN(e){return Ul(e).history}function KN(e){let t=Ul(e).latestProjection;return t?{...t}:null}function YN(e){let t=Ul(e),i=as(e.override,"Native repair override request");Eh(i,["expectedSignatureHash","summary"],"Native repair override request");let n=wa(i.expectedSignatureHash,"Native repair override expected signature");if(typeof i.summary!="string")throw new Error("Native repair override summary is invalid");if(t.latestProjection?.disposition==="hard-stop")throw new Error("Native repair hard stop cannot be overridden");if(t.latestProjection?.disposition!=="manual-stop"||t.latestProjection.signatureHash!==n)throw new Error("Native repair override does not match the latest manual stop");if(t.history.some(a=>a.kind==="override"&&a.signatureHash===n))throw new Error("Native repair signature was already overridden");let r=zl(i.summary);return{history:t.history,eventProjection:{signatureHash:n,disposition:"continue",overrideSummaryHash:r,contractHash:t.latestProjection.contractHash,failedAcceptanceIds:[...t.latestProjection.failedAcceptanceIds],failedCheckIds:[...t.latestProjection.failedCheckIds],maxVerifyFailures:t.latestProjection.maxVerifyFailures}}}function yO(e){let t=pa(e.envelope),i=Kt(e.implementationScope);if(t.result!=="fail")throw new Error("Native repair stagnation requires a failed verification envelope");if(t.contractHash!==i.scope.contractHash||t.implementationScopeHash!==i.scope.scopeHash)throw new Error("Native repair evidence does not match the implementation scope authority");return{contractHash:i.scope.contractHash,implementationScopeHash:ya(i),artifactSnapshotHash:i.scope.currentProjectionHash,failedAcceptanceIds:t.acceptanceTrace.entries.filter(n=>n.status==="failed"||n.status==="missing").map(n=>n.acceptanceId).sort(Gl),failedCheckIds:ga(e.failedCheckIds)}}function NO(e,t){return{signatureHash:e.signature.signatureHash,disposition:e.disposition,overrideSummaryHash:t,contractHash:e.signature.contractHash,failedAcceptanceIds:[...e.signature.failedAcceptanceIds],failedCheckIds:[...e.signature.failedCheckIds],maxVerifyFailures:e.totalRepairFailures+e.remainingIterations}}function bO(e){let t=yO(e),i=Ul(e);return{facts:t,history:i.latestProjection?.contractHash!==null&&i.latestProjection?.contractHash!==t.contractHash?[]:i.history}}function XN(e){let t=bO(e),i=qN({...t,maxVerifyFailures:e.maxVerifyFailures});return{...t,decision:i,eventProjection:NO(i,null)}}var mt={root:"/comet/native-runtime",packageKind:"runtime",definition:{apiVersion:"comet/v1alpha1",kind:"Skill",metadata:{name:"comet-native-runtime",version:"3",description:"Comet-owned state runtime for the Native workflow."},goal:{statement:"Advance a Native change only after its current guard passes.",inputs:[],outputs:[],success:["The Native change and Run state agree on the next phase."]},orchestration:{mode:"deterministic",entry:"shape",steps:[{id:"shape",action:{type:"checkpoint"},next:"build"},{id:"build",action:{type:"checkpoint"},next:"verify"},{id:"verify",action:{type:"checkpoint"},next:"archive"},{id:"archive",action:{type:"checkpoint"}}]},skills:[],agents:[],tools:[]},guardrails:{allowedSkills:[],allowedAgents:[],allowedTools:[],maxIterations:Number.MAX_SAFE_INTEGER,maxRetriesPerAction:2,confirmationRequiredFor:[]},evals:[]},vr=D("comet-native-runtime:v3:semantic-repair-budget"),kO=[{skillVersion:"2",skillHash:D("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:D("comet-native-runtime:v1")}];function QN(e){return e.skillVersion===mt.definition.metadata.version&&e.skillHash===vr||kO.some(t=>t.skillVersion===e.skillVersion&&t.skillHash===e.skillHash)}var Na={resolveStep({pkg:e,state:t}){return e.definition.orchestration.steps?.find(i=>i.id===t.currentStep)},resolveNext({step:e,outcome:t}){return e.id==="verify"&&t.state?.verification_result==="fail"?"build":e.next??null}};async function Fn(e){let i={sequence:(await qe(e.changeDir,e.run.trajectoryRef)).length+1,timestamp:(e.now??new Date).toISOString(),type:e.type,runId:e.run.runId,data:e.data};return await Xw(e.changeDir,e.run.trajectoryRef,i),i}async function gr(e){let t={runId:e.run.runId,stateVersion:e.run.iteration,trajectoryOffset:e.trajectoryOffset,contextHash:null,artifactsHash:D(e.evidenceHash),createdAt:(e.now??new Date).toISOString()};return await Qw(e.changeDir,e.run.checkpointRef,t),t}function Kl(e){return D(JSON.stringify({summary:e.summary,confirmed:e.confirmed??!1,artifacts:[...e.artifacts??[]].sort(),noCodeReason:e.noCodeReason??null,verificationResult:e.verificationResult??null,verificationReport:e.verificationReport??null,allowPartialScopeHash:e.allowPartialScopeHash??null,partialReason:e.partialReason??null,repairOverrideSignature:e.repairOverrideSignature??null,repairOverrideSummary:e.repairOverrideSummary??null}))}var ob=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],CO=new Set(ob),sb=new Set([...ob,"minimum_runtime_version","revision"]),PO=new Set([...sb,"operation"]),xO=512*1024,Ch=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),AO=new Set([...Ch,"implementationScopeHash","repairScopeHash","repairStagnation"]),os=class extends Error{constructor(i){super(`Native transition for ${i} requires doctor migration before recovery`);this.change=i;this.name="NativeTransitionMigrationRequiredError"}change;code="native-transition-migration-required"};function We(e,t){return RO.join(C(e,t),"runtime","transition.json")}function TO(e){return`transition-${e}`}async function _O(e,t,i){let n=TO(t);return di(e,n,i)}async function De(e,t,i,n){let r=await _O(e,t,i);try{return await n()}finally{await fi(r)}}function Xl(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal must be an object");return e}function Ah(e,t){let i=Object.keys(e).find(n=>!t.has(n));if(i)throw new Error(`Native transition journal contains unknown field: ${i}`)}function Yl(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Ni(e,t){return xh(e,t)}function Ph(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal event data is invalid");let i=e,n=Object.keys(i),r=n.find(u=>!AO.has(u)),a=[...Ch].find(u=>!Object.hasOwn(i,u)),o=Ch.size+(Object.hasOwn(i,"implementationScopeHash")?1:0)+(Object.hasOwn(i,"repairScopeHash")?1:0)+(Object.hasOwn(i,"repairStagnation")?1:0);if(r||a||n.length!==o)throw new Error(`Native transition journal event data keys are invalid${r?`: ${r}`:a?`: missing ${a}`:""}`);if(!["shape","build","verify","archive"].includes(i.previousPhase)||!["shape","build","verify","archive"].includes(i.nextPhase))throw new Error("Native transition journal event phases are invalid");if(i.evidenceHash!==t)throw new Error("Native transition journal event evidence hash mismatch");if(Mn(i.summary,"Native transition journal event summary"),ke(i.summary)!==i.summary)throw new Error("Native transition journal event summary contains unredacted credentials");if(!Array.isArray(i.artifacts)||i.artifacts.length>128||i.artifacts.some(u=>typeof u!="string"||u.length===0||Buffer.byteLength(u,"utf8")>512))throw new Error("Native transition journal event artifacts are invalid");if(i.noCodeReason!==null&&(Mn(i.noCodeReason,"Native transition journal event no-code reason"),ke(i.noCodeReason)!==i.noCodeReason))throw new Error("Native transition journal event no-code reason contains unredacted credentials");if(i.verificationResult!==null&&i.verificationResult!=="pass"&&i.verificationResult!=="fail")throw new Error("Native transition journal event verification result is invalid");let s=Object.hasOwn(i,"implementationScopeHash")?i.implementationScopeHash:null;if(s!==null&&(typeof s!="string"||!/^[a-f0-9]{64}$/.test(s)||i.previousPhase!=="build"&&i.previousPhase!=="verify"))throw new Error("Native transition journal implementation scope hash is invalid");let c=Object.hasOwn(i,"repairStagnation")?Rh(i.repairStagnation):null;if(c){let u=c.overrideSummaryHash===null;if(u&&(i.previousPhase!=="verify"||i.nextPhase!=="build"||i.verificationResult!=="fail")||!u&&(i.previousPhase!=="build"||i.nextPhase!=="verify"||i.verificationResult!==null))throw new Error("Native transition journal repair projection does not match its phase")}let l=Object.hasOwn(i,"repairScopeHash")?i.repairScopeHash:null;if(l!==null&&(typeof l!="string"||!/^[a-f0-9]{64}$/.test(l)||i.previousPhase!=="build"&&i.previousPhase!=="verify"||s===null))throw new Error("Native transition journal repair scope hash is invalid");return{previousPhase:i.previousPhase,nextPhase:i.nextPhase,evidenceHash:t,summary:i.summary,artifacts:[...i.artifacts],noCodeReason:i.noCodeReason,verificationResult:i.verificationResult,...s?{implementationScopeHash:s}:{},...l?{repairScopeHash:l}:{},...c?{repairStagnation:c}:{}}}function IO(e,t){if(e&&typeof e=="object"&&!Array.isArray(e)){let i=e,n=Object.keys(i),r=new Set(["previousPhase","nextPhase","evidenceHash","summary","reason"]);if(n.length===r.size&&n.every(a=>r.has(a))&&i.reason==="spec-rebase")return Ph({previousPhase:i.previousPhase,nextPhase:i.nextPhase,evidenceHash:i.evidenceHash,summary:i.summary,artifacts:[],noCodeReason:null,verificationResult:null},t)}return Ph(e,t)}function Th(e,t,i=!1){if(e.change!==t)throw new Error("Native transition journal change mismatch");if(typeof e.id!="string"||e.id.length===0)throw new Error("Native transition journal id is invalid");if(typeof e.evidenceHash!="string"||!/^[a-f0-9]{64}$/u.test(e.evidenceHash))throw new Error("Native transition journal evidence hash is invalid");if(typeof e.createdAt!="string"||Number.isNaN(Date.parse(e.createdAt)))throw new Error("Native transition journal timestamp is invalid");let n=i?IO(e.eventData,e.evidenceHash):Ph(e.eventData,e.evidenceHash),r=Rn(e.nextRun),a=e.previousRun===null?null:Rn(e.previousRun);return{id:e.id,evidenceHash:e.evidenceHash,createdAt:e.createdAt,previousRun:a,nextRun:r,eventData:n}}function ZN(e,t,i=!1){if(e.skill!==mt.definition.metadata.name||(i?!QN(e):e.skillVersion!==mt.definition.metadata.version||e.skillHash!==vr)||e.orchestration!==mt.definition.orchestration.mode||e.pendingRef!==ut.pendingRef||e.trajectoryRef!==ut.trajectoryRef||e.contextRef!==ut.contextRef||e.artifactsRef!==ut.artifactsRef||e.checkpointRef!==ut.checkpointRef)throw new Error(`Native transition journal ${t} metadata or storage refs are invalid`)}function eb(e){return{runId:e.runId,skill:e.skill,skillVersion:e.skillVersion,skillHash:e.skillHash,orchestration:e.orchestration,pendingRef:e.pendingRef,trajectoryRef:e.trajectoryRef,contextRef:e.contextRef,artifactsRef:e.artifactsRef,checkpointRef:e.checkpointRef,retries:e.retries}}function tb(e,t){if(e.status!=="running")throw new Error(`Native transition journal ${t} status must be running`);if(e.pending!==null)throw new Error(`Native transition journal ${t} pending action must be null`)}function _h(e,t,i,n=!1){let{previousRun:r,nextRun:a}=i;if(ZN(a,"next Run",n||r!==null),tb(a,"next Run"),a.runId!==t.run_id||a.currentStep!==t.phase)throw new Error("Native transition journal next Run does not match the next change state");if(r===null){if(e.run_id!==null||e.phase!=="shape"||a.iteration!==1||Object.keys(a.retries).length!==0)throw new Error("Native transition journal first Run transition is invalid");return}if(ZN(r,"previous Run",!0),tb(r,"previous Run"),e.run_id!==r.runId||r.currentStep!==e.phase||t.run_id!==r.runId)throw new Error("Native transition journal previous Run does not match the change state");if(a.iteration!==r.iteration+1)throw new Error("Native transition journal next Run iteration must advance exactly once");if(!xh(eb(r),eb(a)))throw new Error("Native transition journal Run identity or storage invariants changed")}function jO(e,t,i){return D(JSON.stringify({operation:"spec-rebase",change:e,summary:t,specChanges:i}))}function cb(e,t,i){return e.phase!=="shape"&&t.phase==="build"&&i.verificationResult===null?"spec-rebase":"advance"}function ib(e){return"implementation_scope"in e?{implementation_scope:e.implementation_scope,verification_evidence:e.verification_evidence,partial_allowance:e.partial_allowance}:null}function Ih(e,t,i,n,r=!1){let a=i.eventData,o=ib(e),s=ib(t);if(a.previousPhase!==e.phase||a.nextPhase!==t.phase)throw new Error("Native transition journal event phases do not match its states");if(e.archived||t.archived)throw new Error("Native transition journal cannot mutate an archived change");if(n==="evidence-retreat"){let c=e.name===t.name&&e.language===t.language&&e.brief===t.brief&&e.approval===t.approval&&("approved_contract_hash"in e?"approved_contract_hash"in t&&e.approved_contract_hash===t.approved_contract_hash:!("approved_contract_hash"in t))&&e.created_at===t.created_at&&e.run_id===t.run_id&&xh(e.spec_changes,t.spec_changes),l=Kl({summary:a.summary});if(!(e.phase==="archive"&&e.verification_result==="pass"||e.phase==="verify"&&e.verification_result==="pending")||t.phase!=="build"||t.verification_result!=="pending"||t.verification_report!==null||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||i.evidenceHash!==l||!c||o===null||s===null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null)throw new Error("Native transition journal evidence retreat semantics are invalid");return}if(n==="spec-rebase"){let c=jO(e.name,a.summary,t.spec_changes),l=D(`spec-rebase:${e.name}:${a.summary}`);if(e.phase==="shape"||t.phase!=="build"||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||t.verification_result!=="pending"||t.verification_report!==null||!r&&i.evidenceHash!==c||r&&i.evidenceHash!==c&&i.evidenceHash!==l||"implementation_scope"in t&&(t.implementation_scope!==null||t.verification_evidence!==null||t.partial_allowance!==null))throw new Error("Native transition journal spec rebase semantics are invalid");return}if(e.phase==="shape"){if(t.phase!=="build"||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||e.verification_result!=="pending"||t.verification_result!=="pending"||e.verification_report!==null||t.verification_report!==null||o!==null&&s!==null&&(o.implementation_scope!==null||o.verification_evidence!==null||o.partial_allowance!==null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null))throw new Error("Native transition journal Shape to Build semantics are invalid");return}if(e.phase==="build"){if(t.phase!=="verify"||a.verificationResult!==null||a.artifacts.length===0&&a.noCodeReason===null||t.verification_result!=="pending"||t.verification_report!==null||o!==null&&s!==null&&(s.implementation_scope===null||s.verification_evidence!==null||s.implementation_scope!==o.implementation_scope&&s.partial_allowance!==null&&s.partial_allowance===o.partial_allowance))throw new Error("Native transition journal Build to Verify semantics are invalid");return}if(e.phase==="verify"){let c=a.verificationResult==="pass"?"archive":"build";if(a.verificationResult!=="pass"&&a.verificationResult!=="fail"||t.phase!==c||a.artifacts.length!==0||a.noCodeReason!==null||t.verification_result!==a.verificationResult||t.verification_report===null||o!==null&&s!==null&&(o.implementation_scope===null||s.implementation_scope!==o.implementation_scope||s.partial_allowance!==o.partial_allowance||o.verification_evidence!==null||s.verification_evidence===null))throw new Error("Native transition journal Verify outcome semantics are invalid");return}throw new Error("Native transition journal cannot advance from Archive")}function Ql(e,t){let i=Xl(e);if(Ah(i,PO),i.schema!==ji)throw new Error(`Expected Native transition schema ${ji}`);let n=Yl(i.minimum_runtime_version,"Native transition minimum_runtime_version");if(n>3)throw new Error(`Native transition requires runtime protocol ${n}; current protocol is ${3}`);if(n!==3)throw new Error(`Native transition ${ji} minimum_runtime_version must be ${3}`);let r=Yl(i.revision,"Native transition revision");if(r!==1)throw new Error("Native transition journal revision must be 1");if(i.operation!=="advance"&&i.operation!=="spec-rebase"&&i.operation!=="evidence-retreat")throw new Error("Native transition journal operation is invalid");let a=Th(i,t),o=Ot(i.previousState),s=Ot(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native transition journal state mismatch");if(Ih(o,s,a,i.operation),_h(o,s,a),s.revision!==o.revision+1)throw new Error("Native transition journal state revision must advance exactly once");return{schema:ji,minimum_runtime_version:3,revision:r,operation:i.operation,id:a.id,change:t,evidenceHash:a.evidenceHash,createdAt:a.createdAt,previousState:o,nextState:s,previousRun:a.previousRun,nextRun:a.nextRun,eventData:a.eventData}}function OO(e,t){let i=Xl(e);if(Ah(i,CO),i.schema!==cr)throw new Error(`Expected Native transition schema ${cr}`);let n=Th(i,t,!0),r=Uo(i.previousState),a=Uo(i.nextState);if(r.name!==t||a.name!==t)throw new Error("Native transition journal state mismatch");return Ih(r,a,n,cb(r,a,n.eventData),!0),_h(r,a,n,!0),{schema:cr,id:n.id,change:t,evidenceHash:n.evidenceHash,createdAt:n.createdAt,previousState:r,nextState:a,previousRun:n.previousRun,nextRun:n.nextRun,eventData:n.eventData}}function jh(e,t){let i=Xl(e);if(Ah(i,sb),i.schema!==Oi)throw new Error(`Expected Native transition schema ${Oi}`);if(Yl(i.minimum_runtime_version,"Native v2 transition minimum_runtime_version")!==2)throw new Error(`Native transition ${Oi} minimum_runtime_version must be 2`);let r=Yl(i.revision,"Native v2 transition revision");if(r!==1)throw new Error("Native v2 transition journal revision must be 1");let a=Th(i,t,!0),o=An(i.previousState),s=An(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native v2 transition journal state mismatch");if(Ih(o,s,a,cb(o,s,a.eventData),!0),_h(o,s,a,!0),s.revision!==o.revision+1)throw new Error("Native v2 transition journal state revision must advance exactly once");return{schema:Oi,minimum_runtime_version:2,revision:r,id:a.id,change:t,evidenceHash:a.evidenceHash,createdAt:a.createdAt,previousState:o,nextState:s,previousRun:a.previousRun,nextRun:a.nextRun,eventData:a.eventData}}function $O(e,t){let i=Xl(e);if(i.schema===ji)return{status:"current",journal:Ql(i,t)};if(i.schema===cr)return{status:"migration-required",journal:OO(i,t)};if(i.schema===Oi)return{status:"migration-required",journal:jh(i,t)};throw new Error(`Unsupported Native transition journal schema: ${String(i.schema)}`)}async function Oh(e,t){let i=We(e,t);await x(e.nativeRoot,i);try{let n=await ue({root:e.nativeRoot,file:i,maxBytes:xO,label:`Native transition journal ${t}`});return $O(JSON.parse(n.bytes.toString("utf8")),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function bi(e,t){let i=await Oh(e,t);if(!i)return null;if(i.status==="migration-required")throw new os(t);return i.journal}async function ss(e){if(await lr(e.paths,e.nextState.name))throw new Error(`Native schema migration is incomplete for ${e.nextState.name}; run doctor --repair`);await Lo(e.paths,e.nextState.name);let t={schema:ji,minimum_runtime_version:3,revision:1,operation:e.operation??"advance",id:e.transitionId?.()??SO(),change:e.nextState.name,evidenceHash:e.evidenceHash,createdAt:(e.now??new Date).toISOString(),previousState:e.previousState,nextState:e.nextState,previousRun:e.previousRun,nextRun:e.nextRun,eventData:e.eventData},i=Ql(t,t.change),n=We(e.paths,i.change);if(await x(e.paths.nativeRoot,n),await bi(e.paths,i.change))throw new Error(`Native transition recovery is already pending for ${i.change}`);return await le(n,i),i}function nb(e,t){if(Ni(e,t.nextRun))return"next";if(t.previousRun===null){if(e===null)return"previous"}else if(Ni(e,t.previousRun))return"previous";throw new Error(`Native transition Run content changed for ${t.change}; recovery journal was preserved`)}function rb(e,t){if(Ni(e,t.nextState))return"next";if(Ni(e,t.previousState))return"previous";throw new Error(`Native transition change content changed for ${t.change}; recovery journal was preserved`)}function HO(e){let{journal:t}=e;return lb({sequence:e.sequence,timestamp:t.createdAt,type:e.type,runId:t.nextRun.runId,data:e.type==="run_started"?{runtime:"comet-native",phase:t.previousState.phase,transitionId:t.id}:{...t.eventData,transitionId:t.id}})}function lb(e){return{sequence:e.sequence,timestamp:e.timestamp,type:e.type,runId:e.runId,data:e.data}}function ab(e,t){let i=e.map((a,o)=>({event:a,index:o})).filter(({event:a})=>a.data.transitionId===t.id),n=i.filter(({event:a})=>a.type==="run_started"),r=i.filter(({event:a})=>a.type==="state_transitioned");if(i.length!==n.length+r.length||n.length>(t.previousRun===null?1:0)||r.length>1||t.previousRun===null&&r.length===1&&(n.length!==1||n[0].index>=r[0].index))throw new Error(`Native trajectory transition id collision for ${t.change}; recovery journal was preserved`);for(let a of[...n,...r]){let o=HO({sequence:a.index+1,journal:t,type:a.event.type});if(!Ni(lb(a.event),o))throw new Error(`Native trajectory event changed for transition ${t.id}; recovery journal was preserved`)}return{started:n[0]?.event??null,transitioned:r[0]?.event??null}}async function ki(e,t,i){if(await lr(e,t))throw new Error(`Native schema migration is incomplete for ${t}; run doctor --repair`);await Lo(e,t);let n=await bi(e,t);if(!n)return null;let r=C(e,t),a=ab(await qe(r,n.nextRun.trajectoryRef),n),[o,s]=await Promise.all([be(r),G(e,t)]),c=nb(o,n),l=rb(s,n);if((a.started||a.transitioned)&&(c!=="next"||l!=="next"))throw new Error(`Native trajectory is ahead of transition state for ${n.change}; recovery journal was preserved`);if(c==="previous"&&(await rr(r,n.nextRun),await i?.afterRunStateWritten?.(n)),!Ni(await be(r),n.nextRun))throw new Error(`Native transition Run content changed while continuing ${n.change}; recovery journal was preserved`);if(l==="previous"){let v=await oa(e,n.nextState,n.previousState.revision);if(!Ni(v,n.nextState))throw new Error(`Native transition change write diverged for ${n.change}; recovery journal was preserved`);await i?.afterChangeStateWritten?.(n)}if(!Ni(await G(e,t),n.nextState))throw new Error(`Native transition change content changed while continuing ${n.change}; recovery journal was preserved`);let u=await bi(e,t);if(!u||!Ni(u,n))throw new Error(`Native transition journal changed while continuing ${n.change}; it was preserved`);let d=ab(await qe(r,n.nextRun.trajectoryRef),n);n.previousRun===null&&(d.started||await Fn({changeDir:r,run:n.nextRun,type:"run_started",data:{runtime:"comet-native",phase:n.previousState.phase,transitionId:n.id},now:new Date(n.createdAt)}));let f=d.transitioned;f||(f=await Fn({changeDir:r,run:n.nextRun,type:"state_transitioned",data:{...n.eventData,transitionId:n.id},now:new Date(n.createdAt)})),await gr({changeDir:r,run:n.nextRun,trajectoryOffset:f.sequence,evidenceHash:n.evidenceHash,now:new Date(n.createdAt)});let[h,m]=await Promise.all([be(r),G(e,t)]);nb(h,{...n,previousRun:n.nextRun}),rb(m,{...n,previousState:n.nextState});let p=await bi(e,t);if(!p||!Ni(p,n))throw new Error(`Native transition journal changed while continuing ${n.change}; it was not removed`);return await EO.rm(We(e,t),{force:!0}),n.nextState}async function ub(e,t,i){return te(e,`continue transition ${t}`,()=>De(e,t,`continue transition ${t}`,()=>ki(e,t,i)))}import Yb from"node:path";import db from"node:path";var DO="comet.native.acceptance.v1",MO=/^acceptance-[a-f0-9]{64}$/u,FO=new Set(["acceptance_id","status","evidence_refs","skipped_reason"]),LO=/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u,BO=/^[a-f0-9]{64}$/u,qO=/^native-acceptance-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u;function VO(e,t){return et?1:0}var Ji=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),ls=Object.freeze({maxCriteria:1024}),cs="",ba="";function fb(e,t){if(Buffer.byteLength(e,"utf8")<=t)return{value:e,truncated:!1};let i="",n=0;for(let r of e){let a=Buffer.byteLength(r,"utf8");if(n+a>t)break;i+=r,n+=a}return{value:i,truncated:!0}}function hb(e,t){let i=t.toString(36),n=H("comet.native.acceptance-cursor.v1",{acceptanceHash:e,offset:t});return`native-acceptance-v1.${e}.${i}.${n}`}function WO(e){if(!BO.test(e.acceptanceHash))throw new Error("Native acceptance page hash is invalid");if(e.cursor===void 0||e.cursor===null)return 0;let t=qO.exec(e.cursor);if(!t)throw new Error("Native acceptance cursor is invalid");if(t[1]!==e.acceptanceHash)throw new Error("Native acceptance cursor is stale");let i=Number.parseInt(t[2],36);if(!Number.isSafeInteger(i)||i<=0||i>=e.total||i.toString(36)!==t[2])throw new Error("Native acceptance cursor offset is invalid");if(t[3]!==H("comet.native.acceptance-cursor.v1",{acceptanceHash:e.acceptanceHash,offset:i}))throw new Error("Native acceptance cursor integrity check failed");return i}function JO(e,t){let i=fb(e.text,Ji.maxTextBytes),n=e.context.slice(0,Ji.maxContextItems).map(r=>fb(r,Ji.maxContextItemBytes));return{id:e.id,kind:e.kind,source:e.source,context:n.map(r=>r.value),text:i.value,contextTruncated:e.context.length>n.length||n.some(r=>r.truncated),textTruncated:i.truncated,verificationStatus:t}}function Zl(e){let t=WO({acceptanceHash:e.acceptanceHash,total:e.criteria.length,cursor:e.cursor}),i=[],n=[...new Set(e.failedCheckIds??[])].sort(VO),r=n.slice(0,Ji.maxFailedCheckIds),a=e.criteria.slice(t,t+Ji.maxItems);for(let c of a){let l=[...i,JO(c,e.verificationStatuses?.get(c.id)??"unverified")],u=t+l.length,d={schema:"comet.native.acceptance-page.v1",acceptanceHash:e.acceptanceHash,total:e.criteria.length,offset:t,items:l,failedAcceptanceIds:l.filter(f=>f.verificationStatus==="failed").map(f=>f.id),missingAcceptanceIds:l.filter(f=>f.verificationStatus==="missing").map(f=>f.id),failedCheckIds:r,failedCheckIdsTruncated:n.length>r.length,nextCursor:uJi.maxSerializedBytes){if(i.length===0)throw new Error("Native acceptance criterion exceeds the page serialization budget");break}i.push(l.at(-1))}if(e.criteria.length>0&&i.length===0)throw new Error("Native acceptance page could not project its next criterion");let o=t+i.length,s={schema:"comet.native.acceptance-page.v1",acceptanceHash:e.acceptanceHash,total:e.criteria.length,offset:t,items:i,failedAcceptanceIds:i.filter(c=>c.verificationStatus==="failed").map(c=>c.id),missingAcceptanceIds:i.filter(c=>c.verificationStatus==="missing").map(c=>c.id),failedCheckIds:r,failedCheckIdsTruncated:n.length>r.length,nextCursor:oJi.maxSerializedBytes)throw new Error("Native acceptance page exceeds its serialization budget");return s}function Dh(e){let t=/^ {0,3}(#{1,6})[ \t]+(.+?)[ \t]*$/u.exec(e);return t?{level:t[1].length,text:t[2].replace(/[ \t]+#+[ \t]*$/u,"").trim()}:null}function $h(e,t){let i=/^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(e);if(!i)return t;let n=i[1][0];return t===null?{marker:n,length:i[1].length}:n===t.marker&&i[1].length>=t.length&&i[2].trim().length===0?null:t}function pb(e){return e.includes("-->")||e.includes("--!>")}function*ka(e){let t=null,i=!1,n=null,r=new Set(["code","pre","script","style","svg","template"]),a=e.replace(/\r\n?/gu,` `),o=0,s=0;for(;o<=a.length;){let c=a.indexOf(` -`,o),l=c===-1?a.slice(o):a.slice(o,c);if(yield{line:l,body:t===null&&!i&&n===null,index:s},s+=1,t!==null)t=$h(l,t);else if(i)hb(l)&&(i=!1);else if(n!==null)new RegExp(``,"iu").test(l)&&(n=null);else{let d=$h(l,null);if(d!==null)t=d;else{let f=l.trimStart();if(f.startsWith(""||f==="--!>"||/^<\/?[A-Za-z][^>]*>$/u.test(f)||/^<[A-Za-z][^>]*>.*<\/[A-Za-z][^>]*>$/u.test(f)||/^(?:[-*_]\s*){3,}$/u.test(f)||/^\|?(?:\s*:?-{3,}:?\s*\|)+\s*$/u.test(f)){s();continue}let h=/^\s*(?:[-*+]|\d+[.)])[ \t]+(.+)$/u.exec(l);if(h){s(),o={parts:[h[1]],context:r.map(m=>m.text)};continue}if(/^\|.*\|$/u.test(f)){s(),o={parts:[f],context:r.map(m=>m.text)},s();continue}o===null?o={parts:[f],context:r.map(m=>m.text)}:o.parts.push(f)}return s(),Fh(n,"Specification mandatory requirements")}function KO(e,t){let i=e.trim().replaceAll("\\","/");if(i.length===0||GO(i)||ub.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~|[A-Za-z][A-Za-z0-9+.-]*:)/u.test(i)||i.split("/").includes(".."))throw new Error(`Acceptance evidence ${t} has an unsafe evidence ref`);let n=ub.posix.normalize(i);if(n==="."||n===".."||n.startsWith("../"))throw new Error(`Acceptance evidence ${t} has an unsafe evidence ref`);if(n.split("/").some(r=>r.toLowerCase()===".git"||r.toLowerCase().startsWith(".env")))throw new Error(`Acceptance evidence ${t} references sensitive content`);if(!LO.test(n))throw new Error(`Acceptance evidence ${t} must reference a content-addressed typed receipt`);return n}function YO(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`Acceptance evidence entry ${t} must be an object`);let i=e,n=Object.keys(i).filter(r=>!FO.has(r));if(n.length>0)throw new Error(`Acceptance evidence entry ${t} has unknown field(s): ${n.join(", ")}`);return i}function gb(e){if(!Array.isArray(e))throw new Error("Native acceptance evidence block must be a JSON array");let t=new Set;return e.map((i,n)=>{let r=YO(i,n),a=r.acceptance_id;if(typeof a!="string"||!MO.test(a))throw new Error(`Acceptance evidence entry ${n} has an invalid acceptance_id`);if(t.has(a))throw new Error(`Native acceptance evidence has duplicate acceptance_id: ${a}`);if(t.add(a),!Array.isArray(r.evidence_refs))throw new Error(`Acceptance evidence ${a} requires an evidence_refs array`);let o=r.evidence_refs.map(l=>{if(typeof l!="string"||l.trim().length===0)throw new Error(`Acceptance evidence ${a} has a non-empty string requirement`);return KO(l,a)});if(new Set(o).size!==o.length)throw new Error(`Acceptance evidence ${a} has a duplicate evidence ref`);let s=r.status;if(s!=="passed"&&s!=="failed")throw new Error(`Acceptance evidence ${a} status is invalid`);let c;if(Object.prototype.hasOwnProperty.call(r,"skipped_reason")){if(typeof r.skipped_reason!="string"||r.skipped_reason.trim().length===0)throw new Error(`Acceptance evidence ${a} skipped_reason must be a non-empty string`);c=r.skipped_reason.trim()}if(s==="passed"&&o.length===0)throw new Error(`Acceptance evidence ${a} passed status requires evidence_refs`);if(s==="failed"&&o.length===0&&c===void 0)throw new Error(`Acceptance evidence ${a} failed status requires evidence_refs or a skipped_reason`);if(s==="passed"&&c!==void 0)throw new Error(`Acceptance evidence ${a} passed status has invalid fields`);return{acceptance_id:a,status:s,evidence_refs:o,...c===void 0?{}:{skipped_reason:c}}})}function eu(e){let t=zO(e);if(t.some(({line:l,body:u})=>!u&&(l===cs||l===ba)))throw new Error("Native acceptance evidence markers must be in the Markdown body");let n=t.flatMap(({line:l,body:u},d)=>u&&l===cs?[d]:[]),r=t.flatMap(({line:l,body:u},d)=>u&&l===ba?[d]:[]);if(n.length!==1||r.length!==1)throw new Error("Verification must contain exactly one Native acceptance evidence block");if(n[0]>=r[0])throw new Error("Native acceptance evidence markers are out of order");let a=t.slice(n[0]+1,r[0]).map(({line:l})=>l).join(` -`).trim();if(a.length===0)throw new Error("Native acceptance evidence block is empty");let o;try{o=JSON.parse(a)}catch(l){throw new Error(`Native acceptance evidence block is invalid JSON: ${l.message}`,{cause:l})}let s=gb(o),c=wb(s);if(a!==c)throw new Error("Native acceptance evidence block must use canonical serialization");return s}function wb(e){let t=gb([...e]).map(i=>({...i,evidence_refs:[...i.evidence_refs].sort()})).sort((i,n)=>i.acceptance_id.localeCompare(n.acceptance_id));return JSON.stringify(t,null,2)}function tu(e){return[cs,wb(e),ba].join(` -`)}import yb from"node:path";var XO="comet.native.contract.v1",QO="comet.native.acceptance-set.v1",Nb=/^[a-f0-9]{64}$/u,us={maxAcceptanceCriteria:ls.maxCriteria};function bb(e,t){let i=yb.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(n=>{let r=n.codePointAt(0)??0;return r<=31||r===127})||yb.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||i!==e||i==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized project-relative ref`);return e}function kb(e){return H("comet.native.contract-content.v1",e.replace(/\r\n?/gu,` -`))}function ZO(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.capability))throw new Error(`Invalid Native contract capability: ${e.capability}`);if(e.operation!=="create"&&e.operation!=="replace"&&e.operation!=="remove")throw new Error(`Invalid Native contract operation for ${e.capability}`);if(e.operation==="remove"){if(e.source!==null||e.markdown!==null||!e.baseHash?.match(Nb))throw new Error(`Remove contract ${e.capability} requires only a base hash`);return{snapshot:{capability:e.capability,operation:"remove",source:null,baseHash:e.baseHash,contentHash:null},markdown:null}}if(e.source===null||e.markdown===null)throw new Error(`${e.operation} contract ${e.capability} requires source content`);if(e.operation==="create"&&e.baseHash!==null)throw new Error(`Create contract ${e.capability} requires a null base hash`);if(e.operation==="replace"&&!e.baseHash?.match(Nb))throw new Error(`Replace contract ${e.capability} requires a base hash`);let t=bb(e.source,`Contract source for ${e.capability}`);return{snapshot:{capability:e.capability,operation:e.operation,source:t,baseHash:e.baseHash,contentHash:kb(e.markdown)},markdown:e.markdown}}function e$(e,t){return Sb(e.id,t.id)}function Sb(e,t){return et?1:0}function Eb(e){let t=bb(e.briefSource??"brief.md","Native brief source"),i=e.specs.map(ZO).sort((d,f)=>Sb(d.snapshot.capability,f.snapshot.capability)),n=i.map(({snapshot:d})=>d.capability);if(new Set(n).size!==n.length)throw new Error("Native contract contains duplicate capabilities");let r=[t,...i.flatMap(({snapshot:d})=>d.source===null?[]:[d.source])];if(new Set(r).size!==r.length)throw new Error("Native contract contains duplicate artifact sources");let a=pb(e.briefMarkdown,t,us.maxAcceptanceCriteria);for(let{snapshot:d,markdown:f}of i)f===null||d.source===null||(a.push(...mb(f,d.source,us.maxAcceptanceCriteria-a.length)),a.push(...vb(f,d.source,us.maxAcceptanceCriteria-a.length)));if(a.sort(e$),a.length===0)throw new Error("Native contract has no structured acceptance criteria");if(a.length>us.maxAcceptanceCriteria)throw new Error(`Native contract exceeds its ${us.maxAcceptanceCriteria}-criterion acceptance budget`);let o=a.map(({id:d})=>d);if(new Set(o).size!==o.length)throw new Error("Native contract contains duplicate acceptance criteria");let s={source:t,contentHash:kb(e.briefMarkdown)},c=i.map(({snapshot:d})=>d),l=H(QO,a),u={schema:"comet.native.contract.v1",brief:s,specs:c,acceptance:a,acceptanceHash:l};return{...u,contractHash:H(XO,u)}}var Zt={maxSpecs:64,maxFileBytes:ho,maxTotalBytes:4*1024*1024};async function Et(e){if(e.specChanges.length>Zt.maxSpecs)throw new Error("Native contract exceeds its spec-count budget");let t=await ye({root:e.changeDir,ref:e.briefRef,maxBytes:Zt.maxFileBytes}),i=t.size,n=[];for(let r of e.specChanges){if(r.operation==="remove"){n.push({capability:r.capability,operation:"remove",source:null,baseHash:r.base_hash,markdown:null});continue}if(!r.source)throw new Error(`Native contract ${r.capability} has no proposed spec source`);let a=await ye({root:e.changeDir,ref:r.source,maxBytes:Zt.maxFileBytes});if(i+=a.size,i>Zt.maxTotalBytes)throw new Error("Native contract exceeds its total byte budget");n.push({capability:r.capability,operation:r.operation,source:a.ref,baseHash:r.base_hash,markdown:a.text})}return{contract:Eb({briefSource:t.ref,briefMarkdown:t.text,specs:n}),sourceCount:n.filter(r=>r.source!==null).length+1,totalBytes:i}}import{execFile as h$,spawn as Qh}from"node:child_process";import{createHash as p$}from"node:crypto";import{existsSync as qb}from"node:fs";import Si from"node:path";import{promisify as m$}from"node:util";import{spawn as t$}from"node:child_process";import Lh from"node:path";var i$=1e3,n$=2;async function Rb(e){let t=e.pid;if(t===void 0){e.kill("SIGKILL");return}if(process.platform==="win32"){let i=process.env.SystemRoot??process.env.WINDIR,n=i&&Lh.win32.isAbsolute(i)?Lh.win32.resolve(i):"C:\\Windows",r=Lh.win32.join(n,"System32","taskkill.exe"),a=()=>new Promise(o=>{let s=!1,c=null,l=null,u=(d,f=!1)=>{s||(s=!0,l&&clearTimeout(l),f&&c?.kill("SIGKILL"),o(d))};try{c=t$(r,["/pid",String(t),"/t","/f"],{stdio:"ignore",windowsHide:!0}),c.once("error",()=>u(!1)),c.once("close",d=>u(d===0)),l=setTimeout(()=>u(!1,!0),i$)}catch{u(!1)}});for(let o=0;o!n.has(o)),a=t.filter(o=>!(o in e));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`);if(a.length>0)throw new Error(`${i} is missing field(s): ${a.join(", ")}`)}function Ln(e,t,i=2e3){if(typeof e!="string"||e.length===0||e.length>i)throw new Error(`${t} must be a non-empty string of at most ${i} characters`);return e}function Cb(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Bh(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function Pb(e){let t=e.trim().replaceAll("\\","/");if(t.length===0||Sa.isAbsolute(t)||/^(?:[A-Za-z]:|~|\/)/u.test(t)||t.split("/").includes(".."))throw new Error(`Checkpoint artifact must be project-relative: ${e}`);let i=Sa.posix.normalize(t);if(i==="."||i===".."||i.startsWith("../"))throw new Error(`Checkpoint artifact must name a project file: ${e}`);return i}function qh(e,t){return Sa.join(C(e,t),"runtime","checkpoints","progress.json")}function zi(e,t){return Sa.join(C(e,t),"runtime","checkpoint-journal.json")}function Vh(e,t,i){if(!Ea.test(i))throw new Error("Native checkpoint manifest hash is invalid");return Sa.join(C(e,t),"runtime","checkpoints","manifests",`${i}.json`)}function Wh(e){if(!Ea.test(e))throw new Error("Native checkpoint manifest hash is invalid");return`runtime/checkpoints/manifests/${e}.json`}async function Jh(e,t,i){let n=await ue({root:e,file:t,maxBytes:ei.maxDocumentBytes,label:i});return JSON.parse(n.bytes.toString("utf8"))}function r$(e,t){let i=iu(e,`checkpoint manifest artifact ${t}`);nu(i,["path","hash","size"],`checkpoint manifest artifact ${t}`);let n=Pb(Ln(i.path,`checkpoint artifact ${t} path`,4096)),r=ci(n);if(r)throw new Error(`checkpoint artifact ${t} is excluded as sensitive (${r}): ${n}`);if(typeof i.hash!="string"||!Ea.test(i.hash))throw new Error(`checkpoint artifact ${t} hash is invalid`);return{path:n,hash:i.hash,size:Bh(i.size,`checkpoint artifact ${t} size`)}}function ru(e,t){let i=iu(e,"Native checkpoint manifest");if(nu(i,["schema","change","artifacts","totalBytes"],"Native checkpoint manifest"),i.schema!=="comet.native.checkpoint-manifest.v1")throw new Error("Native checkpoint manifest schema is invalid");if(i.change!==t)throw new Error("Native checkpoint manifest change mismatch");if(!Array.isArray(i.artifacts))throw new Error("Native checkpoint manifest artifacts must be an array");if(i.artifacts.length>ei.maxArtifacts)throw new Error("Native checkpoint manifest has too many artifacts");let n=i.artifacts.map(r$),r=[...n].sort((o,s)=>o.path.localeCompare(s.path));if(JSON.stringify(n)!==JSON.stringify(r))throw new Error("Native checkpoint manifest artifacts must be sorted");if(new Set(n.map(o=>o.path)).size!==n.length)throw new Error("Native checkpoint manifest has duplicate artifacts");let a=Bh(i.totalBytes,"checkpoint manifest totalBytes");if(n.reduce((o,s)=>o+s.size,0)!==a)throw new Error("Native checkpoint manifest totalBytes mismatch");if(a>ei.maxTotalBytes)throw new Error("Native checkpoint manifest totalBytes exceeds its budget");return{schema:"comet.native.checkpoint-manifest.v1",change:t,artifacts:n,totalBytes:a}}function ds(e){return D(JSON.stringify(ru(e,e.change)))}function zh(e,t){let i=iu(e,"Native progress checkpoint");if(nu(i,["schema","id","change","phase","previousRevision","stateRevision","summary","nextAction","inputHash","manifestHash","manifestRef","artifactCount","createdAt"],"Native progress checkpoint"),i.schema!=="comet.native.progress-checkpoint.v1")throw new Error("Native progress checkpoint schema is invalid");if(i.change!==t)throw new Error("Native checkpoint change mismatch");let n=i.phase;if(n!=="shape"&&n!=="build"&&n!=="verify"&&n!=="archive")throw new Error("Native checkpoint phase is invalid");let r=Cb(i.previousRevision,"Native checkpoint previousRevision"),a=Cb(i.stateRevision,"Native checkpoint stateRevision");if(a!==r+1)throw new Error("Native checkpoint stateRevision must increment previousRevision once");let o=Ln(i.manifestHash,"Native checkpoint manifestHash",64);if(!Ea.test(o))throw new Error("Native checkpoint manifestHash is invalid");let s=Wh(o);if(i.manifestRef!==s)throw new Error("Native checkpoint manifestRef does not match manifestHash");let c=Ln(i.inputHash,"Native checkpoint inputHash",64);if(!Ea.test(c))throw new Error("Native checkpoint inputHash is invalid");let l=Ln(i.createdAt,"Native checkpoint createdAt",64);if(Number.isNaN(Date.parse(l)))throw new Error("Native checkpoint createdAt is invalid");let u=Bh(i.artifactCount,"Native checkpoint artifactCount");if(u>ei.maxArtifacts)throw new Error("Native checkpoint artifactCount exceeds its budget");let d=Ln(i.summary,"Native checkpoint summary"),f=Ln(i.nextAction,"Native checkpoint nextAction");if(ke(d)!==d||ke(f)!==f)throw new Error("Native checkpoint text contains unredacted credential material");return{schema:"comet.native.progress-checkpoint.v1",id:Ln(i.id,"Native checkpoint id",128),change:t,phase:n,previousRevision:r,stateRevision:a,summary:d,nextAction:f,inputHash:c,manifestHash:o,manifestRef:s,artifactCount:u,createdAt:l}}function xb(e,t){let i=iu(e,"Native checkpoint journal");if(nu(i,["schema","id","change","inputHash","createdAt","previousState","nextState","checkpoint","manifest"],"Native checkpoint journal"),i.schema!=="comet.native.checkpoint-journal.v1")throw new Error("Native checkpoint journal schema is invalid");if(i.change!==t)throw new Error("Native checkpoint journal change mismatch");let n=Ot(i.previousState),r=Ot(i.nextState),a=zh(i.checkpoint,t),o=ru(i.manifest,t),s=Ln(i.inputHash,"Native checkpoint journal inputHash",64),c=D(JSON.stringify({summary:a.summary,nextAction:a.nextAction,artifacts:o.artifacts}));if(!Ea.test(s)||s!==a.inputHash||s!==c||i.id!==a.id||i.createdAt!==a.createdAt)throw new Error("Native checkpoint journal envelope mismatch");if(n.name!==t||r.name!==t||r.revision!==n.revision+1||a.previousRevision!==n.revision||a.stateRevision!==r.revision||a.phase!==r.phase||a.manifestHash!==ds(o)||a.artifactCount!==o.artifacts.length)throw new Error("Native checkpoint journal state mismatch");return{schema:"comet.native.checkpoint-journal.v1",id:a.id,change:t,inputHash:s,createdAt:a.createdAt,previousState:n,nextState:r,checkpoint:a,manifest:o}}async function Ab(e,t,i){let n=Sa.resolve(e.projectRoot,...t.split("/"));if(!$(e.projectRoot,n)||$(e.nativeRoot,n))throw new Error(`Checkpoint artifact is outside project content: ${t}`);let r=fo(e,t);if(r)throw new Error(`Checkpoint artifact is excluded as sensitive (${r}): ${t}`);let a=await ue({root:e.projectRoot,file:n,maxBytes:ei.maxFileBytes,label:`Checkpoint artifact ${t}`,forbiddenRoots:[e.nativeRoot],hooks:{afterParentChainCaptured:()=>i?.afterParentChainCaptured?.(t),afterOpen:()=>i?.afterOpen?.(t),beforeRead:()=>i?.beforeRead?.(t)}});return{path:t,hash:a.hash,size:a.size}}async function Tb(e,t,i,n){let r=i.map(Pb).sort();if(r.length>ei.maxArtifacts)throw new Error(`Checkpoint supports at most ${ei.maxArtifacts} artifacts`);if(new Set(r).size!==r.length)throw new Error("Checkpoint artifacts must not contain duplicates");let a=[],o=0;for(let s of r){let c=await Ab(e,s,n);if(o+=c.size,o>ei.maxTotalBytes)throw new Error("Checkpoint artifacts exceed the total byte budget");a.push(c)}return{schema:"comet.native.checkpoint-manifest.v1",change:t,artifacts:a,totalBytes:o}}async function Gh(e,t){let i=qh(e,t);await x(e.nativeRoot,i);try{return zh(await Jh(e.nativeRoot,i,"Native progress checkpoint"),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Uh(e,t,i){let n=Vh(e,t,i);await x(e.nativeRoot,n);let r=await Jh(e.nativeRoot,n,"Native checkpoint manifest"),a=ru(r,t);if(Yh(e,a),ds(a)!==i)throw new Error("Native checkpoint manifest content hash mismatch");return a}async function Gi(e,t){let i=zi(e,t);await x(e.nativeRoot,i);try{let n=xb(await Jh(e.nativeRoot,i,"Native checkpoint journal"),t);return Yh(e,n.manifest),n}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Kh(e,t,i,n){let r=ru(i,t);Yh(e,r);let a=ds(r),o=Vh(e,t,a);await x(e.nativeRoot,o);try{let s=await Uh(e,t,a);if(JSON.stringify(s)!==JSON.stringify(r))throw new Error("Native checkpoint manifest hash collision")}catch(s){if(s.code!=="ENOENT")throw s}return await le(o,r,{containedRoot:e.nativeRoot,beforeCommit:n?.beforeCommit}),a}function Yh(e,t){for(let i of t.artifacts){let n=fo(e,i.path);if(n)throw new Error(`Native checkpoint manifest contains a sensitive artifact (${n}): ${i.path}`)}}async function _b(e,t){let i=zh(t,t.change),n=await Uh(e,i.change,i.manifestHash),r=D(JSON.stringify({summary:i.summary,nextAction:i.nextAction,artifacts:n.artifacts}));if(i.inputHash!==r||i.artifactCount!==n.artifacts.length)throw new Error("Native progress checkpoint does not match its artifact manifest");let a=qh(e,t.change);await x(e.nativeRoot,a),await le(a,i,{containedRoot:e.nativeRoot})}async function Ib(e,t){let i=xb(t,t.change),n=zi(e,t.change);if(await x(e.nativeRoot,n),await Gi(e,t.change))throw new Error(`Native checkpoint recovery is already pending for ${t.change}`);await le(n,i,{containedRoot:e.nativeRoot})}async function jb(e){let t;try{t=await Gh(e.paths,e.name)}catch(a){return{checkpoint:null,manifest:null,freshness:"stale",reasons:["checkpoint-progress-invalid"],findings:[{code:"checkpoint-progress-invalid",message:`Native progress checkpoint is invalid: ${a.message}. Automatic repair is unavailable; inspect and move the invalid checkpoint file aside before retrying`,path:qh(e.paths,e.name)}]}}if(!t)return{checkpoint:null,manifest:null,freshness:"fresh",reasons:["no-checkpoint"],findings:[]};let i=[],n=[];t.stateRevision!==e.stateRevision&&i.push("state-revision-changed");let r=null;try{r=await Uh(e.paths,e.name,t.manifestHash);let a=D(JSON.stringify({summary:t.summary,nextAction:t.nextAction,artifacts:r.artifacts}));if(t.inputHash!==a||t.artifactCount!==r.artifacts.length)throw new Error("Native progress checkpoint does not match its artifact manifest");for(let o of r.artifacts)try{let s=await Ab(e.paths,o.path);(s.hash!==o.hash||s.size!==o.size)&&i.push(`artifact-changed:${o.path}`)}catch{i.push(`artifact-unavailable:${o.path}`)}}catch(a){i.push("checkpoint-manifest-invalid"),n.push({code:"checkpoint-manifest-invalid",message:`Native checkpoint manifest is invalid: ${a.message}`,path:Vh(e.paths,e.name,t.manifestHash)})}return{checkpoint:t,manifest:r,freshness:i.length===0?"fresh":"stale",reasons:i,findings:n}}async function Ob(e){let t=(e.now??new Date).toISOString(),i=e.checkpointId?.()??a$(),n={...e.checkpoint,id:i,createdAt:t},r={schema:"comet.native.checkpoint-journal.v1",id:i,change:e.previousState.name,inputHash:n.inputHash,createdAt:t,previousState:e.previousState,nextState:e.nextState,checkpoint:n,manifest:e.manifest};return await Kh(e.paths,e.previousState.name,e.manifest),await Ib(e.paths,r),r}async function fs(e,t,i){let n=await Gi(e,t);if(!n)return null;if(await Kh(e,n.change,n.manifest)!==n.checkpoint.manifestHash)throw new Error("Native checkpoint recovery manifest hash mismatch");return await oa(e,n.nextState,n.previousState.revision,{allowPendingCheckpointRecovery:!0}),await i?.afterStateWritten?.(n),await _b(e,n.checkpoint),await i?.afterProgressWritten?.(n),await o$.rm(zi(e,t),{force:!0}),n}async function $b(e,t,i){return te(e,`continue checkpoint ${t}`,()=>De(e,t,`continue checkpoint ${t}`,async()=>(await ki(e,t),fs(e,t,i))))}async function Rt(e,t){await ki(e,t),await fs(e,t)}import{constants as Xh,promises as Mt}from"node:fs";import wr from"node:path";var s$=/^[a-f0-9]{64}$/u,c$=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,yr=512*1024;function l$(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function au(e,t){let i={...e,birthtime:e.birthtimeMs},n={...t,birthtime:t.birthtimeMs};return Ue(i,n)?M(i,n):M(i,n)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function u$(e,t){let i=wr.resolve(e),n=wr.resolve(t);if(!$(i,n))throw new Error("Native check receipt parent is outside the Native root");let r=[],a=i;for(let o of["",...wr.relative(i,n).split(wr.sep).filter(Boolean)]){o&&(a=wr.join(a,o));let s=await Mt.lstat(a);if(!s.isDirectory()||s.isSymbolicLink())throw new Error(`Native check receipt parent must be a real directory: ${a}`);let c=await Mt.realpath(a);if(r.length>0&&!$(r[0].realPath,c))throw new Error("Native check receipt parent resolves outside the Native root");r.push({path:a,realPath:c,dev:s.dev,ino:s.ino,birthtimeMs:s.birthtimeMs})}return r}async function Hb(e){for(let t of e){let i=await Mt.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!l$(t,i)||await Mt.realpath(t.path)!==t.realPath)throw new Error(`Native check receipt parent changed while reading: ${t.path}`)}}function Db(e){if(!s$.test(e))throw new Error("Native check receipt hash is invalid");return`runtime/evidence/check-receipts/${e}.json`}function d$(e){let t=c$.exec(e);if(!t)throw new Error("Native check receipt ref is invalid");return t[1]}function Mb(e,t,i){return wr.join(C(e,t),...Db(i).split("/"))}async function f$(e,t,i){let n=await u$(i,wr.dirname(e)),r=await Mt.lstat(e);if(!r.isFile()||r.isSymbolicLink())throw new Error("Native check receipt must be a regular file");if(r.size>yr)throw new Error(`Native check receipt exceeds ${yr} bytes`);let[a,o]=await Promise.all([Mt.realpath(t),Mt.realpath(e)]);if(!$(a,o))throw new Error("Native check receipt resolves outside its change");let s=process.platform==="win32"?"r":Xh.O_RDONLY|Xh.O_NOFOLLOW|Xh.O_NONBLOCK,c=await Mt.open(e,s).catch(l=>{throw l.code==="ELOOP"||l.code==="ENXIO"?new Error("Native check receipt became unsafe while opening"):l});try{let[l,u,d]=await Promise.all([c.stat(),Mt.lstat(e),Mt.realpath(e)]);if(await Hb(n),!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!au(r,l)||!au(l,u))throw new Error("Native check receipt changed while opening");let f=[],h=0,m=Buffer.allocUnsafe(16*1024);for(;;){let k=yr+1-h,N=await c.read(m,0,Math.min(m.length,k),null);if(N.bytesRead===0)break;if(h+=N.bytesRead,h>yr)throw new Error(`Native check receipt exceeds ${yr} bytes`);f.push(Buffer.from(m.subarray(0,N.bytesRead)))}let[p,v,S]=await Promise.all([c.stat(),Mt.lstat(e),Mt.realpath(e)]);if(await Hb(n),!v.isFile()||v.isSymbolicLink()||S!==o||!$(a,S)||!au(l,p)||!au(l,v))throw new Error("Native check receipt changed while reading");return JSON.parse(Buffer.concat(f,h).toString("utf8"))}finally{await c.close()}}async function ou(e,t,i){let n=d$(i),r=C(e,t),a=Mb(e,t,n);await x(e.nativeRoot,a);let o=qi(await f$(a,r,e.nativeRoot));if(o.change!==t||o.receiptHash!==n)throw new Error("Native check receipt ref/hash/change mismatch");return o}async function Fb(e){let t=qi(e.receipt);if(t.change!==e.name)throw new Error("Native check receipt change mismatch");let i=Db(t.receiptHash),n=Mb(e.paths,e.name,t.receiptHash);if(Buffer.byteLength(JSON.stringify(t,null,2)+` -`,"utf8")>yr)throw new Error(`Native check receipt exceeds ${yr} bytes`);await x(e.paths.nativeRoot,n);try{let o=await ou(e.paths,e.name,i);if(JSON.stringify(o)!==JSON.stringify(t))throw new Error(`Native check receipt hash collision for ${t.receiptHash}`);return i}catch(o){if(o.code!=="ENOENT")throw o}await le(n,t,{containedRoot:e.paths.nativeRoot});let a=await ou(e.paths,e.name,i);if(JSON.stringify(a)!==JSON.stringify(t))throw new Error("Native check receipt changed while being persisted");return i}var Ra=class extends Error{recovery;constructor(t,i){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=i}};var Zh=64*1024,v$=12e4,hs=3600*1e3,g$=4e3,w$="native-runtime:manual-evidence",Lb=m$(h$),y$=new Set([".bat",".cmd",".ps1"]),N$=["$ProgressPreference = 'SilentlyContinue'","$encoded = $env:COMET_NATIVE_COMMAND_PAYLOAD","Remove-Item Env:COMET_NATIVE_COMMAND_PAYLOAD -ErrorAction SilentlyContinue","$json = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($encoded))","$payload = ConvertFrom-Json $json","$commandArgs = @($payload.arguments)","& $payload.command @commandArgs","if ($null -eq $LASTEXITCODE) { if ($?) { exit 0 } else { exit 1 } }","exit $LASTEXITCODE"].join("; ");function b$(e){let t=(e.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";").map(i=>i.trim().toLowerCase()).filter(Boolean);return[...new Set([...t,".ps1"])]}function k$(e,t,i){let r=Si.win32.isAbsolute(e)||/[\\/]/u.test(e)?[""]:(t.PATH??"").split(Si.delimiter).map(s=>s.trim().replace(/^"(.*)"$/u,"$1")).filter(Boolean),o=Si.win32.extname(e)?[e]:b$(t).map(s=>`${e}${s}`);return r.flatMap(s=>o.map(c=>s?Si.join(s,c):Si.resolve(i,c)))}function S$(e,t,i){return k$(e,t,i).find(n=>qb(n))??e}function E$(e){let t=e.SYSTEMROOT??e.SystemRoot;if(t){let i=Si.join(t,"System32","WindowsPowerShell","v1.0","powershell.exe");if(qb(i))return i}return"powershell.exe"}function R$(e,t,i){let n=Buffer.from(JSON.stringify({command:e,arguments:[...t]}),"utf8").toString("base64"),r=Buffer.from(N$,"utf16le").toString("base64");return Qh(E$(i.env),["-NoLogo","-NoProfile","-NonInteractive","-InputFormat","None","-OutputFormat","Text","-ExecutionPolicy","Bypass","-EncodedCommand",r],{cwd:i.cwd,env:{...i.env,COMET_NATIVE_COMMAND_PAYLOAD:n},shell:!1,windowsHide:!0,detached:!1,stdio:["ignore","pipe","pipe"]})}function C$(e,t,i){if(process.platform!=="win32")return Qh(e,[...t],{cwd:i.cwd,env:i.env,shell:!1,windowsHide:!0,detached:!0,stdio:["ignore","pipe","pipe"]});let n=S$(e,i.env,i.cwd);return y$.has(Si.win32.extname(n).toLowerCase())?R$(n,t,i):Qh(n,[...t],{cwd:i.cwd,env:i.env,shell:!1,windowsHide:!0,detached:!1,stdio:["ignore","pipe","pipe"]})}async function Vb(e){return te(e.paths,e.operation,()=>De(e.paths,e.name,e.operation,async()=>(await Rt(e.paths,e.name),e.issue(await G(e.paths,e.name)))))}function P$(e,t){let i=e.trim();if(!i||Buffer.byteLength(i,"utf8")>Zh)throw new Error(`${t} is invalid`);return i}function Wb(e,t){let i=[...e].sort();if(i.length===0||new Set(i).size!==i.length||i.some(n=>!t.includes(n)))throw new Error("Native receipt acceptance IDs do not match the current contract");return i}async function Nr(e,t){if(t.phase!=="verify")throw new Error(`Native verification receipt issuance requires Verify, got ${t.phase}`);if(!t.implementation_scope)throw new Error("Native verification receipt issuance requires an implementation scope");let[i,n]=await Promise.all([yi(e,t.name,t.implementation_scope),Et({changeDir:C(e,t.name),briefRef:t.brief,specChanges:t.spec_changes})]);if(i.scope.contractHash!==n.contract.contractHash)throw new Error("Native verification receipt contract/scope mismatch");let r=t.run_id?`run:${t.run_id}`:`scope:${i.scope.scopeHash}`;return{bindings:{change:t.name,sourceRevision:t.revision,contractHash:n.contract.contractHash,scopeHash:i.scope.scopeHash,snapshotHash:i.scope.currentProjectionHash,artifactHash:Ml(i.scope.declaredArtifacts)},acceptanceIds:n.contract.acceptance.map(a=>a.id).sort(),implementationAuthor:`native-implementation:${r}`,implementationExecutionId:r,scope:i}}var x$=["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"];function ps(e,t){let i=[];for(let n of x$){let r=e.bindings[n],a=t[n];r!==a&&i.push(`${n}: expected ${JSON.stringify(a)}, got ${JSON.stringify(r)}`)}return{ok:i.length===0,mismatches:i}}function A$(e,t){return ps(e,t).ok}async function Jb(e){let t=await Nr(e.paths,e.state),i=e.checkReceipt.stale||e.checkReceipt.issues.some(o=>["scan-limit","scope-mismatch","unsafe-file","binary-skipped"].includes(o.kind)),n=e.checkReceipt.status==="passed"?"passed":i?"blocked":"failed",r=Dl({kind:"static-inspection",role:"required-check",status:n,bindings:t.bindings,acceptanceIds:[],actor:`native-runtime:${e.checkReceipt.checker.policy}`,issuedAt:e.checkReceipt.endedAt,evidence:{subjects:t.scope.scope.changes.map(o=>o.path).sort(),rule:e.checkReceipt.checker.policy,resultSummary:n==="passed"?"The built-in scoped inspection passed without skipped or blocking input.":`The built-in scoped inspection recorded ${e.checkReceipt.counts.issueCount} blocking issue(s).`,checkReceiptRef:e.checkReceiptRef,checkReceiptHash:e.checkReceipt.receiptHash}}),a=await ql({paths:e.paths,name:e.state.name,receipt:r});return{receipt:r,ref:a}}function T$(e){let{receipt:t,checkReceipt:i,context:n}=e;if(t.kind!=="static-inspection"||t.role!=="required-check"||t.status!=="passed"||!A$(t,n.bindings)||i.status!=="passed"||i.stale)return!1;let r=n.scope.scope.changes.filter(o=>o.after!==null),a=r.reduce((o,s)=>o+s.after.size,0);return i.change===n.bindings.change&&i.sourceRevision===n.bindings.sourceRevision&&i.contract.expectedHash===n.bindings.contractHash&&i.contract.beforeHash===n.bindings.contractHash&&i.contract.afterHash===n.bindings.contractHash&&i.implementation.scopeHash===n.bindings.scopeHash&&i.implementation.expectedSnapshotHash===n.bindings.snapshotHash&&i.implementation.beforeSnapshotHash===n.bindings.snapshotHash&&i.implementation.afterSnapshotHash===n.bindings.snapshotHash&&i.counts.filesSelected===r.length&&i.counts.filesScanned+i.counts.binaryFilesSkipped===r.length&&i.counts.bytesScanned===a&&i.counts.issueCount===0&&i.counts.recordedIssueCount===0&&i.issues.length===0&&!i.issuesTruncated}async function zb(e){let t=await ON(e.paths,e.state.name);if(t.length===0)return null;let i=[];for(let a of t)try{let o=await Hn(e.paths,e.state.name,a);o.kind==="static-inspection"&&o.role==="required-check"&&o.status==="passed"&&i.push({ref:a,receipt:o})}catch{}if(i.length===0)return null;let n;try{if(n=await Nr(e.paths,e.state),!(await ep({paths:e.paths,context:n})).matched)return null}catch{return null}let r=null;for(let{ref:a,receipt:o}of i)try{let s=await tp({paths:e.paths,state:e.state,receipt:o});if(s===null||!T$({receipt:o,checkReceipt:s,context:n}))continue;let c={receipt:o,ref:a,checkReceipt:s,checkReceiptRef:o.evidence.checkReceiptRef};(r===null||c.receipt.issuedAt>r.receipt.issuedAt||c.receipt.issuedAt===r.receipt.issuedAt&&c.ref>r.ref)&&(r=c)}catch{}return r}async function su(e){return Vb({paths:e.paths,name:e.name,operation:`issue manual receipt ${e.name}`,issue:t=>_$({...e,state:t})})}async function _$(e){let t=await Nr(e.paths,e.state);await cu({paths:e.paths,state:e.state,context:t});let i=Dl({kind:"manual-evidence",role:"acceptance-evidence",status:"passed",bindings:t.bindings,acceptanceIds:Wb(e.acceptanceIds,t.acceptanceIds),actor:w$,issuedAt:(e.now??new Date).toISOString(),evidence:{steps:[...e.steps],observations:[...e.observations]}});return{receipt:i,ref:await ql({paths:e.paths,name:e.state.name,receipt:i})}}function I$(e){return{schema:"comet.native.content-snapshot.v1",origin:e.origin,...e.capture?{capture:e.capture}:{},createdAt:"1970-01-01T00:00:00.000Z",complete:e.complete,limits:e.limits,...e.policy?{policy:e.policy}:{},entries:e.entries,omitted:e.omitted,omittedCount:e.omittedCount,...e.omissionOverflow?{omissionOverflow:e.omissionOverflow}:{}}}var j$=20;function O$(e,t){let i=[],n=0,r=0,a=0;for(;rs.path?1:0,l=c<=0?o:void 0,u=c>=0?s:void 0;if(c<=0&&(r+=1),c>=0&&(a+=1),l&&u&&l.hash===u.hash&&l.size===u.size)continue;let d=l?.path??u?.path;d&&(n+=1,i.length`${r.kind}: ${r.path}`).join(", ");return new Ra(`Native receipt stopped before command execution because the implementation scope changed after Build${n?` (${n}${i.changedPathsTruncated?", ...":""})`:""}. Return to Build with \`${i.nextCommand}\`, re-freeze the implementation scope, and then issue fresh receipts.`,i)}async function ep(e){let t=I$(e.context.scope.baseline),i=await Sn(e.paths,t,{origin:"explicit",now:e.now}),n=In({baseline:t,current:i,contractHash:e.context.bindings.contractHash,declaredArtifacts:e.context.scope.scope.declaredArtifacts,noCodeReason:e.context.scope.scope.noCodeReason,gitChangedPaths:e.context.scope.authority.gitChangedPaths}),r=O$(e.context.scope.current,n.current);return{expectedScopeHash:e.context.bindings.scopeHash,actualScopeHash:n.scope.scopeHash,expectedSnapshotHash:e.context.bindings.snapshotHash,actualSnapshotHash:n.scope.currentProjectionHash,matched:n.scope.currentProjectionHash===e.context.bindings.snapshotHash&&n.scope.scopeHash===e.context.bindings.scopeHash,...r}}async function cu(e){let t=e.context??await Nr(e.paths,e.state),i=await ep({paths:e.paths,context:t});if(!i.matched)throw $$(e.state.name,i);return t}async function Bb(e){try{let[{stdout:t},{stdout:i}]=await Promise.all([Lb("git",["-C",e,"rev-parse","--show-toplevel"],{windowsHide:!0,timeout:1e4}),Lb("git",["-C",e,"rev-parse","HEAD"],{windowsHide:!0,timeout:1e4})]),n=Si.resolve(t.trim()),r=Si.relative(e,n).replaceAll("\\","/");if(r===".."||r.startsWith("../")||Si.posix.isAbsolute(r))throw new Error("Git worktree is outside the Native project root");let a=i.trim().toLowerCase();if(!/^[a-f0-9]{40,64}$/u.test(a))throw new Error("Git commit identity is invalid");return{provider:"git",root:r||".",commit:a}}catch{return{provider:"none",root:".",commit:null}}}async function Ub(e){return Vb({paths:e.paths,name:e.name,operation:`issue automated receipt ${e.name}`,issue:t=>H$({...e,state:t})})}async function H$(e){let t=await Nr(e.paths,e.state);await cu({paths:e.paths,state:e.state,context:t});let i=await Bb(e.paths.projectRoot),n=(e.now?.()??new Date).toISOString(),r=e.timeoutMs??v$;if(!Number.isSafeInteger(r)||r<1||r>hs)throw new Error(`Native automated command timeout must be an integer from 1 through ${hs}`);let a=[],o=0,s=0,c=p$("sha256"),l=!1,u=C$(e.command,e.args,{cwd:e.paths.projectRoot,env:{...process.env}}),d=y=>{if(c.update(y),s+=y.byteLength,o>=Zh)return;let w=Zh-o,g=y.subarray(0,w);a.push(Buffer.from(g)),o+=g.byteLength};u.stdout.on("data",d),u.stderr.on("data",d);let f=await new Promise((y,w)=>{let g=!1,E=null,O=null,B=U=>{g||(g=!0,clearTimeout(q),O&&clearTimeout(O),y(U))},q=setTimeout(()=>{l=!0,E=Rb(u).catch(()=>{u.kill("SIGKILL"),u.stdout?.destroy(),u.stderr?.destroy()}),O=setTimeout(()=>{u.stdout?.destroy(),u.stderr?.destroy(),B({exitCode:124,signal:"SIGKILL"})},g$)},r);u.once("error",U=>{if(l){(E??Promise.resolve()).then(()=>B({exitCode:124,signal:"SIGKILL"}));return}g||(g=!0,clearTimeout(q),O&&clearTimeout(O),w(U))}),u.once("close",(U,oe)=>{(E??Promise.resolve()).then(()=>B({exitCode:l?124:U??1,signal:oe??(l?"SIGKILL":null)}))})}),h=(e.now?.()??new Date).toISOString(),[m,p]=await Promise.all([Bb(e.paths.projectRoot),ep({paths:e.paths,context:t,now:e.now?.()})]),v=t.scope.current.capture,k=(!(v?.provider==="git"||v?.provider==="physical-tree"&&v.projection?.provider==="git")||i.provider==="git")&&i.provider===m.provider&&i.root===m.root&&i.commit===m.commit,N=l||!p.matched||!k?"blocked":f.exitCode===0?"passed":"failed",b=Buffer.concat(a,o).toString("utf8").trim(),R=Dl({kind:"automated-check",role:"acceptance-evidence",status:N,bindings:t.bindings,acceptanceIds:Wb(e.acceptanceIds,t.acceptanceIds),actor:`native-runtime:command:${e.command}`,issuedAt:h,evidence:{executable:e.command,args:[...e.args],cwd:".",exitCode:f.exitCode,signal:f.signal,timedOut:l,timeoutMs:r,startedAt:n,endedAt:h,worktree:{provider:i.provider,root:i.root,beforeCommit:i.commit,afterCommit:m.commit},afterFence:{snapshotHash:p.actualSnapshotHash,scopeHash:p.actualScopeHash,matched:p.matched&&k},outputHash:c.digest("hex"),outputSummary:P$(ke(b||`(exit ${f.exitCode})`),"Native command output summary"),outputTruncated:s>o}});return{receipt:R,ref:await ql({paths:e.paths,name:e.state.name,receipt:R}),...!p.matched||!k?{recovery:Gb(e.state.name,p,!0)}:{}}}async function tp(e){if(e.receipt.kind!=="static-inspection")return null;let t=await ou(e.paths,e.state.name,e.receipt.evidence.checkReceiptRef);if(t.receiptHash!==e.receipt.evidence.checkReceiptHash)throw new Error("Native static receipt dependency hash mismatch");return t}var Ui=class extends Error{details;constructor(t){let i=t.length===0?"Native verification receipt binding is invalid":`Native verification receipt binding is invalid (${t.length} receipt(s)): ${t.map(n=>`${n.ref}${n.acceptanceId?`[${n.acceptanceId}]`:""} -> ${n.mismatches.join("; ")}`).join(" | ")}`;super(i),this.name="NativeVerificationReceiptBindingError",this.details=t}};function D$(e){return{schema:"comet.native.content-snapshot.v1",origin:e.origin,...e.capture?{capture:e.capture}:{},createdAt:"1970-01-01T00:00:00.000Z",complete:e.complete,limits:e.limits,...e.policy?{policy:e.policy}:{},entries:e.entries,omitted:e.omitted,omittedCount:e.omittedCount,...e.omissionOverflow?{omissionOverflow:e.omissionOverflow}:{}}}function M$(e){let t=Kb.relative(e.projectRoot,e.nativeRoot).replaceAll("\\","/");if(!t||t===".."||t.startsWith("../")||Kb.posix.isAbsolute(t))throw new Error("Native root is outside the project root");return t}async function F$(e){let t=D$(e.bundle.baseline),i=await Sn(e.paths,t,{origin:"explicit",now:e.now});return In({baseline:t,current:i,contractHash:e.bundle.scope.contractHash,declaredArtifacts:e.bundle.scope.declaredArtifacts,noCodeReason:e.bundle.scope.noCodeReason}).scope.currentProjectionHash}async function np(e){if(!e.state.implementation_scope)throw new Error("Native change has no implementation scope");let t=await yi(e.paths,e.state.name,e.state.implementation_scope),i=await Et({changeDir:C(e.paths,e.state.name),briefRef:e.state.brief,specChanges:e.state.spec_changes}),n=await F$({paths:e.paths,bundle:t,now:e.now}),r=[];return i.contract.contractHash!==t.scope.contractHash&&r.push("verification-contract-stale"),n!==t.scope.currentProjectionHash&&r.push("verification-implementation-stale"),{bundle:t,contract:i.contract,contractHash:i.contract.contractHash,acceptanceHash:i.contract.acceptanceHash,findingCodes:r}}async function ms(e){if(!e.state.implementation_scope)return{freshness:"missing",findingCodes:["verification-evidence-missing"]};try{let t=await np(e),i=[...new Set(t.findingCodes)].sort();return{freshness:i.length===0?"fresh":"stale",findingCodes:i}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"]}}}async function Xb(e){let t=await ye({root:C(e.paths,e.state.name),ref:e.reportRef});return{ref:t.ref,hash:t.hash,text:t.text,entries:eu(t.text)}}function L$(e){let{receipt:t,implementationScope:i}=e,n=[],r=i.scope.changes.filter(o=>o.after!==null),a=r.reduce((o,s)=>o+s.after.size,0);return(t.stale||t.sourceRevision!==e.sourceRevision||t.contract.expectedHash!==e.contractHash||t.contract.beforeHash!==e.contractHash||t.contract.afterHash!==e.contractHash||t.implementation.scopeHash!==i.scope.scopeHash||t.implementation.expectedSnapshotHash!==i.scope.currentProjectionHash||t.implementation.beforeSnapshotHash!==i.scope.currentProjectionHash||t.implementation.afterSnapshotHash!==i.scope.currentProjectionHash||t.counts.filesSelected!==r.length||t.status==="passed"&&(t.counts.filesScanned+t.counts.binaryFilesSkipped!==r.length||t.counts.bytesScanned!==a))&&n.push("verification-receipt-stale"),e.result==="pass"&&t.status!=="passed"&&n.push("verification-receipt-outcome-mismatch"),n}function B$(e){return{change:e.state.name,sourceRevision:e.sourceRevision??e.state.revision,contractHash:e.contractHash,scopeHash:e.implementationScope.scope.scopeHash,snapshotHash:e.implementationScope.scope.currentProjectionHash,artifactHash:Ml(e.implementationScope.scope.declaredArtifacts)}}async function Yb(e){let t=await Hn(e.paths,e.state.name,e.ref),i=[];t.role!==e.role&&i.push(`role: expected ${e.role}, got ${t.role}`);let n=ps(t,e.expectedBindings);if(i.push(...n.mismatches),e.acceptanceId!==void 0&&!t.acceptanceIds.includes(e.acceptanceId)&&i.push(`acceptanceId: expected ${e.acceptanceId} in [${t.acceptanceIds.join(", ")}]`),i.length>0)throw new Ui([{ref:e.ref,role:e.role,...e.acceptanceId!==void 0?{acceptanceId:e.acceptanceId}:{},mismatches:i}]);if(e.result==="pass"&&t.status!=="passed")throw new Error(`Native verification receipt is ${t.status}`);let r=await tp({paths:e.paths,state:e.state,receipt:t});if(r){let a=L$({receipt:r,sourceRevision:e.expectedBindings.sourceRevision,result:e.result,contractHash:e.contractHash,implementationScope:e.implementationScope});if(a.length>0)throw new Error(`Native static receipt dependency is invalid: ${a.join(", ")}`)}return t}async function Qb(e){let t=B$({state:e.state,contractHash:e.contractHash,implementationScope:e.implementationScope,sourceRevision:e.sourceRevision}),i=[];for(let n of e.requiredReceiptRefs){let r=await Yb({...e,ref:n,expectedBindings:t,role:"required-check"}).catch(a=>{if(a instanceof Ui)return i.push(...a.details),null;throw a});if(r!==null&&r.kind!=="static-inspection")throw new Error("Native required-check evidence must be a static-inspection receipt")}for(let n of e.trace.entries)if(n.status!=="missing")for(let r of n.evidenceRefs){let a=await Yb({...e,result:n.status==="passed"?"pass":"fail",ref:r,expectedBindings:t,acceptanceId:n.acceptanceId,role:"acceptance-evidence"}).catch(o=>{if(o instanceof Ui)return i.push(...o.details),null;throw o});if(a!==null){if(a.kind!=="automated-check"&&a.kind!=="manual-evidence")throw new Error("Native acceptance evidence must be automated-check or manual-evidence");if(n.status==="failed"&&a.status==="passed")throw new Error("Native failed acceptance evidence must reference a non-passing receipt")}}if(i.length>0)throw new Ui(i)}async function rp(e){if(e.state.phase!=="verify")throw new Error(`Native verification evidence requires Verify, got ${e.state.phase}`);let t=await np(e);if(t.findingCodes.length>0)return{ready:!1,findingCodes:t.findingCodes,envelope:null,evidenceRef:null,reportSnapshot:null};let i=e.preflight?.report??await Xb(e);if(e.result==="pass"&&!e.receiptRef&&e.requireReceipt!==!1)throw new Error("Native passing verification requires a typed required-check receipt");let n=e.receiptRef?[e.receiptRef]:[],r=e.preflight?.trace??aN(t.contract.acceptance,i.entries,{nativeRootRef:M$(e.paths),allowMissing:e.result==="fail"});if(e.result==="pass"&&r.entries.some(c=>c.status==="failed"||c.status==="missing"))throw new Error("Native passing verification cannot include failed or missing acceptance criteria");try{await Qb({paths:e.paths,state:e.state,result:e.result,trace:r,requiredReceiptRefs:n,contractHash:t.contractHash,implementationScope:t.bundle})}catch(c){if(c instanceof Ui)return{ready:!1,findingCodes:["verification-receipt-binding-mismatch"],envelope:null,evidenceRef:null,reportSnapshot:null,...c.details.length>0?{receiptBindingFailures:c.details}:{}};throw c}let a=e.state.partial_allowance?await bh(e.paths,e.state.name,e.state.partial_allowance):null;if(e.preflightOnly)return{ready:!0,findingCodes:[],envelope:null,evidenceRef:null,reportSnapshot:{hash:i.hash,text:i.text},preflight:{report:i,trace:r},preflightOnly:!0};let o=sN({change:e.state.name,sourceRevision:e.state.revision,result:e.result,contractHash:t.contractHash,acceptanceHash:t.acceptanceHash,implementationScope:{ref:e.state.implementation_scope,bundle:t.bundle},reportRef:i.ref,reportHash:i.hash,requiredReceiptRefs:n,acceptanceTrace:r,partialAllowance:e.state.partial_allowance&&a?{ref:e.state.partial_allowance,allowance:a}:null,now:e.now}),s=pt("verifications",o.envelopeHash);return{ready:!0,findingCodes:[],envelope:o,evidenceRef:s,reportSnapshot:{hash:i.hash,text:i.text},preflight:{report:i,trace:r}}}async function Zb(e){if(!e.preparation.ready||e.preparation.preflightOnly||e.preparation.envelope===null||e.preparation.evidenceRef===null||e.preparation.reportSnapshot===null)throw new Error("Native verification evidence is not ready to persist");if(await PN({paths:e.paths,name:e.state.name,...e.preparation.reportSnapshot}),await $N({paths:e.paths,name:e.state.name,evidence:e.preparation.envelope})!==e.preparation.evidenceRef)throw new Error("Native verification evidence persistence ref changed")}function ip(e,t){return{result:e,freshness:t,contractHash:null,acceptanceHash:null,implementationScopeHash:null,reportHash:null,envelopeHash:null,partialAllowanceHash:null,skippedAcceptanceCount:0}}async function br(e){if(!e.state.implementation_scope||!e.state.verification_evidence||!e.state.verification_report)return{freshness:"missing",findingCodes:["verification-evidence-missing"],evidence:ip(e.state.verification_result,"missing"),envelope:null};try{let[t,i]=await Promise.all([np(e),Dn(e.paths,e.state.name,e.state.verification_evidence)]);if(i.schema!=="comet.native.verification-evidence.v2")return{freshness:"stale",findingCodes:["verification-protocol-legacy"],evidence:ip(e.state.verification_result,"stale"),envelope:null};let n=await Xb({paths:e.paths,state:e.state,reportRef:e.state.verification_report}),r=[...t.findingCodes];(n.hash!==i.reportHash||n.ref!==i.reportRef)&&r.push("verification-report-stale"),(i.result!==e.state.verification_result||i.implementationScopeRef!==e.state.implementation_scope||i.partialAllowanceRef!==e.state.partial_allowance||i.sourceRevision>=e.state.revision||i.contractHash!==t.bundle.scope.contractHash||i.acceptanceCriteriaHash!==t.acceptanceHash)&&r.push("verification-state-mismatch");try{await Qb({paths:e.paths,state:e.state,result:i.result,trace:i.acceptanceTrace,requiredReceiptRefs:i.requiredReceiptRefs,contractHash:i.contractHash,implementationScope:t.bundle,sourceRevision:i.sourceRevision})}catch{r.push("verification-receipt-invalid")}let a=[...new Set(r)].sort(),o=a.length>0?"stale":i.freshness;return{freshness:o,findingCodes:a,evidence:{result:e.state.verification_result,freshness:o,contractHash:i.contractHash,acceptanceHash:i.acceptanceCriteriaHash,implementationScopeHash:i.implementationScopeHash,reportHash:i.reportHash,envelopeHash:i.envelopeHash,partialAllowanceHash:i.partialAllowanceHash,skippedAcceptanceCount:i.acceptanceTrace.skipped},envelope:i}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"],evidence:ip(e.state.verification_result,"invalid"),envelope:null}}}function V$(e,t){return`archive/${t.toISOString().slice(0,10)}-${e}`}async function tk(e){try{return await q$.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function W$(e,t){try{return(await ye({root:e,ref:t})).hash}catch(i){if(i.code==="ENOENT")return null;throw i}}async function J$(e,t,i){let n=Gt(e,i.capability);if(!$(e.nativeRoot,n))throw new Error(`Native canonical spec escapes its root: ${i.capability}`);let r=ek.relative(e.nativeRoot,n).replaceAll("\\","/"),a=await W$(e.nativeRoot,r),o=null;if(i.operation!=="remove"){if(!i.source)throw new Error(`Native proposed spec is missing: ${i.capability}`);o=(await ye({root:C(e,t),ref:i.source})).hash}return{capability:i.capability,operation:i.operation,expectedBaseHash:i.operation==="create"?null:i.base_hash,actualBaseHash:a,proposedHash:o}}async function z$(e,t){return tk(We(e,t))}async function kr(e){let t=e.now??new Date,i=await G(e.paths,e.name),n=await Ve(e.paths,e.name),r=await re(e.paths.projectRoot),a=V$(i.name,t),o=ek.resolve(e.paths.nativeRoot,...a.split("/"));if(!$(e.paths.nativeRoot,o))throw new Error("Native archive target escapes its root");let[s,c,l,u,d,f,h]=await Promise.all([Promise.all(i.spec_changes.map(m=>J$(e.paths,i.name,m))),br({paths:e.paths,state:i,now:t}),Vl(e.paths,i.name),lr(e.paths,i.name),aa(e.paths,i.name),z$(e.paths,i.name),tk(o)]);return Ty({change:i.name,archiveConfirmation:r?.native.archive_confirmation??"automatic",stateSchema:i.schema,revision:i.revision,phase:i.phase,archived:i.archived,pendingJournal:u||d||f,targetRef:a,targetExists:h,specs:s,evidence:c.evidence,workspace:n?.schema==="comet.native.workspace.v3"?{schema:n.schema,isolation:n.isolation,changeBranch:n.changeBranch,targetBranch:n.targetBranch,finish:n.finish}:null,findingCodes:[...c.findingCodes,...l.findingCodes]})}import{promises as ap}from"node:fs";import Ki from"node:path";var G$="comet.native.archive-tree.v1",U$={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};function rk(e){let t={...U$,...e};for(let[i,n]of Object.entries(t))if(!Number.isSafeInteger(n)||n<=0)throw new Error(`Native Archive content limit ${i} must be a positive safe integer`);return t}function ik(e){return JSON.stringify(e.map(t=>({name:t.name,kind:t.isDirectory()?"directory":t.isFile()?"file":t.isSymbolicLink()?"symlink":"other"})).sort((t,i)=>t.name.localeCompare(i.name)))}function nk(e,t,i,n){if(i.entryCount+=1,i.entryCount>n.maxEntries)throw new Error(`Native Archive content exceeds ${n.maxEntries} entries`);if(Buffer.byteLength(t.ref,"utf8")>n.maxRefBytes)throw new Error(`Native Archive content ref exceeds ${n.maxRefBytes} bytes: ${t.ref}`);let r=Buffer.byteLength(JSON.stringify(t),"utf8");if(i.manifestBytes+=r+(e.length===0?0:1),i.manifestBytes+2>n.maxManifestBytes)throw new Error(`Native Archive content manifest exceeds ${n.maxManifestBytes} bytes`);e.push(t)}async function ak(e,t,i,n,r,a){if(a>r.maxDepth)throw new Error(`Native Archive content exceeds depth ${r.maxDepth}`);let o=await st({root:e,directory:t,label:`Native Archive content directory ${Ki.relative(e,t)||"."}`,maxEntries:r.maxEntries}),s=ik(o.entries),c=[...o.entries];c.sort((u,d)=>u.name.localeCompare(d.name));for(let u of c){await o.verify();let d=Ki.join(t,u.name),f=Ki.relative(e,d).replaceAll("\\","/"),h=await ap.lstat(d);if(u.isSymbolicLink()||h.isSymbolicLink())throw new Error(`Native Archive content must not contain symlinks or junctions: ${f}`);if(u.isDirectory()&&h.isDirectory()){nk(i,{ref:f,kind:"directory"},n,r),await ak(e,d,i,n,r,a+1);continue}if(!u.isFile()||!h.isFile())throw new Error(`Native Archive content must contain only files and directories: ${f}`);let m=await ue({root:e,file:d,maxBytes:r.maxFileBytes,label:`Native Archive content file ${f}`});if(n.totalBytes+=m.size,n.totalBytes>r.maxTotalBytes)throw new Error(`Native Archive content exceeds ${r.maxTotalBytes} total file bytes`);nk(i,{ref:f,kind:"file",hash:m.hash,size:m.size},n,r),await o.verify()}await o.verify();let l=await st({root:e,directory:t,label:`Native Archive content directory ${Ki.relative(e,t)||"."}`,maxEntries:r.maxEntries});if(ik(l.entries)!==s)throw new Error(`Native Archive content directory changed while reading: ${Ki.relative(e,t)||"."}`);await Promise.all([o.verify(),l.verify()])}async function op(e,t={}){let i=rk(t);e=Ki.resolve(e);let n=await ap.lstat(e);if(!n.isDirectory()||n.isSymbolicLink())throw new Error(`Native Archive move source must be a real directory: ${e}`);let r=[];await ak(e,e,r,{entryCount:0,totalBytes:0,manifestBytes:0},i,0);let o=JSON.stringify(r);if(Buffer.byteLength(o,"utf8")>i.maxManifestBytes)throw new Error(`Native Archive content manifest exceeds ${i.maxManifestBytes} bytes`);return D(`${G$}\0${o}`)}async function ti(e,t={}){let i=rk(t);e=Ki.resolve(e);let n;try{n=await ap.lstat(e)}catch(r){if(r.code==="ENOENT")return null;throw r}if(n.isSymbolicLink())throw new Error(`Native Archive transaction path must not be a symlink or junction: ${e}`);if(n.isFile())return{kind:"file",hash:(await ue({root:Ki.dirname(e),file:e,maxBytes:i.maxFileBytes,label:`Native Archive transaction file ${Ki.basename(e)}`})).hash};if(n.isDirectory())return{kind:"directory",hash:await op(e,i)};throw new Error(`Native Archive transaction path has an unsupported file type: ${e}`)}import{promises as ze}from"node:fs";import Se from"node:path";var cp=16*1024*1024,K$=256*1024,Y$=16*1024,vs="comet.native.archive-cas.v1";function X$(e,t){let i=Se.resolve(e.nativeRoot,...t.split("/"));if(Se.relative(e.nativeRoot,i).split(Se.sep).includes(".."))throw new Error(`Unsafe Native Archive transaction ref: ${t}`);return i}async function Je(e,t){return x(e.nativeRoot,X$(e,t))}function Bn(e,t,i="file"){return t===null?e===null:e?.kind===i&&e.hash===t}function Ca(e){return e===null?"missing":`${e.kind}:${e.hash}`}async function vt(e){let t=await ti(e.target);if(!Bn(t,e.expectedHash,e.expectedKind))throw new Error(`${e.label} content changed: expected ${e.expectedHash??"missing"}, got ${Ca(t)}`);return t}async function uk(e,t){let i=_o(t),n=await Tt(e,i.id);await ze.mkdir(n.staged,{recursive:!0}),await ze.mkdir(n.backups,{recursive:!0}),await le(n.journal,i,{containedRoot:e.nativeRoot}),await Nt(e,i.id,"prepared")}async function lp(e,t){let i=await Tt(e,t),n=await ue({root:e.nativeRoot,file:i.journal,maxBytes:K$,label:`Native Archive transaction journal ${t}`}),r=_o(JSON.parse(n.bytes.toString("utf8")));if(r.id!==t)throw new Error(`Invalid Native Archive transaction journal: ${t}`);return r}async function lu(e,t,i){let n=_o({...t,status:i}),r=await Tt(e,n.id);return await le(r.journal,n,{containedRoot:e.nativeRoot}),n}function uu(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}function ok(e){return{...uu(e),ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function qn(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs}function Q$(e,t){return qn(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function ce(e){try{return await ze.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Ei(e){let t=await ze.lstat(e.file);if(!t.isFile()||t.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);let i=ok(t),n=await ue({root:e.paths.nativeRoot,file:e.file,maxBytes:cp,label:e.label}),r=await ze.lstat(e.file);if(!r.isFile()||r.isSymbolicLink()||!Q$(i,ok(r))||n.hash!==e.expectedHash)throw new Error(`${e.label} content changed or object identity changed while binding`);return{identity:uu(r),size:n.size}}function Z$(e,t,i,n){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Archive CAS ${t.id} ${i} record must be an object`);let r=e;if(Object.keys(r).sort().join(",")!=="hash,identity,operationId,role,schema")throw new Error(`Archive CAS ${t.id} ${i} record has an invalid shape`);let o=r.identity;if(!o||typeof o!="object"||Array.isArray(o))throw new Error(`Archive CAS ${t.id} ${i} identity must be an object`);let s=o;if(Object.keys(s).sort().join(",")!=="birthtimeMs,dev,ino")throw new Error(`Archive CAS ${t.id} ${i} identity has an invalid shape`);for(let c of["dev","ino","birthtimeMs"])if(typeof s[c]!="number"||!Number.isFinite(s[c])||s[c]<0)throw new Error(`Archive CAS ${t.id} ${i} identity ${c} is invalid`);if(r.schema!==vs||r.operationId!==t.id||r.role!==i||r.hash!==n)throw new Error(`Archive CAS ${t.id} ${i} record is not transaction-bound`);return{schema:vs,operationId:t.id,role:i,hash:n,identity:{dev:s.dev,ino:s.ino,birthtimeMs:s.birthtimeMs}}}async function Ri(e,t,i,n){let r=await Tt(e,t.id),a=Se.join(r.backups,".cas"),o=`.${Se.basename(n)}.comet-archive-cas-${t.id}-${i.id}`,s={directory:a,originalRecord:Se.join(a,`${i.id}.original.json`),postRecord:Se.join(a,`${i.id}.post.json`),candidate:Se.join(a,`${i.id}.candidate`),originalQuarantine:Se.join(Se.dirname(n),`${o}.original`),rollbackQuarantine:Se.join(Se.dirname(n),`${o}.rollback`)};return await Promise.all(Object.values(s).map(c=>x(e.nativeRoot,c))),s}async function Ft(e){if(!await ce(e.file))return null;let t=await ue({root:e.paths.nativeRoot,file:e.file,maxBytes:Y$,label:`Archive CAS ${e.operation.id} ${e.role} record`});return Z$(JSON.parse(t.bytes.toString("utf8")),e.operation,e.role,e.expectedHash)}async function du(e){let t=await Ft(e);if(t){if(!qn(t.identity,e.identity))throw new Error(`Archive CAS ${e.operation.id} ${e.role} object identity changed`);return t}await pi({root:e.paths.nativeRoot,directory:Se.dirname(e.file),label:`Archive CAS ${e.operation.id} records`});let i={schema:vs,operationId:e.operation.id,role:e.role,hash:e.expectedHash,identity:e.identity};try{await le(e.file,i,{containedRoot:e.paths.nativeRoot,exclusive:!0})}catch(r){if(r.code!=="EEXIST")throw r}let n=await Ft(e);if(!n||!qn(n.identity,e.identity))throw new Error(`Archive CAS ${e.operation.id} ${e.role} record changed`);return n}async function Te(e){let t=await Ei({paths:e.paths,file:e.file,expectedHash:e.record.hash,label:e.label});if(!qn(e.record.identity,t.identity))throw new Error(`${e.label} object identity changed`)}async function eH(e){let t=await Ei({paths:e.paths,file:e.file,expectedHash:e.expectedHash,label:e.label}),i=await du({paths:e.paths,file:e.recordFile,operation:e.operation,role:e.role,expectedHash:e.expectedHash,identity:t.identity});return await Te({paths:e.paths,file:e.file,operation:e.operation,record:i,label:e.label}),i}async function tH(e){if(!await ce(e.quarantine)||await ce(e.target))return;let t=await hi({root:e.paths.nativeRoot,directory:Se.dirname(e.target),label:`Archive CAS ${e.operation.id} quarantine restoration`});await t.verify();try{await ze.link(e.quarantine,e.target)}catch(r){if(r.code==="EEXIST")return;throw r}await t.verify();let[i,n]=await Promise.all([ze.lstat(e.quarantine),ze.lstat(e.target)]);if(!qn(uu(i),uu(n)))throw new Error(`Archive CAS ${e.operation.id} could not restore quarantined content`);await ze.unlink(e.quarantine),await t.verify()}async function dk(e){if(await ce(e.quarantine)){await Te({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive ${e.phase} quarantine ${e.operation.target}`});return}let t=await hi({root:e.paths.nativeRoot,directory:Se.dirname(e.target),label:`Archive ${e.phase} target ${e.operation.target}`});await Te({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive ${e.phase} target ${e.operation.target}`}),await e.hooks?.afterArchiveTargetBound?.(e.phase,e.operation,e.target),await t.verify(),await Te({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive ${e.phase} target ${e.operation.target}`});try{await ze.rename(e.target,e.quarantine),await t.verify(),await Te({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive ${e.phase} quarantine ${e.operation.target}`})}catch(i){throw await tH(e),new Error(`Archive ${e.phase} target ${e.operation.target} changed during quarantine`,{cause:i})}await e.hooks?.afterArchiveTargetQuarantined?.(e.phase,e.operation,e.quarantine)}async function Sr(e){if(!await ce(e.file))return;await Te(e);let t=await hi({root:e.paths.nativeRoot,directory:Se.dirname(e.file),label:e.label});await t.verify(),await Te(e),await ze.unlink(e.file),await t.verify()}async function sk(e,t,i){if(!t.backup||t.expectedTargetHash===null)return;let n=await Je(e,t.target),r=await Je(e,t.backup),a=await ti(r);if(a!==null){if(!Bn(a,t.expectedTargetHash))throw new Error(`Archive transaction backup content changed: ${t.backup}`);return}await vt({target:n,expectedHash:t.expectedTargetHash,label:`Archive transaction target ${t.target}`}),await Ti({sourceRoot:e.nativeRoot,source:n,targetRoot:e.nativeRoot,target:r,maxBytes:cp,label:`Archive transaction backup ${t.backup}`,expectedHash:t.expectedTargetHash,expectedTargetHash:null,exclusive:!0,hooks:{afterParentChainCaptured:()=>i?.afterProtectedCopySourceParentCaptured?.("backup",t.target)}}),await vt({target:r,expectedHash:t.expectedTargetHash,label:`Archive transaction backup ${t.backup}`})}async function fk(e){let t=e.operation.expectedTargetHash;if(t===null)throw new Error(`Archive operation ${e.operation.id} has no original target to quarantine`);let i=await Ri(e.paths,e.journal,e.operation,e.target),n=await Ft({paths:e.paths,file:i.originalRecord,operation:e.operation,role:"original",expectedHash:t});if(await ce(i.originalQuarantine)){if(!n)throw new Error(`Archive apply quarantine ${e.operation.target} has no bound object identity`);return await Te({paths:e.paths,file:i.originalQuarantine,operation:e.operation,record:n,label:`Archive apply quarantine ${e.operation.target}`}),await sk(e.paths,e.operation,e.hooks),{record:n,quarantine:i.originalQuarantine}}if(!await ce(e.target))throw new Error(`Archive apply target ${e.operation.target} disappeared before quarantine`);return n??=await eH({paths:e.paths,file:e.target,recordFile:i.originalRecord,operation:e.operation,role:"original",expectedHash:t,label:`Archive apply target ${e.operation.target}`}),await Te({paths:e.paths,file:e.target,operation:e.operation,record:n,label:`Archive apply target ${e.operation.target}`}),await sk(e.paths,e.operation,e.hooks),await dk({paths:e.paths,operation:e.operation,phase:"apply",target:e.target,quarantine:i.originalQuarantine,record:n,hooks:e.hooks}),{record:n,quarantine:i.originalQuarantine}}async function ck(e){let t=await Ri(e.paths,e.journal,e.operation,e.target);return await ce(t.candidate)?(await Ei({paths:e.paths,file:t.candidate,expectedHash:e.operation.stagedHash,label:`Archive write candidate ${e.operation.target}`}),t.candidate):(await pi({root:e.paths.nativeRoot,directory:t.directory,label:`Archive CAS ${e.operation.id} records`}),await Ti({sourceRoot:e.paths.nativeRoot,source:e.staged,targetRoot:e.paths.nativeRoot,target:t.candidate,maxBytes:cp,label:`Archive transaction staged file ${e.operation.staged}`,expectedHash:e.operation.stagedHash,expectedTargetHash:null,exclusive:!0,hooks:{afterParentChainCaptured:()=>e.hooks?.afterProtectedCopySourceParentCaptured?.("apply",e.operation.staged)}}),t.candidate)}async function iH(e){let t=e.operation.stagedHash,i=await Ri(e.paths,e.journal,e.operation,e.target),n=await Ft({paths:e.paths,file:i.postRecord,operation:e.operation,role:"post",expectedHash:t});if(n&&await ce(e.target))return await Te({paths:e.paths,file:e.target,operation:e.operation,record:n,label:`Archive write target ${e.operation.target}`}),await ce(i.candidate)&&await Sr({paths:e.paths,file:i.candidate,operation:e.operation,record:n,label:`Archive write candidate ${e.operation.target}`}),n;if(await ce(e.target)){let c=await ck(e),l=await Ei({paths:e.paths,file:c,expectedHash:t,label:`Archive write candidate ${e.operation.target}`}),u=await Ei({paths:e.paths,file:e.target,expectedHash:t,label:`Archive write target ${e.operation.target}`});if(!qn(l.identity,u.identity))throw new Error(`Archive write target ${e.operation.target} is occupied by an external object`);return n=await du({paths:e.paths,file:i.postRecord,operation:e.operation,role:"post",expectedHash:t,identity:u.identity}),await Sr({paths:e.paths,file:c,operation:e.operation,record:n,label:`Archive write candidate ${e.operation.target}`}),n}let r=await ck(e),a=await Ei({paths:e.paths,file:r,expectedHash:t,label:`Archive write candidate ${e.operation.target}`});await pi({root:e.paths.nativeRoot,directory:Se.dirname(e.target),label:`Archive write target ${e.operation.target}`});let o=await hi({root:e.paths.nativeRoot,directory:Se.dirname(e.target),label:`Archive write target ${e.operation.target}`});await e.hooks?.beforeArchiveTargetInstall?.("apply",e.operation,e.target),await o.verify(),await Te({paths:e.paths,file:r,operation:e.operation,record:{schema:vs,operationId:e.operation.id,role:"post",hash:t,identity:a.identity},label:`Archive write candidate ${e.operation.target}`});try{await ze.link(r,e.target)}catch(c){throw c.code==="EEXIST"?new Error(`Archive write target ${e.operation.target} was created before exclusive install`,{cause:c}):c}await o.verify(),await e.hooks?.afterArchiveTargetInstalled?.("apply",e.operation,e.target);let s=await Ei({paths:e.paths,file:e.target,expectedHash:t,label:`Archive write target ${e.operation.target}`});if(!qn(a.identity,s.identity))throw new Error(`Archive write target ${e.operation.target} changed during install`);return n=await du({paths:e.paths,file:i.postRecord,operation:e.operation,role:"post",expectedHash:t,identity:s.identity}),await Sr({paths:e.paths,file:r,operation:e.operation,record:n,label:`Archive write candidate ${e.operation.target}`}),n}async function nH(e,t,i,n){let r=await Je(e,i.target),a=await Je(e,i.staged);if(await vt({target:a,expectedHash:i.stagedHash,label:`Archive transaction staged file ${i.staged}`}),i.expectedTargetHash!==null){let o=await Ri(e,t,i,r);(!await Ft({paths:e,file:o.postRecord,operation:i,role:"post",expectedHash:i.stagedHash})||!await ce(r))&&await fk({paths:e,journal:t,operation:i,target:r,hooks:n})}else{let o=await ti(r);if(o!==null&&!Bn(o,i.stagedHash))throw new Error(`Archive transaction target ${i.target} changed before create: ${Ca(o)}`)}await iH({paths:e,journal:t,operation:i,staged:a,target:r,hooks:n}),await vt({target:r,expectedHash:i.stagedHash,label:`Archive transaction target ${i.target}`})}async function rH(e,t,i,n){let r=await Je(e,i.target);await fk({paths:e,journal:t,operation:i,target:r,hooks:n}),await vt({target:r,expectedHash:null,label:`Archive transaction target ${i.target}`})}async function aH(e,t){let i=await Je(e,t.source),n=await Je(e,t.target),[r,a]=await Promise.all([ti(i),ti(n)]);if(!(r===null&&Bn(a,t.expectedSourceHash,"directory"))){if(!Bn(r,t.expectedSourceHash,"directory")||a!==null)throw new Error(`Archive transaction move ${t.id} content changed: source=${Ca(r)}, target=${Ca(a)}`);await ze.mkdir(Se.dirname(n),{recursive:!0}),await ze.rename(i,n),await vt({target:n,expectedHash:t.expectedSourceHash,expectedKind:"directory",label:`Archive transaction move target ${t.target}`})}}async function oH(e,t,i,n){return i.type==="write"?nH(e,t,i,n):i.type==="remove"?rH(e,t,i,n):aH(e,i)}function sH(e){let t=0,i=!1,n=[];for(let r of e.events){if(r.type!=="operation-started"&&r.type!=="operation-completed")continue;let a=e.journal.operations[t];if(!a||r.operationId!==a.id)throw new Error(`Native Archive transaction ${e.journal.id} operation events are out of order`);if(r.type==="operation-started"){i=!0;continue}if(!i)throw new Error(`Native Archive transaction ${e.journal.id} completed an operation before it started`);n.push(a.id),t+=1,i=!1}return n}async function cH(e,t,i,n){let r=await Je(e,i.target);if(i.type==="write"){let a=await Je(e,i.staged);await vt({target:a,expectedHash:i.stagedHash,label:`Completed Archive staged file ${i.staged}`});let o=await Ri(e,t,i,r),s=await Ft({paths:e,file:o.postRecord,operation:i,role:"post",expectedHash:i.stagedHash});if(!s)throw new Error(`Completed Archive target ${i.target} has no CAS identity`);if(await Te({paths:e,file:r,operation:i,record:s,label:`Completed Archive target ${i.target}`}),i.expectedTargetHash!==null){await vt({target:await Je(e,i.backup),expectedHash:i.expectedTargetHash,label:`Completed Archive backup ${i.backup}`});let c=await Ft({paths:e,file:o.originalRecord,operation:i,role:"original",expectedHash:i.expectedTargetHash});if(!c)throw new Error(`Completed Archive target ${i.target} has no original CAS identity`);if(await ce(o.originalQuarantine))await Te({paths:e,file:o.originalQuarantine,operation:i,record:c,label:`Completed Archive original quarantine ${i.target}`});else if(!n)throw new Error(`Completed Archive original quarantine ${i.target} disappeared`)}return}if(i.type==="remove"){await vt({target:r,expectedHash:null,label:`Completed Archive target ${i.target}`}),await vt({target:await Je(e,i.backup),expectedHash:i.expectedTargetHash,label:`Completed Archive backup ${i.backup}`});let a=await Ri(e,t,i,r),o=await Ft({paths:e,file:a.originalRecord,operation:i,role:"original",expectedHash:i.expectedTargetHash});if(!o)throw new Error(`Completed Archive remove ${i.target} has no original CAS identity`);if(await ce(a.originalQuarantine))await Te({paths:e,file:a.originalQuarantine,operation:i,record:o,label:`Completed Archive original quarantine ${i.target}`});else if(!n)throw new Error(`Completed Archive original quarantine ${i.target} disappeared`);return}n||(await vt({target:await Je(e,i.source),expectedHash:null,label:`Completed Archive move source ${i.source}`}),await vt({target:r,expectedHash:i.expectedSourceHash,expectedKind:"directory",label:`Completed Archive move target ${i.target}`}))}async function hk(e,t,i){let n=t.status==="prepared"?await lu(e,t,"applying"):t;if(n.status!=="applying")throw new Error(`Native Archive transaction ${n.id} cannot apply from ${n.status}`);let r=await wn(e,n.id),a=sH({journal:n,events:r}),o=new Set(a),s=r.some(l=>l.type==="archive-finalization-started");for(let l of n.operations.slice(0,a.length))await cH(e,n,l,s);let c=o.size;for(let l of n.operations)o.has(l.id)||(l.id==="archive-change"&&await i?.beforeArchiveChangeMove?.(l),await Nt(e,n.id,"operation-started",l.id),await oH(e,n,l,i),await Nt(e,n.id,"operation-completed",l.id),c+=1,await i?.afterOperation?.(l,c));return n=await lp(e,n.id),n}async function lH(e){try{return await Te(e),!0}catch{return!1}}async function uH(e){await Te({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive rollback original quarantine ${e.operation.target}`});let t=await hi({root:e.paths.nativeRoot,directory:Se.dirname(e.target),label:`Archive rollback target ${e.operation.target}`});await e.hooks?.beforeArchiveTargetInstall?.("rollback",e.operation,e.target),await t.verify(),await Te({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive rollback original quarantine ${e.operation.target}`});try{await ze.link(e.quarantine,e.target)}catch(i){throw i.code==="EEXIST"?new Error(`Archive rollback target ${e.operation.target} was created before exclusive restore`,{cause:i}):i}await t.verify(),await e.hooks?.afterArchiveTargetInstalled?.("rollback",e.operation,e.target),await Te({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive rollback target ${e.operation.target}`})}async function sp(e){if(e.operation.type!=="write")return;let t=await Ri(e.paths,e.journal,e.operation,e.target);if(!await ce(t.candidate))return;let i=await Ei({paths:e.paths,file:t.candidate,expectedHash:e.operation.stagedHash,label:`Archive write candidate ${e.operation.target}`});await Sr({paths:e.paths,file:t.candidate,operation:e.operation,record:{schema:vs,operationId:e.operation.id,role:"post",hash:e.operation.stagedHash,identity:i.identity},label:`Archive write candidate ${e.operation.target}`})}async function dH(e,t,i,n){let r=await Je(e,i.target),a=await Ri(e,t,i,r),o=i.expectedTargetHash,s=o===null?null:await Ft({paths:e,file:a.originalRecord,operation:i,role:"original",expectedHash:o}),c=i.type==="write"?await Ft({paths:e,file:a.postRecord,operation:i,role:"post",expectedHash:i.stagedHash}):null;if(i.type==="write"&&!c&&await ce(a.candidate)&&await ce(r)){let l=await Ei({paths:e,file:a.candidate,expectedHash:i.stagedHash,label:`Archive write candidate ${i.target}`}),u=await Ei({paths:e,file:r,expectedHash:i.stagedHash,label:`Archive rollback target ${i.target}`});qn(l.identity,u.identity)&&(c=await du({paths:e,file:a.postRecord,operation:i,role:"post",expectedHash:i.stagedHash,identity:u.identity}))}if(await ce(a.rollbackQuarantine)){if(!c)throw new Error(`Archive rollback quarantine ${i.target} has no CAS identity`);await Te({paths:e,file:a.rollbackQuarantine,operation:i,record:c,label:`Archive rollback quarantine ${i.target}`})}if(await ce(r)&&!(s!==null&&await lH({paths:e,file:r,operation:i,record:s,label:`Archive rollback target ${i.target}`}))){if(!c){if(!s){let u=await ti(r);if(Bn(u,o)){await sp({paths:e,journal:t,operation:i,target:r});return}}throw new Error(`Archive rollback target ${i.target} is occupied by an external object`)}await dk({paths:e,operation:i,phase:"rollback",target:r,quarantine:a.rollbackQuarantine,record:c,hooks:n})}if(o===null){if(await ce(r))throw new Error(`Archive rollback create target ${i.target} could not be removed`)}else if(!await ce(r)){if(!s||!await ce(a.originalQuarantine))throw new Error(`Archive rollback original target ${i.target} cannot be recovered safely`);await uH({paths:e,operation:i,target:r,quarantine:a.originalQuarantine,record:s,hooks:n})}s&&await ce(a.originalQuarantine)&&await Sr({paths:e,file:a.originalQuarantine,operation:i,record:s,label:`Archive rollback original quarantine ${i.target}`}),c&&await ce(a.rollbackQuarantine)&&await Sr({paths:e,file:a.rollbackQuarantine,operation:i,record:c,label:`Archive rollback quarantine ${i.target}`}),await sp({paths:e,journal:t,operation:i,target:r}),await vt({target:r,expectedHash:o,label:`Archive rollback target ${i.target}`})}async function fH(e,t){let i=await Je(e,t.source),n=await Je(e,t.target),[r,a]=await Promise.all([ti(i),ti(n)]);if(!(Bn(r,t.expectedSourceHash,"directory")&&a===null)){if(r!==null||!Bn(a,t.expectedSourceHash,"directory"))throw new Error(`Archive rollback move ${t.id} content changed: source=${Ca(r)}, target=${Ca(a)}`);await ze.mkdir(Se.dirname(i),{recursive:!0}),await ze.rename(n,i)}}async function pk(e,t,i){let n=await wn(e,t.id);if(n.some(o=>o.type==="archive-finalization-started"||o.type==="archive-finalized"))throw new Error("An archive whose finalization started can only be recovered by continuing it");let r=await lu(e,t,"rolling-back");await Nt(e,r.id,"rollback-started");let a=new Set(n.filter(o=>o.type==="operation-started"||o.type==="operation-completed").map(o=>o.operationId));for(let o of[...r.operations].reverse())a.has(o.id)&&(o.type==="move"?await fH(e,o):await dH(e,r,o,i));return await Nt(e,r.id,"rollback-completed"),r=await lu(e,r,"rolled-back"),r}async function lk(e,t,i){let n=await Je(e,i.target);if(i.type==="write"){let r=await Ri(e,t,i,n),a=await Ft({paths:e,file:r.postRecord,operation:i,role:"post",expectedHash:i.stagedHash});if(!a)throw new Error(`Archive commit target ${i.target} has no CAS identity`);await Te({paths:e,file:n,operation:i,record:a,label:`Archive commit target ${i.target}`});return}await vt({target:n,expectedHash:null,label:`Archive commit target ${i.target}`})}async function hH(e,t){for(let i of t.operations){if(i.type==="move")continue;let n=await Je(e,i.target),r=await Ri(e,t,i,n);if(await ce(r.rollbackQuarantine))throw new Error(`Archive commit found an unfinished rollback for ${i.target}`);if(await lk(e,t,i),i.expectedTargetHash!==null){let a=await Ft({paths:e,file:r.originalRecord,operation:i,role:"original",expectedHash:i.expectedTargetHash});if(!a)throw new Error(`Archive commit target ${i.target} has no original CAS identity`);await ce(r.originalQuarantine)&&await Sr({paths:e,file:r.originalQuarantine,operation:i,record:a,label:`Archive commit original quarantine ${i.target}`})}await sp({paths:e,journal:t,operation:i,target:n})}for(let i of t.operations)i.type!=="move"&&await lk(e,t,i)}async function fu(e,t,i){return i==="commit"&&await hH(e,t),await Nt(e,t.id,i),i==="commit"?lu(e,t,"committed"):t}import{randomUUID as pH}from"crypto";import{promises as gs}from"fs";import vk from"path";var up="comet.selection.v2",mH=16*1024;function ws(e){return vk.join(e,".comet","current-change.json")}function vH(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function mk(e){return e===null||typeof e=="string"}function gk(e){let t;try{t=JSON.parse(e)}catch(i){throw new Error(`current change selection contains invalid JSON: ${i instanceof Error?i.message:String(i)}`,{cause:i})}if(!vH(t))throw new Error("current change selection must be a JSON object");if(t.version===1){if(typeof t.change!="string")throw new Error("legacy current change selection change must be a string");if(t.branch!==void 0&&!mk(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:up,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==up)throw new Error(`current change selection schema must be ${up}`);if(t.workflow!=="native"&&t.workflow!=="classic")throw new Error("current change selection workflow must be native or classic");if(typeof t.change!="string")throw new Error("current change selection change must be a string");if(!mk(t.branch))throw new Error("current change selection branch must be a string or null");if(t.workflow==="native"&&t.branch!==null)throw new Error("Native current change selection branch must be null");return{selection:t,legacy:!1}}async function dp(e){let t;try{let n=ws(e),{bytes:r}=await fn(n,mH,{label:"current change selection"});t=r.toString("utf8")}catch(n){if(n.code==="ENOENT")return{status:"missing"};throw new Error(`cannot read current change selection: ${n instanceof Error?n.message:String(n)}`,{cause:n})}return{status:"selected",...gk(t)}}async function wk(e,t){let i=gk(JSON.stringify(t));if(i.legacy)throw new Error("cannot write a legacy current change selection");let n=ws(e),r=`${n}.${pH()}.tmp`;await gs.mkdir(vk.dirname(n),{recursive:!0});try{await gs.writeFile(r,`${JSON.stringify(i.selection,null,2)} -`,"utf8"),await gs.rename(r,n)}catch(a){throw await gs.rm(r,{force:!0}),a}}async function yk(e){await gs.rm(ws(e),{force:!0})}async function Nk(e,t,i){let n=await dp(e);return n.status!=="selected"||n.selection.workflow!==t||n.selection.change!==i?!1:(await yk(e),!0)}var lJ=16*1024;async function ys(e){let t=await dp(e.projectRoot);return t.status==="missing"||t.selection.workflow!=="native"?null:(zt(t.selection.change),t.selection)}function bk(e){return ws(e.projectRoot)}async function hu(e,t){return te(e,`select change ${t}`,async()=>{zt(t),await G(e,t),await wk(e.projectRoot,{schema:"comet.selection.v2",workflow:"native",change:t,branch:null})})}async function kk(e){let t=await ys(e);return t?(await G(e,t.change),t.change):null}async function Sk(e,t){return await Vr(e.projectRoot),Nk(e.projectRoot,"native",t)}var NH=16*1024*1024,Ns=class extends Error{constructor(i,n,r,a){super(`Canonical spec conflict for ${i}: expected ${n??"(missing)"}, actual ${r??"(missing)"}`);this.capability=i;this.expectedHash=n;this.actualHash=r;this.canonicalPath=a;this.name="NativeSpecConflictError"}capability;expectedHash;actualHash;canonicalPath;code="native-spec-conflict"},Pa=class extends Error{constructor(i,n=i.ready?"Native Archive preflight no longer matches the expected hash":`Native Archive preflight is blocked: ${i.findingCodes.join(", ")}`){super(n);this.preflight=i;this.name="NativeArchivePreflightError"}preflight;code="native-archive-preflight"};async function bH(e){try{return await lt(e)}catch(t){if(t.code==="ENOENT")return null;throw t}}function kH(e){if(e.phase!=="archive")throw new Error(`Native change ${e.name} is not in Archive`);if(e.verification_result!=="pass")throw new Error(`Native change ${e.name} has not passed verification`);if(!e.verification_report)throw new Error(`Native change ${e.name} has no verification report`);if(e.archived)throw new Error(`Native change ${e.name} is already archived`)}async function SH(e,t){let i=C(e,t.name),n=await ur(i,t.brief),r=await sa(i,t.verification_report),a=[...n.findings,...r.findings];if(a.length>0)throw new Error(`Native archive artifacts are invalid: ${a[0].message}`)}async function EH(e,t){let i=Gt(e,t.capability);await x(e.nativeRoot,i);let n=await bH(i),r=t.operation==="create"?null:t.base_hash;if(n!==r)throw new Ns(t.capability,r,n,i)}function RH(e,t,i){return Ci.join(e.archiveDir,`${i.toISOString().slice(0,10)}-${t}`)}async function CH(e){try{return await wH.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function PH(e){let{paths:t,state:i,now:n,transactionId:r,preflight:a}=e,o=RH(t,i.name,n);if(await CH(o))throw new Error(`Native archive target already exists: ${o}`);if(_i(t,o)!==a.targetRef)throw new Error("Native Archive target changed after preflight");let s=await Tt(t,r),c=[];for(let[u,d]of i.spec_changes.entries()){await EH(t,d);let f=Gt(t,d.capability),h=a.operations.find(b=>b.capability===d.capability&&b.operation===d.operation);if(!h)throw new Error(`Native Archive preflight has no operation for ${d.capability}`);if(d.operation!=="remove"&&h.proposedHash===null)throw new Error(`Native Archive preflight has no proposed hash for ${d.capability}`);let m=Ci.join(s.backups,"specs",d.capability,"spec.md");if(d.operation==="remove"){c.push({id:`spec-${u+1}-${d.capability}`,type:"remove",target:_i(t,f),backup:_i(t,m),expectedTargetHash:d.base_hash});continue}let p=C(t,i.name);await Py(p,d.source);let v=Ci.resolve(p,...d.source.split(/[\\/]/u)),S=Ci.join(s.staged,"specs",d.capability,"spec.md"),N=(await Ti({sourceRoot:p,source:v,targetRoot:t.nativeRoot,target:S,maxBytes:NH,label:`Native Archive proposed spec ${d.capability}`,expectedHash:h.proposedHash,expectedTargetHash:null,exclusive:!0,hooks:{afterParentChainCaptured:()=>e.hooks?.afterProtectedCopySourceParentCaptured?.("stage",d.source)}})).hash;if(N!==h.proposedHash)throw new Error(`Proposed Native spec changed after preflight: ${d.capability}`);c.push({id:`spec-${u+1}-${d.capability}`,type:"write",target:_i(t,f),staged:_i(t,S),...d.operation==="replace"?{backup:_i(t,m)}:{},expectedTargetHash:d.operation==="create"?null:d.base_hash,stagedHash:N})}let l=C(t,i.name);return c.push({id:"archive-change",type:"move",source:_i(t,l),target:_i(t,o),expectedSourceHash:await op(l),expectedTargetHash:null}),{schema:"comet.native.transaction.v2",id:r,kind:"archive",status:"prepared",change:i.name,createdAt:n.toISOString(),preflightHash:a.preflightHash,operations:c}}function fp(e,t){let i=t.operations.find(n=>n.id==="archive-change");if(!i||i.type!=="move")throw new Error(`Archive transaction ${t.id} has no archive move`);return Ci.resolve(e.nativeRoot,...i.target.split("/"))}async function Ek(e,t,i){let n=await wn(e,t.id);if(n.some(p=>p.type==="archive-finalized"))return;let r=n.some(p=>p.type==="archive-finalization-started");if(t.schema==="comet.native.transaction.v2"&&!r){let p=t.operations.find(S=>S.id==="archive-change");if(!p||p.type!=="move"||!p.expectedSourceHash)throw new Error(`Archive transaction ${t.id} has no content-bound archive move`);let v=await ti(fp(e,t));if(v?.kind!=="directory"||v.hash!==p.expectedSourceHash)throw new Error(`Native Archive content changed before finalization for transaction ${t.id}`)}let a=fp(e,t),o=Ci.join(a,je),s=await by(o);if(!t.change||s.name!==t.change)throw new Error(`Archive transaction ${t.id} change mismatch`);let c=await be(a);if(!c||c.runId!==s.run_id||c.currentStep!=="archive"&&!(c.currentStep===null&&c.status==="completed"))throw new Error(`Native archive Run state is missing or inconsistent for ${s.name}`);let l=c;if(c.currentStep==="archive"){let p=_s(mt,c,new Set,Na,void 0);if(!p.action)throw new Error(p.reason??"Native archive produced no action");l=Is(mt,p.state,{actionId:p.action.id,status:"succeeded",summary:`Archived Native change ${s.name}`},Na,void 0)}let u=D(`archive:${t.id}:${s.name}`),d=await qe(a,l.trajectoryRef),f=d.filter(p=>p.data.transactionId===t.id);if(t.schema==="comet.native.transaction.v2"&&(f.length>1||f.some(p=>p.type!=="state_transitioned")))throw new Error(`Native Archive trajectory has a transaction id collision: ${t.id}`);let h=f.find(p=>p.type==="state_transitioned"),m={previousPhase:"archive",nextPhase:null,evidenceHash:u,summary:`Archived Native change ${s.name}`,transactionId:t.id};if(h&&t.schema==="comet.native.transaction.v2"&&(!yH(h.data,m)||h.runId!==l.runId||h.timestamp!==t.createdAt||h!==d.at(-1)))throw new Error(`Native Archive trajectory event changed for transaction ${t.id}`);if(!r&&(s.archived||c.currentStep===null||f.length>0))throw new Error(`Native Archive finalization state changed before its irreversible marker: ${t.id}`);if(r||(t.schema==="comet.native.transaction.v2"?(await fu(e,t,"archive-finalization-started"),await i?.afterFinalizationStarted?.(t)):await Ur(e,t,"archive-finalization-started")),!s.archived){let p={...s,archived:!0};await Ny(o,p)}h||(h=await Fn({changeDir:a,run:l,type:"state_transitioned",data:m,...t.schema==="comet.native.transaction.v2"?{now:new Date(t.createdAt)}:{}})),await gr({changeDir:a,run:l,trajectoryOffset:h.sequence,evidenceHash:u,...t.schema==="comet.native.transaction.v2"?{now:new Date(t.createdAt)}:{}}),await rr(a,l),await Sk(e,s.name),t.schema==="comet.native.transaction.v2"?await fu(e,t,"archive-finalized"):await Ur(e,t,"archive-finalized")}async function Rk(e,t,i){if(t.schema==="comet.native.transaction.v2"){if(!(await wn(e,t.id)).some(o=>o.type==="operation-started")){let o=await kr({paths:e,name:t.change,now:new Date(t.createdAt)});if(!o.ready||o.preflightHash!==t.preflightHash)throw new Pa(o,"Native Archive facts changed before the first transaction operation")}let a=await hk(e,t,{...i,beforeArchiveChangeMove:async o=>{await i?.beforeArchiveChangeMove?.(o);let s=await G(e,t.change),c=await br({paths:e,state:s,now:new Date(t.createdAt)});if(s.phase!=="archive"||s.archived||s.verification_result!=="pass"||!["complete","partial"].includes(c.freshness)||c.findingCodes.length>0)throw new Error(`Native Archive verification freshness changed before moving ${t.change}: ${c.findingCodes.join(", ")||c.freshness}`)}});return await Ek(e,a,i),fu(e,a,"commit")}let n=await pw(e,t);return await Ek(e,n,i),Ur(e,n,"commit")}function xH(e,t){if(t.kind!=="archive")throw new Error(`Transaction ${t.id} is not an archive`);if(t.schema==="comet.native.transaction.v2"){if(!t.change)throw new Error(`Archive transaction ${t.id} has no change`);return}if(Ci.resolve(t.projectRoot)!==Ci.resolve(e.projectRoot)||Ci.resolve(t.nativeRoot)!==Ci.resolve(e.nativeRoot))throw new Error(`Transaction ${t.id} belongs to a different Native root`)}async function Ck(e){return te(e.paths,`archive ${e.name}`,()=>De(e.paths,e.name,`archive ${e.name}`,async()=>{await Rt(e.paths,e.name);let t=await di(e.paths,"archive",`archive ${e.name}`);try{if(!/^[a-f0-9]{64}$/u.test(e.expectedPreflightHash))throw new Error("Native Archive expected preflight must be a SHA-256 hash");let i=e.now??new Date,n=await kr({paths:e.paths,name:e.name,now:i});if(!n.ready||n.preflightHash!==e.expectedPreflightHash)throw new Pa(n);let r=await G(e.paths,e.name);kH(r),await SH(e.paths,r);let a=gH(),o=await PH({paths:e.paths,state:r,now:i,transactionId:a,preflight:n,hooks:e.hooks});return await uk(e.paths,o),await e.hooks?.afterPrepared?.(o),await Rk(e.paths,o,e.hooks),{archiveDir:fp(e.paths,o),transactionId:a,preflightHash:n.preflightHash}}finally{await fi(t)}}))}async function Pk(e){return te(e.paths,`recover archive ${e.transactionId}`,async()=>{let t=await di(e.paths,"archive",`recover archive ${e.transactionId}`);try{let i=await ct(e.paths,e.transactionId),n=i.schema==="comet.native.transaction.v2"?await lp(e.paths,e.transactionId):i;return xH(e.paths,n),n.status==="committed"||n.status==="rolled-back"?n:e.strategy==="continue"?Rk(e.paths,n):n.schema==="comet.native.transaction.v2"?pk(e.paths,n):ol(e.paths,n)}finally{await fi(t)}},{allowedTransactionId:e.transactionId})}var AH=/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid|progress-invalid)|transition-(?:incomplete|invalid))/u;function TH(e){return e.phase==="shape"?["summary","shared-understanding-confirmation"]:e.phase==="build"?e.approval==="confirmed"?["summary","artifact-or-no-code-reason"]:["summary","artifact-or-no-code-reason","shared-understanding-confirmation"]:e.phase==="verify"?["summary","verification-result","verification-report"]:[]}function Me(e){let i=(e.findings??[]).filter(u=>!ia(u.code)),n=i.find(u=>u.requiresUserDecision),r=i.find(u=>u.repairCommand!==null||AH.test(u.code)),a=i.find(u=>u.code==="repair-iteration-limit"||u.code==="repair-override-exhausted"),o=i.find(u=>u.code==="repair-stagnation-stop"),s=i.find(u=>u.requiredAction==="return-to-bound-working-directory"||u.requiredAction==="repair-workspace-binding"),c=[...new Set(i.map(u=>u.requiredAction))].sort();if(e.done)return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"done",action:"none",command:null,requiresUserDecision:!1,requiredInputs:[]};if(a)return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"await-user",action:"work-phase",command:null,requiresUserDecision:!0,requiredInputs:["repair-continuation-decision"]};if(n)return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"await-user",action:"work-phase",command:null,requiresUserDecision:!0,requiredInputs:c};if(o)return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"blocked",action:"repair",command:null,requiresUserDecision:!1,requiredInputs:["new-repair-hypothesis"]};if(s)return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"blocked",action:"none",command:null,requiresUserDecision:!1,requiredInputs:c};if(r)return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"blocked",action:"repair",command:r.repairCommand,requiresUserDecision:!1,requiredInputs:c};if(e.evidenceRetreat)return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"continue",action:"advance-phase",command:`comet native next ${e.state.name} --summary ""`,requiresUserDecision:!1,requiredInputs:["summary"]};if(e.state.phase==="build"&&e.state.verification_result==="fail")return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"continue",action:"work-phase",command:null,requiresUserDecision:!1,requiredInputs:["repair-verification-gaps"]};if(i.length>0)return e.state.phase==="archive"?{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"blocked",action:"none",command:null,requiresUserDecision:!1,requiredInputs:c}:c.includes("refresh-verification-receipts")?{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"continue",action:"work-phase",command:`comet native receipt refresh ${e.state.name} --apply`,requiresUserDecision:!1,requiredInputs:c}:{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"continue",action:"work-phase",command:null,requiresUserDecision:!1,requiredInputs:c};if(e.state.phase==="archive"){if(e.archiveReady&&e.archivePreflightHash){if(!/^[a-f0-9]{64}$/u.test(e.archivePreflightHash))throw new Error("Native Archive continuation preflight must be a SHA-256 hash");return e.archiveConfirmation==="required"?{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"await-user",action:"archive",command:null,requiresUserDecision:!0,requiredInputs:["archive-confirmation"]}:{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"continue",action:"archive",command:`comet native archive ${e.state.name} --expect-preflight ${e.archivePreflightHash}`,requiresUserDecision:!1,requiredInputs:[]}}return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:e.archiveReady?"continue":"blocked",action:e.archiveReady?"archive":"none",command:e.archiveReady?`comet native archive ${e.state.name} --dry-run`:null,requiresUserDecision:!1,requiredInputs:e.archiveReady?[]:["archive-readiness"]}}let l=e.state.phase==="shape"||e.state.phase==="build"&&e.state.approval!=="confirmed"?" --confirmed":"";return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"continue",action:"advance-phase",command:`comet native next ${e.state.name} --summary ""${l}`,requiresUserDecision:!1,requiredInputs:TH(e.state)}}import _H from"path";var xk=10*1024*1024,I=class extends Error{},hp=`Usage: comet native [options] +`,o),l=c===-1?a.slice(o):a.slice(o,c);if(yield{line:l,body:t===null&&!i&&n===null,index:s},s+=1,t!==null)t=$h(l,t);else if(i)pb(l)&&(i=!1);else if(n!==null)new RegExp(``,"iu").test(l)&&(n=null);else{let d=$h(l,null);if(d!==null)t=d;else{let f=l.trimStart();if(f.startsWith(""||f==="--!>"||/^<\/?[A-Za-z][^>]*>$/u.test(f)||/^<[A-Za-z][^>]*>.*<\/[A-Za-z][^>]*>$/u.test(f)||/^(?:[-*_]\s*){3,}$/u.test(f)||/^\|?(?:\s*:?-{3,}:?\s*\|)+\s*$/u.test(f)){s();continue}let h=/^\s*(?:[-*+]|\d+[.)])[ \t]+(.+)$/u.exec(l);if(h){s(),o={parts:[h[1]],context:r.map(m=>m.text)};continue}if(/^\|.*\|$/u.test(f)){s(),o={parts:[f],context:r.map(m=>m.text)},s();continue}o===null?o={parts:[f],context:r.map(m=>m.text)}:o.parts.push(f)}return s(),Fh(n,"Specification mandatory requirements")}function KO(e,t){let i=e.trim().replaceAll("\\","/");if(i.length===0||GO(i)||db.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~|[A-Za-z][A-Za-z0-9+.-]*:)/u.test(i)||i.split("/").includes(".."))throw new Error(`Acceptance evidence ${t} has an unsafe evidence ref`);let n=db.posix.normalize(i);if(n==="."||n===".."||n.startsWith("../"))throw new Error(`Acceptance evidence ${t} has an unsafe evidence ref`);if(n.split("/").some(r=>r.toLowerCase()===".git"||r.toLowerCase().startsWith(".env")))throw new Error(`Acceptance evidence ${t} references sensitive content`);if(!LO.test(n))throw new Error(`Acceptance evidence ${t} must reference a content-addressed typed receipt`);return n}function YO(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`Acceptance evidence entry ${t} must be an object`);let i=e,n=Object.keys(i).filter(r=>!FO.has(r));if(n.length>0)throw new Error(`Acceptance evidence entry ${t} has unknown field(s): ${n.join(", ")}`);return i}function wb(e){if(!Array.isArray(e))throw new Error("Native acceptance evidence block must be a JSON array");let t=new Set;return e.map((i,n)=>{let r=YO(i,n),a=r.acceptance_id;if(typeof a!="string"||!MO.test(a))throw new Error(`Acceptance evidence entry ${n} has an invalid acceptance_id`);if(t.has(a))throw new Error(`Native acceptance evidence has duplicate acceptance_id: ${a}`);if(t.add(a),!Array.isArray(r.evidence_refs))throw new Error(`Acceptance evidence ${a} requires an evidence_refs array`);let o=r.evidence_refs.map(l=>{if(typeof l!="string"||l.trim().length===0)throw new Error(`Acceptance evidence ${a} has a non-empty string requirement`);return KO(l,a)});if(new Set(o).size!==o.length)throw new Error(`Acceptance evidence ${a} has a duplicate evidence ref`);let s=r.status;if(s!=="passed"&&s!=="failed")throw new Error(`Acceptance evidence ${a} status is invalid`);let c;if(Object.prototype.hasOwnProperty.call(r,"skipped_reason")){if(typeof r.skipped_reason!="string"||r.skipped_reason.trim().length===0)throw new Error(`Acceptance evidence ${a} skipped_reason must be a non-empty string`);c=r.skipped_reason.trim()}if(s==="passed"&&o.length===0)throw new Error(`Acceptance evidence ${a} passed status requires evidence_refs`);if(s==="failed"&&o.length===0&&c===void 0)throw new Error(`Acceptance evidence ${a} failed status requires evidence_refs or a skipped_reason`);if(s==="passed"&&c!==void 0)throw new Error(`Acceptance evidence ${a} passed status has invalid fields`);return{acceptance_id:a,status:s,evidence_refs:o,...c===void 0?{}:{skipped_reason:c}}})}function eu(e){let t=zO(e);if(t.some(({line:l,body:u})=>!u&&(l===cs||l===ba)))throw new Error("Native acceptance evidence markers must be in the Markdown body");let n=t.flatMap(({line:l,body:u},d)=>u&&l===cs?[d]:[]),r=t.flatMap(({line:l,body:u},d)=>u&&l===ba?[d]:[]);if(n.length!==1||r.length!==1)throw new Error("Verification must contain exactly one Native acceptance evidence block");if(n[0]>=r[0])throw new Error("Native acceptance evidence markers are out of order");let a=t.slice(n[0]+1,r[0]).map(({line:l})=>l).join(` +`).trim();if(a.length===0)throw new Error("Native acceptance evidence block is empty");let o;try{o=JSON.parse(a)}catch(l){throw new Error(`Native acceptance evidence block is invalid JSON: ${l.message}`,{cause:l})}let s=wb(o),c=yb(s);if(a!==c)throw new Error("Native acceptance evidence block must use canonical serialization");return s}function yb(e){let t=wb([...e]).map(i=>({...i,evidence_refs:[...i.evidence_refs].sort()})).sort((i,n)=>i.acceptance_id.localeCompare(n.acceptance_id));return JSON.stringify(t,null,2)}function tu(e){return[cs,yb(e),ba].join(` +`)}import Nb from"node:path";var XO="comet.native.contract.v1",QO="comet.native.acceptance-set.v1",bb=/^[a-f0-9]{64}$/u,us={maxAcceptanceCriteria:ls.maxCriteria};function kb(e,t){let i=Nb.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(n=>{let r=n.codePointAt(0)??0;return r<=31||r===127})||Nb.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||i!==e||i==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized project-relative ref`);return e}function Sb(e){return H("comet.native.contract-content.v1",e.replace(/\r\n?/gu,` +`))}function ZO(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.capability))throw new Error(`Invalid Native contract capability: ${e.capability}`);if(e.operation!=="create"&&e.operation!=="replace"&&e.operation!=="remove")throw new Error(`Invalid Native contract operation for ${e.capability}`);if(e.operation==="remove"){if(e.source!==null||e.markdown!==null||!e.baseHash?.match(bb))throw new Error(`Remove contract ${e.capability} requires only a base hash`);return{snapshot:{capability:e.capability,operation:"remove",source:null,baseHash:e.baseHash,contentHash:null},markdown:null}}if(e.source===null||e.markdown===null)throw new Error(`${e.operation} contract ${e.capability} requires source content`);if(e.operation==="create"&&e.baseHash!==null)throw new Error(`Create contract ${e.capability} requires a null base hash`);if(e.operation==="replace"&&!e.baseHash?.match(bb))throw new Error(`Replace contract ${e.capability} requires a base hash`);let t=kb(e.source,`Contract source for ${e.capability}`);return{snapshot:{capability:e.capability,operation:e.operation,source:t,baseHash:e.baseHash,contentHash:Sb(e.markdown)},markdown:e.markdown}}function e$(e,t){return Eb(e.id,t.id)}function Eb(e,t){return et?1:0}function Rb(e){let t=kb(e.briefSource??"brief.md","Native brief source"),i=e.specs.map(ZO).sort((d,f)=>Eb(d.snapshot.capability,f.snapshot.capability)),n=i.map(({snapshot:d})=>d.capability);if(new Set(n).size!==n.length)throw new Error("Native contract contains duplicate capabilities");let r=[t,...i.flatMap(({snapshot:d})=>d.source===null?[]:[d.source])];if(new Set(r).size!==r.length)throw new Error("Native contract contains duplicate artifact sources");let a=mb(e.briefMarkdown,t,us.maxAcceptanceCriteria);for(let{snapshot:d,markdown:f}of i)f===null||d.source===null||(a.push(...vb(f,d.source,us.maxAcceptanceCriteria-a.length)),a.push(...gb(f,d.source,us.maxAcceptanceCriteria-a.length)));if(a.sort(e$),a.length===0)throw new Error("Native contract has no structured acceptance criteria");if(a.length>us.maxAcceptanceCriteria)throw new Error(`Native contract exceeds its ${us.maxAcceptanceCriteria}-criterion acceptance budget`);let o=a.map(({id:d})=>d);if(new Set(o).size!==o.length)throw new Error("Native contract contains duplicate acceptance criteria");let s={source:t,contentHash:Sb(e.briefMarkdown)},c=i.map(({snapshot:d})=>d),l=H(QO,a),u={schema:"comet.native.contract.v1",brief:s,specs:c,acceptance:a,acceptanceHash:l};return{...u,contractHash:H(XO,u)}}var Zt={maxSpecs:64,maxFileBytes:ho,maxTotalBytes:4*1024*1024};async function Et(e){if(e.specChanges.length>Zt.maxSpecs)throw new Error("Native contract exceeds its spec-count budget");let t=await ye({root:e.changeDir,ref:e.briefRef,maxBytes:Zt.maxFileBytes}),i=t.size,n=[];for(let r of e.specChanges){if(r.operation==="remove"){n.push({capability:r.capability,operation:"remove",source:null,baseHash:r.base_hash,markdown:null});continue}if(!r.source)throw new Error(`Native contract ${r.capability} has no proposed spec source`);let a=await ye({root:e.changeDir,ref:r.source,maxBytes:Zt.maxFileBytes});if(i+=a.size,i>Zt.maxTotalBytes)throw new Error("Native contract exceeds its total byte budget");n.push({capability:r.capability,operation:r.operation,source:a.ref,baseHash:r.base_hash,markdown:a.text})}return{contract:Rb({briefSource:t.ref,briefMarkdown:t.text,specs:n}),sourceCount:n.filter(r=>r.source!==null).length+1,totalBytes:i}}import{execFile as h$,spawn as Qh}from"node:child_process";import{createHash as p$}from"node:crypto";import{existsSync as Vb}from"node:fs";import Si from"node:path";import{promisify as m$}from"node:util";import{spawn as t$}from"node:child_process";import Lh from"node:path";var i$=1e3,n$=2;async function Cb(e){let t=e.pid;if(t===void 0){e.kill("SIGKILL");return}if(process.platform==="win32"){let i=process.env.SystemRoot??process.env.WINDIR,n=i&&Lh.win32.isAbsolute(i)?Lh.win32.resolve(i):"C:\\Windows",r=Lh.win32.join(n,"System32","taskkill.exe"),a=()=>new Promise(o=>{let s=!1,c=null,l=null,u=(d,f=!1)=>{s||(s=!0,l&&clearTimeout(l),f&&c?.kill("SIGKILL"),o(d))};try{c=t$(r,["/pid",String(t),"/t","/f"],{stdio:"ignore",windowsHide:!0}),c.once("error",()=>u(!1)),c.once("close",d=>u(d===0)),l=setTimeout(()=>u(!1,!0),i$)}catch{u(!1)}});for(let o=0;o!n.has(o)),a=t.filter(o=>!(o in e));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`);if(a.length>0)throw new Error(`${i} is missing field(s): ${a.join(", ")}`)}function Ln(e,t,i=2e3){if(typeof e!="string"||e.length===0||e.length>i)throw new Error(`${t} must be a non-empty string of at most ${i} characters`);return e}function Pb(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Bh(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function xb(e){let t=e.trim().replaceAll("\\","/");if(t.length===0||Sa.isAbsolute(t)||/^(?:[A-Za-z]:|~|\/)/u.test(t)||t.split("/").includes(".."))throw new Error(`Checkpoint artifact must be project-relative: ${e}`);let i=Sa.posix.normalize(t);if(i==="."||i===".."||i.startsWith("../"))throw new Error(`Checkpoint artifact must name a project file: ${e}`);return i}function qh(e,t){return Sa.join(C(e,t),"runtime","checkpoints","progress.json")}function zi(e,t){return Sa.join(C(e,t),"runtime","checkpoint-journal.json")}function Vh(e,t,i){if(!Ea.test(i))throw new Error("Native checkpoint manifest hash is invalid");return Sa.join(C(e,t),"runtime","checkpoints","manifests",`${i}.json`)}function Wh(e){if(!Ea.test(e))throw new Error("Native checkpoint manifest hash is invalid");return`runtime/checkpoints/manifests/${e}.json`}async function Jh(e,t,i){let n=await ue({root:e,file:t,maxBytes:ei.maxDocumentBytes,label:i});return JSON.parse(n.bytes.toString("utf8"))}function r$(e,t){let i=iu(e,`checkpoint manifest artifact ${t}`);nu(i,["path","hash","size"],`checkpoint manifest artifact ${t}`);let n=xb(Ln(i.path,`checkpoint artifact ${t} path`,4096)),r=ci(n);if(r)throw new Error(`checkpoint artifact ${t} is excluded as sensitive (${r}): ${n}`);if(typeof i.hash!="string"||!Ea.test(i.hash))throw new Error(`checkpoint artifact ${t} hash is invalid`);return{path:n,hash:i.hash,size:Bh(i.size,`checkpoint artifact ${t} size`)}}function ru(e,t){let i=iu(e,"Native checkpoint manifest");if(nu(i,["schema","change","artifacts","totalBytes"],"Native checkpoint manifest"),i.schema!=="comet.native.checkpoint-manifest.v1")throw new Error("Native checkpoint manifest schema is invalid");if(i.change!==t)throw new Error("Native checkpoint manifest change mismatch");if(!Array.isArray(i.artifacts))throw new Error("Native checkpoint manifest artifacts must be an array");if(i.artifacts.length>ei.maxArtifacts)throw new Error("Native checkpoint manifest has too many artifacts");let n=i.artifacts.map(r$),r=[...n].sort((o,s)=>o.path.localeCompare(s.path));if(JSON.stringify(n)!==JSON.stringify(r))throw new Error("Native checkpoint manifest artifacts must be sorted");if(new Set(n.map(o=>o.path)).size!==n.length)throw new Error("Native checkpoint manifest has duplicate artifacts");let a=Bh(i.totalBytes,"checkpoint manifest totalBytes");if(n.reduce((o,s)=>o+s.size,0)!==a)throw new Error("Native checkpoint manifest totalBytes mismatch");if(a>ei.maxTotalBytes)throw new Error("Native checkpoint manifest totalBytes exceeds its budget");return{schema:"comet.native.checkpoint-manifest.v1",change:t,artifacts:n,totalBytes:a}}function ds(e){return D(JSON.stringify(ru(e,e.change)))}function zh(e,t){let i=iu(e,"Native progress checkpoint");if(nu(i,["schema","id","change","phase","previousRevision","stateRevision","summary","nextAction","inputHash","manifestHash","manifestRef","artifactCount","createdAt"],"Native progress checkpoint"),i.schema!=="comet.native.progress-checkpoint.v1")throw new Error("Native progress checkpoint schema is invalid");if(i.change!==t)throw new Error("Native checkpoint change mismatch");let n=i.phase;if(n!=="shape"&&n!=="build"&&n!=="verify"&&n!=="archive")throw new Error("Native checkpoint phase is invalid");let r=Pb(i.previousRevision,"Native checkpoint previousRevision"),a=Pb(i.stateRevision,"Native checkpoint stateRevision");if(a!==r+1)throw new Error("Native checkpoint stateRevision must increment previousRevision once");let o=Ln(i.manifestHash,"Native checkpoint manifestHash",64);if(!Ea.test(o))throw new Error("Native checkpoint manifestHash is invalid");let s=Wh(o);if(i.manifestRef!==s)throw new Error("Native checkpoint manifestRef does not match manifestHash");let c=Ln(i.inputHash,"Native checkpoint inputHash",64);if(!Ea.test(c))throw new Error("Native checkpoint inputHash is invalid");let l=Ln(i.createdAt,"Native checkpoint createdAt",64);if(Number.isNaN(Date.parse(l)))throw new Error("Native checkpoint createdAt is invalid");let u=Bh(i.artifactCount,"Native checkpoint artifactCount");if(u>ei.maxArtifacts)throw new Error("Native checkpoint artifactCount exceeds its budget");let d=Ln(i.summary,"Native checkpoint summary"),f=Ln(i.nextAction,"Native checkpoint nextAction");if(ke(d)!==d||ke(f)!==f)throw new Error("Native checkpoint text contains unredacted credential material");return{schema:"comet.native.progress-checkpoint.v1",id:Ln(i.id,"Native checkpoint id",128),change:t,phase:n,previousRevision:r,stateRevision:a,summary:d,nextAction:f,inputHash:c,manifestHash:o,manifestRef:s,artifactCount:u,createdAt:l}}function Ab(e,t){let i=iu(e,"Native checkpoint journal");if(nu(i,["schema","id","change","inputHash","createdAt","previousState","nextState","checkpoint","manifest"],"Native checkpoint journal"),i.schema!=="comet.native.checkpoint-journal.v1")throw new Error("Native checkpoint journal schema is invalid");if(i.change!==t)throw new Error("Native checkpoint journal change mismatch");let n=Ot(i.previousState),r=Ot(i.nextState),a=zh(i.checkpoint,t),o=ru(i.manifest,t),s=Ln(i.inputHash,"Native checkpoint journal inputHash",64),c=D(JSON.stringify({summary:a.summary,nextAction:a.nextAction,artifacts:o.artifacts}));if(!Ea.test(s)||s!==a.inputHash||s!==c||i.id!==a.id||i.createdAt!==a.createdAt)throw new Error("Native checkpoint journal envelope mismatch");if(n.name!==t||r.name!==t||r.revision!==n.revision+1||a.previousRevision!==n.revision||a.stateRevision!==r.revision||a.phase!==r.phase||a.manifestHash!==ds(o)||a.artifactCount!==o.artifacts.length)throw new Error("Native checkpoint journal state mismatch");return{schema:"comet.native.checkpoint-journal.v1",id:a.id,change:t,inputHash:s,createdAt:a.createdAt,previousState:n,nextState:r,checkpoint:a,manifest:o}}async function Tb(e,t,i){let n=Sa.resolve(e.projectRoot,...t.split("/"));if(!$(e.projectRoot,n)||$(e.nativeRoot,n))throw new Error(`Checkpoint artifact is outside project content: ${t}`);let r=fo(e,t);if(r)throw new Error(`Checkpoint artifact is excluded as sensitive (${r}): ${t}`);let a=await ue({root:e.projectRoot,file:n,maxBytes:ei.maxFileBytes,label:`Checkpoint artifact ${t}`,forbiddenRoots:[e.nativeRoot],hooks:{afterParentChainCaptured:()=>i?.afterParentChainCaptured?.(t),afterOpen:()=>i?.afterOpen?.(t),beforeRead:()=>i?.beforeRead?.(t)}});return{path:t,hash:a.hash,size:a.size}}async function _b(e,t,i,n){let r=i.map(xb).sort();if(r.length>ei.maxArtifacts)throw new Error(`Checkpoint supports at most ${ei.maxArtifacts} artifacts`);if(new Set(r).size!==r.length)throw new Error("Checkpoint artifacts must not contain duplicates");let a=[],o=0;for(let s of r){let c=await Tb(e,s,n);if(o+=c.size,o>ei.maxTotalBytes)throw new Error("Checkpoint artifacts exceed the total byte budget");a.push(c)}return{schema:"comet.native.checkpoint-manifest.v1",change:t,artifacts:a,totalBytes:o}}async function Gh(e,t){let i=qh(e,t);await x(e.nativeRoot,i);try{return zh(await Jh(e.nativeRoot,i,"Native progress checkpoint"),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Uh(e,t,i){let n=Vh(e,t,i);await x(e.nativeRoot,n);let r=await Jh(e.nativeRoot,n,"Native checkpoint manifest"),a=ru(r,t);if(Yh(e,a),ds(a)!==i)throw new Error("Native checkpoint manifest content hash mismatch");return a}async function Gi(e,t){let i=zi(e,t);await x(e.nativeRoot,i);try{let n=Ab(await Jh(e.nativeRoot,i,"Native checkpoint journal"),t);return Yh(e,n.manifest),n}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Kh(e,t,i,n){let r=ru(i,t);Yh(e,r);let a=ds(r),o=Vh(e,t,a);await x(e.nativeRoot,o);try{let s=await Uh(e,t,a);if(JSON.stringify(s)!==JSON.stringify(r))throw new Error("Native checkpoint manifest hash collision")}catch(s){if(s.code!=="ENOENT")throw s}return await le(o,r,{containedRoot:e.nativeRoot,beforeCommit:n?.beforeCommit}),a}function Yh(e,t){for(let i of t.artifacts){let n=fo(e,i.path);if(n)throw new Error(`Native checkpoint manifest contains a sensitive artifact (${n}): ${i.path}`)}}async function Ib(e,t){let i=zh(t,t.change),n=await Uh(e,i.change,i.manifestHash),r=D(JSON.stringify({summary:i.summary,nextAction:i.nextAction,artifacts:n.artifacts}));if(i.inputHash!==r||i.artifactCount!==n.artifacts.length)throw new Error("Native progress checkpoint does not match its artifact manifest");let a=qh(e,t.change);await x(e.nativeRoot,a),await le(a,i,{containedRoot:e.nativeRoot})}async function jb(e,t){let i=Ab(t,t.change),n=zi(e,t.change);if(await x(e.nativeRoot,n),await Gi(e,t.change))throw new Error(`Native checkpoint recovery is already pending for ${t.change}`);await le(n,i,{containedRoot:e.nativeRoot})}async function Ob(e){let t;try{t=await Gh(e.paths,e.name)}catch(a){return{checkpoint:null,manifest:null,freshness:"stale",reasons:["checkpoint-progress-invalid"],findings:[{code:"checkpoint-progress-invalid",message:`Native progress checkpoint is invalid: ${a.message}. Automatic repair is unavailable; inspect and move the invalid checkpoint file aside before retrying`,path:qh(e.paths,e.name)}]}}if(!t)return{checkpoint:null,manifest:null,freshness:"fresh",reasons:["no-checkpoint"],findings:[]};let i=[],n=[];t.stateRevision!==e.stateRevision&&i.push("state-revision-changed");let r=null;try{r=await Uh(e.paths,e.name,t.manifestHash);let a=D(JSON.stringify({summary:t.summary,nextAction:t.nextAction,artifacts:r.artifacts}));if(t.inputHash!==a||t.artifactCount!==r.artifacts.length)throw new Error("Native progress checkpoint does not match its artifact manifest");for(let o of r.artifacts)try{let s=await Tb(e.paths,o.path);(s.hash!==o.hash||s.size!==o.size)&&i.push(`artifact-changed:${o.path}`)}catch{i.push(`artifact-unavailable:${o.path}`)}}catch(a){i.push("checkpoint-manifest-invalid"),n.push({code:"checkpoint-manifest-invalid",message:`Native checkpoint manifest is invalid: ${a.message}`,path:Vh(e.paths,e.name,t.manifestHash)})}return{checkpoint:t,manifest:r,freshness:i.length===0?"fresh":"stale",reasons:i,findings:n}}async function $b(e){let t=(e.now??new Date).toISOString(),i=e.checkpointId?.()??a$(),n={...e.checkpoint,id:i,createdAt:t},r={schema:"comet.native.checkpoint-journal.v1",id:i,change:e.previousState.name,inputHash:n.inputHash,createdAt:t,previousState:e.previousState,nextState:e.nextState,checkpoint:n,manifest:e.manifest};return await Kh(e.paths,e.previousState.name,e.manifest),await jb(e.paths,r),r}async function fs(e,t,i){let n=await Gi(e,t);if(!n)return null;if(await Kh(e,n.change,n.manifest)!==n.checkpoint.manifestHash)throw new Error("Native checkpoint recovery manifest hash mismatch");return await oa(e,n.nextState,n.previousState.revision,{allowPendingCheckpointRecovery:!0}),await i?.afterStateWritten?.(n),await Ib(e,n.checkpoint),await i?.afterProgressWritten?.(n),await o$.rm(zi(e,t),{force:!0}),n}async function Hb(e,t,i){return te(e,`continue checkpoint ${t}`,()=>De(e,t,`continue checkpoint ${t}`,async()=>(await ki(e,t),fs(e,t,i))))}async function Rt(e,t){await ki(e,t),await fs(e,t)}import{constants as Xh,promises as Mt}from"node:fs";import wr from"node:path";var s$=/^[a-f0-9]{64}$/u,c$=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,yr=512*1024;function l$(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function au(e,t){let i={...e,birthtime:e.birthtimeMs},n={...t,birthtime:t.birthtimeMs};return Ue(i,n)?M(i,n):M(i,n)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function u$(e,t){let i=wr.resolve(e),n=wr.resolve(t);if(!$(i,n))throw new Error("Native check receipt parent is outside the Native root");let r=[],a=i;for(let o of["",...wr.relative(i,n).split(wr.sep).filter(Boolean)]){o&&(a=wr.join(a,o));let s=await Mt.lstat(a);if(!s.isDirectory()||s.isSymbolicLink())throw new Error(`Native check receipt parent must be a real directory: ${a}`);let c=await Mt.realpath(a);if(r.length>0&&!$(r[0].realPath,c))throw new Error("Native check receipt parent resolves outside the Native root");r.push({path:a,realPath:c,dev:s.dev,ino:s.ino,birthtimeMs:s.birthtimeMs})}return r}async function Db(e){for(let t of e){let i=await Mt.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!l$(t,i)||await Mt.realpath(t.path)!==t.realPath)throw new Error(`Native check receipt parent changed while reading: ${t.path}`)}}function Mb(e){if(!s$.test(e))throw new Error("Native check receipt hash is invalid");return`runtime/evidence/check-receipts/${e}.json`}function d$(e){let t=c$.exec(e);if(!t)throw new Error("Native check receipt ref is invalid");return t[1]}function Fb(e,t,i){return wr.join(C(e,t),...Mb(i).split("/"))}async function f$(e,t,i){let n=await u$(i,wr.dirname(e)),r=await Mt.lstat(e);if(!r.isFile()||r.isSymbolicLink())throw new Error("Native check receipt must be a regular file");if(r.size>yr)throw new Error(`Native check receipt exceeds ${yr} bytes`);let[a,o]=await Promise.all([Mt.realpath(t),Mt.realpath(e)]);if(!$(a,o))throw new Error("Native check receipt resolves outside its change");let s=process.platform==="win32"?"r":Xh.O_RDONLY|Xh.O_NOFOLLOW|Xh.O_NONBLOCK,c=await Mt.open(e,s).catch(l=>{throw l.code==="ELOOP"||l.code==="ENXIO"?new Error("Native check receipt became unsafe while opening"):l});try{let[l,u,d]=await Promise.all([c.stat(),Mt.lstat(e),Mt.realpath(e)]);if(await Db(n),!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!au(r,l)||!au(l,u))throw new Error("Native check receipt changed while opening");let f=[],h=0,m=Buffer.allocUnsafe(16*1024);for(;;){let k=yr+1-h,N=await c.read(m,0,Math.min(m.length,k),null);if(N.bytesRead===0)break;if(h+=N.bytesRead,h>yr)throw new Error(`Native check receipt exceeds ${yr} bytes`);f.push(Buffer.from(m.subarray(0,N.bytesRead)))}let[p,v,S]=await Promise.all([c.stat(),Mt.lstat(e),Mt.realpath(e)]);if(await Db(n),!v.isFile()||v.isSymbolicLink()||S!==o||!$(a,S)||!au(l,p)||!au(l,v))throw new Error("Native check receipt changed while reading");return JSON.parse(Buffer.concat(f,h).toString("utf8"))}finally{await c.close()}}async function ou(e,t,i){let n=d$(i),r=C(e,t),a=Fb(e,t,n);await x(e.nativeRoot,a);let o=qi(await f$(a,r,e.nativeRoot));if(o.change!==t||o.receiptHash!==n)throw new Error("Native check receipt ref/hash/change mismatch");return o}async function Lb(e){let t=qi(e.receipt);if(t.change!==e.name)throw new Error("Native check receipt change mismatch");let i=Mb(t.receiptHash),n=Fb(e.paths,e.name,t.receiptHash);if(Buffer.byteLength(JSON.stringify(t,null,2)+` +`,"utf8")>yr)throw new Error(`Native check receipt exceeds ${yr} bytes`);await x(e.paths.nativeRoot,n);try{let o=await ou(e.paths,e.name,i);if(JSON.stringify(o)!==JSON.stringify(t))throw new Error(`Native check receipt hash collision for ${t.receiptHash}`);return i}catch(o){if(o.code!=="ENOENT")throw o}await le(n,t,{containedRoot:e.paths.nativeRoot});let a=await ou(e.paths,e.name,i);if(JSON.stringify(a)!==JSON.stringify(t))throw new Error("Native check receipt changed while being persisted");return i}var Ra=class extends Error{recovery;constructor(t,i){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=i}};var Zh=64*1024,v$=12e4,hs=3600*1e3,g$=4e3,w$="native-runtime:manual-evidence",Bb=m$(h$),y$=new Set([".bat",".cmd",".ps1"]),N$=["$ProgressPreference = 'SilentlyContinue'","$encoded = $env:COMET_NATIVE_COMMAND_PAYLOAD","Remove-Item Env:COMET_NATIVE_COMMAND_PAYLOAD -ErrorAction SilentlyContinue","$json = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($encoded))","$payload = ConvertFrom-Json $json","$commandArgs = @($payload.arguments)","& $payload.command @commandArgs","if ($null -eq $LASTEXITCODE) { if ($?) { exit 0 } else { exit 1 } }","exit $LASTEXITCODE"].join("; ");function b$(e){let t=(e.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";").map(i=>i.trim().toLowerCase()).filter(Boolean);return[...new Set([...t,".ps1"])]}function k$(e,t,i){let r=Si.win32.isAbsolute(e)||/[\\/]/u.test(e)?[""]:(t.PATH??"").split(Si.delimiter).map(s=>s.trim().replace(/^"(.*)"$/u,"$1")).filter(Boolean),o=Si.win32.extname(e)?[e]:b$(t).map(s=>`${e}${s}`);return r.flatMap(s=>o.map(c=>s?Si.join(s,c):Si.resolve(i,c)))}function S$(e,t,i){return k$(e,t,i).find(n=>Vb(n))??e}function E$(e){let t=e.SYSTEMROOT??e.SystemRoot;if(t){let i=Si.join(t,"System32","WindowsPowerShell","v1.0","powershell.exe");if(Vb(i))return i}return"powershell.exe"}function R$(e,t,i){let n=Buffer.from(JSON.stringify({command:e,arguments:[...t]}),"utf8").toString("base64"),r=Buffer.from(N$,"utf16le").toString("base64");return Qh(E$(i.env),["-NoLogo","-NoProfile","-NonInteractive","-InputFormat","None","-OutputFormat","Text","-ExecutionPolicy","Bypass","-EncodedCommand",r],{cwd:i.cwd,env:{...i.env,COMET_NATIVE_COMMAND_PAYLOAD:n},shell:!1,windowsHide:!0,detached:!1,stdio:["ignore","pipe","pipe"]})}function C$(e,t,i){if(process.platform!=="win32")return Qh(e,[...t],{cwd:i.cwd,env:i.env,shell:!1,windowsHide:!0,detached:!0,stdio:["ignore","pipe","pipe"]});let n=S$(e,i.env,i.cwd);return y$.has(Si.win32.extname(n).toLowerCase())?R$(n,t,i):Qh(n,[...t],{cwd:i.cwd,env:i.env,shell:!1,windowsHide:!0,detached:!1,stdio:["ignore","pipe","pipe"]})}async function Wb(e){return te(e.paths,e.operation,()=>De(e.paths,e.name,e.operation,async()=>(await Rt(e.paths,e.name),e.issue(await G(e.paths,e.name)))))}function P$(e,t){let i=e.trim();if(!i||Buffer.byteLength(i,"utf8")>Zh)throw new Error(`${t} is invalid`);return i}function Jb(e,t){let i=[...e].sort();if(i.length===0||new Set(i).size!==i.length||i.some(n=>!t.includes(n)))throw new Error("Native receipt acceptance IDs do not match the current contract");return i}async function Nr(e,t){if(t.phase!=="verify")throw new Error(`Native verification receipt issuance requires Verify, got ${t.phase}`);if(!t.implementation_scope)throw new Error("Native verification receipt issuance requires an implementation scope");let[i,n]=await Promise.all([yi(e,t.name,t.implementation_scope),Et({changeDir:C(e,t.name),briefRef:t.brief,specChanges:t.spec_changes})]);if(i.scope.contractHash!==n.contract.contractHash)throw new Error("Native verification receipt contract/scope mismatch");let r=t.run_id?`run:${t.run_id}`:`scope:${i.scope.scopeHash}`;return{bindings:{change:t.name,sourceRevision:t.revision,contractHash:n.contract.contractHash,scopeHash:i.scope.scopeHash,snapshotHash:i.scope.currentProjectionHash,artifactHash:Ml(i.scope.declaredArtifacts)},acceptanceIds:n.contract.acceptance.map(a=>a.id).sort(),implementationAuthor:`native-implementation:${r}`,implementationExecutionId:r,scope:i}}var x$=["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"];function ps(e,t){let i=[];for(let n of x$){let r=e.bindings[n],a=t[n];r!==a&&i.push(`${n}: expected ${JSON.stringify(a)}, got ${JSON.stringify(r)}`)}return{ok:i.length===0,mismatches:i}}function A$(e,t){return ps(e,t).ok}async function zb(e){let t=await Nr(e.paths,e.state),i=e.checkReceipt.stale||e.checkReceipt.issues.some(o=>["scan-limit","scope-mismatch","unsafe-file","binary-skipped"].includes(o.kind)),n=e.checkReceipt.status==="passed"?"passed":i?"blocked":"failed",r=Dl({kind:"static-inspection",role:"required-check",status:n,bindings:t.bindings,acceptanceIds:[],actor:`native-runtime:${e.checkReceipt.checker.policy}`,issuedAt:e.checkReceipt.endedAt,evidence:{subjects:t.scope.scope.changes.map(o=>o.path).sort(),rule:e.checkReceipt.checker.policy,resultSummary:n==="passed"?"The built-in scoped inspection passed without skipped or blocking input.":`The built-in scoped inspection recorded ${e.checkReceipt.counts.issueCount} blocking issue(s).`,checkReceiptRef:e.checkReceiptRef,checkReceiptHash:e.checkReceipt.receiptHash}}),a=await ql({paths:e.paths,name:e.state.name,receipt:r});return{receipt:r,ref:a}}function T$(e){let{receipt:t,checkReceipt:i,context:n}=e;if(t.kind!=="static-inspection"||t.role!=="required-check"||t.status!=="passed"||!A$(t,n.bindings)||i.status!=="passed"||i.stale)return!1;let r=n.scope.scope.changes.filter(o=>o.after!==null),a=r.reduce((o,s)=>o+s.after.size,0);return i.change===n.bindings.change&&i.sourceRevision===n.bindings.sourceRevision&&i.contract.expectedHash===n.bindings.contractHash&&i.contract.beforeHash===n.bindings.contractHash&&i.contract.afterHash===n.bindings.contractHash&&i.implementation.scopeHash===n.bindings.scopeHash&&i.implementation.expectedSnapshotHash===n.bindings.snapshotHash&&i.implementation.beforeSnapshotHash===n.bindings.snapshotHash&&i.implementation.afterSnapshotHash===n.bindings.snapshotHash&&i.counts.filesSelected===r.length&&i.counts.filesScanned+i.counts.binaryFilesSkipped===r.length&&i.counts.bytesScanned===a&&i.counts.issueCount===0&&i.counts.recordedIssueCount===0&&i.issues.length===0&&!i.issuesTruncated}async function Gb(e){let t=await $N(e.paths,e.state.name);if(t.length===0)return null;let i=[];for(let a of t)try{let o=await Hn(e.paths,e.state.name,a);o.kind==="static-inspection"&&o.role==="required-check"&&o.status==="passed"&&i.push({ref:a,receipt:o})}catch{}if(i.length===0)return null;let n;try{if(n=await Nr(e.paths,e.state),!(await ep({paths:e.paths,context:n})).matched)return null}catch{return null}let r=null;for(let{ref:a,receipt:o}of i)try{let s=await tp({paths:e.paths,state:e.state,receipt:o});if(s===null||!T$({receipt:o,checkReceipt:s,context:n}))continue;let c={receipt:o,ref:a,checkReceipt:s,checkReceiptRef:o.evidence.checkReceiptRef};(r===null||c.receipt.issuedAt>r.receipt.issuedAt||c.receipt.issuedAt===r.receipt.issuedAt&&c.ref>r.ref)&&(r=c)}catch{}return r}async function su(e){return Wb({paths:e.paths,name:e.name,operation:`issue manual receipt ${e.name}`,issue:t=>_$({...e,state:t})})}async function _$(e){let t=await Nr(e.paths,e.state);await cu({paths:e.paths,state:e.state,context:t});let i=Dl({kind:"manual-evidence",role:"acceptance-evidence",status:"passed",bindings:t.bindings,acceptanceIds:Jb(e.acceptanceIds,t.acceptanceIds),actor:w$,issuedAt:(e.now??new Date).toISOString(),evidence:{steps:[...e.steps],observations:[...e.observations]}});return{receipt:i,ref:await ql({paths:e.paths,name:e.state.name,receipt:i})}}function I$(e){return{schema:"comet.native.content-snapshot.v1",origin:e.origin,...e.capture?{capture:e.capture}:{},createdAt:"1970-01-01T00:00:00.000Z",complete:e.complete,limits:e.limits,...e.policy?{policy:e.policy}:{},entries:e.entries,omitted:e.omitted,omittedCount:e.omittedCount,...e.omissionOverflow?{omissionOverflow:e.omissionOverflow}:{}}}var j$=20;function O$(e,t){let i=[],n=0,r=0,a=0;for(;rs.path?1:0,l=c<=0?o:void 0,u=c>=0?s:void 0;if(c<=0&&(r+=1),c>=0&&(a+=1),l&&u&&l.hash===u.hash&&l.size===u.size)continue;let d=l?.path??u?.path;d&&(n+=1,i.length`${r.kind}: ${r.path}`).join(", ");return new Ra(`Native receipt stopped before command execution because the implementation scope changed after Build${n?` (${n}${i.changedPathsTruncated?", ...":""})`:""}. Return to Build with \`${i.nextCommand}\`, re-freeze the implementation scope, and then issue fresh receipts.`,i)}async function ep(e){let t=I$(e.context.scope.baseline),i=await Sn(e.paths,t,{origin:"explicit",now:e.now}),n=In({baseline:t,current:i,contractHash:e.context.bindings.contractHash,declaredArtifacts:e.context.scope.scope.declaredArtifacts,noCodeReason:e.context.scope.scope.noCodeReason,gitChangedPaths:e.context.scope.authority.gitChangedPaths}),r=O$(e.context.scope.current,n.current);return{expectedScopeHash:e.context.bindings.scopeHash,actualScopeHash:n.scope.scopeHash,expectedSnapshotHash:e.context.bindings.snapshotHash,actualSnapshotHash:n.scope.currentProjectionHash,matched:n.scope.currentProjectionHash===e.context.bindings.snapshotHash&&n.scope.scopeHash===e.context.bindings.scopeHash,...r}}async function cu(e){let t=e.context??await Nr(e.paths,e.state),i=await ep({paths:e.paths,context:t});if(!i.matched)throw $$(e.state.name,i);return t}async function qb(e){try{let[{stdout:t},{stdout:i}]=await Promise.all([Bb("git",["-C",e,"rev-parse","--show-toplevel"],{windowsHide:!0,timeout:1e4}),Bb("git",["-C",e,"rev-parse","HEAD"],{windowsHide:!0,timeout:1e4})]),n=Si.resolve(t.trim()),r=Si.relative(e,n).replaceAll("\\","/");if(r===".."||r.startsWith("../")||Si.posix.isAbsolute(r))throw new Error("Git worktree is outside the Native project root");let a=i.trim().toLowerCase();if(!/^[a-f0-9]{40,64}$/u.test(a))throw new Error("Git commit identity is invalid");return{provider:"git",root:r||".",commit:a}}catch{return{provider:"none",root:".",commit:null}}}async function Kb(e){return Wb({paths:e.paths,name:e.name,operation:`issue automated receipt ${e.name}`,issue:t=>H$({...e,state:t})})}async function H$(e){let t=await Nr(e.paths,e.state);await cu({paths:e.paths,state:e.state,context:t});let i=await qb(e.paths.projectRoot),n=(e.now?.()??new Date).toISOString(),r=e.timeoutMs??v$;if(!Number.isSafeInteger(r)||r<1||r>hs)throw new Error(`Native automated command timeout must be an integer from 1 through ${hs}`);let a=[],o=0,s=0,c=p$("sha256"),l=!1,u=C$(e.command,e.args,{cwd:e.paths.projectRoot,env:{...process.env}}),d=y=>{if(c.update(y),s+=y.byteLength,o>=Zh)return;let w=Zh-o,g=y.subarray(0,w);a.push(Buffer.from(g)),o+=g.byteLength};u.stdout.on("data",d),u.stderr.on("data",d);let f=await new Promise((y,w)=>{let g=!1,E=null,O=null,B=U=>{g||(g=!0,clearTimeout(q),O&&clearTimeout(O),y(U))},q=setTimeout(()=>{l=!0,E=Cb(u).catch(()=>{u.kill("SIGKILL"),u.stdout?.destroy(),u.stderr?.destroy()}),O=setTimeout(()=>{u.stdout?.destroy(),u.stderr?.destroy(),B({exitCode:124,signal:"SIGKILL"})},g$)},r);u.once("error",U=>{if(l){(E??Promise.resolve()).then(()=>B({exitCode:124,signal:"SIGKILL"}));return}g||(g=!0,clearTimeout(q),O&&clearTimeout(O),w(U))}),u.once("close",(U,oe)=>{(E??Promise.resolve()).then(()=>B({exitCode:l?124:U??1,signal:oe??(l?"SIGKILL":null)}))})}),h=(e.now?.()??new Date).toISOString(),[m,p]=await Promise.all([qb(e.paths.projectRoot),ep({paths:e.paths,context:t,now:e.now?.()})]),v=t.scope.current.capture,k=(!(v?.provider==="git"||v?.provider==="physical-tree"&&v.projection?.provider==="git")||i.provider==="git")&&i.provider===m.provider&&i.root===m.root&&i.commit===m.commit,N=l||!p.matched||!k?"blocked":f.exitCode===0?"passed":"failed",b=Buffer.concat(a,o).toString("utf8").trim(),R=Dl({kind:"automated-check",role:"acceptance-evidence",status:N,bindings:t.bindings,acceptanceIds:Jb(e.acceptanceIds,t.acceptanceIds),actor:`native-runtime:command:${e.command}`,issuedAt:h,evidence:{executable:e.command,args:[...e.args],cwd:".",exitCode:f.exitCode,signal:f.signal,timedOut:l,timeoutMs:r,startedAt:n,endedAt:h,worktree:{provider:i.provider,root:i.root,beforeCommit:i.commit,afterCommit:m.commit},afterFence:{snapshotHash:p.actualSnapshotHash,scopeHash:p.actualScopeHash,matched:p.matched&&k},outputHash:c.digest("hex"),outputSummary:P$(ke(b||`(exit ${f.exitCode})`),"Native command output summary"),outputTruncated:s>o}});return{receipt:R,ref:await ql({paths:e.paths,name:e.state.name,receipt:R}),...!p.matched||!k?{recovery:Ub(e.state.name,p,!0)}:{}}}async function tp(e){if(e.receipt.kind!=="static-inspection")return null;let t=await ou(e.paths,e.state.name,e.receipt.evidence.checkReceiptRef);if(t.receiptHash!==e.receipt.evidence.checkReceiptHash)throw new Error("Native static receipt dependency hash mismatch");return t}var Ui=class extends Error{details;constructor(t){let i=t.length===0?"Native verification receipt binding is invalid":`Native verification receipt binding is invalid (${t.length} receipt(s)): ${t.map(n=>`${n.ref}${n.acceptanceId?`[${n.acceptanceId}]`:""} -> ${n.mismatches.join("; ")}`).join(" | ")}`;super(i),this.name="NativeVerificationReceiptBindingError",this.details=t}};function D$(e){return{schema:"comet.native.content-snapshot.v1",origin:e.origin,...e.capture?{capture:e.capture}:{},createdAt:"1970-01-01T00:00:00.000Z",complete:e.complete,limits:e.limits,...e.policy?{policy:e.policy}:{},entries:e.entries,omitted:e.omitted,omittedCount:e.omittedCount,...e.omissionOverflow?{omissionOverflow:e.omissionOverflow}:{}}}function M$(e){let t=Yb.relative(e.projectRoot,e.nativeRoot).replaceAll("\\","/");if(!t||t===".."||t.startsWith("../")||Yb.posix.isAbsolute(t))throw new Error("Native root is outside the project root");return t}async function F$(e){let t=D$(e.bundle.baseline),i=await Sn(e.paths,t,{origin:"explicit",now:e.now});return In({baseline:t,current:i,contractHash:e.bundle.scope.contractHash,declaredArtifacts:e.bundle.scope.declaredArtifacts,noCodeReason:e.bundle.scope.noCodeReason}).scope.currentProjectionHash}async function np(e){if(!e.state.implementation_scope)throw new Error("Native change has no implementation scope");let t=await yi(e.paths,e.state.name,e.state.implementation_scope),i=await Et({changeDir:C(e.paths,e.state.name),briefRef:e.state.brief,specChanges:e.state.spec_changes}),n=await F$({paths:e.paths,bundle:t,now:e.now}),r=[];return i.contract.contractHash!==t.scope.contractHash&&r.push("verification-contract-stale"),n!==t.scope.currentProjectionHash&&r.push("verification-implementation-stale"),{bundle:t,contract:i.contract,contractHash:i.contract.contractHash,acceptanceHash:i.contract.acceptanceHash,findingCodes:r}}async function ms(e){if(!e.state.implementation_scope)return{freshness:"missing",findingCodes:["verification-evidence-missing"]};try{let t=await np(e),i=[...new Set(t.findingCodes)].sort();return{freshness:i.length===0?"fresh":"stale",findingCodes:i}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"]}}}async function Qb(e){let t=await ye({root:C(e.paths,e.state.name),ref:e.reportRef});return{ref:t.ref,hash:t.hash,text:t.text,entries:eu(t.text)}}function L$(e){let{receipt:t,implementationScope:i}=e,n=[],r=i.scope.changes.filter(o=>o.after!==null),a=r.reduce((o,s)=>o+s.after.size,0);return(t.stale||t.sourceRevision!==e.sourceRevision||t.contract.expectedHash!==e.contractHash||t.contract.beforeHash!==e.contractHash||t.contract.afterHash!==e.contractHash||t.implementation.scopeHash!==i.scope.scopeHash||t.implementation.expectedSnapshotHash!==i.scope.currentProjectionHash||t.implementation.beforeSnapshotHash!==i.scope.currentProjectionHash||t.implementation.afterSnapshotHash!==i.scope.currentProjectionHash||t.counts.filesSelected!==r.length||t.status==="passed"&&(t.counts.filesScanned+t.counts.binaryFilesSkipped!==r.length||t.counts.bytesScanned!==a))&&n.push("verification-receipt-stale"),e.result==="pass"&&t.status!=="passed"&&n.push("verification-receipt-outcome-mismatch"),n}function B$(e){return{change:e.state.name,sourceRevision:e.sourceRevision??e.state.revision,contractHash:e.contractHash,scopeHash:e.implementationScope.scope.scopeHash,snapshotHash:e.implementationScope.scope.currentProjectionHash,artifactHash:Ml(e.implementationScope.scope.declaredArtifacts)}}async function Xb(e){let t=await Hn(e.paths,e.state.name,e.ref),i=[];t.role!==e.role&&i.push(`role: expected ${e.role}, got ${t.role}`);let n=ps(t,e.expectedBindings);if(i.push(...n.mismatches),e.acceptanceId!==void 0&&!t.acceptanceIds.includes(e.acceptanceId)&&i.push(`acceptanceId: expected ${e.acceptanceId} in [${t.acceptanceIds.join(", ")}]`),i.length>0)throw new Ui([{ref:e.ref,role:e.role,...e.acceptanceId!==void 0?{acceptanceId:e.acceptanceId}:{},mismatches:i}]);if(e.result==="pass"&&t.status!=="passed")throw new Error(`Native verification receipt is ${t.status}`);let r=await tp({paths:e.paths,state:e.state,receipt:t});if(r){let a=L$({receipt:r,sourceRevision:e.expectedBindings.sourceRevision,result:e.result,contractHash:e.contractHash,implementationScope:e.implementationScope});if(a.length>0)throw new Error(`Native static receipt dependency is invalid: ${a.join(", ")}`)}return t}async function Zb(e){let t=B$({state:e.state,contractHash:e.contractHash,implementationScope:e.implementationScope,sourceRevision:e.sourceRevision}),i=[];for(let n of e.requiredReceiptRefs){let r=await Xb({...e,ref:n,expectedBindings:t,role:"required-check"}).catch(a=>{if(a instanceof Ui)return i.push(...a.details),null;throw a});if(r!==null&&r.kind!=="static-inspection")throw new Error("Native required-check evidence must be a static-inspection receipt")}for(let n of e.trace.entries)if(n.status!=="missing")for(let r of n.evidenceRefs){let a=await Xb({...e,result:n.status==="passed"?"pass":"fail",ref:r,expectedBindings:t,acceptanceId:n.acceptanceId,role:"acceptance-evidence"}).catch(o=>{if(o instanceof Ui)return i.push(...o.details),null;throw o});if(a!==null){if(a.kind!=="automated-check"&&a.kind!=="manual-evidence")throw new Error("Native acceptance evidence must be automated-check or manual-evidence");if(n.status==="failed"&&a.status==="passed")throw new Error("Native failed acceptance evidence must reference a non-passing receipt")}}if(i.length>0)throw new Ui(i)}async function rp(e){if(e.state.phase!=="verify")throw new Error(`Native verification evidence requires Verify, got ${e.state.phase}`);let t=await np(e);if(t.findingCodes.length>0)return{ready:!1,findingCodes:t.findingCodes,envelope:null,evidenceRef:null,reportSnapshot:null};let i=e.preflight?.report??await Qb(e);if(e.result==="pass"&&!e.receiptRef&&e.requireReceipt!==!1)throw new Error("Native passing verification requires a typed required-check receipt");let n=e.receiptRef?[e.receiptRef]:[],r=e.preflight?.trace??oN(t.contract.acceptance,i.entries,{nativeRootRef:M$(e.paths),allowMissing:e.result==="fail"});if(e.result==="pass"&&r.entries.some(c=>c.status==="failed"||c.status==="missing"))throw new Error("Native passing verification cannot include failed or missing acceptance criteria");try{await Zb({paths:e.paths,state:e.state,result:e.result,trace:r,requiredReceiptRefs:n,contractHash:t.contractHash,implementationScope:t.bundle})}catch(c){if(c instanceof Ui)return{ready:!1,findingCodes:["verification-receipt-binding-mismatch"],envelope:null,evidenceRef:null,reportSnapshot:null,...c.details.length>0?{receiptBindingFailures:c.details}:{}};throw c}let a=e.state.partial_allowance?await bh(e.paths,e.state.name,e.state.partial_allowance):null;if(e.preflightOnly)return{ready:!0,findingCodes:[],envelope:null,evidenceRef:null,reportSnapshot:{hash:i.hash,text:i.text},preflight:{report:i,trace:r},preflightOnly:!0};let o=cN({change:e.state.name,sourceRevision:e.state.revision,result:e.result,contractHash:t.contractHash,acceptanceHash:t.acceptanceHash,implementationScope:{ref:e.state.implementation_scope,bundle:t.bundle},reportRef:i.ref,reportHash:i.hash,requiredReceiptRefs:n,acceptanceTrace:r,partialAllowance:e.state.partial_allowance&&a?{ref:e.state.partial_allowance,allowance:a}:null,now:e.now}),s=pt("verifications",o.envelopeHash);return{ready:!0,findingCodes:[],envelope:o,evidenceRef:s,reportSnapshot:{hash:i.hash,text:i.text},preflight:{report:i,trace:r}}}async function ek(e){if(!e.preparation.ready||e.preparation.preflightOnly||e.preparation.envelope===null||e.preparation.evidenceRef===null||e.preparation.reportSnapshot===null)throw new Error("Native verification evidence is not ready to persist");if(await xN({paths:e.paths,name:e.state.name,...e.preparation.reportSnapshot}),await HN({paths:e.paths,name:e.state.name,evidence:e.preparation.envelope})!==e.preparation.evidenceRef)throw new Error("Native verification evidence persistence ref changed")}function ip(e,t){return{result:e,freshness:t,contractHash:null,acceptanceHash:null,implementationScopeHash:null,reportHash:null,envelopeHash:null,partialAllowanceHash:null,skippedAcceptanceCount:0}}async function br(e){if(!e.state.implementation_scope||!e.state.verification_evidence||!e.state.verification_report)return{freshness:"missing",findingCodes:["verification-evidence-missing"],evidence:ip(e.state.verification_result,"missing"),envelope:null};try{let[t,i]=await Promise.all([np(e),Dn(e.paths,e.state.name,e.state.verification_evidence)]);if(i.schema!=="comet.native.verification-evidence.v2")return{freshness:"stale",findingCodes:["verification-protocol-legacy"],evidence:ip(e.state.verification_result,"stale"),envelope:null};let n=await Qb({paths:e.paths,state:e.state,reportRef:e.state.verification_report}),r=[...t.findingCodes];(n.hash!==i.reportHash||n.ref!==i.reportRef)&&r.push("verification-report-stale"),(i.result!==e.state.verification_result||i.implementationScopeRef!==e.state.implementation_scope||i.partialAllowanceRef!==e.state.partial_allowance||i.sourceRevision>=e.state.revision||i.contractHash!==t.bundle.scope.contractHash||i.acceptanceCriteriaHash!==t.acceptanceHash)&&r.push("verification-state-mismatch");try{await Zb({paths:e.paths,state:e.state,result:i.result,trace:i.acceptanceTrace,requiredReceiptRefs:i.requiredReceiptRefs,contractHash:i.contractHash,implementationScope:t.bundle,sourceRevision:i.sourceRevision})}catch{r.push("verification-receipt-invalid")}let a=[...new Set(r)].sort(),o=a.length>0?"stale":i.freshness;return{freshness:o,findingCodes:a,evidence:{result:e.state.verification_result,freshness:o,contractHash:i.contractHash,acceptanceHash:i.acceptanceCriteriaHash,implementationScopeHash:i.implementationScopeHash,reportHash:i.reportHash,envelopeHash:i.envelopeHash,partialAllowanceHash:i.partialAllowanceHash,skippedAcceptanceCount:i.acceptanceTrace.skipped},envelope:i}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"],evidence:ip(e.state.verification_result,"invalid"),envelope:null}}}function V$(e,t){return`archive/${t.toISOString().slice(0,10)}-${e}`}async function ik(e){try{return await q$.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function W$(e,t){try{return(await ye({root:e,ref:t})).hash}catch(i){if(i.code==="ENOENT")return null;throw i}}async function J$(e,t,i){let n=Gt(e,i.capability);if(!$(e.nativeRoot,n))throw new Error(`Native canonical spec escapes its root: ${i.capability}`);let r=tk.relative(e.nativeRoot,n).replaceAll("\\","/"),a=await W$(e.nativeRoot,r),o=null;if(i.operation!=="remove"){if(!i.source)throw new Error(`Native proposed spec is missing: ${i.capability}`);o=(await ye({root:C(e,t),ref:i.source})).hash}return{capability:i.capability,operation:i.operation,expectedBaseHash:i.operation==="create"?null:i.base_hash,actualBaseHash:a,proposedHash:o}}async function z$(e,t){return ik(We(e,t))}async function kr(e){let t=e.now??new Date,i=await G(e.paths,e.name),n=await Ve(e.paths,e.name),r=await re(e.paths.projectRoot),a=V$(i.name,t),o=tk.resolve(e.paths.nativeRoot,...a.split("/"));if(!$(e.paths.nativeRoot,o))throw new Error("Native archive target escapes its root");let[s,c,l,u,d,f,h]=await Promise.all([Promise.all(i.spec_changes.map(m=>J$(e.paths,i.name,m))),br({paths:e.paths,state:i,now:t}),Vl(e.paths,i.name),lr(e.paths,i.name),aa(e.paths,i.name),z$(e.paths,i.name),ik(o)]);return _y({change:i.name,archiveConfirmation:r?.native.archive_confirmation??"automatic",stateSchema:i.schema,revision:i.revision,phase:i.phase,archived:i.archived,pendingJournal:u||d||f,targetRef:a,targetExists:h,specs:s,evidence:c.evidence,workspace:n?.schema==="comet.native.workspace.v3"?{schema:n.schema,isolation:n.isolation,changeBranch:n.changeBranch,targetBranch:n.targetBranch,finish:n.finish}:null,findingCodes:[...c.findingCodes,...l.findingCodes]})}import{promises as ap}from"node:fs";import Ki from"node:path";var G$="comet.native.archive-tree.v1",U$={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};function ak(e){let t={...U$,...e};for(let[i,n]of Object.entries(t))if(!Number.isSafeInteger(n)||n<=0)throw new Error(`Native Archive content limit ${i} must be a positive safe integer`);return t}function nk(e){return JSON.stringify(e.map(t=>({name:t.name,kind:t.isDirectory()?"directory":t.isFile()?"file":t.isSymbolicLink()?"symlink":"other"})).sort((t,i)=>t.name.localeCompare(i.name)))}function rk(e,t,i,n){if(i.entryCount+=1,i.entryCount>n.maxEntries)throw new Error(`Native Archive content exceeds ${n.maxEntries} entries`);if(Buffer.byteLength(t.ref,"utf8")>n.maxRefBytes)throw new Error(`Native Archive content ref exceeds ${n.maxRefBytes} bytes: ${t.ref}`);let r=Buffer.byteLength(JSON.stringify(t),"utf8");if(i.manifestBytes+=r+(e.length===0?0:1),i.manifestBytes+2>n.maxManifestBytes)throw new Error(`Native Archive content manifest exceeds ${n.maxManifestBytes} bytes`);e.push(t)}async function ok(e,t,i,n,r,a){if(a>r.maxDepth)throw new Error(`Native Archive content exceeds depth ${r.maxDepth}`);let o=await st({root:e,directory:t,label:`Native Archive content directory ${Ki.relative(e,t)||"."}`,maxEntries:r.maxEntries}),s=nk(o.entries),c=[...o.entries];c.sort((u,d)=>u.name.localeCompare(d.name));for(let u of c){await o.verify();let d=Ki.join(t,u.name),f=Ki.relative(e,d).replaceAll("\\","/"),h=await ap.lstat(d);if(u.isSymbolicLink()||h.isSymbolicLink())throw new Error(`Native Archive content must not contain symlinks or junctions: ${f}`);if(u.isDirectory()&&h.isDirectory()){rk(i,{ref:f,kind:"directory"},n,r),await ok(e,d,i,n,r,a+1);continue}if(!u.isFile()||!h.isFile())throw new Error(`Native Archive content must contain only files and directories: ${f}`);let m=await ue({root:e,file:d,maxBytes:r.maxFileBytes,label:`Native Archive content file ${f}`});if(n.totalBytes+=m.size,n.totalBytes>r.maxTotalBytes)throw new Error(`Native Archive content exceeds ${r.maxTotalBytes} total file bytes`);rk(i,{ref:f,kind:"file",hash:m.hash,size:m.size},n,r),await o.verify()}await o.verify();let l=await st({root:e,directory:t,label:`Native Archive content directory ${Ki.relative(e,t)||"."}`,maxEntries:r.maxEntries});if(nk(l.entries)!==s)throw new Error(`Native Archive content directory changed while reading: ${Ki.relative(e,t)||"."}`);await Promise.all([o.verify(),l.verify()])}async function op(e,t={}){let i=ak(t);e=Ki.resolve(e);let n=await ap.lstat(e);if(!n.isDirectory()||n.isSymbolicLink())throw new Error(`Native Archive move source must be a real directory: ${e}`);let r=[];await ok(e,e,r,{entryCount:0,totalBytes:0,manifestBytes:0},i,0);let o=JSON.stringify(r);if(Buffer.byteLength(o,"utf8")>i.maxManifestBytes)throw new Error(`Native Archive content manifest exceeds ${i.maxManifestBytes} bytes`);return D(`${G$}\0${o}`)}async function ti(e,t={}){let i=ak(t);e=Ki.resolve(e);let n;try{n=await ap.lstat(e)}catch(r){if(r.code==="ENOENT")return null;throw r}if(n.isSymbolicLink())throw new Error(`Native Archive transaction path must not be a symlink or junction: ${e}`);if(n.isFile())return{kind:"file",hash:(await ue({root:Ki.dirname(e),file:e,maxBytes:i.maxFileBytes,label:`Native Archive transaction file ${Ki.basename(e)}`})).hash};if(n.isDirectory())return{kind:"directory",hash:await op(e,i)};throw new Error(`Native Archive transaction path has an unsupported file type: ${e}`)}import{promises as ze}from"node:fs";import Se from"node:path";var cp=16*1024*1024,K$=256*1024,Y$=16*1024,vs="comet.native.archive-cas.v1";function X$(e,t){let i=Se.resolve(e.nativeRoot,...t.split("/"));if(Se.relative(e.nativeRoot,i).split(Se.sep).includes(".."))throw new Error(`Unsafe Native Archive transaction ref: ${t}`);return i}async function Je(e,t){return x(e.nativeRoot,X$(e,t))}function Bn(e,t,i="file"){return t===null?e===null:e?.kind===i&&e.hash===t}function Ca(e){return e===null?"missing":`${e.kind}:${e.hash}`}async function vt(e){let t=await ti(e.target);if(!Bn(t,e.expectedHash,e.expectedKind))throw new Error(`${e.label} content changed: expected ${e.expectedHash??"missing"}, got ${Ca(t)}`);return t}async function dk(e,t){let i=_o(t),n=await Tt(e,i.id);await ze.mkdir(n.staged,{recursive:!0}),await ze.mkdir(n.backups,{recursive:!0}),await le(n.journal,i,{containedRoot:e.nativeRoot}),await Nt(e,i.id,"prepared")}async function lp(e,t){let i=await Tt(e,t),n=await ue({root:e.nativeRoot,file:i.journal,maxBytes:K$,label:`Native Archive transaction journal ${t}`}),r=_o(JSON.parse(n.bytes.toString("utf8")));if(r.id!==t)throw new Error(`Invalid Native Archive transaction journal: ${t}`);return r}async function lu(e,t,i){let n=_o({...t,status:i}),r=await Tt(e,n.id);return await le(r.journal,n,{containedRoot:e.nativeRoot}),n}function uu(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}function sk(e){return{...uu(e),ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function qn(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs}function Q$(e,t){return qn(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function ce(e){try{return await ze.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Ei(e){let t=await ze.lstat(e.file);if(!t.isFile()||t.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);let i=sk(t),n=await ue({root:e.paths.nativeRoot,file:e.file,maxBytes:cp,label:e.label}),r=await ze.lstat(e.file);if(!r.isFile()||r.isSymbolicLink()||!Q$(i,sk(r))||n.hash!==e.expectedHash)throw new Error(`${e.label} content changed or object identity changed while binding`);return{identity:uu(r),size:n.size}}function Z$(e,t,i,n){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Archive CAS ${t.id} ${i} record must be an object`);let r=e;if(Object.keys(r).sort().join(",")!=="hash,identity,operationId,role,schema")throw new Error(`Archive CAS ${t.id} ${i} record has an invalid shape`);let o=r.identity;if(!o||typeof o!="object"||Array.isArray(o))throw new Error(`Archive CAS ${t.id} ${i} identity must be an object`);let s=o;if(Object.keys(s).sort().join(",")!=="birthtimeMs,dev,ino")throw new Error(`Archive CAS ${t.id} ${i} identity has an invalid shape`);for(let c of["dev","ino","birthtimeMs"])if(typeof s[c]!="number"||!Number.isFinite(s[c])||s[c]<0)throw new Error(`Archive CAS ${t.id} ${i} identity ${c} is invalid`);if(r.schema!==vs||r.operationId!==t.id||r.role!==i||r.hash!==n)throw new Error(`Archive CAS ${t.id} ${i} record is not transaction-bound`);return{schema:vs,operationId:t.id,role:i,hash:n,identity:{dev:s.dev,ino:s.ino,birthtimeMs:s.birthtimeMs}}}async function Ri(e,t,i,n){let r=await Tt(e,t.id),a=Se.join(r.backups,".cas"),o=`.${Se.basename(n)}.comet-archive-cas-${t.id}-${i.id}`,s={directory:a,originalRecord:Se.join(a,`${i.id}.original.json`),postRecord:Se.join(a,`${i.id}.post.json`),candidate:Se.join(a,`${i.id}.candidate`),originalQuarantine:Se.join(Se.dirname(n),`${o}.original`),rollbackQuarantine:Se.join(Se.dirname(n),`${o}.rollback`)};return await Promise.all(Object.values(s).map(c=>x(e.nativeRoot,c))),s}async function Ft(e){if(!await ce(e.file))return null;let t=await ue({root:e.paths.nativeRoot,file:e.file,maxBytes:Y$,label:`Archive CAS ${e.operation.id} ${e.role} record`});return Z$(JSON.parse(t.bytes.toString("utf8")),e.operation,e.role,e.expectedHash)}async function du(e){let t=await Ft(e);if(t){if(!qn(t.identity,e.identity))throw new Error(`Archive CAS ${e.operation.id} ${e.role} object identity changed`);return t}await pi({root:e.paths.nativeRoot,directory:Se.dirname(e.file),label:`Archive CAS ${e.operation.id} records`});let i={schema:vs,operationId:e.operation.id,role:e.role,hash:e.expectedHash,identity:e.identity};try{await le(e.file,i,{containedRoot:e.paths.nativeRoot,exclusive:!0})}catch(r){if(r.code!=="EEXIST")throw r}let n=await Ft(e);if(!n||!qn(n.identity,e.identity))throw new Error(`Archive CAS ${e.operation.id} ${e.role} record changed`);return n}async function Te(e){let t=await Ei({paths:e.paths,file:e.file,expectedHash:e.record.hash,label:e.label});if(!qn(e.record.identity,t.identity))throw new Error(`${e.label} object identity changed`)}async function eH(e){let t=await Ei({paths:e.paths,file:e.file,expectedHash:e.expectedHash,label:e.label}),i=await du({paths:e.paths,file:e.recordFile,operation:e.operation,role:e.role,expectedHash:e.expectedHash,identity:t.identity});return await Te({paths:e.paths,file:e.file,operation:e.operation,record:i,label:e.label}),i}async function tH(e){if(!await ce(e.quarantine)||await ce(e.target))return;let t=await hi({root:e.paths.nativeRoot,directory:Se.dirname(e.target),label:`Archive CAS ${e.operation.id} quarantine restoration`});await t.verify();try{await ze.link(e.quarantine,e.target)}catch(r){if(r.code==="EEXIST")return;throw r}await t.verify();let[i,n]=await Promise.all([ze.lstat(e.quarantine),ze.lstat(e.target)]);if(!qn(uu(i),uu(n)))throw new Error(`Archive CAS ${e.operation.id} could not restore quarantined content`);await ze.unlink(e.quarantine),await t.verify()}async function fk(e){if(await ce(e.quarantine)){await Te({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive ${e.phase} quarantine ${e.operation.target}`});return}let t=await hi({root:e.paths.nativeRoot,directory:Se.dirname(e.target),label:`Archive ${e.phase} target ${e.operation.target}`});await Te({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive ${e.phase} target ${e.operation.target}`}),await e.hooks?.afterArchiveTargetBound?.(e.phase,e.operation,e.target),await t.verify(),await Te({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive ${e.phase} target ${e.operation.target}`});try{await ze.rename(e.target,e.quarantine),await t.verify(),await Te({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive ${e.phase} quarantine ${e.operation.target}`})}catch(i){throw await tH(e),new Error(`Archive ${e.phase} target ${e.operation.target} changed during quarantine`,{cause:i})}await e.hooks?.afterArchiveTargetQuarantined?.(e.phase,e.operation,e.quarantine)}async function Sr(e){if(!await ce(e.file))return;await Te(e);let t=await hi({root:e.paths.nativeRoot,directory:Se.dirname(e.file),label:e.label});await t.verify(),await Te(e),await ze.unlink(e.file),await t.verify()}async function ck(e,t,i){if(!t.backup||t.expectedTargetHash===null)return;let n=await Je(e,t.target),r=await Je(e,t.backup),a=await ti(r);if(a!==null){if(!Bn(a,t.expectedTargetHash))throw new Error(`Archive transaction backup content changed: ${t.backup}`);return}await vt({target:n,expectedHash:t.expectedTargetHash,label:`Archive transaction target ${t.target}`}),await Ti({sourceRoot:e.nativeRoot,source:n,targetRoot:e.nativeRoot,target:r,maxBytes:cp,label:`Archive transaction backup ${t.backup}`,expectedHash:t.expectedTargetHash,expectedTargetHash:null,exclusive:!0,hooks:{afterParentChainCaptured:()=>i?.afterProtectedCopySourceParentCaptured?.("backup",t.target)}}),await vt({target:r,expectedHash:t.expectedTargetHash,label:`Archive transaction backup ${t.backup}`})}async function hk(e){let t=e.operation.expectedTargetHash;if(t===null)throw new Error(`Archive operation ${e.operation.id} has no original target to quarantine`);let i=await Ri(e.paths,e.journal,e.operation,e.target),n=await Ft({paths:e.paths,file:i.originalRecord,operation:e.operation,role:"original",expectedHash:t});if(await ce(i.originalQuarantine)){if(!n)throw new Error(`Archive apply quarantine ${e.operation.target} has no bound object identity`);return await Te({paths:e.paths,file:i.originalQuarantine,operation:e.operation,record:n,label:`Archive apply quarantine ${e.operation.target}`}),await ck(e.paths,e.operation,e.hooks),{record:n,quarantine:i.originalQuarantine}}if(!await ce(e.target))throw new Error(`Archive apply target ${e.operation.target} disappeared before quarantine`);return n??=await eH({paths:e.paths,file:e.target,recordFile:i.originalRecord,operation:e.operation,role:"original",expectedHash:t,label:`Archive apply target ${e.operation.target}`}),await Te({paths:e.paths,file:e.target,operation:e.operation,record:n,label:`Archive apply target ${e.operation.target}`}),await ck(e.paths,e.operation,e.hooks),await fk({paths:e.paths,operation:e.operation,phase:"apply",target:e.target,quarantine:i.originalQuarantine,record:n,hooks:e.hooks}),{record:n,quarantine:i.originalQuarantine}}async function lk(e){let t=await Ri(e.paths,e.journal,e.operation,e.target);return await ce(t.candidate)?(await Ei({paths:e.paths,file:t.candidate,expectedHash:e.operation.stagedHash,label:`Archive write candidate ${e.operation.target}`}),t.candidate):(await pi({root:e.paths.nativeRoot,directory:t.directory,label:`Archive CAS ${e.operation.id} records`}),await Ti({sourceRoot:e.paths.nativeRoot,source:e.staged,targetRoot:e.paths.nativeRoot,target:t.candidate,maxBytes:cp,label:`Archive transaction staged file ${e.operation.staged}`,expectedHash:e.operation.stagedHash,expectedTargetHash:null,exclusive:!0,hooks:{afterParentChainCaptured:()=>e.hooks?.afterProtectedCopySourceParentCaptured?.("apply",e.operation.staged)}}),t.candidate)}async function iH(e){let t=e.operation.stagedHash,i=await Ri(e.paths,e.journal,e.operation,e.target),n=await Ft({paths:e.paths,file:i.postRecord,operation:e.operation,role:"post",expectedHash:t});if(n&&await ce(e.target))return await Te({paths:e.paths,file:e.target,operation:e.operation,record:n,label:`Archive write target ${e.operation.target}`}),await ce(i.candidate)&&await Sr({paths:e.paths,file:i.candidate,operation:e.operation,record:n,label:`Archive write candidate ${e.operation.target}`}),n;if(await ce(e.target)){let c=await lk(e),l=await Ei({paths:e.paths,file:c,expectedHash:t,label:`Archive write candidate ${e.operation.target}`}),u=await Ei({paths:e.paths,file:e.target,expectedHash:t,label:`Archive write target ${e.operation.target}`});if(!qn(l.identity,u.identity))throw new Error(`Archive write target ${e.operation.target} is occupied by an external object`);return n=await du({paths:e.paths,file:i.postRecord,operation:e.operation,role:"post",expectedHash:t,identity:u.identity}),await Sr({paths:e.paths,file:c,operation:e.operation,record:n,label:`Archive write candidate ${e.operation.target}`}),n}let r=await lk(e),a=await Ei({paths:e.paths,file:r,expectedHash:t,label:`Archive write candidate ${e.operation.target}`});await pi({root:e.paths.nativeRoot,directory:Se.dirname(e.target),label:`Archive write target ${e.operation.target}`});let o=await hi({root:e.paths.nativeRoot,directory:Se.dirname(e.target),label:`Archive write target ${e.operation.target}`});await e.hooks?.beforeArchiveTargetInstall?.("apply",e.operation,e.target),await o.verify(),await Te({paths:e.paths,file:r,operation:e.operation,record:{schema:vs,operationId:e.operation.id,role:"post",hash:t,identity:a.identity},label:`Archive write candidate ${e.operation.target}`});try{await ze.link(r,e.target)}catch(c){throw c.code==="EEXIST"?new Error(`Archive write target ${e.operation.target} was created before exclusive install`,{cause:c}):c}await o.verify(),await e.hooks?.afterArchiveTargetInstalled?.("apply",e.operation,e.target);let s=await Ei({paths:e.paths,file:e.target,expectedHash:t,label:`Archive write target ${e.operation.target}`});if(!qn(a.identity,s.identity))throw new Error(`Archive write target ${e.operation.target} changed during install`);return n=await du({paths:e.paths,file:i.postRecord,operation:e.operation,role:"post",expectedHash:t,identity:s.identity}),await Sr({paths:e.paths,file:r,operation:e.operation,record:n,label:`Archive write candidate ${e.operation.target}`}),n}async function nH(e,t,i,n){let r=await Je(e,i.target),a=await Je(e,i.staged);if(await vt({target:a,expectedHash:i.stagedHash,label:`Archive transaction staged file ${i.staged}`}),i.expectedTargetHash!==null){let o=await Ri(e,t,i,r);(!await Ft({paths:e,file:o.postRecord,operation:i,role:"post",expectedHash:i.stagedHash})||!await ce(r))&&await hk({paths:e,journal:t,operation:i,target:r,hooks:n})}else{let o=await ti(r);if(o!==null&&!Bn(o,i.stagedHash))throw new Error(`Archive transaction target ${i.target} changed before create: ${Ca(o)}`)}await iH({paths:e,journal:t,operation:i,staged:a,target:r,hooks:n}),await vt({target:r,expectedHash:i.stagedHash,label:`Archive transaction target ${i.target}`})}async function rH(e,t,i,n){let r=await Je(e,i.target);await hk({paths:e,journal:t,operation:i,target:r,hooks:n}),await vt({target:r,expectedHash:null,label:`Archive transaction target ${i.target}`})}async function aH(e,t){let i=await Je(e,t.source),n=await Je(e,t.target),[r,a]=await Promise.all([ti(i),ti(n)]);if(!(r===null&&Bn(a,t.expectedSourceHash,"directory"))){if(!Bn(r,t.expectedSourceHash,"directory")||a!==null)throw new Error(`Archive transaction move ${t.id} content changed: source=${Ca(r)}, target=${Ca(a)}`);await ze.mkdir(Se.dirname(n),{recursive:!0}),await ze.rename(i,n),await vt({target:n,expectedHash:t.expectedSourceHash,expectedKind:"directory",label:`Archive transaction move target ${t.target}`})}}async function oH(e,t,i,n){return i.type==="write"?nH(e,t,i,n):i.type==="remove"?rH(e,t,i,n):aH(e,i)}function sH(e){let t=0,i=!1,n=[];for(let r of e.events){if(r.type!=="operation-started"&&r.type!=="operation-completed")continue;let a=e.journal.operations[t];if(!a||r.operationId!==a.id)throw new Error(`Native Archive transaction ${e.journal.id} operation events are out of order`);if(r.type==="operation-started"){i=!0;continue}if(!i)throw new Error(`Native Archive transaction ${e.journal.id} completed an operation before it started`);n.push(a.id),t+=1,i=!1}return n}async function cH(e,t,i,n){let r=await Je(e,i.target);if(i.type==="write"){let a=await Je(e,i.staged);await vt({target:a,expectedHash:i.stagedHash,label:`Completed Archive staged file ${i.staged}`});let o=await Ri(e,t,i,r),s=await Ft({paths:e,file:o.postRecord,operation:i,role:"post",expectedHash:i.stagedHash});if(!s)throw new Error(`Completed Archive target ${i.target} has no CAS identity`);if(await Te({paths:e,file:r,operation:i,record:s,label:`Completed Archive target ${i.target}`}),i.expectedTargetHash!==null){await vt({target:await Je(e,i.backup),expectedHash:i.expectedTargetHash,label:`Completed Archive backup ${i.backup}`});let c=await Ft({paths:e,file:o.originalRecord,operation:i,role:"original",expectedHash:i.expectedTargetHash});if(!c)throw new Error(`Completed Archive target ${i.target} has no original CAS identity`);if(await ce(o.originalQuarantine))await Te({paths:e,file:o.originalQuarantine,operation:i,record:c,label:`Completed Archive original quarantine ${i.target}`});else if(!n)throw new Error(`Completed Archive original quarantine ${i.target} disappeared`)}return}if(i.type==="remove"){await vt({target:r,expectedHash:null,label:`Completed Archive target ${i.target}`}),await vt({target:await Je(e,i.backup),expectedHash:i.expectedTargetHash,label:`Completed Archive backup ${i.backup}`});let a=await Ri(e,t,i,r),o=await Ft({paths:e,file:a.originalRecord,operation:i,role:"original",expectedHash:i.expectedTargetHash});if(!o)throw new Error(`Completed Archive remove ${i.target} has no original CAS identity`);if(await ce(a.originalQuarantine))await Te({paths:e,file:a.originalQuarantine,operation:i,record:o,label:`Completed Archive original quarantine ${i.target}`});else if(!n)throw new Error(`Completed Archive original quarantine ${i.target} disappeared`);return}n||(await vt({target:await Je(e,i.source),expectedHash:null,label:`Completed Archive move source ${i.source}`}),await vt({target:r,expectedHash:i.expectedSourceHash,expectedKind:"directory",label:`Completed Archive move target ${i.target}`}))}async function pk(e,t,i){let n=t.status==="prepared"?await lu(e,t,"applying"):t;if(n.status!=="applying")throw new Error(`Native Archive transaction ${n.id} cannot apply from ${n.status}`);let r=await wn(e,n.id),a=sH({journal:n,events:r}),o=new Set(a),s=r.some(l=>l.type==="archive-finalization-started");for(let l of n.operations.slice(0,a.length))await cH(e,n,l,s);let c=o.size;for(let l of n.operations)o.has(l.id)||(l.id==="archive-change"&&await i?.beforeArchiveChangeMove?.(l),await Nt(e,n.id,"operation-started",l.id),await oH(e,n,l,i),await Nt(e,n.id,"operation-completed",l.id),c+=1,await i?.afterOperation?.(l,c));return n=await lp(e,n.id),n}async function lH(e){try{return await Te(e),!0}catch{return!1}}async function uH(e){await Te({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive rollback original quarantine ${e.operation.target}`});let t=await hi({root:e.paths.nativeRoot,directory:Se.dirname(e.target),label:`Archive rollback target ${e.operation.target}`});await e.hooks?.beforeArchiveTargetInstall?.("rollback",e.operation,e.target),await t.verify(),await Te({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive rollback original quarantine ${e.operation.target}`});try{await ze.link(e.quarantine,e.target)}catch(i){throw i.code==="EEXIST"?new Error(`Archive rollback target ${e.operation.target} was created before exclusive restore`,{cause:i}):i}await t.verify(),await e.hooks?.afterArchiveTargetInstalled?.("rollback",e.operation,e.target),await Te({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive rollback target ${e.operation.target}`})}async function sp(e){if(e.operation.type!=="write")return;let t=await Ri(e.paths,e.journal,e.operation,e.target);if(!await ce(t.candidate))return;let i=await Ei({paths:e.paths,file:t.candidate,expectedHash:e.operation.stagedHash,label:`Archive write candidate ${e.operation.target}`});await Sr({paths:e.paths,file:t.candidate,operation:e.operation,record:{schema:vs,operationId:e.operation.id,role:"post",hash:e.operation.stagedHash,identity:i.identity},label:`Archive write candidate ${e.operation.target}`})}async function dH(e,t,i,n){let r=await Je(e,i.target),a=await Ri(e,t,i,r),o=i.expectedTargetHash,s=o===null?null:await Ft({paths:e,file:a.originalRecord,operation:i,role:"original",expectedHash:o}),c=i.type==="write"?await Ft({paths:e,file:a.postRecord,operation:i,role:"post",expectedHash:i.stagedHash}):null;if(i.type==="write"&&!c&&await ce(a.candidate)&&await ce(r)){let l=await Ei({paths:e,file:a.candidate,expectedHash:i.stagedHash,label:`Archive write candidate ${i.target}`}),u=await Ei({paths:e,file:r,expectedHash:i.stagedHash,label:`Archive rollback target ${i.target}`});qn(l.identity,u.identity)&&(c=await du({paths:e,file:a.postRecord,operation:i,role:"post",expectedHash:i.stagedHash,identity:u.identity}))}if(await ce(a.rollbackQuarantine)){if(!c)throw new Error(`Archive rollback quarantine ${i.target} has no CAS identity`);await Te({paths:e,file:a.rollbackQuarantine,operation:i,record:c,label:`Archive rollback quarantine ${i.target}`})}if(await ce(r)&&!(s!==null&&await lH({paths:e,file:r,operation:i,record:s,label:`Archive rollback target ${i.target}`}))){if(!c){if(!s){let u=await ti(r);if(Bn(u,o)){await sp({paths:e,journal:t,operation:i,target:r});return}}throw new Error(`Archive rollback target ${i.target} is occupied by an external object`)}await fk({paths:e,operation:i,phase:"rollback",target:r,quarantine:a.rollbackQuarantine,record:c,hooks:n})}if(o===null){if(await ce(r))throw new Error(`Archive rollback create target ${i.target} could not be removed`)}else if(!await ce(r)){if(!s||!await ce(a.originalQuarantine))throw new Error(`Archive rollback original target ${i.target} cannot be recovered safely`);await uH({paths:e,operation:i,target:r,quarantine:a.originalQuarantine,record:s,hooks:n})}s&&await ce(a.originalQuarantine)&&await Sr({paths:e,file:a.originalQuarantine,operation:i,record:s,label:`Archive rollback original quarantine ${i.target}`}),c&&await ce(a.rollbackQuarantine)&&await Sr({paths:e,file:a.rollbackQuarantine,operation:i,record:c,label:`Archive rollback quarantine ${i.target}`}),await sp({paths:e,journal:t,operation:i,target:r}),await vt({target:r,expectedHash:o,label:`Archive rollback target ${i.target}`})}async function fH(e,t){let i=await Je(e,t.source),n=await Je(e,t.target),[r,a]=await Promise.all([ti(i),ti(n)]);if(!(Bn(r,t.expectedSourceHash,"directory")&&a===null)){if(r!==null||!Bn(a,t.expectedSourceHash,"directory"))throw new Error(`Archive rollback move ${t.id} content changed: source=${Ca(r)}, target=${Ca(a)}`);await ze.mkdir(Se.dirname(i),{recursive:!0}),await ze.rename(n,i)}}async function mk(e,t,i){let n=await wn(e,t.id);if(n.some(o=>o.type==="archive-finalization-started"||o.type==="archive-finalized"))throw new Error("An archive whose finalization started can only be recovered by continuing it");let r=await lu(e,t,"rolling-back");await Nt(e,r.id,"rollback-started");let a=new Set(n.filter(o=>o.type==="operation-started"||o.type==="operation-completed").map(o=>o.operationId));for(let o of[...r.operations].reverse())a.has(o.id)&&(o.type==="move"?await fH(e,o):await dH(e,r,o,i));return await Nt(e,r.id,"rollback-completed"),r=await lu(e,r,"rolled-back"),r}async function uk(e,t,i){let n=await Je(e,i.target);if(i.type==="write"){let r=await Ri(e,t,i,n),a=await Ft({paths:e,file:r.postRecord,operation:i,role:"post",expectedHash:i.stagedHash});if(!a)throw new Error(`Archive commit target ${i.target} has no CAS identity`);await Te({paths:e,file:n,operation:i,record:a,label:`Archive commit target ${i.target}`});return}await vt({target:n,expectedHash:null,label:`Archive commit target ${i.target}`})}async function hH(e,t){for(let i of t.operations){if(i.type==="move")continue;let n=await Je(e,i.target),r=await Ri(e,t,i,n);if(await ce(r.rollbackQuarantine))throw new Error(`Archive commit found an unfinished rollback for ${i.target}`);if(await uk(e,t,i),i.expectedTargetHash!==null){let a=await Ft({paths:e,file:r.originalRecord,operation:i,role:"original",expectedHash:i.expectedTargetHash});if(!a)throw new Error(`Archive commit target ${i.target} has no original CAS identity`);await ce(r.originalQuarantine)&&await Sr({paths:e,file:r.originalQuarantine,operation:i,record:a,label:`Archive commit original quarantine ${i.target}`})}await sp({paths:e,journal:t,operation:i,target:n})}for(let i of t.operations)i.type!=="move"&&await uk(e,t,i)}async function fu(e,t,i){return i==="commit"&&await hH(e,t),await Nt(e,t.id,i),i==="commit"?lu(e,t,"committed"):t}import{randomUUID as pH}from"crypto";import{promises as gs}from"fs";import gk from"path";var up="comet.selection.v2",mH=16*1024;function ws(e){return gk.join(e,".comet","current-change.json")}function vH(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function vk(e){return e===null||typeof e=="string"}function wk(e){let t;try{t=JSON.parse(e)}catch(i){throw new Error(`current change selection contains invalid JSON: ${i instanceof Error?i.message:String(i)}`,{cause:i})}if(!vH(t))throw new Error("current change selection must be a JSON object");if(t.version===1){if(typeof t.change!="string")throw new Error("legacy current change selection change must be a string");if(t.branch!==void 0&&!vk(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:up,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==up)throw new Error(`current change selection schema must be ${up}`);if(t.workflow!=="native"&&t.workflow!=="classic")throw new Error("current change selection workflow must be native or classic");if(typeof t.change!="string")throw new Error("current change selection change must be a string");if(!vk(t.branch))throw new Error("current change selection branch must be a string or null");if(t.workflow==="native"&&t.branch!==null)throw new Error("Native current change selection branch must be null");return{selection:t,legacy:!1}}async function dp(e){let t;try{let n=ws(e),{bytes:r}=await fn(n,mH,{label:"current change selection"});t=r.toString("utf8")}catch(n){if(n.code==="ENOENT")return{status:"missing"};throw new Error(`cannot read current change selection: ${n instanceof Error?n.message:String(n)}`,{cause:n})}return{status:"selected",...wk(t)}}async function yk(e,t){let i=wk(JSON.stringify(t));if(i.legacy)throw new Error("cannot write a legacy current change selection");let n=ws(e),r=`${n}.${pH()}.tmp`;await gs.mkdir(gk.dirname(n),{recursive:!0});try{await gs.writeFile(r,`${JSON.stringify(i.selection,null,2)} +`,"utf8"),await gs.rename(r,n)}catch(a){throw await gs.rm(r,{force:!0}),a}}async function Nk(e){await gs.rm(ws(e),{force:!0})}async function bk(e,t,i){let n=await dp(e);return n.status!=="selected"||n.selection.workflow!==t||n.selection.change!==i?!1:(await Nk(e),!0)}var lJ=16*1024;async function ys(e){let t=await dp(e.projectRoot);return t.status==="missing"||t.selection.workflow!=="native"?null:(zt(t.selection.change),t.selection)}function kk(e){return ws(e.projectRoot)}async function hu(e,t){return te(e,`select change ${t}`,async()=>{zt(t),await G(e,t),await yk(e.projectRoot,{schema:"comet.selection.v2",workflow:"native",change:t,branch:null})})}async function Sk(e){let t=await ys(e);return t?(await G(e,t.change),t.change):null}async function Ek(e,t){return await Vr(e.projectRoot),bk(e.projectRoot,"native",t)}var NH=16*1024*1024,Ns=class extends Error{constructor(i,n,r,a){super(`Canonical spec conflict for ${i}: expected ${n??"(missing)"}, actual ${r??"(missing)"}`);this.capability=i;this.expectedHash=n;this.actualHash=r;this.canonicalPath=a;this.name="NativeSpecConflictError"}capability;expectedHash;actualHash;canonicalPath;code="native-spec-conflict"},Pa=class extends Error{constructor(i,n=i.ready?"Native Archive preflight no longer matches the expected hash":`Native Archive preflight is blocked: ${i.findingCodes.join(", ")}`){super(n);this.preflight=i;this.name="NativeArchivePreflightError"}preflight;code="native-archive-preflight"};async function bH(e){try{return await lt(e)}catch(t){if(t.code==="ENOENT")return null;throw t}}function kH(e){if(e.phase!=="archive")throw new Error(`Native change ${e.name} is not in Archive`);if(e.verification_result!=="pass")throw new Error(`Native change ${e.name} has not passed verification`);if(!e.verification_report)throw new Error(`Native change ${e.name} has no verification report`);if(e.archived)throw new Error(`Native change ${e.name} is already archived`)}async function SH(e,t){let i=C(e,t.name),n=await ur(i,t.brief),r=await sa(i,t.verification_report),a=[...n.findings,...r.findings];if(a.length>0)throw new Error(`Native archive artifacts are invalid: ${a[0].message}`)}async function EH(e,t){let i=Gt(e,t.capability);await x(e.nativeRoot,i);let n=await bH(i),r=t.operation==="create"?null:t.base_hash;if(n!==r)throw new Ns(t.capability,r,n,i)}function RH(e,t,i){return Ci.join(e.archiveDir,`${i.toISOString().slice(0,10)}-${t}`)}async function CH(e){try{return await wH.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function PH(e){let{paths:t,state:i,now:n,transactionId:r,preflight:a}=e,o=RH(t,i.name,n);if(await CH(o))throw new Error(`Native archive target already exists: ${o}`);if(_i(t,o)!==a.targetRef)throw new Error("Native Archive target changed after preflight");let s=await Tt(t,r),c=[];for(let[u,d]of i.spec_changes.entries()){await EH(t,d);let f=Gt(t,d.capability),h=a.operations.find(b=>b.capability===d.capability&&b.operation===d.operation);if(!h)throw new Error(`Native Archive preflight has no operation for ${d.capability}`);if(d.operation!=="remove"&&h.proposedHash===null)throw new Error(`Native Archive preflight has no proposed hash for ${d.capability}`);let m=Ci.join(s.backups,"specs",d.capability,"spec.md");if(d.operation==="remove"){c.push({id:`spec-${u+1}-${d.capability}`,type:"remove",target:_i(t,f),backup:_i(t,m),expectedTargetHash:d.base_hash});continue}let p=C(t,i.name);await xy(p,d.source);let v=Ci.resolve(p,...d.source.split(/[\\/]/u)),S=Ci.join(s.staged,"specs",d.capability,"spec.md"),N=(await Ti({sourceRoot:p,source:v,targetRoot:t.nativeRoot,target:S,maxBytes:NH,label:`Native Archive proposed spec ${d.capability}`,expectedHash:h.proposedHash,expectedTargetHash:null,exclusive:!0,hooks:{afterParentChainCaptured:()=>e.hooks?.afterProtectedCopySourceParentCaptured?.("stage",d.source)}})).hash;if(N!==h.proposedHash)throw new Error(`Proposed Native spec changed after preflight: ${d.capability}`);c.push({id:`spec-${u+1}-${d.capability}`,type:"write",target:_i(t,f),staged:_i(t,S),...d.operation==="replace"?{backup:_i(t,m)}:{},expectedTargetHash:d.operation==="create"?null:d.base_hash,stagedHash:N})}let l=C(t,i.name);return c.push({id:"archive-change",type:"move",source:_i(t,l),target:_i(t,o),expectedSourceHash:await op(l),expectedTargetHash:null}),{schema:"comet.native.transaction.v2",id:r,kind:"archive",status:"prepared",change:i.name,createdAt:n.toISOString(),preflightHash:a.preflightHash,operations:c}}function fp(e,t){let i=t.operations.find(n=>n.id==="archive-change");if(!i||i.type!=="move")throw new Error(`Archive transaction ${t.id} has no archive move`);return Ci.resolve(e.nativeRoot,...i.target.split("/"))}async function Rk(e,t,i){let n=await wn(e,t.id);if(n.some(p=>p.type==="archive-finalized"))return;let r=n.some(p=>p.type==="archive-finalization-started");if(t.schema==="comet.native.transaction.v2"&&!r){let p=t.operations.find(S=>S.id==="archive-change");if(!p||p.type!=="move"||!p.expectedSourceHash)throw new Error(`Archive transaction ${t.id} has no content-bound archive move`);let v=await ti(fp(e,t));if(v?.kind!=="directory"||v.hash!==p.expectedSourceHash)throw new Error(`Native Archive content changed before finalization for transaction ${t.id}`)}let a=fp(e,t),o=Ci.join(a,je),s=await ky(o);if(!t.change||s.name!==t.change)throw new Error(`Archive transaction ${t.id} change mismatch`);let c=await be(a);if(!c||c.runId!==s.run_id||c.currentStep!=="archive"&&!(c.currentStep===null&&c.status==="completed"))throw new Error(`Native archive Run state is missing or inconsistent for ${s.name}`);let l=c;if(c.currentStep==="archive"){let p=_s(mt,c,new Set,Na,void 0);if(!p.action)throw new Error(p.reason??"Native archive produced no action");l=Is(mt,p.state,{actionId:p.action.id,status:"succeeded",summary:`Archived Native change ${s.name}`},Na,void 0)}let u=D(`archive:${t.id}:${s.name}`),d=await qe(a,l.trajectoryRef),f=d.filter(p=>p.data.transactionId===t.id);if(t.schema==="comet.native.transaction.v2"&&(f.length>1||f.some(p=>p.type!=="state_transitioned")))throw new Error(`Native Archive trajectory has a transaction id collision: ${t.id}`);let h=f.find(p=>p.type==="state_transitioned"),m={previousPhase:"archive",nextPhase:null,evidenceHash:u,summary:`Archived Native change ${s.name}`,transactionId:t.id};if(h&&t.schema==="comet.native.transaction.v2"&&(!yH(h.data,m)||h.runId!==l.runId||h.timestamp!==t.createdAt||h!==d.at(-1)))throw new Error(`Native Archive trajectory event changed for transaction ${t.id}`);if(!r&&(s.archived||c.currentStep===null||f.length>0))throw new Error(`Native Archive finalization state changed before its irreversible marker: ${t.id}`);if(r||(t.schema==="comet.native.transaction.v2"?(await fu(e,t,"archive-finalization-started"),await i?.afterFinalizationStarted?.(t)):await Ur(e,t,"archive-finalization-started")),!s.archived){let p={...s,archived:!0};await by(o,p)}h||(h=await Fn({changeDir:a,run:l,type:"state_transitioned",data:m,...t.schema==="comet.native.transaction.v2"?{now:new Date(t.createdAt)}:{}})),await gr({changeDir:a,run:l,trajectoryOffset:h.sequence,evidenceHash:u,...t.schema==="comet.native.transaction.v2"?{now:new Date(t.createdAt)}:{}}),await rr(a,l),await Ek(e,s.name),t.schema==="comet.native.transaction.v2"?await fu(e,t,"archive-finalized"):await Ur(e,t,"archive-finalized")}async function Ck(e,t,i){if(t.schema==="comet.native.transaction.v2"){if(!(await wn(e,t.id)).some(o=>o.type==="operation-started")){let o=await kr({paths:e,name:t.change,now:new Date(t.createdAt)});if(!o.ready||o.preflightHash!==t.preflightHash)throw new Pa(o,"Native Archive facts changed before the first transaction operation")}let a=await pk(e,t,{...i,beforeArchiveChangeMove:async o=>{await i?.beforeArchiveChangeMove?.(o);let s=await G(e,t.change),c=await br({paths:e,state:s,now:new Date(t.createdAt)});if(s.phase!=="archive"||s.archived||s.verification_result!=="pass"||!["complete","partial"].includes(c.freshness)||c.findingCodes.length>0)throw new Error(`Native Archive verification freshness changed before moving ${t.change}: ${c.findingCodes.join(", ")||c.freshness}`)}});return await Rk(e,a,i),fu(e,a,"commit")}let n=await mw(e,t);return await Rk(e,n,i),Ur(e,n,"commit")}function xH(e,t){if(t.kind!=="archive")throw new Error(`Transaction ${t.id} is not an archive`);if(t.schema==="comet.native.transaction.v2"){if(!t.change)throw new Error(`Archive transaction ${t.id} has no change`);return}if(Ci.resolve(t.projectRoot)!==Ci.resolve(e.projectRoot)||Ci.resolve(t.nativeRoot)!==Ci.resolve(e.nativeRoot))throw new Error(`Transaction ${t.id} belongs to a different Native root`)}async function Pk(e){return te(e.paths,`archive ${e.name}`,()=>De(e.paths,e.name,`archive ${e.name}`,async()=>{await Rt(e.paths,e.name);let t=await di(e.paths,"archive",`archive ${e.name}`);try{if(!/^[a-f0-9]{64}$/u.test(e.expectedPreflightHash))throw new Error("Native Archive expected preflight must be a SHA-256 hash");let i=e.now??new Date,n=await kr({paths:e.paths,name:e.name,now:i});if(!n.ready||n.preflightHash!==e.expectedPreflightHash)throw new Pa(n);let r=await G(e.paths,e.name);kH(r),await SH(e.paths,r);let a=gH(),o=await PH({paths:e.paths,state:r,now:i,transactionId:a,preflight:n,hooks:e.hooks});return await dk(e.paths,o),await e.hooks?.afterPrepared?.(o),await Ck(e.paths,o,e.hooks),{archiveDir:fp(e.paths,o),transactionId:a,preflightHash:n.preflightHash}}finally{await fi(t)}}))}async function xk(e){return te(e.paths,`recover archive ${e.transactionId}`,async()=>{let t=await di(e.paths,"archive",`recover archive ${e.transactionId}`);try{let i=await ct(e.paths,e.transactionId),n=i.schema==="comet.native.transaction.v2"?await lp(e.paths,e.transactionId):i;return xH(e.paths,n),n.status==="committed"||n.status==="rolled-back"?n:e.strategy==="continue"?Ck(e.paths,n):n.schema==="comet.native.transaction.v2"?mk(e.paths,n):ol(e.paths,n)}finally{await fi(t)}},{allowedTransactionId:e.transactionId})}var AH=/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid|progress-invalid)|transition-(?:incomplete|invalid))/u;function TH(e){return e.phase==="shape"?["summary","shared-understanding-confirmation"]:e.phase==="build"?e.approval==="confirmed"?["summary","artifact-or-no-code-reason"]:["summary","artifact-or-no-code-reason","shared-understanding-confirmation"]:e.phase==="verify"?["summary","verification-result","verification-report"]:[]}function Me(e){let i=(e.findings??[]).filter(u=>!ia(u.code)),n=i.find(u=>u.requiresUserDecision),r=i.find(u=>u.repairCommand!==null||AH.test(u.code)),a=i.find(u=>u.code==="repair-iteration-limit"||u.code==="repair-override-exhausted"),o=i.find(u=>u.code==="repair-stagnation-stop"),s=i.find(u=>u.requiredAction==="return-to-bound-working-directory"||u.requiredAction==="repair-workspace-binding"),c=[...new Set(i.map(u=>u.requiredAction))].sort();if(e.done)return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"done",action:"none",command:null,requiresUserDecision:!1,requiredInputs:[]};if(a)return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"await-user",action:"work-phase",command:null,requiresUserDecision:!0,requiredInputs:["repair-continuation-decision"]};if(n)return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"await-user",action:"work-phase",command:null,requiresUserDecision:!0,requiredInputs:c};if(o)return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"blocked",action:"repair",command:null,requiresUserDecision:!1,requiredInputs:["new-repair-hypothesis"]};if(s)return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"blocked",action:"none",command:null,requiresUserDecision:!1,requiredInputs:c};if(r)return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"blocked",action:"repair",command:r.repairCommand,requiresUserDecision:!1,requiredInputs:c};if(e.evidenceRetreat)return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"continue",action:"advance-phase",command:`comet native next ${e.state.name} --summary ""`,requiresUserDecision:!1,requiredInputs:["summary"]};if(e.state.phase==="build"&&e.state.verification_result==="fail")return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"continue",action:"work-phase",command:null,requiresUserDecision:!1,requiredInputs:["repair-verification-gaps"]};if(i.length>0)return e.state.phase==="archive"?{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"blocked",action:"none",command:null,requiresUserDecision:!1,requiredInputs:c}:c.includes("refresh-verification-receipts")?{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"continue",action:"work-phase",command:`comet native receipt refresh ${e.state.name} --apply`,requiresUserDecision:!1,requiredInputs:c}:{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"continue",action:"work-phase",command:null,requiresUserDecision:!1,requiredInputs:c};if(e.state.phase==="archive"){if(e.archiveReady&&e.archivePreflightHash){if(!/^[a-f0-9]{64}$/u.test(e.archivePreflightHash))throw new Error("Native Archive continuation preflight must be a SHA-256 hash");return e.archiveConfirmation==="required"?{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"await-user",action:"archive",command:null,requiresUserDecision:!0,requiredInputs:["archive-confirmation"]}:{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"continue",action:"archive",command:`comet native archive ${e.state.name} --expect-preflight ${e.archivePreflightHash}`,requiresUserDecision:!1,requiredInputs:[]}}return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:e.archiveReady?"continue":"blocked",action:e.archiveReady?"archive":"none",command:e.archiveReady?`comet native archive ${e.state.name} --dry-run`:null,requiresUserDecision:!1,requiredInputs:e.archiveReady?[]:["archive-readiness"]}}let l=e.state.phase==="shape"||e.state.phase==="build"&&e.state.approval!=="confirmed"?" --confirmed":"";return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"continue",action:"advance-phase",command:`comet native next ${e.state.name} --summary ""${l}`,requiresUserDecision:!1,requiredInputs:TH(e.state)}}import _H from"path";var Ak=10*1024*1024,I=class extends Error{},hp=`Usage: comet native [options] Commands: hook-guard [--hook-output copilot] @@ -221,33 +221,33 @@ Commands: archive --dry-run [--finish merge|push|pull-request|keep] archive --expect-preflight [--confirmed] doctor [] [--repair] [--strategy continue|rollback] -`;function gt(e,t){let i=e.flatMap((n,r)=>n===t?[r]:[]);if(i.length>1)throw new I(`${t} may only be provided once`);return i.length===0?!1:(e.splice(i[0],1),!0)}function J(e,t){let i=e.flatMap((a,o)=>a===t?[o]:[]);if(i.length>1)throw new I(`${t} may only be provided once`);if(i.length===0)return;let n=i[0],r=e[n+1];if(r===void 0||r.startsWith("--"))throw new I(`${t} requires a value`);return e.splice(n,2),r}function Yi(e,t){let i=[];for(let n=0;n0)throw new I(`Unexpected argument: ${e[0]}`)}function ae(e,t){let i=e.shift();if(!i||i.startsWith("--"))throw new I(`${t} is required`);return i}function pu(e,t="en"){let i=J(e,"--language")??t;if(i!=="en"&&i!=="zh-CN")throw new I("--language must be en or zh-CN");return i}function Ak(e){let t=J(e,"--expect-revision");if(t!==void 0){if(!/^[1-9]\d*$/u.test(t)||!Number.isSafeInteger(Number(t)))throw new I("--expect-revision must be a positive integer");return Number(t)}}async function Tk(e){return e?_H.resolve(e):Wc(process.cwd())}async function Oe(e){let t=await zg({startPath:e,allowMissingConfig:!1});return{config:t.config,paths:t.paths}}async function _k(e){let t=await re(e);return Ne(e,t?.native.artifact_root??"docs")}function Z(e,t,i){return{command:e,exitCode:0,data:t,text:i??JSON.stringify(t,null,2)+` -`}}async function Ik(e,t){try{let{bytes:i}=await fn(e,t,{label:"Acceptance evidence entries file"});return i.toString("utf8")}catch(i){throw i instanceof xt?i.reason==="not-regular-file"?new Error(`Acceptance evidence entries path is not a regular file: ${e}`,{cause:i}):i.reason==="too-large"?new Error(`Acceptance evidence entries file exceeds ${t} bytes: ${e}`,{cause:i}):new Error(`Acceptance evidence entries file changed while reading: ${e}`,{cause:i}):i}}async function jk(e){let t=[],i=0;for await(let n of process.stdin){let r=Buffer.isBuffer(n)?n:Buffer.from(String(n));if(i+=r.byteLength,i>e)throw new Error(`Acceptance evidence entries on stdin exceed ${e} bytes`);t.push(r)}return Buffer.concat(t).toString("utf8")}function Ok(e,t){if(t instanceof I)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof Ns)return{command:e,exitCode:73,data:{capability:t.capability,expectedHash:t.expectedHash,actualHash:t.actualHash,canonicalPath:t.canonicalPath},error:{code:"conflict",message:t.message}};if(t instanceof Pa)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof xn)return{command:e,exitCode:73,data:{change:t.change,expectedRevision:t.expectedRevision,actualRevision:t.actualRevision,outcome:"revision-conflict"},error:{code:"conflict",message:t.message}};if(t instanceof Wo)return{command:e,exitCode:73,data:{requestedIsolation:t.requestedIsolation,activeChanges:t.activeChanges,requiredAction:"create-native-worktree"},error:{code:"workspace-isolation-required",message:t.message}};if(t instanceof gi)return{command:e,exitCode:65,data:{change:t.change,complete:!1,omittedCount:t.omittedCount,omittedByReason:t.omittedByReason,samplePaths:t.samplePaths,sampleTruncated:t.sampleTruncated,effectiveLimits:t.effectiveLimits,policyHash:t.policyHash,configPath:".comet/config.yaml",supportedFixes:["increase native.snapshot.max_files, native.snapshot.max_total_bytes, or native.snapshot.max_duration_ms","add an explicit native.snapshot.exclude pattern for data outside implementation scope"],requiredAction:"resolve-native-baseline"},error:{code:"baseline-incomplete",message:t.message}};if(t instanceof Ui)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof Ra)return{command:e,exitCode:65,data:t.recovery,error:{code:"implementation-scope-stale",message:t.message}};if(t instanceof Error){let i=t.code;if(i&&new Set(["EACCES","EPERM","EIO","EMFILE","ENFILE","ENOSPC","EROFS"]).has(i))return{command:e,exitCode:70,error:{code:"internal",message:t.message}};let n=/\b(lock|transaction|conflict|occupied|incomplete|recovery)\b/iu.test(t.message);return{command:e,exitCode:n?73:65,error:{code:n?"conflict":"invalid-data",message:t.message}}}return{command:e,exitCode:70,error:{code:"internal",message:String(t)}}}function pp(e,t){return t?{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,...e.data===void 0?{}:{data:e.data},...e.error===void 0?{}:{error:e.error}})+` -`}:e.error?{exitCode:e.exitCode,stderr:e.error.message}:{exitCode:e.exitCode,stdout:e.text}}async function $k(e,t){let i=ae(e,"change name"),n=gt(e,"--dry-run"),r=J(e,"--expect-preflight"),a=gt(e,"--confirmed"),s=J(e,"--finish");if(s!==void 0&&s!=="merge"&&s!=="push"&&s!=="pull-request"&&s!=="keep")throw new I("--finish must be merge, push, pull-request, or keep");if(n&&r)throw new I("--dry-run and --expect-preflight cannot be combined");if(n&&a)throw new I("--confirmed is only valid with --expect-preflight");if(!n&&s)throw new I("--finish is only valid with --dry-run");if(!n&&!r)throw new I("archive requires --dry-run or --expect-preflight ");if(r&&!/^[a-f0-9]{64}$/u.test(r))throw new I("--expect-preflight must be a SHA-256 hash");Y(e);let{config:c,paths:l}=await Oe(t);if(n){let h=await Ve(l,i),m=h;if(h?.schema==="comet.native.workspace.v3"){if(h.isolation==="current"){if(s)throw new I("Native current isolation does not accept --finish")}else if(s)m=await uy(l,i,s);else if(h.finish===null)throw new I("Native branch and worktree isolation require --finish with --dry-run")}else if(s)throw new I("--finish requires a workspace v3 branch or worktree binding");let p=await kr({paths:l,name:i}),v=await G(l,i);return Z("archive --dry-run",{...p,workspaceFinish:m?.schema==="comet.native.workspace.v3"?m.finish:null,continuation:Me({state:v,archiveReady:p.ready,archiveConfirmation:p.archiveConfirmation,archivePreflightHash:p.preflightHash})},`Native Archive preview ${p.preflightHash}: ${p.ready?"ready":"blocked"} -`)}if(c.native.archive_confirmation==="required"&&!a)throw new I("archive requires --confirmed when native.archive_confirmation is required");let u=await G(l,i),d=await Ve(l,i);if(d?.schema==="comet.native.workspace.v3"&&d.isolation!=="current"&&d.finish===null)throw new I("Native branch and worktree isolation require a persisted --finish preview");let f=await Ck({paths:l,name:i,expectedPreflightHash:r});return Z("archive",{...f,workspaceFinish:d?.schema==="comet.native.workspace.v3"?d.finish:null,continuation:Me({state:u,done:!0})},`Archived Native change ${i} to ${f.archiveDir} -`)}import{createHash as IH}from"node:crypto";import{constants as mp,promises as ii}from"node:fs";import Er from"node:path";import{TextDecoder as jH}from"node:util";var Hk={"conflict-marker":0,"trailing-whitespace":1,"space-before-tab":2,"scope-mismatch":3,"unsafe-file":4,"binary-skipped":5,"scan-limit":6},Ee=class extends Error{constructor(i,n){super(n);this.kind=i}kind};function OH(e){return{schema:"comet.native.content-snapshot.v1",origin:e.origin,...e.capture?{capture:e.capture}:{},createdAt:"1970-01-01T00:00:00.000Z",complete:e.complete,limits:e.limits,...e.policy?{policy:e.policy}:{},entries:e.entries,omitted:e.omitted,omittedCount:e.omittedCount,...e.omissionOverflow?{omissionOverflow:e.omissionOverflow}:{}}}async function Dk(e){let t=OH(e.scope.baseline),[i,n]=await Promise.all([Et({changeDir:C(e.paths,e.state.name),briefRef:e.state.brief,specChanges:e.state.spec_changes}),Sn(e.paths,t,{origin:"explicit"})]),r=In({baseline:t,current:n,contractHash:e.scope.authority.contractHash,declaredArtifacts:e.scope.authority.declaredArtifacts,noCodeReason:e.scope.authority.noCodeReason,...e.scope.authority.gitChangedPaths?{gitChangedPaths:e.scope.authority.gitChangedPaths}:{}});return{contractHash:i.contract.contractHash,snapshotHash:r.scope.currentProjectionHash}}function Mk(e,t){let i=(e??(()=>new Date))();if(!(i instanceof Date)||!Number.isFinite(i.getTime()))throw new Error(`Native check ${t} time is invalid`);return i.toISOString()}function $H(e,t,i){let n=[],r=i.scope.contractHash,a=i.scope.currentProjectionHash;return e.contractHash!==r&&n.push("contract-before-does-not-match-scope"),e.snapshotHash!==a&&n.push("implementation-before-does-not-match-scope"),t.contractHash!==e.contractHash&&n.push("contract-changed-during-check"),t.snapshotHash!==e.snapshotHash&&n.push("implementation-changed-during-check"),t.contractHash===e.contractHash&&t.contractHash!==r&&n.push("contract-after-does-not-match-scope"),t.snapshotHash===e.snapshotHash&&t.snapshotHash!==a&&n.push("implementation-after-does-not-match-scope"),n}function HH(e,t){return e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function mu(e,t){return e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size&&M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}async function DH(e,t){let i=Er.resolve(e),n=Er.resolve(t);if(!$(i,n))throw new Ee("unsafe-file","Scoped file parent escapes the project root");let r=[],a=i;for(let o of["",...Er.relative(i,n).split(Er.sep).filter(Boolean)]){o&&(a=Er.join(a,o));let s;try{s=await ii.lstat(a)}catch(l){throw l.code==="ENOENT"?new Ee("scope-mismatch","Scoped file parent no longer exists"):l}if(!s.isDirectory()||s.isSymbolicLink())throw new Ee("unsafe-file","Scoped file parent is not a real directory");let c=await ii.realpath(a);if(r.length>0&&!$(r[0].realPath,c))throw new Ee("unsafe-file","Scoped file parent resolves outside the project");r.push({path:a,realPath:c,dev:s.dev,ino:s.ino,birthtimeMs:s.birthtimeMs,ctimeMs:s.ctimeMs})}return{physicalRoot:r[0].realPath,chain:r}}async function Fk(e){for(let t of e){let i;try{i=await ii.lstat(t.path)}catch(n){throw n.code==="ENOENT"?new Ee("unsafe-file","Scoped file parent changed while reading"):n}if(!i.isDirectory()||i.isSymbolicLink()||!HH(t,i)||await ii.realpath(t.path)!==t.realPath)throw new Ee("unsafe-file","Scoped file parent changed while reading")}}async function MH(e){let t=Er.resolve(e.projectRoot,...e.file.path.split("/"));if(!$(e.projectRoot,t))throw new Ee("unsafe-file","Scoped file path escapes the project root");let{physicalRoot:i,chain:n}=await DH(e.projectRoot,Er.dirname(t)),r;try{r=await ii.lstat(t)}catch(c){throw c.code==="ENOENT"?new Ee("scope-mismatch","Scoped file no longer exists"):c}if(!r.isFile()||r.isSymbolicLink())throw new Ee("unsafe-file","Scoped file is not a real regular file");if(r.size!==e.file.expected.size)throw new Ee("scope-mismatch","Scoped file size no longer matches its projection");let a=await ii.realpath(t);if(!$(i,a))throw new Ee("unsafe-file","Scoped file resolves outside the project root");let o=process.platform==="win32"?"r":mp.O_RDONLY|mp.O_NOFOLLOW|mp.O_NONBLOCK,s=await ii.open(t,o).catch(c=>{throw c.code==="ENOENT"?new Ee("scope-mismatch","Scoped file no longer exists"):c.code==="ELOOP"||c.code==="ENXIO"?new Ee("unsafe-file","Scoped file became unsafe while opening"):c});try{let[c,l,u]=await Promise.all([s.stat(),ii.lstat(t),ii.realpath(t)]);if(await Fk(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==a||!mu(r,c)||!mu(c,l))throw new Ee("unsafe-file","Scoped file changed while opening");let d=[],f=IH("sha256"),h=Buffer.allocUnsafe(64*1024),m=0;for(;;){let N=e.file.expected.size+1-m;if(N<1)throw new Ee("scope-mismatch","Scoped file exceeds its projected size");let b=await s.read(h,0,Math.min(h.length,N),null);if(b.bytesRead===0)break;if(m+=b.bytesRead,m>e.file.expected.size)throw new Ee("scope-mismatch","Scoped file exceeds its projected size");let R=Buffer.from(h.subarray(0,b.bytesRead));d.push(R),f.update(R)}let[p,v,S]=await Promise.all([s.stat(),ii.lstat(t),ii.realpath(t)]);if(await Fk(n),m!==e.file.expected.size||f.digest("hex")!==e.file.expected.hash)throw new Ee("scope-mismatch","Scoped file content no longer matches its projection");if(!p.isFile()||!v.isFile()||v.isSymbolicLink()||S!==a||!$(i,S)||!mu(c,p)||!mu(c,v))throw new Ee("unsafe-file","Scoped file changed while reading");let k=Buffer.concat(d,m);if(k.includes(0))return{bytes:m,text:null};try{return{bytes:m,text:new jH("utf-8",{fatal:!0}).decode(k)}}catch{return{bytes:m,text:null}}}finally{await s.close()}}function FH(e){let t=new Map(e.current.entries.map(r=>[r.path,r])),i=[],n=[];for(let r of e.scope.changes){if(!r.after)continue;let a=t.get(r.path);if(!a||a.hash!==r.after.hash||a.size!==r.after.size||a.type!=="file"){n.push(r.path);continue}i.push({path:r.path,expected:r.after})}return i.sort((r,a)=>r.path.localeCompare(a.path,"en")),n.sort((r,a)=>r.localeCompare(a,"en")),{files:i,mismatches:n}}function LH(e,t,i){let n=t.split(` -`);for(let r=0;r{7})(?: |$)/u.test(a)&&i({path:e,line:o,kind:"conflict-marker"}),/[ \t]+$/u.test(a)&&i({path:e,line:o,kind:"trailing-whitespace"}),/^ +\t/u.test(a)&&i({path:e,line:o,kind:"space-before-tab"})}}async function Lk(e){if(!e.state.implementation_scope)throw new Error("Native scoped check requires an implementation scope");let t=await yi(e.paths,e.state.name,e.state.implementation_scope),i=await Dk({paths:e.paths,state:e.state,scope:t}),n=Mk(e.clock,"start"),r=FH(t),a=[],o=0,s=N=>{o+=1,a.lengthN.kind==="scope-detail-overflow")){let N=t.scope.changes.at(-1)?.path??t.current.entries.at(-1)?.path??t.baseline.entries.at(-1)?.path;if(!N)throw new Error("Native implementation scope overflow has no bounded diagnostic path");s({path:N,line:1,kind:"scan-limit"}),c=[]}else if(l>Ae.maxFiles){let N=[...r.files.map(b=>b.path),...r.mismatches].sort((b,R)=>b.localeCompare(R,"en"));s({path:N[Ae.maxFiles],line:1,kind:"scan-limit"}),c=[]}else{let N=0;for(let b of r.files){if(b.expected.size>Ae.maxFileBytes){s({path:b.path,line:1,kind:"scan-limit"}),c=[];break}if(N+=b.expected.size,N>Ae.maxTotalBytes){s({path:b.path,line:1,kind:"scan-limit"}),c=[];break}}}for(let N of r.mismatches)s({path:N,line:1,kind:"scope-mismatch"});let d=0,f=0,h=0;for(let N of c)try{let b=await MH({projectRoot:e.paths.projectRoot,file:N});h+=b.bytes,b.text===null?(f+=1,s({path:N.path,line:1,kind:"binary-skipped"})):(d+=1,LH(N.path,b.text,s))}catch(b){if(!(b instanceof Ee))throw b;s({path:N.path,line:1,kind:b.kind})}let m=await Dk({paths:e.paths,state:e.state,scope:t}),p=Mk(e.clock,"end"),v=$H(i,m,t);a.sort((N,b)=>N.path.localeCompare(b.path,"en")||N.line-b.line||Hk[N.kind]-Hk[b.kind]);let S=gN({change:e.state.name,sourceRevision:e.state.revision,status:o===0&&v.length===0?"passed":"failed",startedAt:n,endedAt:p,contract:{expectedHash:t.scope.contractHash,beforeHash:i.contractHash,afterHash:m.contractHash},implementation:{scopeHash:t.scope.scopeHash,expectedSnapshotHash:t.scope.currentProjectionHash,beforeSnapshotHash:i.snapshotHash,afterSnapshotHash:m.snapshotHash},counts:{filesSelected:l,filesScanned:d,binaryFilesSkipped:f,bytesScanned:h,issueCount:o,recordedIssueCount:a.length},issues:a,issuesTruncated:o>a.length,stale:v.length>0,staleReasons:v}),k=await Fb({paths:e.paths,name:e.state.name,receipt:S});return{receipt:qi(S),ref:k}}async function Bk(e){return te(e.paths,`check ${e.name}`,()=>De(e.paths,e.name,`check ${e.name}`,()=>vp(e)))}async function vp(e){await Rt(e.paths,e.name);let t=await G(e.paths,e.name);if(t.phase!=="verify")throw new Error(`Native check requires Verify, got ${t.phase}`);if(!t.implementation_scope)throw new Error("Native check requires an implementation scope");let i=await zb({paths:e.paths,state:t});if(i)return{change:t,receipt:i.checkReceipt,checkRef:i.checkReceiptRef,ref:i.ref};let n=await Lk({paths:e.paths,state:t}),r=await Jb({paths:e.paths,state:t,checkReceipt:n.receipt,checkReceiptRef:n.ref});return{change:t,receipt:n.receipt,checkRef:n.ref,ref:r.ref}}async function qk(e,t){let i=ae(e,"change name");Y(e);let{paths:n}=await Oe(t),r=await Bk({paths:n,name:i}),a={ref:r.ref,hash:r.receipt.receiptHash,status:r.receipt.status,checker:r.receipt.checker,counts:r.receipt.counts,issues:r.receipt.issues,issuesTruncated:r.receipt.issuesTruncated,stale:r.receipt.stale,staleReasons:r.receipt.staleReasons,startedAt:r.receipt.startedAt,endedAt:r.receipt.endedAt,sourceRevision:r.receipt.sourceRevision},o=r.receipt.status==="passed"&&!r.receipt.stale;return{command:"check",exitCode:o?0:1,data:a,text:`Native check ${o?"passed":"failed"}: ${r.ref} -`}}import aS from"path";import{promises as XH}from"fs";import BH from"path";function gp(e,t){return BH.resolve(e,...t.split(/[\\/]/u))}async function vu(e,t){let i=[],n=C(e,t.name),r=gp(n,ut.stateRef),a;try{a=await be(n)}catch(u){return[{code:"run-state-invalid",message:`Native Run state is invalid: ${u.message}`,path:r}]}if(!a)return(t.run_id!==null||t.phase!=="shape")&&i.push({code:"run-state-missing",message:"Native change references a missing Run state",path:r}),i;if(t.run_id===null)return[{code:"run-state-unexpected",message:"Native change has a Run state but no run_id",path:r}];a.runId!==t.run_id&&i.push({code:"run-id-mismatch",message:`Native Run id ${a.runId} does not match change run_id ${t.run_id}`,path:r}),(a.pending||a.status==="waiting")&&i.push({code:"run-action-pending",message:"Native Run has an unresolved pending action",path:r}),a.currentStep!==t.phase&&i.push({code:"run-phase-mismatch",message:`Native Run step ${a.currentStep??"(none)"} does not match phase ${t.phase}`,path:r});let o=gp(n,a.trajectoryRef),s=await ta(e,t.name);if(s.status==="repairable")return i.push({code:"trajectory-tail-incomplete",message:`Native trajectory final line is incomplete at line ${s.line}; doctor repair can discard ${s.discardedBytes} incomplete byte(s)`,path:o}),i;if(s.status==="invalid")return i.push({code:"trajectory-invalid",message:`Native trajectory is invalid at line ${s.line}: ${s.message}`,path:o}),i;let c;try{if(c=await qe(n,a.trajectoryRef),c.length===0||c.some((u,d)=>!u||typeof u!="object"||u.sequence!==d+1||u.runId!==a.runId||typeof u.type!="string"||!u.data||typeof u.data!="object"||Array.isArray(u.data)))throw new Error("trajectory events are missing or inconsistent")}catch(u){return i.push({code:"trajectory-invalid",message:`Native trajectory is invalid: ${u.message}`,path:o}),i}let l=gp(n,a.checkpointRef);try{let u=await ea(n,a.checkpointRef);u?(u.runId!==a.runId||u.stateVersion!==a.iteration||u.trajectoryOffset!==c.length)&&i.push({code:"checkpoint-mismatch",message:"Native Run checkpoint does not match Run state and trajectory",path:l}):i.push({code:"checkpoint-missing",message:"Native Run checkpoint is missing",path:l})}catch(u){i.push({code:"checkpoint-invalid",message:`Native Run checkpoint is invalid: ${u.message}`,path:l})}return i}import bs from"path";var Vk=8,qH={"brief-blocking-question":{severity:"error",requiredAction:"answer-blocking-question",retry:"next",repair:"none"},"shape-confirmation-required":{severity:"error",requiredAction:"confirm-shared-understanding",retry:"next",repair:"none"},"approval-confirmation-required":{severity:"error",requiredAction:"confirm-shared-understanding",retry:"next",repair:"none"},"transition-incomplete":{severity:"error",requiredAction:"recover-transition",retry:"status",repair:"doctor"},"trajectory-tail-incomplete":{severity:"error",requiredAction:"repair-trajectory-tail",retry:"status",repair:"doctor"},"checkpoint-progress-invalid":{severity:"error",requiredAction:"manually-isolate-invalid-checkpoint",retry:"none",repair:"none"},"checkpoint-progress-incomplete":{severity:"error",requiredAction:"recover-progress-checkpoint",retry:"status",repair:"doctor"},"checkpoint-manifest-invalid":{severity:"error",requiredAction:"record-checkpoint-again",retry:"status",repair:"none"},"verification-scope-partial":{severity:"error",requiredAction:"confirm-partial-verification-scope",retry:"next",repair:"none"},"verification-implementation-stale":{severity:"error",requiredAction:"return-to-build-and-refresh-implementation-scope",retry:"next",repair:"none"},"verification-receipt-binding-mismatch":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"verification-receipt-stale":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"verification-receipt-invalid":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"native-change-conflict":{severity:"error",requiredAction:"resolve-native-change-conflict",retry:"status",repair:"none"},"native-change-overlap":{severity:"error",requiredAction:"inspect-native-change-overlap",retry:"status",repair:"none"},"contract-changed-after-approval":{severity:"error",requiredAction:"re-confirm-contract",retry:"next",repair:"none"},"baseline-snapshot-incomplete":{severity:"error",requiredAction:"resolve-native-baseline",retry:"none",repair:"none"},"baseline-snapshot-missing":{severity:"error",requiredAction:"resolve-native-baseline",retry:"none",repair:"none"},"workspace-inspection-unavailable":{severity:"info",requiredAction:"migrate-workspace-identity",retry:"status",repair:"doctor"},"workspace-binding-root-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-binding-invalid":{severity:"error",requiredAction:"repair-workspace-binding",retry:"status",repair:"none"},"workspace-branch-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-kind-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-vcs-unavailable":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"repair-stagnation-warning":{severity:"warning",requiredAction:"change-repair-approach",retry:"next",repair:"none"},"repair-stagnation-stop":{severity:"error",requiredAction:"try-new-repair-hypothesis-with-status-override",retry:"none",repair:"none"},"repair-iteration-limit":{severity:"error",requiredAction:"choose-repair-continuation",retry:"none",repair:"none"},"repair-override-exhausted":{severity:"error",requiredAction:"choose-repair-continuation",retry:"none",repair:"none"}};function VH(e){let t=qH[e];return t||(/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid)|transition-invalid)/u.test(e)?{severity:"error",requiredAction:"isolate-or-restore-native-runtime-from-a-trusted-copy",retry:"none",repair:"none"}:e.startsWith("brief-")?{severity:"error",requiredAction:"complete-brief",retry:"next",repair:"none"}:e.startsWith("spec-")?{severity:"error",requiredAction:"resolve-spec-state",retry:"next",repair:"none"}:e.startsWith("verification-")?{severity:"error",requiredAction:"complete-verification-evidence",retry:"next",repair:"none"}:e.startsWith("build-")?{severity:"error",requiredAction:"record-build-evidence",retry:"next",repair:"none"}:ia(e)?{severity:e==="workspace-inspection-unavailable"?"info":"warning",requiredAction:"inspect-workspace-advisory",retry:"status",repair:"none"}:{severity:"error",requiredAction:"resolve-finding",retry:"status",repair:"none"})}function WH(e,t,i){if(!i.path)return null;let n;if(bs.isAbsolute(i.path)?n=bs.resolve(i.path):/^(?:brief-|verification-|spec-source)/u.test(i.code)?n=bs.resolve(C(e,t.name),...i.path.split(/[\\/]/u)):n=bs.resolve(e.projectRoot,...i.path.split(/[\\/]/u)),!$(e.projectRoot,n))return null;let r=bs.relative(e.projectRoot,n).replaceAll("\\","/");return r===""?".":r}function JH(e,t,i){return e==="next"?`comet native next ${t.name} --summary ""${i==="contract-changed-after-approval"||i==="shape-confirmation-required"||i==="approval-confirmation-required"?" --confirmed":""}`:e==="status"?`comet native status ${t.name} --details`:null}function ni(e){return e.findings.map(t=>{let i=VH(t.code);return{code:t.code,message:t.message,severity:i.severity,path:WH(e.paths,e.state,t),requiredAction:i.requiredAction,retryCommand:JH(i.retry,e.state,t.code),repairCommand:i.repair==="doctor"?`comet native doctor ${e.state.name} --repair${t.code.startsWith("transition-")?" --strategy continue":""}`:null,requiresUserDecision:t.code==="brief-blocking-question"||t.code==="shape-confirmation-required"||t.code==="approval-confirmation-required"||t.code==="contract-changed-after-approval"||t.code==="verification-scope-partial"||t.code==="repair-iteration-limit"||t.code==="repair-override-exhausted"}}).sort((t,i)=>{let n={error:0,warning:1,info:2};return n[t.severity]-n[i.severity]||t.code.localeCompare(i.code)||(t.path??"").localeCompare(i.path??"")||t.message.localeCompare(i.message)})}function Wk(e){let t=[...new Set(e.map(i=>i.code))];return{total:e.length,errors:e.filter(i=>i.severity==="error").length,warnings:e.filter(i=>i.severity==="warning").length,info:e.filter(i=>i.severity==="info").length,requiresUserDecision:e.some(i=>i.requiresUserDecision),codes:t.slice(0,Vk),truncated:t.length>Vk}}import Jk from"path";var zk=240,Gk=8,gu=50;function Uk(e){let t=Array.from(e);return t.length<=zk?e:`${t.slice(0,zk-1).join("")}…`}function zH(e){let t=e.indexOf(":");return t<0?e:e.slice(0,t)}function GH(e){let t=[...new Set(e.map(zH))],i={freshness:e.length===0||e.length===1&&e[0]==="no-checkpoint"?"fresh":"stale",codes:t.slice(0,Gk),reasonCount:e.length,codesTruncated:t.length>Gk};return{inspection:i,inspectionDetails:{...i,reasons:e.slice(0,gu),reasonsTruncated:e.length>gu}}}async function Kk(e){let t=null;try{let s=await Gi(e.paths,e.state.name);s&&(t={code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${s.id} requires deterministic recovery`,path:zi(e.paths,e.state.name)})}catch(s){t={code:"checkpoint-progress-invalid",message:`Native progress checkpoint journal is invalid: ${s.message}. Automatic repair is unavailable; inspect and move the invalid checkpoint journal aside before retrying`,path:zi(e.paths,e.state.name)}}let i=await jb({paths:e.paths,name:e.state.name,stateRevision:e.state.revision}),n=t?[t.code,...i.reasons]:i.reasons,r=GH(n);if(!i.checkpoint)return{inspection:r.inspection,inspectionDetails:r.inspectionDetails,checkpoint:null,checkpointDetails:null,findings:t?[t,...i.findings]:i.findings,maxCheckpointArtifacts:ei.maxArtifacts};let a={id:i.checkpoint.id,createdAt:i.checkpoint.createdAt,phase:i.checkpoint.phase,stateRevision:i.checkpoint.stateRevision,summary:Uk(i.checkpoint.summary),nextAction:Uk(i.checkpoint.nextAction),artifactCount:i.checkpoint.artifactCount},o=i.manifest?{...a,summary:i.checkpoint.summary,nextAction:i.checkpoint.nextAction,manifestHash:i.checkpoint.manifestHash,manifestRef:Jk.relative(e.paths.projectRoot,Jk.join(C(e.paths,e.state.name),...i.checkpoint.manifestRef.split("/"))).replaceAll("\\","/"),artifacts:i.manifest.artifacts,totalBytes:i.manifest.totalBytes}:null;return{inspection:r.inspection,inspectionDetails:r.inspectionDetails,checkpoint:a,checkpointDetails:o,findings:t?[t,...i.findings]:i.findings,maxCheckpointArtifacts:ei.maxArtifacts}}function UH(e){if(e.phase!=="build"||e.verification_result!=="fail"||!e.implementation_scope||!e.verification_evidence)throw new Error("Native repair guard requires a failed Verify-to-Build state")}async function Yk(e,t){let i=C(e,t.name),n=await be(i);if(!n||!t.run_id||n.runId!==t.run_id)throw new Error("Native repair history Run state is missing or mismatched");let r=await ea(i,n.checkpointRef);if(!r||r.runId!==n.runId||r.stateVersion!==n.iteration)throw new Error("Native repair history checkpoint is missing or mismatched");return{trajectory:await qe(i,n.trajectoryRef),committedTrajectoryOffset:r.trajectoryOffset,runId:n.runId}}async function wp(e,t){let i=await Yk(e,t);return{committed:i,latest:UN(i),history:GN(i)}}function KH(e,t){let i=e.latest;if(!i)return null;let n=e.history.filter(l=>l.kind==="failure"),r=n.length===0?0:rs({signatureHash:i.signatureHash,...i.contractHash===null?{}:{failedAcceptanceIds:i.failedAcceptanceIds,failedCheckIds:i.failedCheckIds}},n.slice(0,-1)),a=i.overrideSummaryHash!==null,o=e.history.some(l=>l.kind==="override"&&l.signatureHash===i.signatureHash),s=n.length>=t,c=i.disposition==="hard-stop"&&!s?"continue":i.disposition;return{disposition:s?"hard-stop":c,reasonCode:a?"override-accepted":o&&i.disposition==="manual-stop"?"override-already-used":s?"repair-iteration-limit":i.disposition==="manual-stop"?"repeated-failure-stop":i.disposition==="warn"?"repeated-failure-warning":"new-failure-signature",signatureHash:i.signatureHash,consecutiveFailures:r,totalRepairFailures:n.length,remainingIterations:Math.max(0,t-n.length),overrideAccepted:a}}async function Xk(e,t,i){return KH(await wp(e,t),i)}function Qk(e){return{disposition:e.decision.disposition,reasonCode:e.decision.reasonCode,signatureHash:e.decision.signature.signatureHash,consecutiveFailures:e.decision.consecutiveFailures,totalRepairFailures:e.decision.totalRepairFailures,remainingIterations:e.decision.remainingIterations,overrideAccepted:e.decision.overrideAccepted}}function YH(e){return ga(e.filter(t=>t.status!=="passed").map(t=>NN(t)))}async function Zk(e){if(!e.state.implementation_scope)throw new Error("Native repair failure has no implementation scope");let t=[...new Set([...e.envelope.requiredReceiptRefs,...e.envelope.receiptRefs])],[i,n,r]=await Promise.all([Yk(e.paths,e.state),yi(e.paths,e.state.name,e.state.implementation_scope),Promise.all(t.map(o=>Hn(e.paths,e.state.name,o)))]),a=YH(r);return YN({...i,envelope:e.envelope,implementationScope:n,maxVerifyFailures:e.maxVerifyFailures,...a.length>0?{failedCheckIds:a}:{}})}async function eS(e){let t=await wp(e.paths,e.state),i=t.latest,n=Kt(e.currentImplementationScope).scope.contractHash;if(i?.contractHash!==null&&i?.contractHash!==n){if(e.override)throw new Error("Native repair override cannot cross a confirmed contract change");return{disposition:"proceed",eventProjection:null}}let r=t.history.filter(u=>u.kind==="failure").length;if(i&&r>=e.maxVerifyFailures){if(e.override)throw new Error("Native repair hard stop cannot be overridden");return{disposition:"hard-stop",signatureHash:i.signatureHash,overrideRecorded:t.history.some(u=>u.kind==="override"&&u.signatureHash===i.signatureHash)}}let a=i?.disposition==="hard-stop"&&ru.kind==="override"&&u.signatureHash===i.signatureHash);if(!(e.state.phase==="build"&&e.state.verification_result==="fail"&&e.state.implementation_scope!==null&&e.state.verification_evidence!==null)){if(e.override)throw new Error("Native repair override requires an active failed Verify-to-Build state");return{disposition:"proceed",eventProjection:null}}UH(e.state);let[c,l]=await Promise.all([Dn(e.paths,e.state.name,e.state.verification_evidence),yi(e.paths,e.state.name,e.state.implementation_scope)]);if(l.scope.scopeHash!==c.implementationScopeHash)throw new Error("Native repair verification evidence does not match its implementation scope");if(i.contractHash===null&&ya(e.currentImplementationScope)!==ya(l)){if(e.override)throw new Error("Native repair override is not valid after implementation scope progress");return{disposition:"proceed",eventProjection:null}}if(i.disposition==="hard-stop"){if(e.override)throw new Error("Native repair hard stop cannot be overridden without implementation progress");return{disposition:"hard-stop",signatureHash:i.signatureHash,overrideRecorded:o}}return o?{disposition:"hard-stop",signatureHash:i.signatureHash,overrideRecorded:o}:e.override?{disposition:"proceed",eventProjection:KN({...t.committed,override:e.override}).eventProjection}:{disposition:"manual-stop",signatureHash:i.signatureHash,overrideRecorded:!1}}async function tS(e,t,i){if(t.phase!=="build"||t.verification_result!=="fail")return null;let n=await wp(e,t),r=n.latest;if(!r)return null;let a=n.history.filter(c=>c.kind==="failure"),o=a.length>=i,s=r.disposition==="hard-stop"&&!o?"continue":r.disposition;return{disposition:o?"hard-stop":s,signatureHash:r.signatureHash,overrideRecorded:n.history.some(c=>c.kind==="override"&&c.signatureHash===r.signatureHash),failedAcceptanceIds:[...r.failedAcceptanceIds],failedCheckIds:[...r.failedCheckIds],totalVerifyFailures:a.length,maxVerifyFailures:i,remainingVerifyFailures:Math.max(0,i-a.length)}}var QH=/^native-status-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u,xa=Object.freeze({maxItems:24,maxChanges:4096,maxSerializedBytes:512*1024});async function ZH(e){return(await ys(e))?.change??null}function e0(e,t,i=!1,n){return e.phase==="archive"?t?`comet native archive ${e.name} --dry-run`:i?`comet native next ${e.name} --summary ""`:null:`comet native next ${e.name} --summary ""${e.phase==="shape"||e.phase==="build"&&e.approval!=="confirmed"?" --confirmed":""}`}async function t0(e,t){let i=C(e,t.name),n=[...(await ur(i,t.brief)).findings,...(await ca(e,t)).findings,...await vu(e,t)];if(t.phase==="shape"||t.phase==="build")try{let r=await vi(e,t.name);if(r===null)n.push({code:"baseline-snapshot-missing",message:"Native baseline is missing; restore a trusted baseline before advancing"});else{let a=await kn(e,r);a.complete||n.push({code:"baseline-snapshot-incomplete",message:`Native baseline is incomplete within the project-owned scope (${a.omittedCount} omitted entries); resolve the omissions before advancing`})}}catch(r){n.push({code:"baseline-snapshot-invalid",message:`Native baseline could not be inspected safely: ${r.message}`})}if(t.phase==="build")try{let r=await Et({changeDir:i,briefRef:t.brief,specChanges:t.spec_changes});(t.approved_contract_hash??null)!==r.contract.contractHash&&n.push({code:"contract-changed-after-approval",message:t.approval===null||t.approved_contract_hash===null||t.approved_contract_hash===void 0?"Native approval is not bound to a contract hash; re-confirm the current contract":"Native contract changed after approval; re-confirm the current contract"})}catch(r){n.push({code:"contract-inspection-invalid",message:`Native approved contract could not be inspected safely: ${r.message}`})}try{await bi(e,t.name)&&n.unshift({code:"transition-incomplete",message:"Native phase transition recovery is pending"})}catch(r){n.unshift({code:"transition-invalid",message:`Native transition journal is invalid: ${r.message}`})}return t.verification_report?n.push(...(await sa(i,t.verification_report)).findings):(t.phase==="verify"||t.phase==="archive"||t.verification_result==="pass")&&n.push({code:"verification-report-missing",message:"Native change has no verification report"}),n}async function Ze(e,t,i){let n=await ZH(e)===t,r;try{let w=await ft(e,t);if(w.status==="migration-required"&&w.state)return{name:t,phase:w.state.phase,revision:"revision"in w.state?w.state.revision:null,approval:w.state.approval,verificationResult:w.state.verification_result,specChanges:w.state.spec_changes.length,selected:n,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["migration-required"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,schema:w.schema,migrationRequired:!0,minimumRuntimeVersion:w.minimumRuntimeVersion,error:w.message};if(w.status!=="current"||!w.state)return{name:t,phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:n,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["runtime-incompatible"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,schema:w.schema,minimumRuntimeVersion:w.minimumRuntimeVersion,error:w.message??`Native change ${t} is incompatible`};r=w.state}catch(w){return{name:t,phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:n,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["change-invalid"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,error:w.message}}let a=await Kk({paths:e,state:r}),o=null,s=[];if(r.phase==="build"&&r.verification_result==="fail")try{if(o=await tS(e,r,i?.maxVerifyFailures??5),o&&(o.disposition==="manual-stop"||o.disposition==="hard-stop")){let w=o.disposition==="hard-stop"?"repair-iteration-limit":o.overrideRecorded?"repair-override-exhausted":"repair-stagnation-stop";s.push({code:w,message:`Native repair is stopped at failure signature: ${o.signatureHash}`})}}catch{s.push({code:"trajectory-invalid",message:"Native repair history could not be reconstructed safely"})}let c;if(i?.details&&(r.phase==="build"||r.phase==="verify"||r.phase==="archive"))try{let w=await Et({changeDir:C(e,r.name),briefRef:r.brief,specChanges:r.spec_changes}),g=new Map;if(r.phase==="build"&&r.verification_result==="fail"&&r.verification_evidence){let E=await Dn(e,r.name,r.verification_evidence);for(let O of E.acceptanceTrace.entries)g.set(O.acceptanceId,O.status==="failed"?"failed":O.status==="missing"?"missing":"satisfied")}c=Zl({criteria:w.contract.acceptance,acceptanceHash:w.contract.acceptanceHash,verificationStatuses:g,failedCheckIds:o?.failedCheckIds??[],...i.acceptanceCursor?{cursor:i.acceptanceCursor}:{}})}catch(w){if(i.acceptanceCursor)throw w;c=void 0}let l=[];if(i?.includeConflictFindings!==!1)try{let w=await Vl(e,r.name,{tolerateInvalidSiblings:!0});l.push(...w.findingCodes.map(g=>({code:g,message:`Native change overlap is visible in the current root: ${g}`})))}catch{l.push({code:"native-conflict-inspection-invalid",message:"Native change overlap could not be recomputed safely"})}let u=[];try{let w=await Ve(e,r.name);if(w)if(w.schema==="comet.native.workspace.v3"){let g=await sr({paths:e,identity:w});g.state==="drifted"&&g.code&&u.push({code:g.code,message:g.message??"Native workspace binding is no longer valid"})}else{let g=await or({paths:e,identity:w});u.push(...g.findingCodes.map(E=>({code:E,message:`Native workspace advisory changed: ${E} (${g.driftComponents.join(", ")||"no-component"})`})))}}catch{u.push({code:"workspace-binding-invalid",message:"Native workspace binding could not be read or validated safely"})}let d=[],f=!1;if(r.phase==="verify"){let w=await ms({paths:e,state:r});f=w.freshness!=="fresh",d.push(...w.findingCodes.map(g=>({code:g,message:`Native Verify implementation scope is not current: ${g}`})))}let h=null,m=[];if(r.phase==="archive")try{h=await kr({paths:e,name:r.name}),m.push(...h.findingCodes.map(w=>({code:w,message:`Native Archive is blocked: ${w}`})))}catch{m.push({code:"archive-preflight-invalid",message:"Native Archive preflight could not be recomputed safely"})}let p=[...await t0(e,r),...a.findings,...l,...u,...d,...s,...m].filter((w,g,E)=>E.findIndex(O=>O.code===w.code&&O.path===w.path)===g),v=ni({paths:e,state:r,findings:p}),S=v.filter(w=>!ia(w.code)),k=r.phase==="archive"&&h?.ready===!0&&S.length===0,N=f||r.phase==="archive"&&(h?.findingCodes??[]).some(w=>new Set(["verification-evidence-stale","verification-evidence-invalid","verification-evidence-missing","verification-contract-stale","verification-implementation-stale","verification-report-stale","verification-state-mismatch"]).has(w)),b=v.some(w=>w.code==="trajectory-tail-incomplete"||w.code==="trajectory-invalid"||w.requiredAction==="return-to-bound-working-directory"||w.requiredAction==="repair-workspace-binding"),R=o?.disposition==="manual-stop"||o?.disposition==="hard-stop",y=v.find(w=>w.severity==="error");return{name:r.name,phase:r.phase,revision:r.revision,approval:r.approval,verificationResult:r.verification_result,specChanges:r.spec_changes.length,selected:n,nextCommand:b||R?null:e0(r,k,N,i?.clarificationMode),archiveReady:k,inspection:a.inspection,findingSummary:Wk(v),detailsCommand:`comet native status ${r.name} --details`,checkpoint:a.checkpoint,continuation:Me({state:r,findings:v,archiveReady:k,evidenceRetreat:N,clarificationMode:i?.clarificationMode}),repair:o,...i?.details?{...c?{acceptancePage:c}:{},findings:v.slice(0,50),inspectionDetails:a.inspectionDetails,checkpointDetails:a.checkpointDetails,budgets:{maxFindings:50,maxInspectionReasons:gu,maxCheckpointArtifacts:a.maxCheckpointArtifacts,findingsTruncated:v.length>50,inspectionReasonsTruncated:a.inspectionDetails.reasonsTruncated,checkpointArtifactsTruncated:!1}}:{},schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,...y?{error:y.message}:{}}}async function i0(e){let t;try{t=await hi({root:e.nativeRoot,directory:e.changesDir,label:"Native status changes directory"})}catch(r){if(r.code==="ENOENT")return[];throw r}let i=[],n=await XH.opendir(e.changesDir);try{for await(let r of n)if(!(!r.isDirectory()||r.isSymbolicLink())&&(i.push(r.name),i.length>xa.maxChanges))throw new Error(`Native status exceeds ${xa.maxChanges} visible changes`)}finally{await n.close().catch(r=>{if(r.code!=="ERR_DIR_CLOSED")throw r})}return await t.verify(),i.sort()}function iS(e,t){let i=t.toString(36),n=H("comet.native.status-cursor.v1",{namesHash:e,offset:t});return`native-status-v1.${e}.${i}.${n}`}function n0(e){if(e.cursor===void 0||e.cursor===null)return 0;let t=QH.exec(e.cursor);if(!t)throw new Error("Native status cursor is invalid");if(t[1]!==e.namesHash)throw new Error("Native status cursor is stale");let i=Number.parseInt(t[2],36);if(!Number.isSafeInteger(i)||i<=0||i>=e.total||i.toString(36)!==t[2])throw new Error("Native status cursor offset is invalid");let n=H("comet.native.status-cursor.v1",{namesHash:e.namesHash,offset:i});if(t[3]!==n)throw new Error("Native status cursor integrity check failed");return i}async function yp(e,t){let i=await i0(e),n=H("comet.native.status-names.v1",i),r=n0({namesHash:n,total:i.length,cursor:t?.cursor}),a=await Promise.all(i.slice(r,r+xa.maxItems).map(c=>Ze(e,c,{includeConflictFindings:!1,clarificationMode:t?.clarificationMode,maxVerifyFailures:t?.maxVerifyFailures}))),o=[];for(let c of a){let l=[...o,c],u=r+l.length,d={schema:"comet.native.status-page.v1",total:i.length,offset:r,items:l,nextCursor:uxa.maxSerializedBytes){if(o.length===0)throw new Error("Native status item exceeds its page serialization budget");break}o.push(c)}let s=r+o.length;return{schema:"comet.native.status-page.v1",total:i.length,offset:r,items:o,nextCursor:s2e3)throw new Error(`${t} must be between 1 and 2000 characters`);return i}function a0(e){if(e!==void 0){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native expected revision must be a positive integer");return e}}async function rS(e){let t=nS(e.summary,"Checkpoint summary"),i=nS(e.nextAction,"Checkpoint next action"),n=a0(e.expectedRevision);return te(e.paths,`checkpoint ${e.name}`,()=>De(e.paths,e.name,`checkpoint ${e.name}`,async()=>{await Rt(e.paths,e.name);let r=await G(e.paths,e.name),a=await Tb(e.paths,e.name,e.artifacts??[]),o=ds(a),s=D(JSON.stringify({summary:t,nextAction:i,artifacts:a.artifacts})),c=await Gh(e.paths,e.name);if(c?.inputHash===s&&c.stateRevision===r.revision&&c.phase===r.phase){if(n!==void 0&&n!==c.previousRevision&&n!==r.revision)throw new xn(r.name,n,r.revision);return{change:r,checkpoint:c,idempotent:!0,expectedRevision:n??c.previousRevision,previousRevision:c.previousRevision,revision:r.revision,outcome:"idempotent",continuation:Me({state:r})}}if(n!==void 0&&r.revision!==n)throw new xn(r.name,n,r.revision);let l={...r,revision:r.revision+1},u={schema:"comet.native.progress-checkpoint.v1",id:e.checkpointId?.()??r0(),change:r.name,phase:r.phase,previousRevision:r.revision,stateRevision:l.revision,summary:t,nextAction:i,inputHash:s,manifestHash:o,manifestRef:Wh(o),artifactCount:a.artifacts.length,createdAt:(e.now??new Date).toISOString()},d=await Ob({paths:e.paths,previousState:r,nextState:l,checkpoint:u,manifest:a,now:e.now,checkpointId:()=>u.id});await e.hooks?.afterPrepared?.(d);let f=await fs(e.paths,e.name,e.hooks);if(!f)throw new Error("Native checkpoint journal disappeared before completion");return{change:f.nextState,checkpoint:f.checkpoint,idempotent:!1,expectedRevision:n??f.checkpoint.previousRevision,previousRevision:f.checkpoint.previousRevision,revision:f.nextState.revision,outcome:"recorded",continuation:Me({state:f.nextState})}}))}async function oS(e,t){let i=ae(e,"change name"),n=J(e,"--summary");if(!n)throw new I("--summary is required");let r=J(e,"--next-action");if(!r)throw new I("--next-action is required");let a=Yi(e,"--artifact"),o=Ak(e);Y(e);let{config:s,paths:c}=await Oe(t),l=await rS({paths:c,name:i,summary:n,nextAction:r,artifacts:a,expectedRevision:o}),u=await Ze(c,i,{clarificationMode:s.native.clarification_mode,maxVerifyFailures:s.native.max_verify_failures}),d=aS.relative(c.projectRoot,aS.join(C(c,i),...l.checkpoint.manifestRef.split("/"))).replaceAll("\\","/");return Z("checkpoint",{...l,checkpoint:{...l.checkpoint,manifestRef:d},continuation:u.continuation})}import{promises as rD}from"fs";import Le from"path";import{createHash as E0,randomUUID as R0}from"node:crypto";import{constants as Rp,promises as ie}from"node:fs";import he from"node:path";var Nu=Ts(uo(),1);import{randomUUID as o0}from"crypto";import{promises as dS}from"fs";import kp from"path";import{isDeepStrictEqual as Sp}from"util";var Rr=/^[a-f0-9]{64}$/u,s0=new Set(["schema","id","change","fromSchema","toSchema","sourceHash","targetHash","createdAt","nextState","transition","transitionSupersede","runRetreat"]),c0=new Set(["sourceHash","targetHash","nextJournal"]),l0=new Set(["sourceHash","transitionId","previousRun","nextRun","evidenceHash","eventData"]),sS=new Set(["fromSchema","toSchema","previousPhase","nextPhase","reason","supersededTransitionId"]),u0=new Set(["previousRun","nextRun","evidenceHash","eventData"]);function wu(e,t,i){let n=Object.keys(e).find(r=>!t.has(r));if(n)throw new Error(`${i} contains unknown field: ${n}`)}function cS(e){return JSON.stringify(e,null,2)+` -`}function Ep(e){return e.schema===He?Sl(e):Pn(e)}function bp(e,t){return{...e,schema:He,minimum_runtime_version:2,revision:t}}function d0(e){return{...e,schema:Oi,minimum_runtime_version:2,revision:1,previousState:bp(e.previousState,1),nextState:bp(e.nextState,2)}}function yu(e,t){let i=t?.retreatEvidencePhase===!0&&(e.phase==="verify"||e.phase==="archive");return{...e,schema:xe,minimum_runtime_version:3,verification_protocol:"legacy-v1",revision:e.revision+(i&&t?.incrementRetreatRevision?1:0),phase:i?"build":e.phase,verification_result:i?"pending":e.verification_result,verification_report:i?null:e.verification_report,approved_contract_hash:null,implementation_scope:null,verification_evidence:null,partial_allowance:null,archived:i?!1:e.archived}}function f0(e){if(e.nextState.phase==="archive")throw new Error("Native v2 Archive transition must be superseded by schema migration");let t=e.previousState.phase!=="shape"&&e.nextState.phase==="build"&&e.eventData.verificationResult===null,i=t?D(JSON.stringify({operation:"spec-rebase",change:e.change,summary:e.eventData.summary,specChanges:e.nextState.spec_changes})):e.evidenceHash;return{...e,schema:ji,minimum_runtime_version:3,revision:1,operation:t?"spec-rebase":"advance",evidenceHash:i,previousState:yu(e.previousState),nextState:{...yu(e.nextState),...t?{implementation_scope:null,verification_evidence:null,partial_allowance:null}:{}},eventData:{...e.eventData,evidenceHash:i},nextRun:e.previousRun===null?{...e.nextRun,skillVersion:mt.definition.metadata.version,skillHash:vr}:e.nextRun}}function lS(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Aa(e,t){return JSON.stringify(Sl(e))===JSON.stringify(Sl(t))}function uS(e,t){return JSON.stringify(Pn(e))===JSON.stringify(Pn(t))}function Xi(e,t){return Sp(e,t)}function h0(e,t,i,n){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Schema migration transition supersede plan is invalid");let r=e;if(wu(r,l0,"Schema migration transition supersede plan"),typeof r.sourceHash!="string"||!Rr.test(r.sourceHash))throw new Error("Schema migration transition supersede source hash is invalid");if(typeof r.transitionId!="string"||r.transitionId.length===0)throw new Error("Schema migration superseded transition id is invalid");if(typeof r.evidenceHash!="string"||!Rr.test(r.evidenceHash))throw new Error("Schema migration transition supersede evidence hash is invalid");let a=Rn(r.previousRun),o=Rn(r.nextRun);if(a.runId!==o.runId||i.run_id!==o.runId||i.phase!=="build"&&i.phase!=="verify"||o.currentStep!==i.phase||o.pending!==null||o.status!=="running"||i.verification_result!=="pending"||i.verification_report!==null||i.implementation_scope!==null||i.verification_evidence!==null||i.partial_allowance!==null)throw new Error("Schema migration transition supersede Run does not match target state");let s=a.currentStep==="verify"&&i.phase==="build"||a.currentStep==="archive"&&i.phase==="build",c=a.currentStep===i.phase?a:s?{...a,currentStep:i.phase,iteration:a.iteration+1,pending:null,status:"running"}:null;if(!c||!Xi(c,o))throw new Error("Schema migration transition supersede Run retreat is invalid");if(!r.eventData||typeof r.eventData!="object"||Array.isArray(r.eventData))throw new Error("Schema migration transition supersede event is invalid");let l=r.eventData,u=Object.keys(l);if(u.length!==sS.size||u.some(f=>!sS.has(f))||l.fromSchema!==He||l.toSchema!==xe||!["build","verify","archive"].includes(l.previousPhase)||l.nextPhase!==i.phase||l.reason!==(i.phase==="build"?"implementation-scope-required":"verification-evidence-required")||l.supersededTransitionId!==r.transitionId)throw new Error("Schema migration transition supersede event semantics are invalid");if(i.name!==t)throw new Error("Schema migration transition supersede change mismatch");let d=D(JSON.stringify({operation:"supersede-v2-evidence-transition",change:t,transitionId:r.transitionId,migrationId:n,previousPhase:l.previousPhase,nextPhase:l.nextPhase,reason:l.reason,previousIteration:a.iteration,nextRevision:i.revision}));if(r.evidenceHash!==d)throw new Error("Schema migration transition supersede evidence hash mismatch");return{sourceHash:r.sourceHash,transitionId:r.transitionId,previousRun:a,nextRun:o,evidenceHash:r.evidenceHash,eventData:l}}function ks(e,t){return kp.join(C(e,t),"runtime","schema-migration.json")}function p0(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native schema migration journal must be an object");wu(e,s0,"Native schema migration journal");let i=e;if(i.schema!=="comet.native.schema-migration.v1")throw new Error("Unsupported Native schema migration journal");if(i.change!==t)throw new Error("Schema migration change mismatch");let n=i.fromSchema===jt&&i.toSchema===He,r=i.fromSchema===He&&i.toSchema===xe;if(!n&&!r)throw new Error("Schema migration route is unsupported");if(typeof i.id!="string"||i.id.length===0)throw new Error("Schema migration id is invalid");if(typeof i.sourceHash!="string"||!Rr.test(i.sourceHash)||typeof i.targetHash!="string"||!Rr.test(i.targetHash))throw new Error("Schema migration hash is invalid");if(typeof i.createdAt!="string"||Number.isNaN(Date.parse(i.createdAt)))throw new Error("Schema migration timestamp is invalid");let a=n?An(i.nextState):Ot(i.nextState);if(a.name!==t)throw new Error("Schema migration target state change mismatch");if(D((0,Nu.stringify)(Ep(a)))!==i.targetHash)throw new Error("Schema migration state target hash does not match its document");let o;if(i.transition!==void 0){if(!i.transition||typeof i.transition!="object")throw new Error("Schema migration transition target is invalid");wu(i.transition,c0,"Schema migration transition target");let l=i.transition;if(typeof l.sourceHash!="string"||!Rr.test(l.sourceHash)||typeof l.targetHash!="string"||!Rr.test(l.targetHash))throw new Error("Schema migration transition hash is invalid");let u=n?jh(l.nextJournal,t):Ql(l.nextJournal,t);if(D(JSON.stringify(l.nextJournal,null,2)+` -`)!==l.targetHash)throw new Error("Schema migration transition target hash does not match its journal");if(!(n&&a.schema===He?Aa(a,u.previousState)||Aa(a,u.nextState):a.schema===xe&&(uS(a,u.previousState)||uS(a,u.nextState))))throw new Error("Schema migration state/transition target mismatch");o={sourceHash:l.sourceHash,targetHash:l.targetHash,nextJournal:l.nextJournal}}if(n&&(!o&&a.revision!==1||o&&a.revision!==1&&a.revision!==2))throw new Error("Schema migration v1 target revision is invalid");let s;if(i.transitionSupersede!==void 0){if(!r||o)throw new Error("Schema migration transition supersede plan is not valid for this route");if(a.schema!==xe)throw new Error("Schema migration transition supersede target schema is invalid");s=h0(i.transitionSupersede,t,a,i.id)}let c;if(i.runRetreat!==void 0){if(!r||o||s)throw new Error("Schema migration Run retreat is not valid for this route");if(!i.runRetreat||typeof i.runRetreat!="object")throw new Error("Schema migration Run retreat is invalid");wu(i.runRetreat,u0,"Schema migration Run retreat");let l=i.runRetreat,u,d;try{u=Rn(l.previousRun),d=Rn(l.nextRun)}catch(f){throw new Error("Schema migration Run retreat is invalid",{cause:f})}if(typeof l.evidenceHash!="string"||!Rr.test(l.evidenceHash)||!l.eventData||typeof l.eventData!="object"||Array.isArray(l.eventData))throw new Error("Schema migration Run retreat is invalid");if(a.schema!==xe||a.phase!=="build"||a.run_id!==d.runId||u.runId!==d.runId||u.currentStep!=="verify"&&u.currentStep!=="archive"||d.currentStep!=="build"||d.iteration!==u.iteration+1)throw new Error("Schema migration Run retreat does not match target state");c={previousRun:u,nextRun:d,evidenceHash:l.evidenceHash,eventData:l.eventData}}if(o&&c||s&&c)throw new Error("Schema migration has conflicting recovery plans");return{schema:"comet.native.schema-migration.v1",id:i.id,change:t,fromSchema:i.fromSchema,toSchema:i.toSchema,sourceHash:i.sourceHash,targetHash:i.targetHash,createdAt:i.createdAt,nextState:a,...o?{transition:o}:{},...s?{transitionSupersede:s}:{},...c?{runRetreat:c}:{}}}async function Ss(e,t){let i=ks(e,t);await x(e.nativeRoot,i);try{let n=await el({root:e.nativeRoot,file:i,maxBytes:524288,label:"Native schema migration journal"});return p0(JSON.parse(n.text),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function m0(e,t,i){let n=await vi(e,t),r=n?await kn(e,n):await $o(e,{now:new Date(i),origin:"legacy-migration"});if(!r.complete){let a=hl(r),o=r.omitted.reduce((c,l)=>(c[l.reason]=(c[l.reason]??0)+1,c),{}),s=r.omissionOverflow?.count??0;throw s>0&&(o.overflow=s),new gi(t,r.omittedCount,o,a.samplePaths,a.sampleTruncated)}n===null&&await pl(e,t,r)}async function fS(e){try{return await lt(e)}catch(t){if(t.code==="ENOENT")return null;throw t}}function v0(e,t){let i=e.transitionSupersede;return{sequence:t,timestamp:e.createdAt,type:"state_migrated",runId:i.nextRun.runId,data:{...i.eventData,migrationId:e.id,evidenceHash:i.evidenceHash}}}async function hS(e,t){let i=t.transitionSupersede,n=C(e,t.change),r=await qe(n,i.nextRun.trajectoryRef),a=r.map((s,c)=>({event:s,index:c})).filter(({event:s})=>s.data.migrationId===t.id);if(a.length>1)throw new Error(`Native schema migration event ${t.id} is duplicated`);let o=a[0];if(o&&!Sp(o.event,v0(t,o.index+1)))throw new Error(`Native schema migration event ${t.id} changed`);return{trajectoryLength:r.length,sequence:o?.event.sequence??null}}async function g0(e,t,i){if(!t.transitionSupersede)return;let n=We(e,t.change),r=await fS(n);if(r===t.transitionSupersede.sourceHash)return;if(r!==null)throw new Error(`Native superseded transition source changed for ${t.change}: expected ${t.transitionSupersede.sourceHash}, actual ${r}`);let a=await be(C(e,t.change)),o=await hS(e,t),s=await ea(C(e,t.change),t.transitionSupersede.nextRun.checkpointRef);if(!i||!a||!Xi(a,t.transitionSupersede.nextRun)||o.sequence===null||!s||s.runId!==t.transitionSupersede.nextRun.runId||s.stateVersion!==t.transitionSupersede.nextRun.iteration||s.trajectoryOffset!==o.sequence||s.contextHash!==null||s.artifactsHash!==D(t.transitionSupersede.evidenceHash)||s.createdAt!==t.createdAt)throw new Error(`Native superseded transition disappeared before migration ${t.id} was durable`)}async function w0(e,t,i){let n=t.transitionSupersede;if(!n)return;let r=C(e,t.change),a=await be(r);if(!a)throw new Error(`Native schema migration Run state disappeared for ${t.change}`);if(!Xi(a,n.nextRun)){if(!Xi(a,n.previousRun))throw new Error(`Native schema migration Run source changed for ${t.change}`);await rr(r,n.nextRun),await i?.afterRunStateWritten?.(t)}if(!Xi(await be(r),n.nextRun))throw new Error(`Native schema migration Run write diverged for ${t.change}`);let o=await hS(e,t);if(o.sequence===null){let l=await Fn({changeDir:r,run:n.nextRun,type:"state_migrated",data:{...n.eventData,migrationId:t.id,evidenceHash:n.evidenceHash},now:new Date(t.createdAt)});o={trajectoryLength:l.sequence,sequence:l.sequence}}await i?.afterTrajectoryWritten?.(t),await gr({changeDir:r,run:n.nextRun,trajectoryOffset:o.sequence,evidenceHash:n.evidenceHash,now:new Date(t.createdAt)}),await i?.afterCheckpointWritten?.(t);let s=We(e,t.change),c=await fS(s);if(c!==null){if(c!==n.sourceHash)throw new Error(`Native superseded transition changed before removal for ${t.change}`);await dS.rm(s),await i?.afterTransitionSuperseded?.(t)}}async function y0(e,t,i){if(!t.runRetreat)return;let n=C(e,t.change),r=await be(n);if(!r)throw new Error(`Native schema migration Run state disappeared for ${t.change}`);if(!Xi(r,t.runRetreat.nextRun)){if(!Xi(r,t.runRetreat.previousRun))throw new Error(`Native schema migration Run source changed for ${t.change}`);await rr(n,t.runRetreat.nextRun),await i?.afterRunStateWritten?.(t)}let a=await qe(n,t.runRetreat.nextRun.trajectoryRef),o=a.find(s=>s.type==="state_migrated"&&s.data.migrationId===t.id);o||(o=await Fn({changeDir:n,run:t.runRetreat.nextRun,type:"state_migrated",data:{...t.runRetreat.eventData,migrationId:t.id,evidenceHash:t.runRetreat.evidenceHash},now:new Date(t.createdAt)}),a=[...a,o]),await i?.afterTrajectoryWritten?.(t),await gr({changeDir:n,run:t.runRetreat.nextRun,trajectoryOffset:a.length,evidenceHash:t.runRetreat.evidenceHash,now:new Date(t.createdAt)}),await i?.afterCheckpointWritten?.(t)}async function N0(e,t,i){let n=await Ss(e,t);if(!n)return null;if(await aa(e,t))throw new Error(`Native change ${t} has a pending progress checkpoint; recover it with its v2 runtime before schema migration`);let r=kp.join(C(e,t),je),a=await lt(r);if(await g0(e,n,a===n.targetHash),await m0(e,t,n.createdAt),a!==n.targetHash){if(a!==n.sourceHash)throw new Error(`Native schema migration source changed for ${t}: expected ${n.sourceHash}, actual ${a}`);await $e(r,(0,Nu.stringify)(Ep(n.nextState))),await i?.afterStateWritten?.(n)}if(n.transition){let o=We(e,t),s=await lt(o);if(s!==n.transition.targetHash){if(s!==n.transition.sourceHash)throw new Error(`Native transition migration source changed for ${t}: expected ${n.transition.sourceHash}, actual ${s}`);await le(o,n.transition.nextJournal),await i?.afterTransitionWritten?.(n)}}return await w0(e,n,i),await y0(e,n,i),await dS.rm(ks(e,t),{force:!0}),n.nextState}async function b0(e){let t=C(e.paths,e.state.name),i=await be(t);if(!i||i.runId!==e.state.run_id||i.currentStep!==e.state.phase||i.currentStep!=="verify"&&i.currentStep!=="archive"||i.pending!==null)throw new Error(`Native v2 ${e.state.phase} change ${e.state.name} has no consistent Run state for safe Build retreat`);let n={...i,currentStep:"build",iteration:i.iteration+1,pending:null,status:"running"},r=D(`schema-v3-evidence-retreat:${e.state.name}:${e.state.revision}:${e.migrationId}`);return{previousRun:i,nextRun:n,evidenceHash:r,eventData:{fromSchema:He,toSchema:xe,previousPhase:e.state.phase,nextPhase:"build",reason:"implementation-scope-required"}}}async function k0(e){let{journal:t,state:i}=e;if(!(t.previousState.phase==="build"&&t.nextState.phase==="verify"||t.previousState.phase==="verify"&&(t.nextState.phase==="build"||t.nextState.phase==="archive")))throw new Error("Only a pending v2 evidence-bearing transition can be superseded");let r=Aa(i,t.previousState),a=Aa(i,t.nextState);if(!r&&!a)throw new Error(`Native change ${i.name} does not match its v2 evidence transition`);let o=C(e.paths,i.name),s=await be(o);if(!s)throw new Error(`Native v2 transition Run is missing for ${i.name}`);let c=t.previousRun!==null&&Xi(s,t.previousRun),l=Xi(s,t.nextRun);if(!c&&!l||a&&!l)throw new Error(`Native v2 transition Run does not match its durable state for ${i.name}`);let d=(await qe(o,t.nextRun.trajectoryRef)).map((S,k)=>({event:S,index:k})).filter(({event:S})=>S.data.transitionId===t.id);if(d.length>1)throw new Error(`Native v2 evidence transition ${t.id} has duplicate trajectory events`);let f=d[0];if(f){let S={sequence:f.index+1,timestamp:t.createdAt,type:"state_transitioned",runId:t.nextRun.runId,data:{...t.eventData,transitionId:t.id}};if(!Sp(f.event,S)||!a||!l)throw new Error(`Native v2 evidence transition ${t.id} trajectory event does not match its journal`)}let h={...yu(i),revision:i.revision+(i.phase==="build"?0:1),phase:"build",verification_result:"pending",verification_report:null,implementation_scope:null,verification_evidence:null,partial_allowance:null,archived:!1},m=s,p=s.currentStep!=="build"?{...s,currentStep:"build",iteration:s.iteration+1,pending:null,status:"running"}:s,v=D(JSON.stringify({operation:"supersede-v2-evidence-transition",change:i.name,transitionId:t.id,migrationId:e.migrationId,previousPhase:i.phase,nextPhase:"build",reason:"implementation-scope-required",previousIteration:s.iteration,nextRevision:h.revision}));return{nextState:h,plan:{sourceHash:await lt(We(e.paths,i.name)),transitionId:t.id,previousRun:m,nextRun:p,evidenceHash:v,eventData:{fromSchema:He,toSchema:xe,previousPhase:i.phase,nextPhase:"build",reason:"implementation-scope-required",supersededTransitionId:t.id}}}}async function S0(e){let t,i,n,r;if(e.state.schema===jt){if(t=bp(e.state,1),e.pendingTransition){if(e.pendingTransition.journal.schema!==cr)throw new Error("Native v1 change has a transition from another schema generation");let s=d0(e.pendingTransition.journal);if(lS(e.state,e.pendingTransition.journal.previousState))t=s.previousState;else if(lS(e.state,e.pendingTransition.journal.nextState))t=s.nextState;else throw new Error(`Native change ${e.name} does not match either state in its v1 transition journal`);let c=We(e.paths,e.name);i={sourceHash:await lt(c),targetHash:D(cS(s)),nextJournal:s}}}else if(e.pendingTransition){if(e.pendingTransition.journal.schema!==Oi)throw new Error("Native v2 change has a transition from another schema generation");let s=e.pendingTransition.journal;if(s.previousState.phase==="build"&&s.nextState.phase==="verify"||s.previousState.phase==="verify"&&(s.nextState.phase==="build"||s.nextState.phase==="archive")){let l=await k0({paths:e.paths,state:e.state,journal:s,migrationId:e.id});t=l.nextState,n=l.plan}else{let l=f0(s);if(Aa(e.state,e.pendingTransition.journal.previousState))t=l.previousState;else if(Aa(e.state,e.pendingTransition.journal.nextState))t=l.nextState;else throw new Error(`Native change ${e.name} does not match either state in its v2 transition journal`);let u=We(e.paths,e.name);i={sourceHash:await lt(u),targetHash:D(cS(l)),nextJournal:l}}}else t=yu(e.state,{retreatEvidencePhase:!0,incrementRetreatRevision:!0}),(e.state.phase==="verify"||e.state.phase==="archive")&&(r=await b0({paths:e.paths,state:e.state,migrationId:e.id}));let a=kp.join(C(e.paths,e.name),je),o=(0,Nu.stringify)(Ep(t));return{schema:"comet.native.schema-migration.v1",id:e.id,change:e.name,fromSchema:e.state.schema,toSchema:e.state.schema===jt?He:xe,sourceHash:await lt(a),targetHash:D(o),createdAt:e.now.toISOString(),nextState:t,...i?{transition:i}:{},...n?{transitionSupersede:n}:{},...r?{runRetreat:r}:{}}}async function pS(e){return te(e.paths,`migrate schema for ${e.name}`,()=>De(e.paths,e.name,`migrate schema for ${e.name}`,async()=>{for(let t=0;t<3;t+=1){let i=await N0(e.paths,e.name,e.hooks);if(i?.schema===xe)return i;let n=await ft(e.paths,e.name);if(n.status==="current"&&n.state)return n.state;if(n.status!=="migration-required"||!n.state)throw new Error(n.message??`Native change ${e.name} cannot be migrated`);if(await aa(e.paths,e.name))throw new Error(`Native change ${e.name} has a pending progress checkpoint; recover it with its v2 runtime before schema migration`);let r=n.state;if(r.schema!==jt&&r.schema!==He)throw new Error(`Native change ${e.name} has no supported migration route`);let a=await Oh(e.paths,e.name);if(a?.status==="current")throw new Error(`Native change ${e.name} has a current-schema pending transition; recover it before schema migration`);let o=await S0({paths:e.paths,name:e.name,state:r,pendingTransition:a,now:e.now??new Date,id:e.id?.()??o0()}),s=ks(e.paths,e.name);await x(e.paths.nativeRoot,s),await le(s,o),await e.hooks?.afterPrepared?.(o)}throw new Error(`Native change ${e.name} exceeded the supported schema migration path`)}))}var Qi=Object.freeze({minimumAgeMs:720*60*60*1e3,keepLatestUnreferencedPerKind:32,maxDocuments:4096,maxScannedBytes:256*1024*1024,maxReportedRefs:8,maxReportMessageBytes:4096}),C0=512*1024,Cr=/^([a-f0-9]{64})\.json$/u,P0=/^\.([a-f0-9]{64}\.json)\.([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})\.gc$/u,x0=/^runtime\/evidence\/(snapshots|scopes|allowances|verifications|reports|receipts|check-receipts)\/[a-f0-9]{64}\.json$/u,bu=["snapshots","scopes","allowances","verifications","reports","receipts","check-receipts"];function Pp(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Pi(e,t){return Pp(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function yS(e,t){return Pp(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function Ta(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function nt(e,t){return et?1:0}function A0(e,t){let i=he.relative(e.projectRoot,t);if(i.length===0||he.isAbsolute(i)||i===".."||i.startsWith(`..${he.sep}`))throw new Error("Native evidence retention finding path is outside the project");return i.split(he.sep).join("/")}function NS(e,t){return he.join(C(e,t),"runtime","evidence")}function ku(e,t){return A0(e,NS(e,t))}async function Su(e,t){let i=he.resolve(e),n=he.resolve(t);if(!$(i,n))throw new Error("Native evidence retention path escapes its managed change");let r=he.relative(i,n).split(he.sep).filter(Boolean),a=[],o=i;for(let s of["",...r]){s&&(o=he.join(o,s));let c=await ie.lstat(o);if(!c.isDirectory()||c.isSymbolicLink())throw new Error(`Native evidence retention parent must be a real directory: ${o}`);let l=await ie.realpath(o);if(a.length>0&&!$(a[0].realPath,l))throw new Error(`Native evidence retention parent resolves outside its change: ${o}`);a.push({path:o,realPath:l,...Ta(c)})}return a}async function Lt(e){for(let t of e){let i=await ie.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!Pp(t,i)||await ie.realpath(t.path)!==t.realPath)throw new Error(`Native evidence retention parent changed: ${t.path}`)}}function bS(e,t){return e==="check-receipts"?`runtime/evidence/check-receipts/${t}.json`:pt(e,t)}function mS(e){return e!==null&&x0.test(e)?[e]:[]}function T0(e,t,i,n){if(e==="snapshots")return{canonical:da(i,t),dependencies:[]};if(e==="scopes"){let a=fa(i);if(a.scopeHash!==t)throw new Error("Native scope filename does not match its hash");return{canonical:a,dependencies:[a.baselineProjectionRef,a.currentProjectionRef]}}if(e==="allowances"){let a=es(i);if(a.change!==n||a.allowanceHash!==t)throw new Error("Native allowance filename/change does not match its content");return{canonical:a,dependencies:[pt("scopes",a.scopeHash)]}}if(e==="verifications"){let a=pa(i);if(a.change!==n||a.envelopeHash!==t)throw new Error("Native verification filename/change does not match its content");let o=a.acceptanceTrace.entries.flatMap(s=>s.evidenceRefs.flatMap(mS));return{canonical:a,dependencies:[a.implementationScopeRef,CN(a.reportHash),...mS(a.partialAllowanceRef),...a.requiredReceiptRefs,...a.receiptRefs,...o]}}if(e==="reports"){if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Native report evidence must be an object");let a=i;if(Object.keys(a).sort().join(",")!=="content,reportHash,schema"||a.schema!=="comet.native.verification-report.v1"||a.reportHash!==t||typeof a.content!="string"||E0("sha256").update(Buffer.from(a.content,"utf8")).digest("hex")!==t)throw new Error("Native report evidence filename/hash does not match its content");return{canonical:a,dependencies:[]}}if(e==="receipts"){let a=ns(i);if(a.bindings.change!==n||a.receiptHash!==t)throw new Error("Native verification receipt filename/change does not match its content");return{canonical:a,dependencies:a.kind==="static-inspection"?[a.evidence.checkReceiptRef]:[]}}let r=qi(i);if(r.change!==n||r.receiptHash!==t)throw new Error("Native check receipt filename/change does not match its content");return{canonical:r,dependencies:[]}}async function Vn(e){let t=await ie.lstat(e.file);if(!t.isFile()||t.isSymbolicLink())throw new Error(`Native evidence entry is not a regular file: ${e.ref}`);let i=e.kind==="check-receipts"?C0:Qt;if(t.size>i)throw new Error(`Native evidence entry exceeds its byte budget: ${e.ref}`);let n=await ie.realpath(e.file);if(!$(e.directoryChain[0].realPath,n))throw new Error(`Native evidence entry resolves outside its change: ${e.ref}`);let r=process.platform==="win32"?"r":Rp.O_RDONLY|Rp.O_NOFOLLOW|Rp.O_NONBLOCK,a=await ie.open(e.file,r).catch(o=>{throw o.code==="ELOOP"||o.code==="ENXIO"?new Error(`Native evidence entry became unsafe while opening: ${e.ref}`):o});try{let[o,s,c]=await Promise.all([a.stat(),ie.lstat(e.file),ie.realpath(e.file)]);if(await Lt(e.directoryChain),!o.isFile()||!s.isFile()||s.isSymbolicLink()||c!==n||!Pi(Ta(t),o)||!Pi(Ta(o),s))throw new Error(`Native evidence entry changed while opening: ${e.ref}`);let l=[],u=Buffer.allocUnsafe(64*1024),d=0;for(;;){let k=i+1-d,N=await a.read(u,0,Math.min(u.length,k),null);if(N.bytesRead===0)break;if(d+=N.bytesRead,d>i)throw new Error(`Native evidence entry exceeds its byte budget: ${e.ref}`);l.push(Buffer.from(u.subarray(0,N.bytesRead)))}let[f,h,m]=await Promise.all([a.stat(),ie.lstat(e.file),ie.realpath(e.file)]);if(await Lt(e.directoryChain),!h.isFile()||h.isSymbolicLink()||m!==n||!Pi(Ta(o),f)||!Pi(Ta(o),h))throw new Error(`Native evidence entry changed while reading: ${e.ref}`);let p=Buffer.concat(l,d).toString("utf8"),v;try{v=JSON.parse(p)}catch(k){throw new Error(`Native evidence entry is not valid JSON: ${e.ref}`,{cause:k})}let S=T0(e.kind,e.hash,v,e.name);if(p!==JSON.stringify(S.canonical,null,2)+` -`)throw new Error(`Native evidence entry is not canonically serialized: ${e.ref}`);return{ref:e.ref,kind:e.kind,change:e.name,changeRoot:e.changeRoot,file:e.file,size:d,mtimeMs:f.mtimeMs,identity:Ta(f),directoryChain:e.directoryChain,dependencies:[...new Set(S.dependencies)].sort(nt)}}finally{await a.close()}}async function vS(e){try{return await ie.lstat(e),!1}catch(t){if(t.code==="ENOENT")return!0;throw t}}async function _0(e){let t=C(e.paths,e.name),i=NS(e.paths,e.name);await x(e.paths.nativeRoot,i);let n;try{let o=await Su(t,i);n=await ie.readdir(i,{withFileTypes:!0}),await Lt(o)}catch(o){if(o.code==="ENOENT")return{findings:[],pending:!1};throw o}let r=[];for(let o of bu){if(!n.some(d=>d.name===o))continue;let s=he.join(i,o),c=await Su(t,s),l=(await ie.readdir(s,{withFileTypes:!0})).sort((d,f)=>nt(d.name,f.name)),u=new Map;for(let d of l){let f=P0.exec(d.name);if(!f)continue;let h=u.get(f[1])??[];h.push(d),u.set(f[1],h)}for(let[d,f]of[...u.entries()].sort(([h],[m])=>nt(h,m))){if(f.length!==1)throw new Error(`Native evidence cleanup has multiple quarantines for ${o}/${d}`);let h=f[0];if(!h.isFile()||h.isSymbolicLink())throw new Error(`Native evidence cleanup quarantine is not a regular file: ${o}/${h.name}`);let m=he.join(s,d),p=Cr.exec(d)?.[1];if(!p)throw new Error(`Native evidence cleanup quarantine name is invalid: ${h.name}`);let v=bS(o,p),S=he.join(s,h.name),k=await Vn({changeRoot:t,file:S,ref:v,kind:o,hash:p,name:e.name,directoryChain:c}),N=await vS(m),b=N?null:await Vn({changeRoot:t,file:m,ref:v,kind:o,hash:p,name:e.name,directoryChain:c});r.push({ref:v,original:m,quarantine:S,document:k,action:N?"restore-original":"finish-linked-recovery",originalDocument:b})}}if(r.length===0)return{findings:[],pending:!1};let a=r.map(o=>o.ref).sort(nt);if(!e.repair)return{pending:!0,findings:[{severity:"warning",code:"evidence-retention-recovery-required",message:_a(`Native evidence cleanup has ${a.length} safely recoverable quarantined document(s) for ${e.name}: ${Eu(a)}`),path:ku(e.paths,e.name)}]};for(let o of r.sort((s,c)=>nt(s.ref,c.ref))){if(await Lt(o.document.directoryChain),o.action==="finish-linked-recovery"){let u=await Vn({changeRoot:t,file:o.original,ref:o.ref,kind:o.document.kind,hash:Cr.exec(he.basename(o.original))[1],name:e.name,directoryChain:o.document.directoryChain}),d=await Vn({changeRoot:t,file:o.quarantine,ref:o.ref,kind:o.document.kind,hash:Cr.exec(he.basename(o.original))[1],name:e.name,directoryChain:o.document.directoryChain});if(!o.originalDocument||!Pi(o.originalDocument.identity,u.identity)||!Pi(o.document.identity,d.identity))throw new Error(`Native evidence cleanup original or quarantine changed during recovery: ${o.ref}`);await ie.rm(o.quarantine),await Lt(o.document.directoryChain);continue}if(!await vS(o.original))throw new Error(`Native evidence cleanup original appeared during recovery: ${o.ref}`);let s=await ie.lstat(o.quarantine);if(!s.isFile()||s.isSymbolicLink()||!Pi(o.document.identity,s))throw new Error(`Native evidence cleanup quarantine changed during recovery: ${o.ref}`);await ie.link(o.quarantine,o.original),await e.hooks.afterRecoveryLink?.({ref:o.ref,original:o.original,quarantine:o.quarantine});let c=await Vn({changeRoot:t,file:o.original,ref:o.ref,kind:o.document.kind,hash:Cr.exec(he.basename(o.original))[1],name:e.name,directoryChain:o.document.directoryChain}),l=await Vn({changeRoot:t,file:o.quarantine,ref:o.ref,kind:o.document.kind,hash:Cr.exec(he.basename(o.original))[1],name:e.name,directoryChain:o.document.directoryChain});if(!yS(o.document.identity,c.identity)||!Pi(c.identity,l.identity))throw new Error(`Native evidence cleanup recovery identity changed: ${o.ref}`);await ie.rm(o.quarantine),await Lt(o.document.directoryChain)}return{pending:!1,findings:[{severity:"info",code:"evidence-retention-cleanup-recovered",message:_a(`Recovered ${a.length} interrupted Native evidence cleanup document(s) for ${e.name}: ${Eu(a)}`),path:ku(e.paths,e.name)}]}}async function I0(e,t){let i=C(e,t),n=he.join(i,"runtime","evidence");await x(e.nativeRoot,n);let r;try{let c=await Su(i,n);r=await ie.readdir(n,{withFileTypes:!0}),await Lt(c)}catch(c){if(c.code==="ENOENT")return[];throw c}let a=r.filter(c=>!bu.includes(c.name)||!c.isDirectory()||c.isSymbolicLink()).map(c=>c.name).sort(nt);if(a.length>0)throw new Error(`Native evidence root has unknown or special entries: ${Eu(a)}`);let o=[],s=0;for(let c of bu){if(!r.some(f=>f.name===c))continue;let l=he.join(n,c),u=await Su(i,l),d=(await ie.readdir(l,{withFileTypes:!0})).sort((f,h)=>nt(f.name,h.name));await Lt(u);for(let f of d){if(o.length>=Qi.maxDocuments)throw new Error(`Native evidence store exceeds ${Qi.maxDocuments} documents`);let h=Cr.exec(f.name);if(!h||!f.isFile()||f.isSymbolicLink())throw new Error(`Native evidence kind ${c} has an unknown or special entry: ${f.name}`);let m=bS(c,h[1]),p=he.join(l,f.name);await x(e.nativeRoot,p);let v=await Vn({changeRoot:i,file:p,ref:m,kind:c,hash:h[1],name:t,directoryChain:u});if(s+=v.size,s>Qi.maxScannedBytes)throw new Error(`Native evidence store exceeds ${Qi.maxScannedBytes} scanned bytes`);o.push(v)}await Lt(u)}return o}function gS(e,t){let i=new Set,n=[...e].sort(nt).reverse();for(;n.length>0;){let r=n.pop();if(i.has(r))continue;let a=t.get(r);if(!a)throw new Error(`Native evidence dependency is missing: ${r}`);i.add(r);for(let o of[...a.dependencies].sort(nt).reverse())i.has(o)||n.push(o)}return i}function j0(e){let t=new Map(e.map(a=>[a.ref,a])),i=new Map(e.map(a=>[a.ref,0]));for(let a of e)for(let o of a.dependencies)t.has(o)&&i.set(o,(i.get(o)??0)+1);let n=[...i].filter(([,a])=>a===0).map(([a])=>a).sort(nt),r=[];for(;n.length>0;){let a=n.shift(),o=t.get(a);r.push(o);for(let s of o.dependencies){let c=i.get(s);if(c===void 0)continue;let l=c-1;i.set(s,l),l===0&&(n.push(s),n.sort(nt))}}if(r.length!==e.length)throw new Error("Native evidence candidate dependency graph contains a cycle");return r}function O0(e,t,i){let n=new Map(e.map(c=>[c.ref,c]));if(n.size!==e.length)throw new Error("Native evidence store has duplicate refs");for(let c of e)for(let l of c.dependencies)if(!n.has(l))throw new Error(`Native evidence dependency is missing: ${l}`);let r=gS(t,n),a=new Set(r);for(let c of e)i-c.mtimeMsu.kind===c&&!r.has(u.ref)).sort((u,d)=>d.mtimeMs-u.mtimeMs||nt(u.ref,d.ref)).slice(0,Qi.keepLatestUnreferencedPerKind);for(let u of l)a.add(u.ref)}let o=gS(a,n),s=e.filter(c=>!o.has(c.ref)&&i-c.mtimeMs>=Qi.minimumAgeMs).sort((c,l)=>nt(c.ref,l.ref));return{candidates:j0(s),candidateBytes:s.reduce((c,l)=>c+l.size,0)}}function Eu(e){let t=e.slice(0,Qi.maxReportedRefs),i=e.length-t.length;return`${t.join(", ")}${i>0?`, ... (${i} more)`:""}`}function _a(e){let t=Qi.maxReportMessageBytes;if(Buffer.byteLength(e,"utf8")<=t)return e;let i=e;for(;i.length>0&&Buffer.byteLength(`${i}...`,"utf8")>t;)i=i.slice(0,-1);return`${i}...`}function Cp(e,t,i,n){let r=t.candidates.map(a=>a.ref).sort(nt);return{severity:"info",code:i?"evidence-retention-cleaned":"evidence-retention-candidates",message:_a(`${i?"Removed":"Found"} ${t.candidates.length} old unreferenced Native evidence document(s) (${t.candidateBytes} bytes) for ${e}: ${Eu(r)}`),path:n}}async function wS(e,t){try{await ie.lstat(t);return}catch(i){if(i.code!=="ENOENT")return}try{await ie.rename(e,t)}catch{}}async function $0(e,t){await t.beforeDelete?.({ref:e.ref,file:e.file}),await Lt(e.directoryChain);let i=await Vn({changeRoot:e.changeRoot,file:e.file,ref:e.ref,kind:e.kind,hash:Cr.exec(he.basename(e.file))[1],name:e.change,directoryChain:e.directoryChain}),n=await ie.lstat(e.file),r=await ie.realpath(e.file);if(!n.isFile()||n.isSymbolicLink()||!Pi(e.identity,n)||!Pi(e.identity,i.identity)||!$(e.directoryChain[0].realPath,r))throw new Error(`Native evidence candidate changed before cleanup: ${e.ref}`);let a=he.join(he.dirname(e.file),`.${he.basename(e.file)}.${R0()}.gc`);await ie.rename(e.file,a);try{let[o,s]=await Promise.all([ie.lstat(a),ie.realpath(a)]);if(await Lt(e.directoryChain),!o.isFile()||o.isSymbolicLink()||!yS(e.identity,o)||!$(e.directoryChain[0].realPath,s))throw await wS(a,e.file),new Error(`Native evidence candidate changed during cleanup: ${e.ref}`);await ie.rm(a),await Lt(e.directoryChain)}catch(o){throw await wS(a,e.file),o}}async function H0(e){if((await re(e.projectRoot))?.native.pending_root_move)return!0;let i;try{i=await ie.readdir(e.transactionsDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return!1;throw n}for(let n of i){if(!n.isDirectory()||n.isSymbolicLink())return!0;try{let r=await ct(e,n.name);if(r.status!=="committed"&&r.status!=="rolled-back")return!0}catch{return!0}}return!1}async function D0(e,t){if(t)return[t];let i;try{i=await ie.readdir(e.changesDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}return i.filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort(nt)}async function M0(e,t){let i=await ft(e,t);if(i.status!=="current"||!i.state||i.state.archived)return!0;let[n,r,a]=await Promise.all([bi(e,t),Ss(e,t),Gi(e,t)]);return n!==null||r!==null||a!==null}async function F0(e){if(await M0(e.paths,e.name))return[];let t=await ft(e.paths,e.name);if(t.status!=="current"||!t.state)return[];if(!("implementation_scope"in t.state))return[];let i=await _0({paths:e.paths,name:e.name,repair:e.repair,hooks:e.hooks});if(i.pending)return i.findings;let n=[];for(let c of[t.state.implementation_scope,t.state.partial_allowance,t.state.verification_evidence])c!==null&&n.push(c);let r=await I0(e.paths,e.name),a=O0(r,n,e.nowMs);if(a.candidates.length===0)return i.findings;let o=ku(e.paths,e.name);if(!e.repair)return[...i.findings,Cp(e.name,a,!1,o)];let s=[];for(let c of a.candidates)try{await $0(c,e.hooks),s.push(c)}catch(l){let u=s.reduce((d,f)=>d+f.size,0);return[...i.findings,...s.length>0?[Cp(e.name,{candidates:s,candidateBytes:u},!0,o)]:[],{severity:"error",code:"evidence-retention-cleanup-failed",message:_a(`Native evidence cleanup stopped safely for ${e.name}: ${l.message}`),path:o}]}return[...i.findings,Cp(e.name,a,!0,o)]}async function kS(e){if(e.deferAll||await H0(e.paths))return[];let t=e.now??new Date;if(Number.isNaN(t.getTime()))throw new Error("Native evidence retention time is invalid");let i=async r=>{let a=[];for(let o of await D0(e.paths,e.name))try{a.push(...await F0({paths:e.paths,name:o,repair:r,nowMs:t.getTime(),hooks:e.hooks??{}}))}catch(s){a.push({severity:"error",code:"evidence-retention-unsafe",message:_a(`Native evidence retention refused to clean ${o}: ${s.message}`),path:ku(e.paths,o)})}return a};if(!(e.repair??!1))return i(!1);let n=await i(!1);if(n.some(r=>r.severity==="error")||!n.some(r=>r.code==="evidence-retention-candidates"||r.code==="evidence-retention-recovery-required"))return n;try{return await te(e.paths,"prune Native evidence",()=>i(!0))}catch(r){return[{severity:"info",code:"evidence-retention-cleanup-deferred",message:_a(`Native evidence cleanup was deferred until the project mutation lock is available: ${r.message}`)}]}}import{createHash as L0,randomUUID as B0}from"crypto";import{promises as Wn}from"fs";import ne from"path";var Ap=64*1024*1024,q0=256*1024,CS=16*1024*1024;async function Fe(e){try{return await Wn.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function V0(e){let t;try{t=await Wn.readdir(e.transactionsDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return;throw i}for(let i of t){if(!i.isDirectory()||i.isSymbolicLink())continue;let n;try{n=await ct(e,i.name)}catch(r){throw r.code==="ENOENT"?new Error(`Native transaction ${i.name} has no journal; run doctor before moving`,{cause:r}):r}if(n.status!=="committed"&&n.status!=="rolled-back")throw new Error(`Native transaction ${n.id} is unfinished; recover it before moving`)}}async function W0(e,t){for(let i of await Wn.readdir(e.locksDir,{withFileTypes:!0})){let n=ne.join(e.locksDir,i.name);if(ne.resolve(n)!==ne.resolve(t)&&(i.isFile()||i.isSymbolicLink()))throw new Error(`Native lock must be diagnosed before moving the root: ${n}`)}}async function J0(e){let t;try{t=await Wn.readdir(e.changesDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return;throw i}for(let i of t.sort((n,r)=>n.name.localeCompare(r.name))){if(!i.isDirectory()||i.isSymbolicLink())continue;let n=await Ve(e,i.name);if(n){await ra({paths:e,name:i.name,revision:n.capturedRevision,...n.schema==="comet.native.workspace.v3"?{binding:{isolation:n.isolation,changeBranch:n.changeBranch,targetBranch:n.targetBranch},...n.finish?{finish:n.finish}:{}}:{}});continue}let r;try{r=await ft(e,i.name)}catch{continue}r.status!=="current"||!r.state||!("revision"in r.state)||await ra({paths:e,name:i.name,revision:r.state.revision})}}async function z0(e){let t;try{t=await Wn.readdir(e.changesDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return;throw i}for(let i of t.sort((n,r)=>n.name.localeCompare(r.name)))if(!(!i.isDirectory()||i.isSymbolicLink()))try{let n=await Ve(e,i.name);if(n?.schema==="comet.native.workspace.v3"){let r=await sr({paths:e,identity:n});if(r.state!=="aligned")throw new Error(r.message??"workspace binding is not aligned")}else if(n){let r=await or({paths:e,identity:n});if(r.state!=="aligned")throw new Error(`legacy workspace ownership is ${r.state}`)}}catch(n){throw new Error(`Native workspace identity for ${i.name} must be aligned and repaired before moving the root`,{cause:n})}}async function Rs(e,t){let i=[];async function n(r){let a=await st({root:e,directory:r,label:"Native root tree"}),o=a.entries;o.sort((s,c)=>s.name.localeCompare(c.name));for(let s of o){await a.verify();let c=ne.join(r,s.name);if(t.excludedFiles?.has(ne.resolve(c))){await a.verify();continue}let l=await Wn.lstat(c);if(s.isSymbolicLink()||l.isSymbolicLink()){if(t.rejectSymlinks)throw new Error(`Native root contains a symlink: ${c}`);await a.verify();continue}if(s.isDirectory()&&l.isDirectory())i.push({ref:ne.relative(e,c).split(ne.sep).join("/"),type:"directory"}),await n(c);else if(s.isFile()&&l.isFile()){let u=await ue({root:e,file:c,maxBytes:Ap,label:`Native root file ${ne.relative(e,c)}`});i.push({ref:ne.relative(e,c).split(ne.sep).join("/"),type:"file",size:u.size,hash:u.hash})}else throw new Error(`Native root contains an unsupported file type: ${c}`);await a.verify()}}return await n(e),i.sort((r,a)=>r.ref.localeCompare(a.ref))}async function G0(e,t,i,n){await pi({root:n,directory:t,label:"Native root move staging directory"});async function r(a,o){let s=await st({root:e,directory:a,label:"Native root move source directory"}),c=s.entries;for(let l of c){await s.verify();let u=ne.join(a,l.name);if(ne.resolve(u)===ne.resolve(i)){await s.verify();continue}let d=await Wn.lstat(u);if(l.isSymbolicLink()||d.isSymbolicLink())throw new Error(`Native root contains a symlink: ${u}`);let f=ne.join(o,l.name);if(l.isDirectory()&&d.isDirectory())await pi({root:n,directory:f,label:"Native root move staging directory"}),await r(u,f);else if(l.isFile()&&d.isFile())await Ti({sourceRoot:e,source:u,targetRoot:n,target:f,maxBytes:Ap,label:`Native root move file ${ne.relative(e,u)}`,exclusive:!0,expectedTargetHash:null});else throw new Error(`Native root contains an unsupported file type: ${u}`);await s.verify()}}await r(e,t)}async function Ia(e,t,i,n){let r=await Rs(e,{rejectSymlinks:!0,excludedFiles:i?new Set([ne.resolve(i)]):void 0}),a=await Rs(t,{rejectSymlinks:!0,excludedFiles:n?new Set([ne.resolve(n)]):void 0});if(JSON.stringify(r)!==JSON.stringify(a))throw new Error(`Native root copies differ; preserve both trees for manual recovery: ${e} and ${t}`)}function PS(e,t){return ne.join(e.artifactRoot,`.comet-native-move-${t}`)}function U0(e,t){return ne.join(e.artifactRoot,`.comet-native-source-${t}.removing`)}function K0(e){return`${e}.removing`}function SS(e,t){return ne.join(ne.dirname(e),`.${ne.basename(e)}.${t}.rollback-removing`)}function xS(e,t,i){return ne.join(al(e,t).directory,`root-move-cleanup-${i}.json`)}function Y0(e){return JSON.stringify(e,null,2)+` -`}function X0(e){return L0("sha256").update(e).digest("hex")}function Q0(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Native root-move cleanup manifest entry ${t} must be an object`);let i=e,n=Object.keys(i).sort(),r=i.type==="file"?["hash","ref","size","type"]:["ref","type"];if(JSON.stringify(n)!==JSON.stringify(r))throw new Error(`Native root-move cleanup manifest entry ${t} has invalid fields`);if(typeof i.ref!="string"||i.ref.length===0||i.ref.includes("\\")||ne.posix.normalize(i.ref)!==i.ref||i.ref.startsWith("/")||i.ref.split("/").includes("..")||Buffer.byteLength(i.ref,"utf8")>4096)throw new Error(`Native root-move cleanup manifest entry ${t} has an invalid ref`);if(i.type==="directory")return{ref:i.ref,type:"directory"};if(i.type!=="file"||typeof i.size!="number"||!Number.isSafeInteger(i.size)||i.size<0||typeof i.hash!="string"||!/^[a-f0-9]{64}$/u.test(i.hash))throw new Error(`Native root-move cleanup manifest entry ${t} is invalid`);return{ref:i.ref,type:"file",size:i.size,hash:i.hash}}function Z0(e,t,i){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native root-move cleanup manifest must be an object");let n=e;if(JSON.stringify(Object.keys(n).sort())!==JSON.stringify(["entries","kind","schema","transactionId"])||n.schema!=="comet.native.root-move-cleanup.v1"||n.transactionId!==t||n.kind!==i||!Array.isArray(n.entries))throw new Error("Native root-move cleanup manifest binding is invalid");let r=n.entries.map(Q0);for(let a=0;a0&&r[a-1].ref.localeCompare(r[a].ref)>=0)throw new Error("Native root-move cleanup manifest refs must be unique and sorted");let o=ne.posix.dirname(r[a].ref);if(o!=="."&&!r.some(s=>s.ref===o&&s.type==="directory"))throw new Error(`Native root-move cleanup manifest parent is missing: ${o}`)}return{schema:"comet.native.root-move-cleanup.v1",transactionId:t,kind:i,entries:r}}async function eD(e){let t={schema:"comet.native.root-move-cleanup.v1",transactionId:e.id,kind:e.kind,entries:e.entries},i=Y0(t);if(Buffer.byteLength(i,"utf8")>CS)throw new Error("Native root-move cleanup manifest exceeds its byte budget");return await $e(xS(e.paths,e.id,e.kind),i,{containedRoot:e.paths.nativeRoot}),X0(i)}async function tD(e){let t=await ue({root:e.paths.nativeRoot,file:xS(e.paths,e.id,e.cleanup.kind),maxBytes:CS,label:`Native root-move cleanup manifest ${e.cleanup.kind}`});if(t.hash!==e.cleanup.manifestHash)throw new Error("Native root-move cleanup manifest hash changed");return Z0(JSON.parse(t.bytes.toString("utf8")),e.id,e.cleanup.kind)}async function xp(e){let t=await Rs(e.quarantine,{rejectSymlinks:!0}),i=new Map(e.manifest.entries.map(n=>[n.ref,n]));for(let n of t){let r=i.get(n.ref);if(!r||JSON.stringify(r)!==JSON.stringify(n))throw new Error(`Native root-move cleanup quarantine differs from its bound manifest: ${n.ref}`)}if(e.exact&&t.length!==e.manifest.entries.length)throw new Error("Native root-move cleanup quarantine is incomplete before deletion");return t}function ES(e){return e.ref.split("/").length}async function iD(e){let i=[...await xp({quarantine:e.quarantine,manifest:e.manifest,exact:!1})].sort((r,a)=>ES(a)-ES(r)||(r.type===a.type?a.ref.localeCompare(r.ref):r.type==="file"?-1:1)),n=0;for(let r of i){let a=ne.join(e.quarantine,...r.ref.split("/"));r.type==="file"?await tl({root:e.projectRoot,file:a,maxBytes:Ap,expectedHash:r.hash,expectedSize:r.size,label:`Native root-move cleanup file ${r.ref}`}):await If({root:e.projectRoot,directory:a,label:`Native root-move cleanup directory ${r.ref}`}),n+=1,await e.hooks?.afterRootMoveCleanupEntryRemoved?.(e.manifest.kind,r.ref,n)}await xp({quarantine:e.quarantine,manifest:e.manifest,exact:!1}),await If({root:e.projectRoot,directory:e.quarantine,label:`Native root-move cleanup quarantine ${e.manifest.kind}`})}function Ru(e,t,i=e.native.artifact_root){return{...e,native:{...e.native,artifact_root:i,pending_root_move:t}}}function AS(e){return{schema:"comet.native.transaction.v1",id:e.id,kind:"root-move",status:"prepared",projectRoot:e.paths.projectRoot,nativeRoot:e.paths.nativeRoot,createdAt:e.now.toISOString(),operations:[]}}async function nD(e,t,i,n){for(let a of[e,t])try{let o=await ct(a,n);if(o.kind!=="root-move")throw new Error(`Transaction ${n} is not a root move`);return{journal:o,paths:a}}catch(o){if(o.code!=="ENOENT")throw o}let r=ne.join(i,"runtime","transactions",n,"transaction.json");try{let a=await ue({root:i,file:r,maxBytes:q0,label:`Staged Native root-move journal ${n}`}),o=JSON.parse(a.bytes.toString("utf8"));if(o.schema!=="comet.native.transaction.v1"||o.kind!=="root-move")throw new Error(`Invalid staged root-move journal: ${n}`);return{journal:o,paths:t}}catch(a){throw a.code!=="ENOENT"?a:new Error(`Native root-move journal is missing: ${n}`,{cause:a})}}async function RS(e){let t=Ru(e.config,{...e.pending,stage:e.stage},e.activeArtifactRoot);return await li(e.projectRoot,t),t}async function Es(e){let t=e.config.native.pending_root_move;if(!t||t.id!==e.id)throw new Error(`Native root-move cleanup ${e.id} lost its pending configuration`);let i=Ru(e.config,{id:t.id,fromArtifactRoot:t.fromArtifactRoot,toArtifactRoot:t.toArtifactRoot,stage:t.stage,...e.cleanup?{cleanup:e.cleanup}:{}},e.config.native.artifact_root);return await li(e.projectRoot,i),i}async function Cu(e){let t=e.config,i=t.native.pending_root_move;if(!i||i.id!==e.id)throw new Error(`Native root-move cleanup ${e.id} lost its pending configuration`);let n=i.cleanup;if(n&&n.kind!==e.kind)throw new Error(`Native root move has unfinished ${n.kind} cleanup; cannot start ${e.kind}`);let r=await Fe(e.target),a=await Fe(e.quarantine);if(r&&a)throw new Error(`Native root-move cleanup target and quarantine both exist: ${e.kind}`);if(!n){if(!r&&!a)return t;if(!r&&a)throw new Error(`Native root-move cleanup quarantine is not transaction-bound: ${e.kind}`);let s=await eD({paths:e.stablePaths,id:e.id,kind:e.kind,entries:await Rs(e.target,{rejectSymlinks:!0})});n={kind:e.kind,state:"prepared",manifestHash:s},t=await Es({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:n})}let o=await tD({paths:e.stablePaths,id:e.id,cleanup:n});if(r=await Fe(e.target),a=await Fe(e.quarantine),r&&a)throw new Error(`Native root-move cleanup target and quarantine both exist: ${e.kind}`);if(r){if(n.state!=="prepared")throw new Error(`Native root-move cleanup target reappeared after quarantine: ${e.kind}`);await nw({root:e.projectRoot,directory:e.target,quarantine:e.quarantine,label:e.label,beforeQuarantine:e.beforeQuarantine,afterQuarantine:e.afterQuarantine}),a=!0}if(!a){if(n.state!=="deleting")throw new Error(`Native root-move cleanup quarantine disappeared: ${e.kind}`);return Es({projectRoot:e.projectRoot,config:t,id:e.id})}return await xp({quarantine:e.quarantine,manifest:o,exact:n.state!=="deleting"}),n.state==="prepared"&&(n={...n,state:"quarantined"},t=await Es({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:n})),n.state==="quarantined"&&(n={...n,state:"deleting"},t=await Es({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:n})),await iD({projectRoot:e.projectRoot,quarantine:e.quarantine,manifest:o,hooks:e.hooks}),Es({projectRoot:e.projectRoot,config:t,id:e.id})}async function TS(e){let t=e.config,i=t.native.pending_root_move.stage;if(i==="copying"){if(!await Fe(e.sourcePaths.nativeRoot))throw new Error(`Native source root is missing: ${e.sourcePaths.nativeRoot}`);let s=K0(e.staging);t=await Cu({projectRoot:e.projectRoot,config:t,id:e.pending.id,kind:"restart-staging",stablePaths:e.sourcePaths,target:e.staging,quarantine:s,label:"Native root move stale staging removal",hooks:e.hooks}),await Rs(e.sourcePaths.nativeRoot,{rejectSymlinks:!0,excludedFiles:new Set([ne.resolve(e.lockFile)])}),await G0(e.sourcePaths.nativeRoot,e.staging,e.lockFile,e.destinationPaths.projectRoot),await Ia(e.sourcePaths.nativeRoot,e.staging,e.lockFile),t=await RS({projectRoot:e.projectRoot,config:t,pending:e.pending,stage:"ready"}),i="ready",await e.hooks?.afterRootMoveStage?.("ready",e.journal)}if(i==="ready"){if(await Fe(e.destinationPaths.nativeRoot)){if(await Fe(e.staging))throw new Error(`Native destination is occupied: ${e.destinationPaths.nativeRoot}`);await Ia(e.sourcePaths.nativeRoot,e.destinationPaths.nativeRoot,e.lockFile)}else{if(!await Fe(e.staging))throw new Error("Native move staging tree is missing");await Ia(e.sourcePaths.nativeRoot,e.staging,e.lockFile),await Wn.rename(e.staging,e.destinationPaths.nativeRoot)}t=await RS({projectRoot:e.projectRoot,config:t,pending:e.pending,stage:"switched",activeArtifactRoot:e.pending.toArtifactRoot}),i="switched",await e.hooks?.afterRootMoveStage?.("switched",e.journal)}if(i!=="switched")throw new Error(`Unsupported Native root-move stage: ${i}`);if(!await Fe(e.destinationPaths.nativeRoot))throw new Error(`Native destination root is missing: ${e.destinationPaths.nativeRoot}`);let n=U0(e.sourcePaths,e.pending.id);!t.native.pending_root_move?.cleanup&&await Fe(e.sourcePaths.nativeRoot)&&await Ia(e.sourcePaths.nativeRoot,e.destinationPaths.nativeRoot,e.lockFile),t=await Cu({projectRoot:e.projectRoot,config:t,id:e.pending.id,kind:"forward-source",stablePaths:e.destinationPaths,target:e.sourcePaths.nativeRoot,quarantine:n,label:"Native root move source removal",beforeQuarantine:()=>e.hooks?.beforeRootMoveSourceRemove?.(e.sourcePaths.nativeRoot),afterQuarantine:s=>e.hooks?.afterRootMoveSourceQuarantined?.(s),hooks:e.hooks}),await J0(e.destinationPaths);let r=await ct(e.destinationPaths,e.pending.id);await Ur(e.destinationPaths,r,"commit");let a={artifact_root:t.native.artifact_root,language:t.native.language,clarification_mode:t.native.clarification_mode,archive_confirmation:t.native.archive_confirmation,max_verify_failures:t.native.max_verify_failures,snapshot:t.native.snapshot},o={...t,native:{...a,artifact_root:e.pending.toArtifactRoot}};return await li(e.projectRoot,o),o}async function _S(e){let t=await re(e.projectRoot)??tr("docs");if(t.native.pending_root_move)throw new Error(`Native root move ${t.native.pending_root_move.id} is already incomplete`);let i=pn(e.toArtifactRoot);if(i===t.native.artifact_root)throw new Error(`Native artifact root is already ${i}`);let n=await Ne(e.projectRoot,t.native.artifact_root),r=await Ne(e.projectRoot,i);if($(n.nativeRoot,r.nativeRoot)||$(r.nativeRoot,n.nativeRoot))throw new Error("Native source and destination roots must not overlap");if(!await Fe(n.nativeRoot))throw new Error(`Native source root does not exist: ${n.nativeRoot}`);if(await V0(n),await Fe(r.nativeRoot))throw new Error(`Native destination is occupied: ${r.nativeRoot}`);let a=await di(n,"root-move",`move root to ${i}`),o=B0(),s={id:o,fromArtifactRoot:t.native.artifact_root,toArtifactRoot:i,stage:"copying"},c=AS({id:o,paths:n,now:e.now??new Date}),l=PS(r,o);try{if(await W0(n,a.file),await z0(n),await Fe(l))throw new Error(`Native move staging path is occupied: ${l}`);return await li(e.projectRoot,Ru(t,s)),await Ff(n,c),await e.hooks?.afterRootMoveStage?.("copying",c),await TS({projectRoot:e.projectRoot,config:Ru(t,s),pending:s,sourcePaths:n,destinationPaths:r,staging:l,journal:c,lockFile:a.file,hooks:e.hooks}),{fromNativeRoot:n.nativeRoot,toNativeRoot:r.nativeRoot,transactionId:o}}finally{await fi(a)}}async function IS(e){let t=await re(e.projectRoot),i=t?.native.pending_root_move;if(!t||!i)throw new Error("No pending Native root move was found");let n=await Ne(e.projectRoot,i.fromArtifactRoot),r=await Ne(e.projectRoot,i.toArtifactRoot),a=PS(r,i.id),o=await Fe(n.nativeRoot)?n:r,s=await di(o,"root-move",`recover root ${i.id}`);try{let c;try{c=await nD(n,r,a,i.id)}catch(m){if(i.stage!=="copying"||!await Fe(n.nativeRoot))throw m;let p=AS({id:i.id,paths:n,now:new Date});await Ff(n,p),c={journal:p,paths:n}}if(e.strategy==="continue"){let m=await TS({projectRoot:e.projectRoot,config:t,pending:i,sourcePaths:n,destinationPaths:r,staging:a,journal:c.journal,lockFile:s.file,hooks:e.hooks});return{activeNativeRoot:r.nativeRoot,config:m}}if(!await Fe(n.nativeRoot))throw new Error("Cannot roll back after the old Native root was removed; continue recovery");let l=SS(r.nativeRoot,i.id);!t.native.pending_root_move?.cleanup&&await Fe(r.nativeRoot)&&await Ia(n.nativeRoot,r.nativeRoot,s.file),(!t.native.pending_root_move?.cleanup||t.native.pending_root_move.cleanup.kind==="rollback-destination")&&(t=await Cu({projectRoot:e.projectRoot,config:t,id:i.id,kind:"rollback-destination",stablePaths:n,target:r.nativeRoot,quarantine:l,label:"Native root move rollback destination removal",hooks:e.hooks}));let u=SS(a,i.id);!t.native.pending_root_move?.cleanup&&await Fe(a)&&await Ia(n.nativeRoot,a,s.file),(!t.native.pending_root_move?.cleanup||t.native.pending_root_move.cleanup.kind==="rollback-staging")&&(t=await Cu({projectRoot:e.projectRoot,config:t,id:i.id,kind:"rollback-staging",stablePaths:n,target:a,quarantine:u,label:"Native root move rollback staging removal",hooks:e.hooks}));let d=await ct(n,i.id);await ol(n,d);let f={artifact_root:t.native.artifact_root,language:t.native.language,clarification_mode:t.native.clarification_mode,archive_confirmation:t.native.archive_confirmation,max_verify_failures:t.native.max_verify_failures,snapshot:t.native.snapshot},h={...t,native:{...f,artifact_root:i.fromArtifactRoot}};return await li(e.projectRoot,h),{activeNativeRoot:n.nativeRoot,config:h}}finally{await fi(s)}}var Cs=4096,aD=4096,oD=1024;async function Pr(e,t,i){try{let n=await st({root:e.nativeRoot,directory:t,label:"Native doctor directory",maxEntries:i});return await n.verify(),n.entries}catch(n){if(n.code==="ENOENT")return[];throw n}}async function Pu(e,t){let i=new Map(e.map(n=>[Le.resolve(n.file),{...n,file:Le.resolve(n.file)}]));for(let{paths:n,file:r}of i.values()){let a;try{a=await Po(r)}catch(o){return t.push({severity:"error",code:"lock-invalid",message:`Native recovery lock is invalid: ${o.message}`,path:r}),!1}if(a.status!=="missing"){if(a.status==="stale"){let o=await _f(n,r,a);if(o.status==="removed"){t.push({severity:"info",code:"stale-recovery-lock-removed",message:"Removed stale lock before explicit transaction recovery",path:r});continue}if(o.status==="missing")continue;a=o.diagnosis}return a.status==="stale"?(t.push({severity:"error",code:"lock-takeover-raced",message:"Native recovery lock changed while doctor was preparing stale takeover",path:r}),!1):(t.push({severity:"error",code:a.status==="active"?"lock-active":"lock-owner-unknown",message:a.status==="active"?"Native recovery lock is still owned by a live process":"Native recovery lock owner cannot be proven stale",path:r}),!1)}}return!0}async function sD(e,t){let i=bk(e),n;try{await x(e.projectRoot,i);let r=await ys(e);if(!r)return[];n=r}catch(r){return r.code==="ENOENT"?[]:[{severity:"error",code:"selection-invalid",message:`Native selection is invalid: ${r.message}`,path:i}]}if(n.schema!=="comet.selection.v2"||n.workflow!=="native"||typeof n.change!="string")return[{severity:"error",code:"selection-invalid",message:"Native selection has an invalid schema or change name",path:i}];try{return await G(e,n.change),[]}catch(r){if(r.code!=="ENOENT")return[{severity:"error",code:"selection-target-invalid",message:`Selected Native change is invalid: ${r.message}`,path:i}]}return t?(await rD.rm(i,{force:!0}),[{severity:"info",code:"selection-cleared",message:`Cleared stale Native selection ${n.change}`,path:i}]):[{severity:"warning",code:"selection-stale",message:`Selected Native change does not exist: ${n.change}`,path:i}]}async function cD(e){let t=[];for(let i of[e.specsDir,e.changesDir,e.archiveDir,e.runtimeDir,e.locksDir,e.transactionsDir])try{await x(e.nativeRoot,i)}catch(n){t.push({severity:"error",code:"native-path-unsafe",message:`Managed Native path is unsafe: ${n.message}`,path:i})}return t}async function lD(e,t){let i=[],n=[];for(let r of await Pr(e,e.transactionsDir,aD)){if(!r.isDirectory()||r.isSymbolicLink())continue;let a;try{a=await ct(e,r.name)}catch(o){i.push({severity:"error",code:"transaction-invalid",message:`Native transaction ${r.name} is invalid: ${o.message}`,path:Le.join(e.transactionsDir,r.name)});continue}if(!(a.status==="committed"||a.status==="rolled-back")&&!(t.name&&a.change&&a.change!==t.name)){if(a.kind!=="archive"){n.push(a),i.push({severity:"error",code:"root-move-transaction-orphaned",message:`Root-move transaction ${a.id} is incomplete but project config has no matching pending move`});continue}if(t.repair&&t.recoveryStrategy)try{if(!await Qc([e],`doctor archive recovery ${a.id}`,async()=>await Pu([{paths:e,file:Le.join(e.locksDir,"root-move.lock")},{paths:e,file:Le.join(e.locksDir,"archive.lock")}],i)?(await Pk({paths:e,transactionId:a.id,strategy:t.recoveryStrategy}),!0):!1)){n.push(a);continue}i.push({severity:"info",code:"archive-transaction-recovered",message:`${t.recoveryStrategy==="continue"?"Continued":"Rolled back"} archive transaction ${a.id}`})}catch(o){n.push(a),i.push({severity:"error",code:"archive-recovery-failed",message:`Archive recovery failed: ${o.message}`})}else n.push(a),i.push({severity:"error",code:"archive-transaction-incomplete",message:t.repair?`Archive transaction ${a.id} needs an explicit recovery strategy`:`Archive transaction ${a.id} is incomplete`,repair:t.recoveryStrategy??"continue"})}}return{findings:i,unfinished:n}}async function uD(e,t,i){let n=[];for(let r of await Pr(e,e.locksDir,oD)){if(!r.isFile()||r.isSymbolicLink()||!r.name.endsWith(".lock"))continue;let a=Le.join(e.locksDir,r.name);try{let o=await Po(a);if(o.status==="active")n.push({severity:"warning",code:"lock-active",message:`Native lock is active for ${o.owner?.operation??"an operation"}`,path:a});else if(o.status==="unknown")n.push({severity:"warning",code:"lock-owner-unknown",message:"Native lock owner cannot be proven stale",path:a});else if(o.status==="stale")if(t&&i.length===0){let s=await _f(e,a,o);s.status==="removed"?n.push({severity:"info",code:"stale-lock-removed",message:"Removed a Native lock whose local owner process is absent",path:a}):s.status==="changed"&&n.push({severity:s.diagnosis.status==="active"?"warning":"error",code:"lock-takeover-raced",message:"Native lock changed while doctor was preparing stale takeover",path:a})}else n.push({severity:i.length>0?"error":"warning",code:"lock-stale",message:i.length>0?"Native lock is stale but an unfinished transaction still requires recovery":"Native lock owner process is absent",path:a})}catch(o){n.push({severity:"error",code:"lock-invalid",message:`Native lock metadata is invalid: ${o.message}`,path:a})}}return n}async function dD(e,t,i=5){let n=[],r=t?await Np(e,{maxVerifyFailures:i}).then(a=>a.filter(o=>o.name===t)):await Np(e,{maxVerifyFailures:i});if(t&&r.length===0)return[{severity:"error",code:"change-missing",message:`Native change does not exist: ${t}`}];for(let a of r){if(a.migrationRequired)continue;if(a.phase==="invalid"){n.push({severity:"error",code:"change-invalid",message:a.error??`Native change ${a.name} is invalid`,path:Le.join(e.changesDir,a.name,je)});continue}let o=await Ze(e,a.name,{details:!0,maxVerifyFailures:i});for(let s of o.findings??[])s.code==="trajectory-tail-incomplete"||s.code==="checkpoint-progress-incomplete"||n.push({severity:s.severity,code:s.code,message:`${a.name}: ${s.message}`,...s.path?{path:Le.join(e.projectRoot,s.path)}:{}})}return n}async function fD(e,t){let i=[],n=t.name?[t.name]:(await Pr(e,e.changesDir,Cs)).filter(r=>r.isDirectory()&&!r.isSymbolicLink()).map(r=>r.name).sort();for(let r of n)try{let a=await ta(e,r);if(a.status!=="repairable")continue;if(!t.repair){i.push({severity:"error",code:"trajectory-tail-incomplete",message:`Native trajectory for ${r} has an incomplete final line ${a.line}; ${a.discardedBytes} byte(s) are outside the last complete event`,path:a.file,repair:"truncate-tail"});continue}let o=await Zw(e,r);o&&i.push({severity:"info",code:"trajectory-tail-repaired",message:`Removed the incomplete Native trajectory tail for ${r} and preserved all complete events`,path:o.file})}catch(a){i.push({severity:"error",code:"trajectory-tail-repair-failed",message:`Native trajectory tail repair failed for ${r}: ${a.message}`,path:Le.join(e.changesDir,r,"runtime","trajectory.jsonl")})}return i}async function hD(e,t){let i=[],n=t.name?[t.name]:(await Pr(e,e.changesDir,Cs)).filter(r=>r.isDirectory()&&!r.isSymbolicLink()).map(r=>r.name).sort();for(let r of n)try{if(!await nh(e,r))continue;if(!t.repair){i.push({severity:"warning",code:"workspace-identity-migration-required",message:`Native workspace identity for ${r} uses legacy external-probe or hash-only metadata`,path:ar(e,r),repair:"migrate"});continue}let a=await G(e,r);await dy({paths:e,name:r,revision:a.revision})&&i.push({severity:"info",code:"workspace-identity-migrated",message:`Replaced legacy workspace metadata for ${r} with process-free root identities`,path:ar(e,r)})}catch(a){i.push({severity:"error",code:"workspace-identity-migration-failed",message:`Native workspace identity migration failed for ${r}: ${a.message}`,path:ar(e,r)})}return i}async function pD(e,t){let i=[],n=t.name?[t.name]:(await Pr(e,e.changesDir,Cs)).filter(r=>r.isDirectory()&&!r.isSymbolicLink()).map(r=>r.name).sort();for(let r of n){let a=ks(e,r);try{let o=await Ss(e,r),s=await ft(e,r);if(!o&&s.status==="current")continue;if(s.status==="runtime-incompatible"){i.push({severity:"error",code:"change-runtime-incompatible",message:s.message??`Native change ${r} requires a newer runtime`,path:Le.join(e.changesDir,r,je)});continue}if(!t.repair){i.push({severity:"error",code:o?"schema-migration-incomplete":"schema-migration-required",message:o?`Native schema migration ${o.id} is incomplete for ${r}`:`Native change ${r} requires migration to the current schema`,path:o?a:Le.join(e.changesDir,r,je),repair:"migrate"});continue}await pS({paths:e,name:r}),i.push({severity:"info",code:o?"schema-migration-recovered":"schema-migrated",message:`Migrated Native change ${r} to the current schema`,path:Le.join(e.changesDir,r,je)})}catch(o){if(o.code==="ENOENT")continue;i.push({severity:"error",code:"schema-migration-failed",message:`Native schema migration failed for ${r}: ${o.message}`,path:a})}}return i}async function mD(e,t){let i=[],n=t.name?[t.name]:(await Pr(e,e.changesDir,Cs)).filter(r=>r.isDirectory()&&!r.isSymbolicLink()).map(r=>r.name).sort();for(let r of n){let a;try{a=await bi(e,r)}catch(o){if(o instanceof os)continue;i.push({severity:"error",code:"transition-invalid",message:`Native transition journal is invalid: ${o.message}`,path:We(e,r)});continue}if(a){if(t.repair&&t.recoveryStrategy==="continue"){try{if(!await Qc([e],`doctor transition recovery ${r}`,async()=>await Pu([{paths:e,file:Le.join(e.locksDir,"root-move.lock")},{paths:e,file:Le.join(e.locksDir,`transition-${r}.lock`)}],i)?(await lb(e,r),!0):!1))continue;i.push({severity:"info",code:"transition-recovered",message:`Continued Native phase transition ${a.id} for ${r}`,path:We(e,r)})}catch(o){i.push({severity:"error",code:"transition-recovery-failed",message:`Native transition recovery failed: ${o.message}`,path:We(e,r)})}continue}i.push({severity:"error",code:"transition-incomplete",message:t.repair&&t.recoveryStrategy==="rollback"?`Native phase transition ${a.id} only supports deterministic continue recovery`:`Native phase transition ${a.id} is incomplete for ${r}`,path:We(e,r),repair:"continue"})}}return i}async function vD(e,t){let i=[],n=t.name?[t.name]:(await Pr(e,e.changesDir,Cs)).filter(r=>r.isDirectory()&&!r.isSymbolicLink()).map(r=>r.name).sort();for(let r of n){let a=zi(e,r),o;try{o=await Gi(e,r)}catch(s){if(s.code==="ENOENT")continue;i.push({severity:"error",code:"checkpoint-progress-invalid",message:`Native progress checkpoint journal is invalid: ${s.message}`,path:a});continue}if(o){if(!t.repair){i.push({severity:"error",code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${o.id} is incomplete for ${r}`,path:a});continue}try{if(!await Qc([e],`doctor checkpoint recovery ${r}`,async()=>await Pu([{paths:e,file:Le.join(e.locksDir,"root-move.lock")},{paths:e,file:Le.join(e.locksDir,`transition-${r}.lock`)}],i)?(await $b(e,r),!0):!1))continue;i.push({severity:"info",code:"checkpoint-progress-recovered",message:`Continued Native progress checkpoint ${o.id} for ${r}`,path:a})}catch(s){i.push({severity:"error",code:"checkpoint-progress-recovery-failed",message:`Native progress checkpoint recovery failed: ${s.message}`,path:a})}}}return i}async function jS(e){let t=e.repair??!1,i=[],n=e.paths,r;try{r=await re(n.projectRoot)}catch(c){return{healthy:!1,findings:[{severity:"error",code:"config-invalid",message:`Comet project config is invalid: ${c.message}`,path:n.configFile}]}}let a=!!r?.native.pending_root_move;if(r?.native.pending_root_move){let c=r.native.pending_root_move,[l,u]=await Promise.all([Ne(n.projectRoot,c.fromArtifactRoot),Ne(n.projectRoot,c.toArtifactRoot)]);if(t&&e.recoveryStrategy)try{if(!await Pu([{paths:l,file:Le.join(l.locksDir,"root-move.lock")},{paths:u,file:Le.join(u.locksDir,"root-move.lock")}],i))return{healthy:!1,findings:i};let f=await IS({projectRoot:n.projectRoot,strategy:e.recoveryStrategy});n=await Ne(n.projectRoot,f.config.native.artifact_root),a=!1,i.push({severity:"info",code:"root-move-recovered",message:`${e.recoveryStrategy==="continue"?"Continued":"Rolled back"} Native root move ${c.id}`})}catch(d){return i.push({severity:"error",code:"root-move-recovery-failed",message:`Native root recovery failed: ${d.message}`}),{healthy:!1,findings:i}}else i.push({severity:"error",code:"root-move-incomplete",message:`Native root move ${c.id} is ${c.stage}; inspect ${l.nativeRoot} and ${u.nativeRoot}`,repair:e.recoveryStrategy??"continue"})}let o=await cD(n);if(i.push(...o),o.length>0)return{healthy:!1,findings:i};let s=await lD(n,{name:e.name,repair:t,recoveryStrategy:e.recoveryStrategy});return i.push(...s.findings),i.push(...await pD(n,{name:e.name,repair:t})),i.push(...await hD(n,{name:e.name,repair:t})),i.push(...await fD(n,{name:e.name,repair:t})),i.push(...await mD(n,{name:e.name,repair:t,recoveryStrategy:e.recoveryStrategy})),i.push(...await vD(n,{name:e.name,repair:t})),i.push(...await kS({paths:n,name:e.name,repair:t,now:e.now,deferAll:a||s.unfinished.length>0})),i.push(...await uD(n,t,s.unfinished)),i.push(...await sD(n,t)),i.push(...await dD(n,e.name,r?.native.max_verify_failures??5)),{healthy:i.every(c=>c.severity==="info"),findings:i}}async function OS(e,t){let i=gt(e,"--repair"),n=J(e,"--strategy");if(n!==void 0&&n!=="continue"&&n!=="rollback")throw new I("--strategy must be continue or rollback");let r=e[0]?.startsWith("--")?void 0:e.shift();Y(e);let a=await _k(t),o=await jS({paths:a,...r?{name:r}:{},repair:i,...n?{recoveryStrategy:n}:{}});return o.healthy?Z("doctor",o):{command:"doctor",exitCode:65,data:o,error:{code:"invalid-data",message:"Native project needs attention"}}}import gD from"path";async function $S(e,t){let i=ae(e,"evidence subcommand");if(i==="format"){let n=J(e,"--entries");Y(e);let r;if(n)r=await Ik(gD.resolve(n),wi);else{if(process.stdin.isTTY)throw new I("evidence format requires acceptance evidence entries JSON on stdin, or --entries ");r=await jk(wi)}let a;try{a=JSON.parse(r)}catch(s){throw new Error(`Acceptance evidence entries must be valid JSON: ${s.message}`,{cause:s})}if(!Array.isArray(a))throw new Error("Acceptance evidence entries must be a JSON array");let o=tu(a);return Z("evidence format",{block:o},`${o} -`)}throw new I(`Unknown evidence command: ${i}`)}import{promises as AD}from"fs";import ja from"path";var wD=null;function yD(e,t){let i=e;for(let n of t)i+="\0"+(typeof n=="string"?n:JSON.stringify(n));return i}function HS(e,t){return(...i)=>{let n=wD;if(n===null)return t(...i);let r=yD(`async:${e}`,i),a=n.entries.get(r);if(a)return a.value;let o=t(...i).catch(s=>{throw n.entries.delete(r),s});return n.entries.set(r,{value:o}),o}}import{readFileSync as ND}from"fs";import DS from"path";var bD=new Set(["applypatch","create","createfile","deletefile","edit","editfile","patch","strreplaceeditor","write","writefile","writefiletool"]),kD=new Set(["glob","grep","listfiles","read","readfile","search","view"]),LS=["file_path","filePath","path","target_file","targetFile"],BS=["file_paths","filePaths","paths","files","targets"],qS=["operations","edits"],SD=["patch","diff","patchText","patch_text","changes"];function Tp(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function MS(e){return e.toLowerCase().replace(/[^a-z0-9]+/gu,"")}function ED(e){for(let t of["tool_name","toolName","tool","name"]){let i=e[t];if(typeof i=="string"&&i.trim())return i.trim()}return null}function RD(e){for(let t of["cwd","working_directory","workspaceRoot"]){let i=e[t];if(!(typeof i!="string"||!i.trim()||!DS.isAbsolute(i.trim())))return DS.resolve(i.trim())}}function CD(e){if(typeof e!="string")return e;let t=e.trim();if(!t.startsWith("{")&&!t.startsWith("["))return e;try{return JSON.parse(t)}catch{return e}}function PD(e){for(let t of["tool_input","toolInput","toolArgs","tool_args","arguments"])if(e[t]!==void 0)return CD(e[t]);return e}function FS(e){let t=[],i=[/^\*\*\* (?:Add|Update|Delete) File:\s+(.+?)\s*$/gmu,/^\+\+\+\s+(?:b\/)?(.+?)\s*$/gmu];for(let n of i)for(let r of e.matchAll(n)){let a=r[1]?.trim();a&&a!=="/dev/null"&&t.push(a)}return t}function xr(e,t){if(typeof t=="string"){let i=t.trim();i&&e.push(i);return}if(Array.isArray(t)){for(let i of t)xr(e,i);return}if(Tp(t)){for(let i of LS)xr(e,t[i]);for(let i of BS)xr(e,t[i]);for(let i of qS)xr(e,t[i])}}function xD(e,t){let i=[],n=[t,e].filter(Tp);for(let r of n){for(let a of LS)xr(i,r[a]);for(let a of BS)xr(i,r[a]);for(let a of qS)xr(i,r[a]);for(let a of SD){let o=r[a];typeof o=="string"&&i.push(...FS(o))}}return typeof t=="string"&&i.push(...FS(t)),[...new Set(i)]}function Ps(e,t){if(t?.trim())return{intent:"write",targets:[t.trim()],toolName:null};if(!e.trim())return{intent:"unknown",targets:[],toolName:null};let i;try{i=JSON.parse(e)}catch{return{intent:"unknown",targets:[],toolName:null}}if(!Tp(i))return{intent:"unknown",targets:[],toolName:null};let n=ED(i),r=xD(i,PD(i)),a=RD(i);return n&&bD.has(MS(n))?{intent:r.length>0?"write":"unknown",targets:r,toolName:n,...a?{cwd:a}:{}}:n&&kD.has(MS(n))?{intent:"non-write",targets:[],toolName:n,...a?{cwd:a}:{}}:n?{intent:"unknown",targets:r,toolName:n,...a?{cwd:a}:{}}:{intent:r.length>0?"write":"unknown",targets:r,toolName:null,...a?{cwd:a}:{}}}function VS(){let e=process.env.FILE_PATH;if(e?.trim()||process.stdin.isTTY)return Ps("",e);try{return Ps(ND(0,"utf8"),e)}catch{return Ps("",e)}}function xu(e,t){let i=ja.relative(e,t);return i===""||!i.startsWith("..")&&!ja.isAbsolute(i)}function TD(e,t,i){return i.targets.length>0&&i.targets.every(n=>{let r=ja.resolve(e,n);return xu(e,r)?ja.relative(e,r).replaceAll("\\","/")===".comet/config.yaml"||xu(t,r):!0})}async function _D(e){let t=await re(e);if(!t||!(t.workflows??[t.default_workflow]).includes("native"))return null;let i=await Ne(e,t.native.artifact_root),n;try{n=await AD.readdir(i.changesDir,{withFileTypes:!0})}catch(a){if(a.code==="ENOENT")return{paths:i,changes:[]};throw a}let r=[];for(let a of n.sort((o,s)=>o.name.localeCompare(s.name))){if(!a.isDirectory()||a.isSymbolicLink())continue;let o=await G(i,a.name);o.archived||r.push(o)}return{paths:i,changes:r}}var ID=HS("nativeActiveContext",e=>_D(e));async function WS(){let{intent:e,targets:t}=await VS();return{intent:e,targets:t}}async function JS(e,t,i){let n=await ID(e);if(!n)return{allowed:!0,reason:"Native workflow is not enabled"};if(t.intent==="non-write")return{allowed:!0,reason:"Hook event is not a write"};if(n.changes.length===0)return{allowed:!0,reason:TD(e,n.paths.nativeRoot,t)?"Native control artifact write":"No Native changes exist"};let r;if(i){if(r=n.changes.find(s=>s.name===i),!r)return{allowed:!1,reason:`Selected Native change ${i} is missing or archived; resume /comet-native before retrying`,workflow:"native",change:i}}else if(n.changes.length===1)r=n.changes[0];else{let s=await kk(n.paths);if(r=n.changes.find(c=>c.name===s),!r)return{allowed:!1,reason:"Multiple Native changes are active; select the change to resume before writing code",workflow:"native"}}if(r.phase==="build")return{allowed:!0,reason:"Native change is in Build",workflow:"native",phase:r.phase,change:r.name};if(t.intent==="unknown"||t.targets.length===0)return{allowed:!0,reason:"Hook write target was not attributed to the guarded project",workflow:"native",phase:r.phase,change:r.name};let a=!1,o=!1;for(let s of t.targets){let c=ja.resolve(e,s);if(!xu(e,c)){o=!0;continue}if(ja.relative(e,c).replaceAll("\\","/")===".comet/config.yaml"||xu(n.paths.nativeRoot,c)){a=!0;continue}return{allowed:!1,reason:`Native change ${r.name} is in ${r.phase}; implementation writes are only allowed in build. Resume /comet-native to continue safely`,workflow:"native",phase:r.phase,change:r.name}}return{allowed:!0,reason:a?"Native control artifact write":o?"Write target is outside the guarded project":"No guarded write target was provided",workflow:"native",phase:r.phase,change:r.name}}async function zS(e,t){let i=J(e,"--hook-output");if(i!==void 0&&i!=="copilot")throw new I("--hook-output must be copilot");Y(e);let n=await JS(t,await WS());return i==="copilot"?{command:"hook-guard",exitCode:0,data:n,text:n.allowed?`{} +`;function gt(e,t){let i=e.flatMap((n,r)=>n===t?[r]:[]);if(i.length>1)throw new I(`${t} may only be provided once`);return i.length===0?!1:(e.splice(i[0],1),!0)}function J(e,t){let i=e.flatMap((a,o)=>a===t?[o]:[]);if(i.length>1)throw new I(`${t} may only be provided once`);if(i.length===0)return;let n=i[0],r=e[n+1];if(r===void 0||r.startsWith("--"))throw new I(`${t} requires a value`);return e.splice(n,2),r}function Yi(e,t){let i=[];for(let n=0;n0)throw new I(`Unexpected argument: ${e[0]}`)}function ae(e,t){let i=e.shift();if(!i||i.startsWith("--"))throw new I(`${t} is required`);return i}function pu(e,t="en"){let i=J(e,"--language")??t;if(i!=="en"&&i!=="zh-CN")throw new I("--language must be en or zh-CN");return i}function Tk(e){let t=J(e,"--expect-revision");if(t!==void 0){if(!/^[1-9]\d*$/u.test(t)||!Number.isSafeInteger(Number(t)))throw new I("--expect-revision must be a positive integer");return Number(t)}}async function _k(e){return e?_H.resolve(e):Wc(process.cwd())}async function Oe(e){let t=await Gg({startPath:e,allowMissingConfig:!1});return{config:t.config,paths:t.paths}}async function Ik(e){let t=await re(e);return Ne(e,t?.native.artifact_root??"docs")}function Z(e,t,i){return{command:e,exitCode:0,data:t,text:i??JSON.stringify(t,null,2)+` +`}}async function jk(e,t){try{let{bytes:i}=await fn(e,t,{label:"Acceptance evidence entries file"});return i.toString("utf8")}catch(i){throw i instanceof xt?i.reason==="not-regular-file"?new Error(`Acceptance evidence entries path is not a regular file: ${e}`,{cause:i}):i.reason==="too-large"?new Error(`Acceptance evidence entries file exceeds ${t} bytes: ${e}`,{cause:i}):new Error(`Acceptance evidence entries file changed while reading: ${e}`,{cause:i}):i}}async function Ok(e){let t=[],i=0;for await(let n of process.stdin){let r=Buffer.isBuffer(n)?n:Buffer.from(String(n));if(i+=r.byteLength,i>e)throw new Error(`Acceptance evidence entries on stdin exceed ${e} bytes`);t.push(r)}return Buffer.concat(t).toString("utf8")}function $k(e,t){if(t instanceof I)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof Ns)return{command:e,exitCode:73,data:{capability:t.capability,expectedHash:t.expectedHash,actualHash:t.actualHash,canonicalPath:t.canonicalPath},error:{code:"conflict",message:t.message}};if(t instanceof Pa)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof xn)return{command:e,exitCode:73,data:{change:t.change,expectedRevision:t.expectedRevision,actualRevision:t.actualRevision,outcome:"revision-conflict"},error:{code:"conflict",message:t.message}};if(t instanceof Wo)return{command:e,exitCode:73,data:{requestedIsolation:t.requestedIsolation,activeChanges:t.activeChanges,requiredAction:"create-native-worktree"},error:{code:"workspace-isolation-required",message:t.message}};if(t instanceof gi)return{command:e,exitCode:65,data:{change:t.change,complete:!1,omittedCount:t.omittedCount,omittedByReason:t.omittedByReason,samplePaths:t.samplePaths,sampleTruncated:t.sampleTruncated,effectiveLimits:t.effectiveLimits,policyHash:t.policyHash,configPath:".comet/config.yaml",supportedFixes:["increase native.snapshot.max_files, native.snapshot.max_total_bytes, or native.snapshot.max_duration_ms","add an explicit native.snapshot.exclude pattern for data outside implementation scope"],requiredAction:"resolve-native-baseline"},error:{code:"baseline-incomplete",message:t.message}};if(t instanceof Ui)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof Ra)return{command:e,exitCode:65,data:t.recovery,error:{code:"implementation-scope-stale",message:t.message}};if(t instanceof Error){let i=t.code;if(i&&new Set(["EACCES","EPERM","EIO","EMFILE","ENFILE","ENOSPC","EROFS"]).has(i))return{command:e,exitCode:70,error:{code:"internal",message:t.message}};let n=/\b(lock|transaction|conflict|occupied|incomplete|recovery)\b/iu.test(t.message);return{command:e,exitCode:n?73:65,error:{code:n?"conflict":"invalid-data",message:t.message}}}return{command:e,exitCode:70,error:{code:"internal",message:String(t)}}}function pp(e,t){return t?{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,...e.data===void 0?{}:{data:e.data},...e.error===void 0?{}:{error:e.error}})+` +`}:e.error?{exitCode:e.exitCode,stderr:e.error.message}:{exitCode:e.exitCode,stdout:e.text}}async function Hk(e,t){let i=ae(e,"change name"),n=gt(e,"--dry-run"),r=J(e,"--expect-preflight"),a=gt(e,"--confirmed"),s=J(e,"--finish");if(s!==void 0&&s!=="merge"&&s!=="push"&&s!=="pull-request"&&s!=="keep")throw new I("--finish must be merge, push, pull-request, or keep");if(n&&r)throw new I("--dry-run and --expect-preflight cannot be combined");if(n&&a)throw new I("--confirmed is only valid with --expect-preflight");if(!n&&s)throw new I("--finish is only valid with --dry-run");if(!n&&!r)throw new I("archive requires --dry-run or --expect-preflight ");if(r&&!/^[a-f0-9]{64}$/u.test(r))throw new I("--expect-preflight must be a SHA-256 hash");Y(e);let{config:c,paths:l}=await Oe(t);if(n){let h=await Ve(l,i),m=h;if(h?.schema==="comet.native.workspace.v3"){if(h.isolation==="current"){if(s)throw new I("Native current isolation does not accept --finish")}else if(s)m=await dy(l,i,s);else if(h.finish===null)throw new I("Native branch and worktree isolation require --finish with --dry-run")}else if(s)throw new I("--finish requires a workspace v3 branch or worktree binding");let p=await kr({paths:l,name:i}),v=await G(l,i);return Z("archive --dry-run",{...p,workspaceFinish:m?.schema==="comet.native.workspace.v3"?m.finish:null,continuation:Me({state:v,archiveReady:p.ready,archiveConfirmation:p.archiveConfirmation,archivePreflightHash:p.preflightHash})},`Native Archive preview ${p.preflightHash}: ${p.ready?"ready":"blocked"} +`)}if(c.native.archive_confirmation==="required"&&!a)throw new I("archive requires --confirmed when native.archive_confirmation is required");let u=await G(l,i),d=await Ve(l,i);if(d?.schema==="comet.native.workspace.v3"&&d.isolation!=="current"&&d.finish===null)throw new I("Native branch and worktree isolation require a persisted --finish preview");let f=await Pk({paths:l,name:i,expectedPreflightHash:r});return Z("archive",{...f,workspaceFinish:d?.schema==="comet.native.workspace.v3"?d.finish:null,continuation:Me({state:u,done:!0})},`Archived Native change ${i} to ${f.archiveDir} +`)}import{createHash as IH}from"node:crypto";import{constants as mp,promises as ii}from"node:fs";import Er from"node:path";import{TextDecoder as jH}from"node:util";var Dk={"conflict-marker":0,"trailing-whitespace":1,"space-before-tab":2,"scope-mismatch":3,"unsafe-file":4,"binary-skipped":5,"scan-limit":6},Ee=class extends Error{constructor(i,n){super(n);this.kind=i}kind};function OH(e){return{schema:"comet.native.content-snapshot.v1",origin:e.origin,...e.capture?{capture:e.capture}:{},createdAt:"1970-01-01T00:00:00.000Z",complete:e.complete,limits:e.limits,...e.policy?{policy:e.policy}:{},entries:e.entries,omitted:e.omitted,omittedCount:e.omittedCount,...e.omissionOverflow?{omissionOverflow:e.omissionOverflow}:{}}}async function Mk(e){let t=OH(e.scope.baseline),[i,n]=await Promise.all([Et({changeDir:C(e.paths,e.state.name),briefRef:e.state.brief,specChanges:e.state.spec_changes}),Sn(e.paths,t,{origin:"explicit"})]),r=In({baseline:t,current:n,contractHash:e.scope.authority.contractHash,declaredArtifacts:e.scope.authority.declaredArtifacts,noCodeReason:e.scope.authority.noCodeReason,...e.scope.authority.gitChangedPaths?{gitChangedPaths:e.scope.authority.gitChangedPaths}:{}});return{contractHash:i.contract.contractHash,snapshotHash:r.scope.currentProjectionHash}}function Fk(e,t){let i=(e??(()=>new Date))();if(!(i instanceof Date)||!Number.isFinite(i.getTime()))throw new Error(`Native check ${t} time is invalid`);return i.toISOString()}function $H(e,t,i){let n=[],r=i.scope.contractHash,a=i.scope.currentProjectionHash;return e.contractHash!==r&&n.push("contract-before-does-not-match-scope"),e.snapshotHash!==a&&n.push("implementation-before-does-not-match-scope"),t.contractHash!==e.contractHash&&n.push("contract-changed-during-check"),t.snapshotHash!==e.snapshotHash&&n.push("implementation-changed-during-check"),t.contractHash===e.contractHash&&t.contractHash!==r&&n.push("contract-after-does-not-match-scope"),t.snapshotHash===e.snapshotHash&&t.snapshotHash!==a&&n.push("implementation-after-does-not-match-scope"),n}function HH(e,t){return e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function mu(e,t){return e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size&&M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}async function DH(e,t){let i=Er.resolve(e),n=Er.resolve(t);if(!$(i,n))throw new Ee("unsafe-file","Scoped file parent escapes the project root");let r=[],a=i;for(let o of["",...Er.relative(i,n).split(Er.sep).filter(Boolean)]){o&&(a=Er.join(a,o));let s;try{s=await ii.lstat(a)}catch(l){throw l.code==="ENOENT"?new Ee("scope-mismatch","Scoped file parent no longer exists"):l}if(!s.isDirectory()||s.isSymbolicLink())throw new Ee("unsafe-file","Scoped file parent is not a real directory");let c=await ii.realpath(a);if(r.length>0&&!$(r[0].realPath,c))throw new Ee("unsafe-file","Scoped file parent resolves outside the project");r.push({path:a,realPath:c,dev:s.dev,ino:s.ino,birthtimeMs:s.birthtimeMs,ctimeMs:s.ctimeMs})}return{physicalRoot:r[0].realPath,chain:r}}async function Lk(e){for(let t of e){let i;try{i=await ii.lstat(t.path)}catch(n){throw n.code==="ENOENT"?new Ee("unsafe-file","Scoped file parent changed while reading"):n}if(!i.isDirectory()||i.isSymbolicLink()||!HH(t,i)||await ii.realpath(t.path)!==t.realPath)throw new Ee("unsafe-file","Scoped file parent changed while reading")}}async function MH(e){let t=Er.resolve(e.projectRoot,...e.file.path.split("/"));if(!$(e.projectRoot,t))throw new Ee("unsafe-file","Scoped file path escapes the project root");let{physicalRoot:i,chain:n}=await DH(e.projectRoot,Er.dirname(t)),r;try{r=await ii.lstat(t)}catch(c){throw c.code==="ENOENT"?new Ee("scope-mismatch","Scoped file no longer exists"):c}if(!r.isFile()||r.isSymbolicLink())throw new Ee("unsafe-file","Scoped file is not a real regular file");if(r.size!==e.file.expected.size)throw new Ee("scope-mismatch","Scoped file size no longer matches its projection");let a=await ii.realpath(t);if(!$(i,a))throw new Ee("unsafe-file","Scoped file resolves outside the project root");let o=process.platform==="win32"?"r":mp.O_RDONLY|mp.O_NOFOLLOW|mp.O_NONBLOCK,s=await ii.open(t,o).catch(c=>{throw c.code==="ENOENT"?new Ee("scope-mismatch","Scoped file no longer exists"):c.code==="ELOOP"||c.code==="ENXIO"?new Ee("unsafe-file","Scoped file became unsafe while opening"):c});try{let[c,l,u]=await Promise.all([s.stat(),ii.lstat(t),ii.realpath(t)]);if(await Lk(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==a||!mu(r,c)||!mu(c,l))throw new Ee("unsafe-file","Scoped file changed while opening");let d=[],f=IH("sha256"),h=Buffer.allocUnsafe(64*1024),m=0;for(;;){let N=e.file.expected.size+1-m;if(N<1)throw new Ee("scope-mismatch","Scoped file exceeds its projected size");let b=await s.read(h,0,Math.min(h.length,N),null);if(b.bytesRead===0)break;if(m+=b.bytesRead,m>e.file.expected.size)throw new Ee("scope-mismatch","Scoped file exceeds its projected size");let R=Buffer.from(h.subarray(0,b.bytesRead));d.push(R),f.update(R)}let[p,v,S]=await Promise.all([s.stat(),ii.lstat(t),ii.realpath(t)]);if(await Lk(n),m!==e.file.expected.size||f.digest("hex")!==e.file.expected.hash)throw new Ee("scope-mismatch","Scoped file content no longer matches its projection");if(!p.isFile()||!v.isFile()||v.isSymbolicLink()||S!==a||!$(i,S)||!mu(c,p)||!mu(c,v))throw new Ee("unsafe-file","Scoped file changed while reading");let k=Buffer.concat(d,m);if(k.includes(0))return{bytes:m,text:null};try{return{bytes:m,text:new jH("utf-8",{fatal:!0}).decode(k)}}catch{return{bytes:m,text:null}}}finally{await s.close()}}function FH(e){let t=new Map(e.current.entries.map(r=>[r.path,r])),i=[],n=[];for(let r of e.scope.changes){if(!r.after)continue;let a=t.get(r.path);if(!a||a.hash!==r.after.hash||a.size!==r.after.size||a.type!=="file"){n.push(r.path);continue}i.push({path:r.path,expected:r.after})}return i.sort((r,a)=>r.path.localeCompare(a.path,"en")),n.sort((r,a)=>r.localeCompare(a,"en")),{files:i,mismatches:n}}function LH(e,t,i){let n=t.split(` +`);for(let r=0;r{7})(?: |$)/u.test(a)&&i({path:e,line:o,kind:"conflict-marker"}),/[ \t]+$/u.test(a)&&i({path:e,line:o,kind:"trailing-whitespace"}),/^ +\t/u.test(a)&&i({path:e,line:o,kind:"space-before-tab"})}}async function Bk(e){if(!e.state.implementation_scope)throw new Error("Native scoped check requires an implementation scope");let t=await yi(e.paths,e.state.name,e.state.implementation_scope),i=await Mk({paths:e.paths,state:e.state,scope:t}),n=Fk(e.clock,"start"),r=FH(t),a=[],o=0,s=N=>{o+=1,a.lengthN.kind==="scope-detail-overflow")){let N=t.scope.changes.at(-1)?.path??t.current.entries.at(-1)?.path??t.baseline.entries.at(-1)?.path;if(!N)throw new Error("Native implementation scope overflow has no bounded diagnostic path");s({path:N,line:1,kind:"scan-limit"}),c=[]}else if(l>Ae.maxFiles){let N=[...r.files.map(b=>b.path),...r.mismatches].sort((b,R)=>b.localeCompare(R,"en"));s({path:N[Ae.maxFiles],line:1,kind:"scan-limit"}),c=[]}else{let N=0;for(let b of r.files){if(b.expected.size>Ae.maxFileBytes){s({path:b.path,line:1,kind:"scan-limit"}),c=[];break}if(N+=b.expected.size,N>Ae.maxTotalBytes){s({path:b.path,line:1,kind:"scan-limit"}),c=[];break}}}for(let N of r.mismatches)s({path:N,line:1,kind:"scope-mismatch"});let d=0,f=0,h=0;for(let N of c)try{let b=await MH({projectRoot:e.paths.projectRoot,file:N});h+=b.bytes,b.text===null?(f+=1,s({path:N.path,line:1,kind:"binary-skipped"})):(d+=1,LH(N.path,b.text,s))}catch(b){if(!(b instanceof Ee))throw b;s({path:N.path,line:1,kind:b.kind})}let m=await Mk({paths:e.paths,state:e.state,scope:t}),p=Fk(e.clock,"end"),v=$H(i,m,t);a.sort((N,b)=>N.path.localeCompare(b.path,"en")||N.line-b.line||Dk[N.kind]-Dk[b.kind]);let S=wN({change:e.state.name,sourceRevision:e.state.revision,status:o===0&&v.length===0?"passed":"failed",startedAt:n,endedAt:p,contract:{expectedHash:t.scope.contractHash,beforeHash:i.contractHash,afterHash:m.contractHash},implementation:{scopeHash:t.scope.scopeHash,expectedSnapshotHash:t.scope.currentProjectionHash,beforeSnapshotHash:i.snapshotHash,afterSnapshotHash:m.snapshotHash},counts:{filesSelected:l,filesScanned:d,binaryFilesSkipped:f,bytesScanned:h,issueCount:o,recordedIssueCount:a.length},issues:a,issuesTruncated:o>a.length,stale:v.length>0,staleReasons:v}),k=await Lb({paths:e.paths,name:e.state.name,receipt:S});return{receipt:qi(S),ref:k}}async function qk(e){return te(e.paths,`check ${e.name}`,()=>De(e.paths,e.name,`check ${e.name}`,()=>vp(e)))}async function vp(e){await Rt(e.paths,e.name);let t=await G(e.paths,e.name);if(t.phase!=="verify")throw new Error(`Native check requires Verify, got ${t.phase}`);if(!t.implementation_scope)throw new Error("Native check requires an implementation scope");let i=await Gb({paths:e.paths,state:t});if(i)return{change:t,receipt:i.checkReceipt,checkRef:i.checkReceiptRef,ref:i.ref};let n=await Bk({paths:e.paths,state:t}),r=await zb({paths:e.paths,state:t,checkReceipt:n.receipt,checkReceiptRef:n.ref});return{change:t,receipt:n.receipt,checkRef:n.ref,ref:r.ref}}async function Vk(e,t){let i=ae(e,"change name");Y(e);let{paths:n}=await Oe(t),r=await qk({paths:n,name:i}),a={ref:r.ref,hash:r.receipt.receiptHash,status:r.receipt.status,checker:r.receipt.checker,counts:r.receipt.counts,issues:r.receipt.issues,issuesTruncated:r.receipt.issuesTruncated,stale:r.receipt.stale,staleReasons:r.receipt.staleReasons,startedAt:r.receipt.startedAt,endedAt:r.receipt.endedAt,sourceRevision:r.receipt.sourceRevision},o=r.receipt.status==="passed"&&!r.receipt.stale;return{command:"check",exitCode:o?0:1,data:a,text:`Native check ${o?"passed":"failed"}: ${r.ref} +`}}import oS from"path";import{promises as XH}from"fs";import BH from"path";function gp(e,t){return BH.resolve(e,...t.split(/[\\/]/u))}async function vu(e,t){let i=[],n=C(e,t.name),r=gp(n,ut.stateRef),a;try{a=await be(n)}catch(u){return[{code:"run-state-invalid",message:`Native Run state is invalid: ${u.message}`,path:r}]}if(!a)return(t.run_id!==null||t.phase!=="shape")&&i.push({code:"run-state-missing",message:"Native change references a missing Run state",path:r}),i;if(t.run_id===null)return[{code:"run-state-unexpected",message:"Native change has a Run state but no run_id",path:r}];a.runId!==t.run_id&&i.push({code:"run-id-mismatch",message:`Native Run id ${a.runId} does not match change run_id ${t.run_id}`,path:r}),(a.pending||a.status==="waiting")&&i.push({code:"run-action-pending",message:"Native Run has an unresolved pending action",path:r}),a.currentStep!==t.phase&&i.push({code:"run-phase-mismatch",message:`Native Run step ${a.currentStep??"(none)"} does not match phase ${t.phase}`,path:r});let o=gp(n,a.trajectoryRef),s=await ta(e,t.name);if(s.status==="repairable")return i.push({code:"trajectory-tail-incomplete",message:`Native trajectory final line is incomplete at line ${s.line}; doctor repair can discard ${s.discardedBytes} incomplete byte(s)`,path:o}),i;if(s.status==="invalid")return i.push({code:"trajectory-invalid",message:`Native trajectory is invalid at line ${s.line}: ${s.message}`,path:o}),i;let c;try{if(c=await qe(n,a.trajectoryRef),c.length===0||c.some((u,d)=>!u||typeof u!="object"||u.sequence!==d+1||u.runId!==a.runId||typeof u.type!="string"||!u.data||typeof u.data!="object"||Array.isArray(u.data)))throw new Error("trajectory events are missing or inconsistent")}catch(u){return i.push({code:"trajectory-invalid",message:`Native trajectory is invalid: ${u.message}`,path:o}),i}let l=gp(n,a.checkpointRef);try{let u=await ea(n,a.checkpointRef);u?(u.runId!==a.runId||u.stateVersion!==a.iteration||u.trajectoryOffset!==c.length)&&i.push({code:"checkpoint-mismatch",message:"Native Run checkpoint does not match Run state and trajectory",path:l}):i.push({code:"checkpoint-missing",message:"Native Run checkpoint is missing",path:l})}catch(u){i.push({code:"checkpoint-invalid",message:`Native Run checkpoint is invalid: ${u.message}`,path:l})}return i}import bs from"path";var Wk=8,qH={"brief-blocking-question":{severity:"error",requiredAction:"answer-blocking-question",retry:"next",repair:"none"},"shape-confirmation-required":{severity:"error",requiredAction:"confirm-shared-understanding",retry:"next",repair:"none"},"approval-confirmation-required":{severity:"error",requiredAction:"confirm-shared-understanding",retry:"next",repair:"none"},"transition-incomplete":{severity:"error",requiredAction:"recover-transition",retry:"status",repair:"doctor"},"trajectory-tail-incomplete":{severity:"error",requiredAction:"repair-trajectory-tail",retry:"status",repair:"doctor"},"checkpoint-progress-invalid":{severity:"error",requiredAction:"manually-isolate-invalid-checkpoint",retry:"none",repair:"none"},"checkpoint-progress-incomplete":{severity:"error",requiredAction:"recover-progress-checkpoint",retry:"status",repair:"doctor"},"checkpoint-manifest-invalid":{severity:"error",requiredAction:"record-checkpoint-again",retry:"status",repair:"none"},"verification-scope-partial":{severity:"error",requiredAction:"confirm-partial-verification-scope",retry:"next",repair:"none"},"verification-implementation-stale":{severity:"error",requiredAction:"return-to-build-and-refresh-implementation-scope",retry:"next",repair:"none"},"verification-receipt-binding-mismatch":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"verification-receipt-stale":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"verification-receipt-invalid":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"native-change-conflict":{severity:"error",requiredAction:"resolve-native-change-conflict",retry:"status",repair:"none"},"native-change-overlap":{severity:"error",requiredAction:"inspect-native-change-overlap",retry:"status",repair:"none"},"contract-changed-after-approval":{severity:"error",requiredAction:"re-confirm-contract",retry:"next",repair:"none"},"baseline-snapshot-incomplete":{severity:"error",requiredAction:"resolve-native-baseline",retry:"none",repair:"none"},"baseline-snapshot-missing":{severity:"error",requiredAction:"resolve-native-baseline",retry:"none",repair:"none"},"workspace-inspection-unavailable":{severity:"info",requiredAction:"migrate-workspace-identity",retry:"status",repair:"doctor"},"workspace-binding-root-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-binding-invalid":{severity:"error",requiredAction:"repair-workspace-binding",retry:"status",repair:"none"},"workspace-branch-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-kind-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-vcs-unavailable":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"repair-stagnation-warning":{severity:"warning",requiredAction:"change-repair-approach",retry:"next",repair:"none"},"repair-stagnation-stop":{severity:"error",requiredAction:"try-new-repair-hypothesis-with-status-override",retry:"none",repair:"none"},"repair-iteration-limit":{severity:"error",requiredAction:"choose-repair-continuation",retry:"none",repair:"none"},"repair-override-exhausted":{severity:"error",requiredAction:"choose-repair-continuation",retry:"none",repair:"none"}};function VH(e){let t=qH[e];return t||(/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid)|transition-invalid)/u.test(e)?{severity:"error",requiredAction:"isolate-or-restore-native-runtime-from-a-trusted-copy",retry:"none",repair:"none"}:e.startsWith("brief-")?{severity:"error",requiredAction:"complete-brief",retry:"next",repair:"none"}:e.startsWith("spec-")?{severity:"error",requiredAction:"resolve-spec-state",retry:"next",repair:"none"}:e.startsWith("verification-")?{severity:"error",requiredAction:"complete-verification-evidence",retry:"next",repair:"none"}:e.startsWith("build-")?{severity:"error",requiredAction:"record-build-evidence",retry:"next",repair:"none"}:ia(e)?{severity:e==="workspace-inspection-unavailable"?"info":"warning",requiredAction:"inspect-workspace-advisory",retry:"status",repair:"none"}:{severity:"error",requiredAction:"resolve-finding",retry:"status",repair:"none"})}function WH(e,t,i){if(!i.path)return null;let n;if(bs.isAbsolute(i.path)?n=bs.resolve(i.path):/^(?:brief-|verification-|spec-source)/u.test(i.code)?n=bs.resolve(C(e,t.name),...i.path.split(/[\\/]/u)):n=bs.resolve(e.projectRoot,...i.path.split(/[\\/]/u)),!$(e.projectRoot,n))return null;let r=bs.relative(e.projectRoot,n).replaceAll("\\","/");return r===""?".":r}function JH(e,t,i){return e==="next"?`comet native next ${t.name} --summary ""${i==="contract-changed-after-approval"||i==="shape-confirmation-required"||i==="approval-confirmation-required"?" --confirmed":""}`:e==="status"?`comet native status ${t.name} --details`:null}function ni(e){return e.findings.map(t=>{let i=VH(t.code);return{code:t.code,message:t.message,severity:i.severity,path:WH(e.paths,e.state,t),requiredAction:i.requiredAction,retryCommand:JH(i.retry,e.state,t.code),repairCommand:i.repair==="doctor"?`comet native doctor ${e.state.name} --repair${t.code.startsWith("transition-")?" --strategy continue":""}`:null,requiresUserDecision:t.code==="brief-blocking-question"||t.code==="shape-confirmation-required"||t.code==="approval-confirmation-required"||t.code==="contract-changed-after-approval"||t.code==="verification-scope-partial"||t.code==="repair-iteration-limit"||t.code==="repair-override-exhausted"}}).sort((t,i)=>{let n={error:0,warning:1,info:2};return n[t.severity]-n[i.severity]||t.code.localeCompare(i.code)||(t.path??"").localeCompare(i.path??"")||t.message.localeCompare(i.message)})}function Jk(e){let t=[...new Set(e.map(i=>i.code))];return{total:e.length,errors:e.filter(i=>i.severity==="error").length,warnings:e.filter(i=>i.severity==="warning").length,info:e.filter(i=>i.severity==="info").length,requiresUserDecision:e.some(i=>i.requiresUserDecision),codes:t.slice(0,Wk),truncated:t.length>Wk}}import zk from"path";var Gk=240,Uk=8,gu=50;function Kk(e){let t=Array.from(e);return t.length<=Gk?e:`${t.slice(0,Gk-1).join("")}…`}function zH(e){let t=e.indexOf(":");return t<0?e:e.slice(0,t)}function GH(e){let t=[...new Set(e.map(zH))],i={freshness:e.length===0||e.length===1&&e[0]==="no-checkpoint"?"fresh":"stale",codes:t.slice(0,Uk),reasonCount:e.length,codesTruncated:t.length>Uk};return{inspection:i,inspectionDetails:{...i,reasons:e.slice(0,gu),reasonsTruncated:e.length>gu}}}async function Yk(e){let t=null;try{let s=await Gi(e.paths,e.state.name);s&&(t={code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${s.id} requires deterministic recovery`,path:zi(e.paths,e.state.name)})}catch(s){t={code:"checkpoint-progress-invalid",message:`Native progress checkpoint journal is invalid: ${s.message}. Automatic repair is unavailable; inspect and move the invalid checkpoint journal aside before retrying`,path:zi(e.paths,e.state.name)}}let i=await Ob({paths:e.paths,name:e.state.name,stateRevision:e.state.revision}),n=t?[t.code,...i.reasons]:i.reasons,r=GH(n);if(!i.checkpoint)return{inspection:r.inspection,inspectionDetails:r.inspectionDetails,checkpoint:null,checkpointDetails:null,findings:t?[t,...i.findings]:i.findings,maxCheckpointArtifacts:ei.maxArtifacts};let a={id:i.checkpoint.id,createdAt:i.checkpoint.createdAt,phase:i.checkpoint.phase,stateRevision:i.checkpoint.stateRevision,summary:Kk(i.checkpoint.summary),nextAction:Kk(i.checkpoint.nextAction),artifactCount:i.checkpoint.artifactCount},o=i.manifest?{...a,summary:i.checkpoint.summary,nextAction:i.checkpoint.nextAction,manifestHash:i.checkpoint.manifestHash,manifestRef:zk.relative(e.paths.projectRoot,zk.join(C(e.paths,e.state.name),...i.checkpoint.manifestRef.split("/"))).replaceAll("\\","/"),artifacts:i.manifest.artifacts,totalBytes:i.manifest.totalBytes}:null;return{inspection:r.inspection,inspectionDetails:r.inspectionDetails,checkpoint:a,checkpointDetails:o,findings:t?[t,...i.findings]:i.findings,maxCheckpointArtifacts:ei.maxArtifacts}}function UH(e){if(e.phase!=="build"||e.verification_result!=="fail"||!e.implementation_scope||!e.verification_evidence)throw new Error("Native repair guard requires a failed Verify-to-Build state")}async function Xk(e,t){let i=C(e,t.name),n=await be(i);if(!n||!t.run_id||n.runId!==t.run_id)throw new Error("Native repair history Run state is missing or mismatched");let r=await ea(i,n.checkpointRef);if(!r||r.runId!==n.runId||r.stateVersion!==n.iteration)throw new Error("Native repair history checkpoint is missing or mismatched");return{trajectory:await qe(i,n.trajectoryRef),committedTrajectoryOffset:r.trajectoryOffset,runId:n.runId}}async function wp(e,t){let i=await Xk(e,t);return{committed:i,latest:KN(i),history:UN(i)}}function KH(e,t){let i=e.latest;if(!i)return null;let n=e.history.filter(l=>l.kind==="failure"),r=n.length===0?0:rs({signatureHash:i.signatureHash,...i.contractHash===null?{}:{failedAcceptanceIds:i.failedAcceptanceIds,failedCheckIds:i.failedCheckIds}},n.slice(0,-1)),a=i.overrideSummaryHash!==null,o=e.history.some(l=>l.kind==="override"&&l.signatureHash===i.signatureHash),s=n.length>=t,c=i.disposition==="hard-stop"&&!s?"continue":i.disposition;return{disposition:s?"hard-stop":c,reasonCode:a?"override-accepted":o&&i.disposition==="manual-stop"?"override-already-used":s?"repair-iteration-limit":i.disposition==="manual-stop"?"repeated-failure-stop":i.disposition==="warn"?"repeated-failure-warning":"new-failure-signature",signatureHash:i.signatureHash,consecutiveFailures:r,totalRepairFailures:n.length,remainingIterations:Math.max(0,t-n.length),overrideAccepted:a}}async function Qk(e,t,i){return KH(await wp(e,t),i)}function Zk(e){return{disposition:e.decision.disposition,reasonCode:e.decision.reasonCode,signatureHash:e.decision.signature.signatureHash,consecutiveFailures:e.decision.consecutiveFailures,totalRepairFailures:e.decision.totalRepairFailures,remainingIterations:e.decision.remainingIterations,overrideAccepted:e.decision.overrideAccepted}}function YH(e){return ga(e.filter(t=>t.status!=="passed").map(t=>bN(t)))}async function eS(e){if(!e.state.implementation_scope)throw new Error("Native repair failure has no implementation scope");let t=[...new Set([...e.envelope.requiredReceiptRefs,...e.envelope.receiptRefs])],[i,n,r]=await Promise.all([Xk(e.paths,e.state),yi(e.paths,e.state.name,e.state.implementation_scope),Promise.all(t.map(o=>Hn(e.paths,e.state.name,o)))]),a=YH(r);return XN({...i,envelope:e.envelope,implementationScope:n,maxVerifyFailures:e.maxVerifyFailures,...a.length>0?{failedCheckIds:a}:{}})}async function tS(e){let t=await wp(e.paths,e.state),i=t.latest,n=Kt(e.currentImplementationScope).scope.contractHash;if(i?.contractHash!==null&&i?.contractHash!==n){if(e.override)throw new Error("Native repair override cannot cross a confirmed contract change");return{disposition:"proceed",eventProjection:null}}let r=t.history.filter(u=>u.kind==="failure").length;if(i&&r>=e.maxVerifyFailures){if(e.override)throw new Error("Native repair hard stop cannot be overridden");return{disposition:"hard-stop",signatureHash:i.signatureHash,overrideRecorded:t.history.some(u=>u.kind==="override"&&u.signatureHash===i.signatureHash)}}let a=i?.disposition==="hard-stop"&&ru.kind==="override"&&u.signatureHash===i.signatureHash);if(!(e.state.phase==="build"&&e.state.verification_result==="fail"&&e.state.implementation_scope!==null&&e.state.verification_evidence!==null)){if(e.override)throw new Error("Native repair override requires an active failed Verify-to-Build state");return{disposition:"proceed",eventProjection:null}}UH(e.state);let[c,l]=await Promise.all([Dn(e.paths,e.state.name,e.state.verification_evidence),yi(e.paths,e.state.name,e.state.implementation_scope)]);if(l.scope.scopeHash!==c.implementationScopeHash)throw new Error("Native repair verification evidence does not match its implementation scope");if(i.contractHash===null&&ya(e.currentImplementationScope)!==ya(l)){if(e.override)throw new Error("Native repair override is not valid after implementation scope progress");return{disposition:"proceed",eventProjection:null}}if(i.disposition==="hard-stop"){if(e.override)throw new Error("Native repair hard stop cannot be overridden without implementation progress");return{disposition:"hard-stop",signatureHash:i.signatureHash,overrideRecorded:o}}return o?{disposition:"hard-stop",signatureHash:i.signatureHash,overrideRecorded:o}:e.override?{disposition:"proceed",eventProjection:YN({...t.committed,override:e.override}).eventProjection}:{disposition:"manual-stop",signatureHash:i.signatureHash,overrideRecorded:!1}}async function iS(e,t,i){if(t.phase!=="build"||t.verification_result!=="fail")return null;let n=await wp(e,t),r=n.latest;if(!r)return null;let a=n.history.filter(c=>c.kind==="failure"),o=a.length>=i,s=r.disposition==="hard-stop"&&!o?"continue":r.disposition;return{disposition:o?"hard-stop":s,signatureHash:r.signatureHash,overrideRecorded:n.history.some(c=>c.kind==="override"&&c.signatureHash===r.signatureHash),failedAcceptanceIds:[...r.failedAcceptanceIds],failedCheckIds:[...r.failedCheckIds],totalVerifyFailures:a.length,maxVerifyFailures:i,remainingVerifyFailures:Math.max(0,i-a.length)}}var QH=/^native-status-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u,xa=Object.freeze({maxItems:24,maxChanges:4096,maxSerializedBytes:512*1024});async function ZH(e){return(await ys(e))?.change??null}function e0(e,t,i=!1,n){return e.phase==="archive"?t?`comet native archive ${e.name} --dry-run`:i?`comet native next ${e.name} --summary ""`:null:`comet native next ${e.name} --summary ""${e.phase==="shape"||e.phase==="build"&&e.approval!=="confirmed"?" --confirmed":""}`}async function t0(e,t){let i=C(e,t.name),n=[...(await ur(i,t.brief)).findings,...(await ca(e,t)).findings,...await vu(e,t)];if(t.phase==="shape"||t.phase==="build")try{let r=await vi(e,t.name);if(r===null)n.push({code:"baseline-snapshot-missing",message:"Native baseline is missing; restore a trusted baseline before advancing"});else{let a=await kn(e,r);a.complete||n.push({code:"baseline-snapshot-incomplete",message:`Native baseline is incomplete within the project-owned scope (${a.omittedCount} omitted entries); resolve the omissions before advancing`})}}catch(r){n.push({code:"baseline-snapshot-invalid",message:`Native baseline could not be inspected safely: ${r.message}`})}if(t.phase==="build")try{let r=await Et({changeDir:i,briefRef:t.brief,specChanges:t.spec_changes});(t.approved_contract_hash??null)!==r.contract.contractHash&&n.push({code:"contract-changed-after-approval",message:t.approval===null||t.approved_contract_hash===null||t.approved_contract_hash===void 0?"Native approval is not bound to a contract hash; re-confirm the current contract":"Native contract changed after approval; re-confirm the current contract"})}catch(r){n.push({code:"contract-inspection-invalid",message:`Native approved contract could not be inspected safely: ${r.message}`})}try{await bi(e,t.name)&&n.unshift({code:"transition-incomplete",message:"Native phase transition recovery is pending"})}catch(r){n.unshift({code:"transition-invalid",message:`Native transition journal is invalid: ${r.message}`})}return t.verification_report?n.push(...(await sa(i,t.verification_report)).findings):(t.phase==="verify"||t.phase==="archive"||t.verification_result==="pass")&&n.push({code:"verification-report-missing",message:"Native change has no verification report"}),n}async function Ze(e,t,i){let n=await ZH(e)===t,r;try{let w=await ft(e,t);if(w.status==="migration-required"&&w.state)return{name:t,phase:w.state.phase,revision:"revision"in w.state?w.state.revision:null,approval:w.state.approval,verificationResult:w.state.verification_result,specChanges:w.state.spec_changes.length,selected:n,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["migration-required"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,schema:w.schema,migrationRequired:!0,minimumRuntimeVersion:w.minimumRuntimeVersion,error:w.message};if(w.status!=="current"||!w.state)return{name:t,phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:n,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["runtime-incompatible"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,schema:w.schema,minimumRuntimeVersion:w.minimumRuntimeVersion,error:w.message??`Native change ${t} is incompatible`};r=w.state}catch(w){return{name:t,phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:n,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["change-invalid"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,error:w.message}}let a=await Yk({paths:e,state:r}),o=null,s=[];if(r.phase==="build"&&r.verification_result==="fail")try{if(o=await iS(e,r,i?.maxVerifyFailures??5),o&&(o.disposition==="manual-stop"||o.disposition==="hard-stop")){let w=o.disposition==="hard-stop"?"repair-iteration-limit":o.overrideRecorded?"repair-override-exhausted":"repair-stagnation-stop";s.push({code:w,message:`Native repair is stopped at failure signature: ${o.signatureHash}`})}}catch{s.push({code:"trajectory-invalid",message:"Native repair history could not be reconstructed safely"})}let c;if(i?.details&&(r.phase==="build"||r.phase==="verify"||r.phase==="archive"))try{let w=await Et({changeDir:C(e,r.name),briefRef:r.brief,specChanges:r.spec_changes}),g=new Map;if(r.phase==="build"&&r.verification_result==="fail"&&r.verification_evidence){let E=await Dn(e,r.name,r.verification_evidence);for(let O of E.acceptanceTrace.entries)g.set(O.acceptanceId,O.status==="failed"?"failed":O.status==="missing"?"missing":"satisfied")}c=Zl({criteria:w.contract.acceptance,acceptanceHash:w.contract.acceptanceHash,verificationStatuses:g,failedCheckIds:o?.failedCheckIds??[],...i.acceptanceCursor?{cursor:i.acceptanceCursor}:{}})}catch(w){if(i.acceptanceCursor)throw w;c=void 0}let l=[];if(i?.includeConflictFindings!==!1)try{let w=await Vl(e,r.name,{tolerateInvalidSiblings:!0});l.push(...w.findingCodes.map(g=>({code:g,message:`Native change overlap is visible in the current root: ${g}`})))}catch{l.push({code:"native-conflict-inspection-invalid",message:"Native change overlap could not be recomputed safely"})}let u=[];try{let w=await Ve(e,r.name);if(w)if(w.schema==="comet.native.workspace.v3"){let g=await sr({paths:e,identity:w});g.state==="drifted"&&g.code&&u.push({code:g.code,message:g.message??"Native workspace binding is no longer valid"})}else{let g=await or({paths:e,identity:w});u.push(...g.findingCodes.map(E=>({code:E,message:`Native workspace advisory changed: ${E} (${g.driftComponents.join(", ")||"no-component"})`})))}}catch{u.push({code:"workspace-binding-invalid",message:"Native workspace binding could not be read or validated safely"})}let d=[],f=!1;if(r.phase==="verify"){let w=await ms({paths:e,state:r});f=w.freshness!=="fresh",d.push(...w.findingCodes.map(g=>({code:g,message:`Native Verify implementation scope is not current: ${g}`})))}let h=null,m=[];if(r.phase==="archive")try{h=await kr({paths:e,name:r.name}),m.push(...h.findingCodes.map(w=>({code:w,message:`Native Archive is blocked: ${w}`})))}catch{m.push({code:"archive-preflight-invalid",message:"Native Archive preflight could not be recomputed safely"})}let p=[...await t0(e,r),...a.findings,...l,...u,...d,...s,...m].filter((w,g,E)=>E.findIndex(O=>O.code===w.code&&O.path===w.path)===g),v=ni({paths:e,state:r,findings:p}),S=v.filter(w=>!ia(w.code)),k=r.phase==="archive"&&h?.ready===!0&&S.length===0,N=f||r.phase==="archive"&&(h?.findingCodes??[]).some(w=>new Set(["verification-evidence-stale","verification-evidence-invalid","verification-evidence-missing","verification-contract-stale","verification-implementation-stale","verification-report-stale","verification-state-mismatch"]).has(w)),b=v.some(w=>w.code==="trajectory-tail-incomplete"||w.code==="trajectory-invalid"||w.requiredAction==="return-to-bound-working-directory"||w.requiredAction==="repair-workspace-binding"),R=o?.disposition==="manual-stop"||o?.disposition==="hard-stop",y=v.find(w=>w.severity==="error");return{name:r.name,phase:r.phase,revision:r.revision,approval:r.approval,verificationResult:r.verification_result,specChanges:r.spec_changes.length,selected:n,nextCommand:b||R?null:e0(r,k,N,i?.clarificationMode),archiveReady:k,inspection:a.inspection,findingSummary:Jk(v),detailsCommand:`comet native status ${r.name} --details`,checkpoint:a.checkpoint,continuation:Me({state:r,findings:v,archiveReady:k,evidenceRetreat:N,clarificationMode:i?.clarificationMode}),repair:o,...i?.details?{...c?{acceptancePage:c}:{},findings:v.slice(0,50),inspectionDetails:a.inspectionDetails,checkpointDetails:a.checkpointDetails,budgets:{maxFindings:50,maxInspectionReasons:gu,maxCheckpointArtifacts:a.maxCheckpointArtifacts,findingsTruncated:v.length>50,inspectionReasonsTruncated:a.inspectionDetails.reasonsTruncated,checkpointArtifactsTruncated:!1}}:{},schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,...y?{error:y.message}:{}}}async function i0(e){let t;try{t=await hi({root:e.nativeRoot,directory:e.changesDir,label:"Native status changes directory"})}catch(r){if(r.code==="ENOENT")return[];throw r}let i=[],n=await XH.opendir(e.changesDir);try{for await(let r of n)if(!(!r.isDirectory()||r.isSymbolicLink())&&(i.push(r.name),i.length>xa.maxChanges))throw new Error(`Native status exceeds ${xa.maxChanges} visible changes`)}finally{await n.close().catch(r=>{if(r.code!=="ERR_DIR_CLOSED")throw r})}return await t.verify(),i.sort()}function nS(e,t){let i=t.toString(36),n=H("comet.native.status-cursor.v1",{namesHash:e,offset:t});return`native-status-v1.${e}.${i}.${n}`}function n0(e){if(e.cursor===void 0||e.cursor===null)return 0;let t=QH.exec(e.cursor);if(!t)throw new Error("Native status cursor is invalid");if(t[1]!==e.namesHash)throw new Error("Native status cursor is stale");let i=Number.parseInt(t[2],36);if(!Number.isSafeInteger(i)||i<=0||i>=e.total||i.toString(36)!==t[2])throw new Error("Native status cursor offset is invalid");let n=H("comet.native.status-cursor.v1",{namesHash:e.namesHash,offset:i});if(t[3]!==n)throw new Error("Native status cursor integrity check failed");return i}async function yp(e,t){let i=await i0(e),n=H("comet.native.status-names.v1",i),r=n0({namesHash:n,total:i.length,cursor:t?.cursor}),a=await Promise.all(i.slice(r,r+xa.maxItems).map(c=>Ze(e,c,{includeConflictFindings:!1,clarificationMode:t?.clarificationMode,maxVerifyFailures:t?.maxVerifyFailures}))),o=[];for(let c of a){let l=[...o,c],u=r+l.length,d={schema:"comet.native.status-page.v1",total:i.length,offset:r,items:l,nextCursor:uxa.maxSerializedBytes){if(o.length===0)throw new Error("Native status item exceeds its page serialization budget");break}o.push(c)}let s=r+o.length;return{schema:"comet.native.status-page.v1",total:i.length,offset:r,items:o,nextCursor:s2e3)throw new Error(`${t} must be between 1 and 2000 characters`);return i}function a0(e){if(e!==void 0){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native expected revision must be a positive integer");return e}}async function aS(e){let t=rS(e.summary,"Checkpoint summary"),i=rS(e.nextAction,"Checkpoint next action"),n=a0(e.expectedRevision);return te(e.paths,`checkpoint ${e.name}`,()=>De(e.paths,e.name,`checkpoint ${e.name}`,async()=>{await Rt(e.paths,e.name);let r=await G(e.paths,e.name),a=await _b(e.paths,e.name,e.artifacts??[]),o=ds(a),s=D(JSON.stringify({summary:t,nextAction:i,artifacts:a.artifacts})),c=await Gh(e.paths,e.name);if(c?.inputHash===s&&c.stateRevision===r.revision&&c.phase===r.phase){if(n!==void 0&&n!==c.previousRevision&&n!==r.revision)throw new xn(r.name,n,r.revision);return{change:r,checkpoint:c,idempotent:!0,expectedRevision:n??c.previousRevision,previousRevision:c.previousRevision,revision:r.revision,outcome:"idempotent",continuation:Me({state:r})}}if(n!==void 0&&r.revision!==n)throw new xn(r.name,n,r.revision);let l={...r,revision:r.revision+1},u={schema:"comet.native.progress-checkpoint.v1",id:e.checkpointId?.()??r0(),change:r.name,phase:r.phase,previousRevision:r.revision,stateRevision:l.revision,summary:t,nextAction:i,inputHash:s,manifestHash:o,manifestRef:Wh(o),artifactCount:a.artifacts.length,createdAt:(e.now??new Date).toISOString()},d=await $b({paths:e.paths,previousState:r,nextState:l,checkpoint:u,manifest:a,now:e.now,checkpointId:()=>u.id});await e.hooks?.afterPrepared?.(d);let f=await fs(e.paths,e.name,e.hooks);if(!f)throw new Error("Native checkpoint journal disappeared before completion");return{change:f.nextState,checkpoint:f.checkpoint,idempotent:!1,expectedRevision:n??f.checkpoint.previousRevision,previousRevision:f.checkpoint.previousRevision,revision:f.nextState.revision,outcome:"recorded",continuation:Me({state:f.nextState})}}))}async function sS(e,t){let i=ae(e,"change name"),n=J(e,"--summary");if(!n)throw new I("--summary is required");let r=J(e,"--next-action");if(!r)throw new I("--next-action is required");let a=Yi(e,"--artifact"),o=Tk(e);Y(e);let{config:s,paths:c}=await Oe(t),l=await aS({paths:c,name:i,summary:n,nextAction:r,artifacts:a,expectedRevision:o}),u=await Ze(c,i,{clarificationMode:s.native.clarification_mode,maxVerifyFailures:s.native.max_verify_failures}),d=oS.relative(c.projectRoot,oS.join(C(c,i),...l.checkpoint.manifestRef.split("/"))).replaceAll("\\","/");return Z("checkpoint",{...l,checkpoint:{...l.checkpoint,manifestRef:d},continuation:u.continuation})}import{promises as rD}from"fs";import Le from"path";import{createHash as E0,randomUUID as R0}from"node:crypto";import{constants as Rp,promises as ie}from"node:fs";import he from"node:path";var Nu=Ts(uo(),1);import{randomUUID as o0}from"crypto";import{promises as fS}from"fs";import kp from"path";import{isDeepStrictEqual as Sp}from"util";var Rr=/^[a-f0-9]{64}$/u,s0=new Set(["schema","id","change","fromSchema","toSchema","sourceHash","targetHash","createdAt","nextState","transition","transitionSupersede","runRetreat"]),c0=new Set(["sourceHash","targetHash","nextJournal"]),l0=new Set(["sourceHash","transitionId","previousRun","nextRun","evidenceHash","eventData"]),cS=new Set(["fromSchema","toSchema","previousPhase","nextPhase","reason","supersededTransitionId"]),u0=new Set(["previousRun","nextRun","evidenceHash","eventData"]);function wu(e,t,i){let n=Object.keys(e).find(r=>!t.has(r));if(n)throw new Error(`${i} contains unknown field: ${n}`)}function lS(e){return JSON.stringify(e,null,2)+` +`}function Ep(e){return e.schema===He?Sl(e):Pn(e)}function bp(e,t){return{...e,schema:He,minimum_runtime_version:2,revision:t}}function d0(e){return{...e,schema:Oi,minimum_runtime_version:2,revision:1,previousState:bp(e.previousState,1),nextState:bp(e.nextState,2)}}function yu(e,t){let i=t?.retreatEvidencePhase===!0&&(e.phase==="verify"||e.phase==="archive");return{...e,schema:xe,minimum_runtime_version:3,verification_protocol:"legacy-v1",revision:e.revision+(i&&t?.incrementRetreatRevision?1:0),phase:i?"build":e.phase,verification_result:i?"pending":e.verification_result,verification_report:i?null:e.verification_report,approved_contract_hash:null,implementation_scope:null,verification_evidence:null,partial_allowance:null,archived:i?!1:e.archived}}function f0(e){if(e.nextState.phase==="archive")throw new Error("Native v2 Archive transition must be superseded by schema migration");let t=e.previousState.phase!=="shape"&&e.nextState.phase==="build"&&e.eventData.verificationResult===null,i=t?D(JSON.stringify({operation:"spec-rebase",change:e.change,summary:e.eventData.summary,specChanges:e.nextState.spec_changes})):e.evidenceHash;return{...e,schema:ji,minimum_runtime_version:3,revision:1,operation:t?"spec-rebase":"advance",evidenceHash:i,previousState:yu(e.previousState),nextState:{...yu(e.nextState),...t?{implementation_scope:null,verification_evidence:null,partial_allowance:null}:{}},eventData:{...e.eventData,evidenceHash:i},nextRun:e.previousRun===null?{...e.nextRun,skillVersion:mt.definition.metadata.version,skillHash:vr}:e.nextRun}}function uS(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Aa(e,t){return JSON.stringify(Sl(e))===JSON.stringify(Sl(t))}function dS(e,t){return JSON.stringify(Pn(e))===JSON.stringify(Pn(t))}function Xi(e,t){return Sp(e,t)}function h0(e,t,i,n){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Schema migration transition supersede plan is invalid");let r=e;if(wu(r,l0,"Schema migration transition supersede plan"),typeof r.sourceHash!="string"||!Rr.test(r.sourceHash))throw new Error("Schema migration transition supersede source hash is invalid");if(typeof r.transitionId!="string"||r.transitionId.length===0)throw new Error("Schema migration superseded transition id is invalid");if(typeof r.evidenceHash!="string"||!Rr.test(r.evidenceHash))throw new Error("Schema migration transition supersede evidence hash is invalid");let a=Rn(r.previousRun),o=Rn(r.nextRun);if(a.runId!==o.runId||i.run_id!==o.runId||i.phase!=="build"&&i.phase!=="verify"||o.currentStep!==i.phase||o.pending!==null||o.status!=="running"||i.verification_result!=="pending"||i.verification_report!==null||i.implementation_scope!==null||i.verification_evidence!==null||i.partial_allowance!==null)throw new Error("Schema migration transition supersede Run does not match target state");let s=a.currentStep==="verify"&&i.phase==="build"||a.currentStep==="archive"&&i.phase==="build",c=a.currentStep===i.phase?a:s?{...a,currentStep:i.phase,iteration:a.iteration+1,pending:null,status:"running"}:null;if(!c||!Xi(c,o))throw new Error("Schema migration transition supersede Run retreat is invalid");if(!r.eventData||typeof r.eventData!="object"||Array.isArray(r.eventData))throw new Error("Schema migration transition supersede event is invalid");let l=r.eventData,u=Object.keys(l);if(u.length!==cS.size||u.some(f=>!cS.has(f))||l.fromSchema!==He||l.toSchema!==xe||!["build","verify","archive"].includes(l.previousPhase)||l.nextPhase!==i.phase||l.reason!==(i.phase==="build"?"implementation-scope-required":"verification-evidence-required")||l.supersededTransitionId!==r.transitionId)throw new Error("Schema migration transition supersede event semantics are invalid");if(i.name!==t)throw new Error("Schema migration transition supersede change mismatch");let d=D(JSON.stringify({operation:"supersede-v2-evidence-transition",change:t,transitionId:r.transitionId,migrationId:n,previousPhase:l.previousPhase,nextPhase:l.nextPhase,reason:l.reason,previousIteration:a.iteration,nextRevision:i.revision}));if(r.evidenceHash!==d)throw new Error("Schema migration transition supersede evidence hash mismatch");return{sourceHash:r.sourceHash,transitionId:r.transitionId,previousRun:a,nextRun:o,evidenceHash:r.evidenceHash,eventData:l}}function ks(e,t){return kp.join(C(e,t),"runtime","schema-migration.json")}function p0(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native schema migration journal must be an object");wu(e,s0,"Native schema migration journal");let i=e;if(i.schema!=="comet.native.schema-migration.v1")throw new Error("Unsupported Native schema migration journal");if(i.change!==t)throw new Error("Schema migration change mismatch");let n=i.fromSchema===jt&&i.toSchema===He,r=i.fromSchema===He&&i.toSchema===xe;if(!n&&!r)throw new Error("Schema migration route is unsupported");if(typeof i.id!="string"||i.id.length===0)throw new Error("Schema migration id is invalid");if(typeof i.sourceHash!="string"||!Rr.test(i.sourceHash)||typeof i.targetHash!="string"||!Rr.test(i.targetHash))throw new Error("Schema migration hash is invalid");if(typeof i.createdAt!="string"||Number.isNaN(Date.parse(i.createdAt)))throw new Error("Schema migration timestamp is invalid");let a=n?An(i.nextState):Ot(i.nextState);if(a.name!==t)throw new Error("Schema migration target state change mismatch");if(D((0,Nu.stringify)(Ep(a)))!==i.targetHash)throw new Error("Schema migration state target hash does not match its document");let o;if(i.transition!==void 0){if(!i.transition||typeof i.transition!="object")throw new Error("Schema migration transition target is invalid");wu(i.transition,c0,"Schema migration transition target");let l=i.transition;if(typeof l.sourceHash!="string"||!Rr.test(l.sourceHash)||typeof l.targetHash!="string"||!Rr.test(l.targetHash))throw new Error("Schema migration transition hash is invalid");let u=n?jh(l.nextJournal,t):Ql(l.nextJournal,t);if(D(JSON.stringify(l.nextJournal,null,2)+` +`)!==l.targetHash)throw new Error("Schema migration transition target hash does not match its journal");if(!(n&&a.schema===He?Aa(a,u.previousState)||Aa(a,u.nextState):a.schema===xe&&(dS(a,u.previousState)||dS(a,u.nextState))))throw new Error("Schema migration state/transition target mismatch");o={sourceHash:l.sourceHash,targetHash:l.targetHash,nextJournal:l.nextJournal}}if(n&&(!o&&a.revision!==1||o&&a.revision!==1&&a.revision!==2))throw new Error("Schema migration v1 target revision is invalid");let s;if(i.transitionSupersede!==void 0){if(!r||o)throw new Error("Schema migration transition supersede plan is not valid for this route");if(a.schema!==xe)throw new Error("Schema migration transition supersede target schema is invalid");s=h0(i.transitionSupersede,t,a,i.id)}let c;if(i.runRetreat!==void 0){if(!r||o||s)throw new Error("Schema migration Run retreat is not valid for this route");if(!i.runRetreat||typeof i.runRetreat!="object")throw new Error("Schema migration Run retreat is invalid");wu(i.runRetreat,u0,"Schema migration Run retreat");let l=i.runRetreat,u,d;try{u=Rn(l.previousRun),d=Rn(l.nextRun)}catch(f){throw new Error("Schema migration Run retreat is invalid",{cause:f})}if(typeof l.evidenceHash!="string"||!Rr.test(l.evidenceHash)||!l.eventData||typeof l.eventData!="object"||Array.isArray(l.eventData))throw new Error("Schema migration Run retreat is invalid");if(a.schema!==xe||a.phase!=="build"||a.run_id!==d.runId||u.runId!==d.runId||u.currentStep!=="verify"&&u.currentStep!=="archive"||d.currentStep!=="build"||d.iteration!==u.iteration+1)throw new Error("Schema migration Run retreat does not match target state");c={previousRun:u,nextRun:d,evidenceHash:l.evidenceHash,eventData:l.eventData}}if(o&&c||s&&c)throw new Error("Schema migration has conflicting recovery plans");return{schema:"comet.native.schema-migration.v1",id:i.id,change:t,fromSchema:i.fromSchema,toSchema:i.toSchema,sourceHash:i.sourceHash,targetHash:i.targetHash,createdAt:i.createdAt,nextState:a,...o?{transition:o}:{},...s?{transitionSupersede:s}:{},...c?{runRetreat:c}:{}}}async function Ss(e,t){let i=ks(e,t);await x(e.nativeRoot,i);try{let n=await el({root:e.nativeRoot,file:i,maxBytes:524288,label:"Native schema migration journal"});return p0(JSON.parse(n.text),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function m0(e,t,i){let n=await vi(e,t),r=n?await kn(e,n):await $o(e,{now:new Date(i),origin:"legacy-migration"});if(!r.complete){let a=hl(r),o=r.omitted.reduce((c,l)=>(c[l.reason]=(c[l.reason]??0)+1,c),{}),s=r.omissionOverflow?.count??0;throw s>0&&(o.overflow=s),new gi(t,r.omittedCount,o,a.samplePaths,a.sampleTruncated)}n===null&&await pl(e,t,r)}async function hS(e){try{return await lt(e)}catch(t){if(t.code==="ENOENT")return null;throw t}}function v0(e,t){let i=e.transitionSupersede;return{sequence:t,timestamp:e.createdAt,type:"state_migrated",runId:i.nextRun.runId,data:{...i.eventData,migrationId:e.id,evidenceHash:i.evidenceHash}}}async function pS(e,t){let i=t.transitionSupersede,n=C(e,t.change),r=await qe(n,i.nextRun.trajectoryRef),a=r.map((s,c)=>({event:s,index:c})).filter(({event:s})=>s.data.migrationId===t.id);if(a.length>1)throw new Error(`Native schema migration event ${t.id} is duplicated`);let o=a[0];if(o&&!Sp(o.event,v0(t,o.index+1)))throw new Error(`Native schema migration event ${t.id} changed`);return{trajectoryLength:r.length,sequence:o?.event.sequence??null}}async function g0(e,t,i){if(!t.transitionSupersede)return;let n=We(e,t.change),r=await hS(n);if(r===t.transitionSupersede.sourceHash)return;if(r!==null)throw new Error(`Native superseded transition source changed for ${t.change}: expected ${t.transitionSupersede.sourceHash}, actual ${r}`);let a=await be(C(e,t.change)),o=await pS(e,t),s=await ea(C(e,t.change),t.transitionSupersede.nextRun.checkpointRef);if(!i||!a||!Xi(a,t.transitionSupersede.nextRun)||o.sequence===null||!s||s.runId!==t.transitionSupersede.nextRun.runId||s.stateVersion!==t.transitionSupersede.nextRun.iteration||s.trajectoryOffset!==o.sequence||s.contextHash!==null||s.artifactsHash!==D(t.transitionSupersede.evidenceHash)||s.createdAt!==t.createdAt)throw new Error(`Native superseded transition disappeared before migration ${t.id} was durable`)}async function w0(e,t,i){let n=t.transitionSupersede;if(!n)return;let r=C(e,t.change),a=await be(r);if(!a)throw new Error(`Native schema migration Run state disappeared for ${t.change}`);if(!Xi(a,n.nextRun)){if(!Xi(a,n.previousRun))throw new Error(`Native schema migration Run source changed for ${t.change}`);await rr(r,n.nextRun),await i?.afterRunStateWritten?.(t)}if(!Xi(await be(r),n.nextRun))throw new Error(`Native schema migration Run write diverged for ${t.change}`);let o=await pS(e,t);if(o.sequence===null){let l=await Fn({changeDir:r,run:n.nextRun,type:"state_migrated",data:{...n.eventData,migrationId:t.id,evidenceHash:n.evidenceHash},now:new Date(t.createdAt)});o={trajectoryLength:l.sequence,sequence:l.sequence}}await i?.afterTrajectoryWritten?.(t),await gr({changeDir:r,run:n.nextRun,trajectoryOffset:o.sequence,evidenceHash:n.evidenceHash,now:new Date(t.createdAt)}),await i?.afterCheckpointWritten?.(t);let s=We(e,t.change),c=await hS(s);if(c!==null){if(c!==n.sourceHash)throw new Error(`Native superseded transition changed before removal for ${t.change}`);await fS.rm(s),await i?.afterTransitionSuperseded?.(t)}}async function y0(e,t,i){if(!t.runRetreat)return;let n=C(e,t.change),r=await be(n);if(!r)throw new Error(`Native schema migration Run state disappeared for ${t.change}`);if(!Xi(r,t.runRetreat.nextRun)){if(!Xi(r,t.runRetreat.previousRun))throw new Error(`Native schema migration Run source changed for ${t.change}`);await rr(n,t.runRetreat.nextRun),await i?.afterRunStateWritten?.(t)}let a=await qe(n,t.runRetreat.nextRun.trajectoryRef),o=a.find(s=>s.type==="state_migrated"&&s.data.migrationId===t.id);o||(o=await Fn({changeDir:n,run:t.runRetreat.nextRun,type:"state_migrated",data:{...t.runRetreat.eventData,migrationId:t.id,evidenceHash:t.runRetreat.evidenceHash},now:new Date(t.createdAt)}),a=[...a,o]),await i?.afterTrajectoryWritten?.(t),await gr({changeDir:n,run:t.runRetreat.nextRun,trajectoryOffset:a.length,evidenceHash:t.runRetreat.evidenceHash,now:new Date(t.createdAt)}),await i?.afterCheckpointWritten?.(t)}async function N0(e,t,i){let n=await Ss(e,t);if(!n)return null;if(await aa(e,t))throw new Error(`Native change ${t} has a pending progress checkpoint; recover it with its v2 runtime before schema migration`);let r=kp.join(C(e,t),je),a=await lt(r);if(await g0(e,n,a===n.targetHash),await m0(e,t,n.createdAt),a!==n.targetHash){if(a!==n.sourceHash)throw new Error(`Native schema migration source changed for ${t}: expected ${n.sourceHash}, actual ${a}`);await $e(r,(0,Nu.stringify)(Ep(n.nextState))),await i?.afterStateWritten?.(n)}if(n.transition){let o=We(e,t),s=await lt(o);if(s!==n.transition.targetHash){if(s!==n.transition.sourceHash)throw new Error(`Native transition migration source changed for ${t}: expected ${n.transition.sourceHash}, actual ${s}`);await le(o,n.transition.nextJournal),await i?.afterTransitionWritten?.(n)}}return await w0(e,n,i),await y0(e,n,i),await fS.rm(ks(e,t),{force:!0}),n.nextState}async function b0(e){let t=C(e.paths,e.state.name),i=await be(t);if(!i||i.runId!==e.state.run_id||i.currentStep!==e.state.phase||i.currentStep!=="verify"&&i.currentStep!=="archive"||i.pending!==null)throw new Error(`Native v2 ${e.state.phase} change ${e.state.name} has no consistent Run state for safe Build retreat`);let n={...i,currentStep:"build",iteration:i.iteration+1,pending:null,status:"running"},r=D(`schema-v3-evidence-retreat:${e.state.name}:${e.state.revision}:${e.migrationId}`);return{previousRun:i,nextRun:n,evidenceHash:r,eventData:{fromSchema:He,toSchema:xe,previousPhase:e.state.phase,nextPhase:"build",reason:"implementation-scope-required"}}}async function k0(e){let{journal:t,state:i}=e;if(!(t.previousState.phase==="build"&&t.nextState.phase==="verify"||t.previousState.phase==="verify"&&(t.nextState.phase==="build"||t.nextState.phase==="archive")))throw new Error("Only a pending v2 evidence-bearing transition can be superseded");let r=Aa(i,t.previousState),a=Aa(i,t.nextState);if(!r&&!a)throw new Error(`Native change ${i.name} does not match its v2 evidence transition`);let o=C(e.paths,i.name),s=await be(o);if(!s)throw new Error(`Native v2 transition Run is missing for ${i.name}`);let c=t.previousRun!==null&&Xi(s,t.previousRun),l=Xi(s,t.nextRun);if(!c&&!l||a&&!l)throw new Error(`Native v2 transition Run does not match its durable state for ${i.name}`);let d=(await qe(o,t.nextRun.trajectoryRef)).map((S,k)=>({event:S,index:k})).filter(({event:S})=>S.data.transitionId===t.id);if(d.length>1)throw new Error(`Native v2 evidence transition ${t.id} has duplicate trajectory events`);let f=d[0];if(f){let S={sequence:f.index+1,timestamp:t.createdAt,type:"state_transitioned",runId:t.nextRun.runId,data:{...t.eventData,transitionId:t.id}};if(!Sp(f.event,S)||!a||!l)throw new Error(`Native v2 evidence transition ${t.id} trajectory event does not match its journal`)}let h={...yu(i),revision:i.revision+(i.phase==="build"?0:1),phase:"build",verification_result:"pending",verification_report:null,implementation_scope:null,verification_evidence:null,partial_allowance:null,archived:!1},m=s,p=s.currentStep!=="build"?{...s,currentStep:"build",iteration:s.iteration+1,pending:null,status:"running"}:s,v=D(JSON.stringify({operation:"supersede-v2-evidence-transition",change:i.name,transitionId:t.id,migrationId:e.migrationId,previousPhase:i.phase,nextPhase:"build",reason:"implementation-scope-required",previousIteration:s.iteration,nextRevision:h.revision}));return{nextState:h,plan:{sourceHash:await lt(We(e.paths,i.name)),transitionId:t.id,previousRun:m,nextRun:p,evidenceHash:v,eventData:{fromSchema:He,toSchema:xe,previousPhase:i.phase,nextPhase:"build",reason:"implementation-scope-required",supersededTransitionId:t.id}}}}async function S0(e){let t,i,n,r;if(e.state.schema===jt){if(t=bp(e.state,1),e.pendingTransition){if(e.pendingTransition.journal.schema!==cr)throw new Error("Native v1 change has a transition from another schema generation");let s=d0(e.pendingTransition.journal);if(uS(e.state,e.pendingTransition.journal.previousState))t=s.previousState;else if(uS(e.state,e.pendingTransition.journal.nextState))t=s.nextState;else throw new Error(`Native change ${e.name} does not match either state in its v1 transition journal`);let c=We(e.paths,e.name);i={sourceHash:await lt(c),targetHash:D(lS(s)),nextJournal:s}}}else if(e.pendingTransition){if(e.pendingTransition.journal.schema!==Oi)throw new Error("Native v2 change has a transition from another schema generation");let s=e.pendingTransition.journal;if(s.previousState.phase==="build"&&s.nextState.phase==="verify"||s.previousState.phase==="verify"&&(s.nextState.phase==="build"||s.nextState.phase==="archive")){let l=await k0({paths:e.paths,state:e.state,journal:s,migrationId:e.id});t=l.nextState,n=l.plan}else{let l=f0(s);if(Aa(e.state,e.pendingTransition.journal.previousState))t=l.previousState;else if(Aa(e.state,e.pendingTransition.journal.nextState))t=l.nextState;else throw new Error(`Native change ${e.name} does not match either state in its v2 transition journal`);let u=We(e.paths,e.name);i={sourceHash:await lt(u),targetHash:D(lS(l)),nextJournal:l}}}else t=yu(e.state,{retreatEvidencePhase:!0,incrementRetreatRevision:!0}),(e.state.phase==="verify"||e.state.phase==="archive")&&(r=await b0({paths:e.paths,state:e.state,migrationId:e.id}));let a=kp.join(C(e.paths,e.name),je),o=(0,Nu.stringify)(Ep(t));return{schema:"comet.native.schema-migration.v1",id:e.id,change:e.name,fromSchema:e.state.schema,toSchema:e.state.schema===jt?He:xe,sourceHash:await lt(a),targetHash:D(o),createdAt:e.now.toISOString(),nextState:t,...i?{transition:i}:{},...n?{transitionSupersede:n}:{},...r?{runRetreat:r}:{}}}async function mS(e){return te(e.paths,`migrate schema for ${e.name}`,()=>De(e.paths,e.name,`migrate schema for ${e.name}`,async()=>{for(let t=0;t<3;t+=1){let i=await N0(e.paths,e.name,e.hooks);if(i?.schema===xe)return i;let n=await ft(e.paths,e.name);if(n.status==="current"&&n.state)return n.state;if(n.status!=="migration-required"||!n.state)throw new Error(n.message??`Native change ${e.name} cannot be migrated`);if(await aa(e.paths,e.name))throw new Error(`Native change ${e.name} has a pending progress checkpoint; recover it with its v2 runtime before schema migration`);let r=n.state;if(r.schema!==jt&&r.schema!==He)throw new Error(`Native change ${e.name} has no supported migration route`);let a=await Oh(e.paths,e.name);if(a?.status==="current")throw new Error(`Native change ${e.name} has a current-schema pending transition; recover it before schema migration`);let o=await S0({paths:e.paths,name:e.name,state:r,pendingTransition:a,now:e.now??new Date,id:e.id?.()??o0()}),s=ks(e.paths,e.name);await x(e.paths.nativeRoot,s),await le(s,o),await e.hooks?.afterPrepared?.(o)}throw new Error(`Native change ${e.name} exceeded the supported schema migration path`)}))}var Qi=Object.freeze({minimumAgeMs:720*60*60*1e3,keepLatestUnreferencedPerKind:32,maxDocuments:4096,maxScannedBytes:256*1024*1024,maxReportedRefs:8,maxReportMessageBytes:4096}),C0=512*1024,Cr=/^([a-f0-9]{64})\.json$/u,P0=/^\.([a-f0-9]{64}\.json)\.([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})\.gc$/u,x0=/^runtime\/evidence\/(snapshots|scopes|allowances|verifications|reports|receipts|check-receipts)\/[a-f0-9]{64}\.json$/u,bu=["snapshots","scopes","allowances","verifications","reports","receipts","check-receipts"];function Pp(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Pi(e,t){return Pp(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function NS(e,t){return Pp(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function Ta(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function nt(e,t){return et?1:0}function A0(e,t){let i=he.relative(e.projectRoot,t);if(i.length===0||he.isAbsolute(i)||i===".."||i.startsWith(`..${he.sep}`))throw new Error("Native evidence retention finding path is outside the project");return i.split(he.sep).join("/")}function bS(e,t){return he.join(C(e,t),"runtime","evidence")}function ku(e,t){return A0(e,bS(e,t))}async function Su(e,t){let i=he.resolve(e),n=he.resolve(t);if(!$(i,n))throw new Error("Native evidence retention path escapes its managed change");let r=he.relative(i,n).split(he.sep).filter(Boolean),a=[],o=i;for(let s of["",...r]){s&&(o=he.join(o,s));let c=await ie.lstat(o);if(!c.isDirectory()||c.isSymbolicLink())throw new Error(`Native evidence retention parent must be a real directory: ${o}`);let l=await ie.realpath(o);if(a.length>0&&!$(a[0].realPath,l))throw new Error(`Native evidence retention parent resolves outside its change: ${o}`);a.push({path:o,realPath:l,...Ta(c)})}return a}async function Lt(e){for(let t of e){let i=await ie.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!Pp(t,i)||await ie.realpath(t.path)!==t.realPath)throw new Error(`Native evidence retention parent changed: ${t.path}`)}}function kS(e,t){return e==="check-receipts"?`runtime/evidence/check-receipts/${t}.json`:pt(e,t)}function vS(e){return e!==null&&x0.test(e)?[e]:[]}function T0(e,t,i,n){if(e==="snapshots")return{canonical:da(i,t),dependencies:[]};if(e==="scopes"){let a=fa(i);if(a.scopeHash!==t)throw new Error("Native scope filename does not match its hash");return{canonical:a,dependencies:[a.baselineProjectionRef,a.currentProjectionRef]}}if(e==="allowances"){let a=es(i);if(a.change!==n||a.allowanceHash!==t)throw new Error("Native allowance filename/change does not match its content");return{canonical:a,dependencies:[pt("scopes",a.scopeHash)]}}if(e==="verifications"){let a=pa(i);if(a.change!==n||a.envelopeHash!==t)throw new Error("Native verification filename/change does not match its content");let o=a.acceptanceTrace.entries.flatMap(s=>s.evidenceRefs.flatMap(vS));return{canonical:a,dependencies:[a.implementationScopeRef,PN(a.reportHash),...vS(a.partialAllowanceRef),...a.requiredReceiptRefs,...a.receiptRefs,...o]}}if(e==="reports"){if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Native report evidence must be an object");let a=i;if(Object.keys(a).sort().join(",")!=="content,reportHash,schema"||a.schema!=="comet.native.verification-report.v1"||a.reportHash!==t||typeof a.content!="string"||E0("sha256").update(Buffer.from(a.content,"utf8")).digest("hex")!==t)throw new Error("Native report evidence filename/hash does not match its content");return{canonical:a,dependencies:[]}}if(e==="receipts"){let a=ns(i);if(a.bindings.change!==n||a.receiptHash!==t)throw new Error("Native verification receipt filename/change does not match its content");return{canonical:a,dependencies:a.kind==="static-inspection"?[a.evidence.checkReceiptRef]:[]}}let r=qi(i);if(r.change!==n||r.receiptHash!==t)throw new Error("Native check receipt filename/change does not match its content");return{canonical:r,dependencies:[]}}async function Vn(e){let t=await ie.lstat(e.file);if(!t.isFile()||t.isSymbolicLink())throw new Error(`Native evidence entry is not a regular file: ${e.ref}`);let i=e.kind==="check-receipts"?C0:Qt;if(t.size>i)throw new Error(`Native evidence entry exceeds its byte budget: ${e.ref}`);let n=await ie.realpath(e.file);if(!$(e.directoryChain[0].realPath,n))throw new Error(`Native evidence entry resolves outside its change: ${e.ref}`);let r=process.platform==="win32"?"r":Rp.O_RDONLY|Rp.O_NOFOLLOW|Rp.O_NONBLOCK,a=await ie.open(e.file,r).catch(o=>{throw o.code==="ELOOP"||o.code==="ENXIO"?new Error(`Native evidence entry became unsafe while opening: ${e.ref}`):o});try{let[o,s,c]=await Promise.all([a.stat(),ie.lstat(e.file),ie.realpath(e.file)]);if(await Lt(e.directoryChain),!o.isFile()||!s.isFile()||s.isSymbolicLink()||c!==n||!Pi(Ta(t),o)||!Pi(Ta(o),s))throw new Error(`Native evidence entry changed while opening: ${e.ref}`);let l=[],u=Buffer.allocUnsafe(64*1024),d=0;for(;;){let k=i+1-d,N=await a.read(u,0,Math.min(u.length,k),null);if(N.bytesRead===0)break;if(d+=N.bytesRead,d>i)throw new Error(`Native evidence entry exceeds its byte budget: ${e.ref}`);l.push(Buffer.from(u.subarray(0,N.bytesRead)))}let[f,h,m]=await Promise.all([a.stat(),ie.lstat(e.file),ie.realpath(e.file)]);if(await Lt(e.directoryChain),!h.isFile()||h.isSymbolicLink()||m!==n||!Pi(Ta(o),f)||!Pi(Ta(o),h))throw new Error(`Native evidence entry changed while reading: ${e.ref}`);let p=Buffer.concat(l,d).toString("utf8"),v;try{v=JSON.parse(p)}catch(k){throw new Error(`Native evidence entry is not valid JSON: ${e.ref}`,{cause:k})}let S=T0(e.kind,e.hash,v,e.name);if(p!==JSON.stringify(S.canonical,null,2)+` +`)throw new Error(`Native evidence entry is not canonically serialized: ${e.ref}`);return{ref:e.ref,kind:e.kind,change:e.name,changeRoot:e.changeRoot,file:e.file,size:d,mtimeMs:f.mtimeMs,identity:Ta(f),directoryChain:e.directoryChain,dependencies:[...new Set(S.dependencies)].sort(nt)}}finally{await a.close()}}async function gS(e){try{return await ie.lstat(e),!1}catch(t){if(t.code==="ENOENT")return!0;throw t}}async function _0(e){let t=C(e.paths,e.name),i=bS(e.paths,e.name);await x(e.paths.nativeRoot,i);let n;try{let o=await Su(t,i);n=await ie.readdir(i,{withFileTypes:!0}),await Lt(o)}catch(o){if(o.code==="ENOENT")return{findings:[],pending:!1};throw o}let r=[];for(let o of bu){if(!n.some(d=>d.name===o))continue;let s=he.join(i,o),c=await Su(t,s),l=(await ie.readdir(s,{withFileTypes:!0})).sort((d,f)=>nt(d.name,f.name)),u=new Map;for(let d of l){let f=P0.exec(d.name);if(!f)continue;let h=u.get(f[1])??[];h.push(d),u.set(f[1],h)}for(let[d,f]of[...u.entries()].sort(([h],[m])=>nt(h,m))){if(f.length!==1)throw new Error(`Native evidence cleanup has multiple quarantines for ${o}/${d}`);let h=f[0];if(!h.isFile()||h.isSymbolicLink())throw new Error(`Native evidence cleanup quarantine is not a regular file: ${o}/${h.name}`);let m=he.join(s,d),p=Cr.exec(d)?.[1];if(!p)throw new Error(`Native evidence cleanup quarantine name is invalid: ${h.name}`);let v=kS(o,p),S=he.join(s,h.name),k=await Vn({changeRoot:t,file:S,ref:v,kind:o,hash:p,name:e.name,directoryChain:c}),N=await gS(m),b=N?null:await Vn({changeRoot:t,file:m,ref:v,kind:o,hash:p,name:e.name,directoryChain:c});r.push({ref:v,original:m,quarantine:S,document:k,action:N?"restore-original":"finish-linked-recovery",originalDocument:b})}}if(r.length===0)return{findings:[],pending:!1};let a=r.map(o=>o.ref).sort(nt);if(!e.repair)return{pending:!0,findings:[{severity:"warning",code:"evidence-retention-recovery-required",message:_a(`Native evidence cleanup has ${a.length} safely recoverable quarantined document(s) for ${e.name}: ${Eu(a)}`),path:ku(e.paths,e.name)}]};for(let o of r.sort((s,c)=>nt(s.ref,c.ref))){if(await Lt(o.document.directoryChain),o.action==="finish-linked-recovery"){let u=await Vn({changeRoot:t,file:o.original,ref:o.ref,kind:o.document.kind,hash:Cr.exec(he.basename(o.original))[1],name:e.name,directoryChain:o.document.directoryChain}),d=await Vn({changeRoot:t,file:o.quarantine,ref:o.ref,kind:o.document.kind,hash:Cr.exec(he.basename(o.original))[1],name:e.name,directoryChain:o.document.directoryChain});if(!o.originalDocument||!Pi(o.originalDocument.identity,u.identity)||!Pi(o.document.identity,d.identity))throw new Error(`Native evidence cleanup original or quarantine changed during recovery: ${o.ref}`);await ie.rm(o.quarantine),await Lt(o.document.directoryChain);continue}if(!await gS(o.original))throw new Error(`Native evidence cleanup original appeared during recovery: ${o.ref}`);let s=await ie.lstat(o.quarantine);if(!s.isFile()||s.isSymbolicLink()||!Pi(o.document.identity,s))throw new Error(`Native evidence cleanup quarantine changed during recovery: ${o.ref}`);await ie.link(o.quarantine,o.original),await e.hooks.afterRecoveryLink?.({ref:o.ref,original:o.original,quarantine:o.quarantine});let c=await Vn({changeRoot:t,file:o.original,ref:o.ref,kind:o.document.kind,hash:Cr.exec(he.basename(o.original))[1],name:e.name,directoryChain:o.document.directoryChain}),l=await Vn({changeRoot:t,file:o.quarantine,ref:o.ref,kind:o.document.kind,hash:Cr.exec(he.basename(o.original))[1],name:e.name,directoryChain:o.document.directoryChain});if(!NS(o.document.identity,c.identity)||!Pi(c.identity,l.identity))throw new Error(`Native evidence cleanup recovery identity changed: ${o.ref}`);await ie.rm(o.quarantine),await Lt(o.document.directoryChain)}return{pending:!1,findings:[{severity:"info",code:"evidence-retention-cleanup-recovered",message:_a(`Recovered ${a.length} interrupted Native evidence cleanup document(s) for ${e.name}: ${Eu(a)}`),path:ku(e.paths,e.name)}]}}async function I0(e,t){let i=C(e,t),n=he.join(i,"runtime","evidence");await x(e.nativeRoot,n);let r;try{let c=await Su(i,n);r=await ie.readdir(n,{withFileTypes:!0}),await Lt(c)}catch(c){if(c.code==="ENOENT")return[];throw c}let a=r.filter(c=>!bu.includes(c.name)||!c.isDirectory()||c.isSymbolicLink()).map(c=>c.name).sort(nt);if(a.length>0)throw new Error(`Native evidence root has unknown or special entries: ${Eu(a)}`);let o=[],s=0;for(let c of bu){if(!r.some(f=>f.name===c))continue;let l=he.join(n,c),u=await Su(i,l),d=(await ie.readdir(l,{withFileTypes:!0})).sort((f,h)=>nt(f.name,h.name));await Lt(u);for(let f of d){if(o.length>=Qi.maxDocuments)throw new Error(`Native evidence store exceeds ${Qi.maxDocuments} documents`);let h=Cr.exec(f.name);if(!h||!f.isFile()||f.isSymbolicLink())throw new Error(`Native evidence kind ${c} has an unknown or special entry: ${f.name}`);let m=kS(c,h[1]),p=he.join(l,f.name);await x(e.nativeRoot,p);let v=await Vn({changeRoot:i,file:p,ref:m,kind:c,hash:h[1],name:t,directoryChain:u});if(s+=v.size,s>Qi.maxScannedBytes)throw new Error(`Native evidence store exceeds ${Qi.maxScannedBytes} scanned bytes`);o.push(v)}await Lt(u)}return o}function wS(e,t){let i=new Set,n=[...e].sort(nt).reverse();for(;n.length>0;){let r=n.pop();if(i.has(r))continue;let a=t.get(r);if(!a)throw new Error(`Native evidence dependency is missing: ${r}`);i.add(r);for(let o of[...a.dependencies].sort(nt).reverse())i.has(o)||n.push(o)}return i}function j0(e){let t=new Map(e.map(a=>[a.ref,a])),i=new Map(e.map(a=>[a.ref,0]));for(let a of e)for(let o of a.dependencies)t.has(o)&&i.set(o,(i.get(o)??0)+1);let n=[...i].filter(([,a])=>a===0).map(([a])=>a).sort(nt),r=[];for(;n.length>0;){let a=n.shift(),o=t.get(a);r.push(o);for(let s of o.dependencies){let c=i.get(s);if(c===void 0)continue;let l=c-1;i.set(s,l),l===0&&(n.push(s),n.sort(nt))}}if(r.length!==e.length)throw new Error("Native evidence candidate dependency graph contains a cycle");return r}function O0(e,t,i){let n=new Map(e.map(c=>[c.ref,c]));if(n.size!==e.length)throw new Error("Native evidence store has duplicate refs");for(let c of e)for(let l of c.dependencies)if(!n.has(l))throw new Error(`Native evidence dependency is missing: ${l}`);let r=wS(t,n),a=new Set(r);for(let c of e)i-c.mtimeMsu.kind===c&&!r.has(u.ref)).sort((u,d)=>d.mtimeMs-u.mtimeMs||nt(u.ref,d.ref)).slice(0,Qi.keepLatestUnreferencedPerKind);for(let u of l)a.add(u.ref)}let o=wS(a,n),s=e.filter(c=>!o.has(c.ref)&&i-c.mtimeMs>=Qi.minimumAgeMs).sort((c,l)=>nt(c.ref,l.ref));return{candidates:j0(s),candidateBytes:s.reduce((c,l)=>c+l.size,0)}}function Eu(e){let t=e.slice(0,Qi.maxReportedRefs),i=e.length-t.length;return`${t.join(", ")}${i>0?`, ... (${i} more)`:""}`}function _a(e){let t=Qi.maxReportMessageBytes;if(Buffer.byteLength(e,"utf8")<=t)return e;let i=e;for(;i.length>0&&Buffer.byteLength(`${i}...`,"utf8")>t;)i=i.slice(0,-1);return`${i}...`}function Cp(e,t,i,n){let r=t.candidates.map(a=>a.ref).sort(nt);return{severity:"info",code:i?"evidence-retention-cleaned":"evidence-retention-candidates",message:_a(`${i?"Removed":"Found"} ${t.candidates.length} old unreferenced Native evidence document(s) (${t.candidateBytes} bytes) for ${e}: ${Eu(r)}`),path:n}}async function yS(e,t){try{await ie.lstat(t);return}catch(i){if(i.code!=="ENOENT")return}try{await ie.rename(e,t)}catch{}}async function $0(e,t){await t.beforeDelete?.({ref:e.ref,file:e.file}),await Lt(e.directoryChain);let i=await Vn({changeRoot:e.changeRoot,file:e.file,ref:e.ref,kind:e.kind,hash:Cr.exec(he.basename(e.file))[1],name:e.change,directoryChain:e.directoryChain}),n=await ie.lstat(e.file),r=await ie.realpath(e.file);if(!n.isFile()||n.isSymbolicLink()||!Pi(e.identity,n)||!Pi(e.identity,i.identity)||!$(e.directoryChain[0].realPath,r))throw new Error(`Native evidence candidate changed before cleanup: ${e.ref}`);let a=he.join(he.dirname(e.file),`.${he.basename(e.file)}.${R0()}.gc`);await ie.rename(e.file,a);try{let[o,s]=await Promise.all([ie.lstat(a),ie.realpath(a)]);if(await Lt(e.directoryChain),!o.isFile()||o.isSymbolicLink()||!NS(e.identity,o)||!$(e.directoryChain[0].realPath,s))throw await yS(a,e.file),new Error(`Native evidence candidate changed during cleanup: ${e.ref}`);await ie.rm(a),await Lt(e.directoryChain)}catch(o){throw await yS(a,e.file),o}}async function H0(e){if((await re(e.projectRoot))?.native.pending_root_move)return!0;let i;try{i=await ie.readdir(e.transactionsDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return!1;throw n}for(let n of i){if(!n.isDirectory()||n.isSymbolicLink())return!0;try{let r=await ct(e,n.name);if(r.status!=="committed"&&r.status!=="rolled-back")return!0}catch{return!0}}return!1}async function D0(e,t){if(t)return[t];let i;try{i=await ie.readdir(e.changesDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}return i.filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort(nt)}async function M0(e,t){let i=await ft(e,t);if(i.status!=="current"||!i.state||i.state.archived)return!0;let[n,r,a]=await Promise.all([bi(e,t),Ss(e,t),Gi(e,t)]);return n!==null||r!==null||a!==null}async function F0(e){if(await M0(e.paths,e.name))return[];let t=await ft(e.paths,e.name);if(t.status!=="current"||!t.state)return[];if(!("implementation_scope"in t.state))return[];let i=await _0({paths:e.paths,name:e.name,repair:e.repair,hooks:e.hooks});if(i.pending)return i.findings;let n=[];for(let c of[t.state.implementation_scope,t.state.partial_allowance,t.state.verification_evidence])c!==null&&n.push(c);let r=await I0(e.paths,e.name),a=O0(r,n,e.nowMs);if(a.candidates.length===0)return i.findings;let o=ku(e.paths,e.name);if(!e.repair)return[...i.findings,Cp(e.name,a,!1,o)];let s=[];for(let c of a.candidates)try{await $0(c,e.hooks),s.push(c)}catch(l){let u=s.reduce((d,f)=>d+f.size,0);return[...i.findings,...s.length>0?[Cp(e.name,{candidates:s,candidateBytes:u},!0,o)]:[],{severity:"error",code:"evidence-retention-cleanup-failed",message:_a(`Native evidence cleanup stopped safely for ${e.name}: ${l.message}`),path:o}]}return[...i.findings,Cp(e.name,a,!0,o)]}async function SS(e){if(e.deferAll||await H0(e.paths))return[];let t=e.now??new Date;if(Number.isNaN(t.getTime()))throw new Error("Native evidence retention time is invalid");let i=async r=>{let a=[];for(let o of await D0(e.paths,e.name))try{a.push(...await F0({paths:e.paths,name:o,repair:r,nowMs:t.getTime(),hooks:e.hooks??{}}))}catch(s){a.push({severity:"error",code:"evidence-retention-unsafe",message:_a(`Native evidence retention refused to clean ${o}: ${s.message}`),path:ku(e.paths,o)})}return a};if(!(e.repair??!1))return i(!1);let n=await i(!1);if(n.some(r=>r.severity==="error")||!n.some(r=>r.code==="evidence-retention-candidates"||r.code==="evidence-retention-recovery-required"))return n;try{return await te(e.paths,"prune Native evidence",()=>i(!0))}catch(r){return[{severity:"info",code:"evidence-retention-cleanup-deferred",message:_a(`Native evidence cleanup was deferred until the project mutation lock is available: ${r.message}`)}]}}import{createHash as L0,randomUUID as B0}from"crypto";import{promises as Wn}from"fs";import ne from"path";var Ap=64*1024*1024,q0=256*1024,PS=16*1024*1024;async function Fe(e){try{return await Wn.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function V0(e){let t;try{t=await Wn.readdir(e.transactionsDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return;throw i}for(let i of t){if(!i.isDirectory()||i.isSymbolicLink())continue;let n;try{n=await ct(e,i.name)}catch(r){throw r.code==="ENOENT"?new Error(`Native transaction ${i.name} has no journal; run doctor before moving`,{cause:r}):r}if(n.status!=="committed"&&n.status!=="rolled-back")throw new Error(`Native transaction ${n.id} is unfinished; recover it before moving`)}}async function W0(e,t){for(let i of await Wn.readdir(e.locksDir,{withFileTypes:!0})){let n=ne.join(e.locksDir,i.name);if(ne.resolve(n)!==ne.resolve(t)&&(i.isFile()||i.isSymbolicLink()))throw new Error(`Native lock must be diagnosed before moving the root: ${n}`)}}async function J0(e){let t;try{t=await Wn.readdir(e.changesDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return;throw i}for(let i of t.sort((n,r)=>n.name.localeCompare(r.name))){if(!i.isDirectory()||i.isSymbolicLink())continue;let n=await Ve(e,i.name);if(n){await ra({paths:e,name:i.name,revision:n.capturedRevision,...n.schema==="comet.native.workspace.v3"?{binding:{isolation:n.isolation,changeBranch:n.changeBranch,targetBranch:n.targetBranch},...n.finish?{finish:n.finish}:{}}:{}});continue}let r;try{r=await ft(e,i.name)}catch{continue}r.status!=="current"||!r.state||!("revision"in r.state)||await ra({paths:e,name:i.name,revision:r.state.revision})}}async function z0(e){let t;try{t=await Wn.readdir(e.changesDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return;throw i}for(let i of t.sort((n,r)=>n.name.localeCompare(r.name)))if(!(!i.isDirectory()||i.isSymbolicLink()))try{let n=await Ve(e,i.name);if(n?.schema==="comet.native.workspace.v3"){let r=await sr({paths:e,identity:n});if(r.state!=="aligned")throw new Error(r.message??"workspace binding is not aligned")}else if(n){let r=await or({paths:e,identity:n});if(r.state!=="aligned")throw new Error(`legacy workspace ownership is ${r.state}`)}}catch(n){throw new Error(`Native workspace identity for ${i.name} must be aligned and repaired before moving the root`,{cause:n})}}async function Rs(e,t){let i=[];async function n(r){let a=await st({root:e,directory:r,label:"Native root tree"}),o=a.entries;o.sort((s,c)=>s.name.localeCompare(c.name));for(let s of o){await a.verify();let c=ne.join(r,s.name);if(t.excludedFiles?.has(ne.resolve(c))){await a.verify();continue}let l=await Wn.lstat(c);if(s.isSymbolicLink()||l.isSymbolicLink()){if(t.rejectSymlinks)throw new Error(`Native root contains a symlink: ${c}`);await a.verify();continue}if(s.isDirectory()&&l.isDirectory())i.push({ref:ne.relative(e,c).split(ne.sep).join("/"),type:"directory"}),await n(c);else if(s.isFile()&&l.isFile()){let u=await ue({root:e,file:c,maxBytes:Ap,label:`Native root file ${ne.relative(e,c)}`});i.push({ref:ne.relative(e,c).split(ne.sep).join("/"),type:"file",size:u.size,hash:u.hash})}else throw new Error(`Native root contains an unsupported file type: ${c}`);await a.verify()}}return await n(e),i.sort((r,a)=>r.ref.localeCompare(a.ref))}async function G0(e,t,i,n){await pi({root:n,directory:t,label:"Native root move staging directory"});async function r(a,o){let s=await st({root:e,directory:a,label:"Native root move source directory"}),c=s.entries;for(let l of c){await s.verify();let u=ne.join(a,l.name);if(ne.resolve(u)===ne.resolve(i)){await s.verify();continue}let d=await Wn.lstat(u);if(l.isSymbolicLink()||d.isSymbolicLink())throw new Error(`Native root contains a symlink: ${u}`);let f=ne.join(o,l.name);if(l.isDirectory()&&d.isDirectory())await pi({root:n,directory:f,label:"Native root move staging directory"}),await r(u,f);else if(l.isFile()&&d.isFile())await Ti({sourceRoot:e,source:u,targetRoot:n,target:f,maxBytes:Ap,label:`Native root move file ${ne.relative(e,u)}`,exclusive:!0,expectedTargetHash:null});else throw new Error(`Native root contains an unsupported file type: ${u}`);await s.verify()}}await r(e,t)}async function Ia(e,t,i,n){let r=await Rs(e,{rejectSymlinks:!0,excludedFiles:i?new Set([ne.resolve(i)]):void 0}),a=await Rs(t,{rejectSymlinks:!0,excludedFiles:n?new Set([ne.resolve(n)]):void 0});if(JSON.stringify(r)!==JSON.stringify(a))throw new Error(`Native root copies differ; preserve both trees for manual recovery: ${e} and ${t}`)}function xS(e,t){return ne.join(e.artifactRoot,`.comet-native-move-${t}`)}function U0(e,t){return ne.join(e.artifactRoot,`.comet-native-source-${t}.removing`)}function K0(e){return`${e}.removing`}function ES(e,t){return ne.join(ne.dirname(e),`.${ne.basename(e)}.${t}.rollback-removing`)}function AS(e,t,i){return ne.join(al(e,t).directory,`root-move-cleanup-${i}.json`)}function Y0(e){return JSON.stringify(e,null,2)+` +`}function X0(e){return L0("sha256").update(e).digest("hex")}function Q0(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Native root-move cleanup manifest entry ${t} must be an object`);let i=e,n=Object.keys(i).sort(),r=i.type==="file"?["hash","ref","size","type"]:["ref","type"];if(JSON.stringify(n)!==JSON.stringify(r))throw new Error(`Native root-move cleanup manifest entry ${t} has invalid fields`);if(typeof i.ref!="string"||i.ref.length===0||i.ref.includes("\\")||ne.posix.normalize(i.ref)!==i.ref||i.ref.startsWith("/")||i.ref.split("/").includes("..")||Buffer.byteLength(i.ref,"utf8")>4096)throw new Error(`Native root-move cleanup manifest entry ${t} has an invalid ref`);if(i.type==="directory")return{ref:i.ref,type:"directory"};if(i.type!=="file"||typeof i.size!="number"||!Number.isSafeInteger(i.size)||i.size<0||typeof i.hash!="string"||!/^[a-f0-9]{64}$/u.test(i.hash))throw new Error(`Native root-move cleanup manifest entry ${t} is invalid`);return{ref:i.ref,type:"file",size:i.size,hash:i.hash}}function Z0(e,t,i){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native root-move cleanup manifest must be an object");let n=e;if(JSON.stringify(Object.keys(n).sort())!==JSON.stringify(["entries","kind","schema","transactionId"])||n.schema!=="comet.native.root-move-cleanup.v1"||n.transactionId!==t||n.kind!==i||!Array.isArray(n.entries))throw new Error("Native root-move cleanup manifest binding is invalid");let r=n.entries.map(Q0);for(let a=0;a0&&r[a-1].ref.localeCompare(r[a].ref)>=0)throw new Error("Native root-move cleanup manifest refs must be unique and sorted");let o=ne.posix.dirname(r[a].ref);if(o!=="."&&!r.some(s=>s.ref===o&&s.type==="directory"))throw new Error(`Native root-move cleanup manifest parent is missing: ${o}`)}return{schema:"comet.native.root-move-cleanup.v1",transactionId:t,kind:i,entries:r}}async function eD(e){let t={schema:"comet.native.root-move-cleanup.v1",transactionId:e.id,kind:e.kind,entries:e.entries},i=Y0(t);if(Buffer.byteLength(i,"utf8")>PS)throw new Error("Native root-move cleanup manifest exceeds its byte budget");return await $e(AS(e.paths,e.id,e.kind),i,{containedRoot:e.paths.nativeRoot}),X0(i)}async function tD(e){let t=await ue({root:e.paths.nativeRoot,file:AS(e.paths,e.id,e.cleanup.kind),maxBytes:PS,label:`Native root-move cleanup manifest ${e.cleanup.kind}`});if(t.hash!==e.cleanup.manifestHash)throw new Error("Native root-move cleanup manifest hash changed");return Z0(JSON.parse(t.bytes.toString("utf8")),e.id,e.cleanup.kind)}async function xp(e){let t=await Rs(e.quarantine,{rejectSymlinks:!0}),i=new Map(e.manifest.entries.map(n=>[n.ref,n]));for(let n of t){let r=i.get(n.ref);if(!r||JSON.stringify(r)!==JSON.stringify(n))throw new Error(`Native root-move cleanup quarantine differs from its bound manifest: ${n.ref}`)}if(e.exact&&t.length!==e.manifest.entries.length)throw new Error("Native root-move cleanup quarantine is incomplete before deletion");return t}function RS(e){return e.ref.split("/").length}async function iD(e){let i=[...await xp({quarantine:e.quarantine,manifest:e.manifest,exact:!1})].sort((r,a)=>RS(a)-RS(r)||(r.type===a.type?a.ref.localeCompare(r.ref):r.type==="file"?-1:1)),n=0;for(let r of i){let a=ne.join(e.quarantine,...r.ref.split("/"));r.type==="file"?await tl({root:e.projectRoot,file:a,maxBytes:Ap,expectedHash:r.hash,expectedSize:r.size,label:`Native root-move cleanup file ${r.ref}`}):await If({root:e.projectRoot,directory:a,label:`Native root-move cleanup directory ${r.ref}`}),n+=1,await e.hooks?.afterRootMoveCleanupEntryRemoved?.(e.manifest.kind,r.ref,n)}await xp({quarantine:e.quarantine,manifest:e.manifest,exact:!1}),await If({root:e.projectRoot,directory:e.quarantine,label:`Native root-move cleanup quarantine ${e.manifest.kind}`})}function Ru(e,t,i=e.native.artifact_root){return{...e,native:{...e.native,artifact_root:i,pending_root_move:t}}}function TS(e){return{schema:"comet.native.transaction.v1",id:e.id,kind:"root-move",status:"prepared",projectRoot:e.paths.projectRoot,nativeRoot:e.paths.nativeRoot,createdAt:e.now.toISOString(),operations:[]}}async function nD(e,t,i,n){for(let a of[e,t])try{let o=await ct(a,n);if(o.kind!=="root-move")throw new Error(`Transaction ${n} is not a root move`);return{journal:o,paths:a}}catch(o){if(o.code!=="ENOENT")throw o}let r=ne.join(i,"runtime","transactions",n,"transaction.json");try{let a=await ue({root:i,file:r,maxBytes:q0,label:`Staged Native root-move journal ${n}`}),o=JSON.parse(a.bytes.toString("utf8"));if(o.schema!=="comet.native.transaction.v1"||o.kind!=="root-move")throw new Error(`Invalid staged root-move journal: ${n}`);return{journal:o,paths:t}}catch(a){throw a.code!=="ENOENT"?a:new Error(`Native root-move journal is missing: ${n}`,{cause:a})}}async function CS(e){let t=Ru(e.config,{...e.pending,stage:e.stage},e.activeArtifactRoot);return await li(e.projectRoot,t),t}async function Es(e){let t=e.config.native.pending_root_move;if(!t||t.id!==e.id)throw new Error(`Native root-move cleanup ${e.id} lost its pending configuration`);let i=Ru(e.config,{id:t.id,fromArtifactRoot:t.fromArtifactRoot,toArtifactRoot:t.toArtifactRoot,stage:t.stage,...e.cleanup?{cleanup:e.cleanup}:{}},e.config.native.artifact_root);return await li(e.projectRoot,i),i}async function Cu(e){let t=e.config,i=t.native.pending_root_move;if(!i||i.id!==e.id)throw new Error(`Native root-move cleanup ${e.id} lost its pending configuration`);let n=i.cleanup;if(n&&n.kind!==e.kind)throw new Error(`Native root move has unfinished ${n.kind} cleanup; cannot start ${e.kind}`);let r=await Fe(e.target),a=await Fe(e.quarantine);if(r&&a)throw new Error(`Native root-move cleanup target and quarantine both exist: ${e.kind}`);if(!n){if(!r&&!a)return t;if(!r&&a)throw new Error(`Native root-move cleanup quarantine is not transaction-bound: ${e.kind}`);let s=await eD({paths:e.stablePaths,id:e.id,kind:e.kind,entries:await Rs(e.target,{rejectSymlinks:!0})});n={kind:e.kind,state:"prepared",manifestHash:s},t=await Es({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:n})}let o=await tD({paths:e.stablePaths,id:e.id,cleanup:n});if(r=await Fe(e.target),a=await Fe(e.quarantine),r&&a)throw new Error(`Native root-move cleanup target and quarantine both exist: ${e.kind}`);if(r){if(n.state!=="prepared")throw new Error(`Native root-move cleanup target reappeared after quarantine: ${e.kind}`);await rw({root:e.projectRoot,directory:e.target,quarantine:e.quarantine,label:e.label,beforeQuarantine:e.beforeQuarantine,afterQuarantine:e.afterQuarantine}),a=!0}if(!a){if(n.state!=="deleting")throw new Error(`Native root-move cleanup quarantine disappeared: ${e.kind}`);return Es({projectRoot:e.projectRoot,config:t,id:e.id})}return await xp({quarantine:e.quarantine,manifest:o,exact:n.state!=="deleting"}),n.state==="prepared"&&(n={...n,state:"quarantined"},t=await Es({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:n})),n.state==="quarantined"&&(n={...n,state:"deleting"},t=await Es({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:n})),await iD({projectRoot:e.projectRoot,quarantine:e.quarantine,manifest:o,hooks:e.hooks}),Es({projectRoot:e.projectRoot,config:t,id:e.id})}async function _S(e){let t=e.config,i=t.native.pending_root_move.stage;if(i==="copying"){if(!await Fe(e.sourcePaths.nativeRoot))throw new Error(`Native source root is missing: ${e.sourcePaths.nativeRoot}`);let s=K0(e.staging);t=await Cu({projectRoot:e.projectRoot,config:t,id:e.pending.id,kind:"restart-staging",stablePaths:e.sourcePaths,target:e.staging,quarantine:s,label:"Native root move stale staging removal",hooks:e.hooks}),await Rs(e.sourcePaths.nativeRoot,{rejectSymlinks:!0,excludedFiles:new Set([ne.resolve(e.lockFile)])}),await G0(e.sourcePaths.nativeRoot,e.staging,e.lockFile,e.destinationPaths.projectRoot),await Ia(e.sourcePaths.nativeRoot,e.staging,e.lockFile),t=await CS({projectRoot:e.projectRoot,config:t,pending:e.pending,stage:"ready"}),i="ready",await e.hooks?.afterRootMoveStage?.("ready",e.journal)}if(i==="ready"){if(await Fe(e.destinationPaths.nativeRoot)){if(await Fe(e.staging))throw new Error(`Native destination is occupied: ${e.destinationPaths.nativeRoot}`);await Ia(e.sourcePaths.nativeRoot,e.destinationPaths.nativeRoot,e.lockFile)}else{if(!await Fe(e.staging))throw new Error("Native move staging tree is missing");await Ia(e.sourcePaths.nativeRoot,e.staging,e.lockFile),await Wn.rename(e.staging,e.destinationPaths.nativeRoot)}t=await CS({projectRoot:e.projectRoot,config:t,pending:e.pending,stage:"switched",activeArtifactRoot:e.pending.toArtifactRoot}),i="switched",await e.hooks?.afterRootMoveStage?.("switched",e.journal)}if(i!=="switched")throw new Error(`Unsupported Native root-move stage: ${i}`);if(!await Fe(e.destinationPaths.nativeRoot))throw new Error(`Native destination root is missing: ${e.destinationPaths.nativeRoot}`);let n=U0(e.sourcePaths,e.pending.id);!t.native.pending_root_move?.cleanup&&await Fe(e.sourcePaths.nativeRoot)&&await Ia(e.sourcePaths.nativeRoot,e.destinationPaths.nativeRoot,e.lockFile),t=await Cu({projectRoot:e.projectRoot,config:t,id:e.pending.id,kind:"forward-source",stablePaths:e.destinationPaths,target:e.sourcePaths.nativeRoot,quarantine:n,label:"Native root move source removal",beforeQuarantine:()=>e.hooks?.beforeRootMoveSourceRemove?.(e.sourcePaths.nativeRoot),afterQuarantine:s=>e.hooks?.afterRootMoveSourceQuarantined?.(s),hooks:e.hooks}),await J0(e.destinationPaths);let r=await ct(e.destinationPaths,e.pending.id);await Ur(e.destinationPaths,r,"commit");let a={artifact_root:t.native.artifact_root,language:t.native.language,clarification_mode:t.native.clarification_mode,archive_confirmation:t.native.archive_confirmation,max_verify_failures:t.native.max_verify_failures,snapshot:t.native.snapshot},o={...t,native:{...a,artifact_root:e.pending.toArtifactRoot}};return await li(e.projectRoot,o),o}async function IS(e){let t=await re(e.projectRoot)??tr("docs");if(t.native.pending_root_move)throw new Error(`Native root move ${t.native.pending_root_move.id} is already incomplete`);let i=pn(e.toArtifactRoot);if(i===t.native.artifact_root)throw new Error(`Native artifact root is already ${i}`);let n=await Ne(e.projectRoot,t.native.artifact_root),r=await Ne(e.projectRoot,i);if($(n.nativeRoot,r.nativeRoot)||$(r.nativeRoot,n.nativeRoot))throw new Error("Native source and destination roots must not overlap");if(!await Fe(n.nativeRoot))throw new Error(`Native source root does not exist: ${n.nativeRoot}`);if(await V0(n),await Fe(r.nativeRoot))throw new Error(`Native destination is occupied: ${r.nativeRoot}`);let a=await di(n,"root-move",`move root to ${i}`),o=B0(),s={id:o,fromArtifactRoot:t.native.artifact_root,toArtifactRoot:i,stage:"copying"},c=TS({id:o,paths:n,now:e.now??new Date}),l=xS(r,o);try{if(await W0(n,a.file),await z0(n),await Fe(l))throw new Error(`Native move staging path is occupied: ${l}`);return await li(e.projectRoot,Ru(t,s)),await Ff(n,c),await e.hooks?.afterRootMoveStage?.("copying",c),await _S({projectRoot:e.projectRoot,config:Ru(t,s),pending:s,sourcePaths:n,destinationPaths:r,staging:l,journal:c,lockFile:a.file,hooks:e.hooks}),{fromNativeRoot:n.nativeRoot,toNativeRoot:r.nativeRoot,transactionId:o}}finally{await fi(a)}}async function jS(e){let t=await re(e.projectRoot),i=t?.native.pending_root_move;if(!t||!i)throw new Error("No pending Native root move was found");let n=await Ne(e.projectRoot,i.fromArtifactRoot),r=await Ne(e.projectRoot,i.toArtifactRoot),a=xS(r,i.id),o=await Fe(n.nativeRoot)?n:r,s=await di(o,"root-move",`recover root ${i.id}`);try{let c;try{c=await nD(n,r,a,i.id)}catch(m){if(i.stage!=="copying"||!await Fe(n.nativeRoot))throw m;let p=TS({id:i.id,paths:n,now:new Date});await Ff(n,p),c={journal:p,paths:n}}if(e.strategy==="continue"){let m=await _S({projectRoot:e.projectRoot,config:t,pending:i,sourcePaths:n,destinationPaths:r,staging:a,journal:c.journal,lockFile:s.file,hooks:e.hooks});return{activeNativeRoot:r.nativeRoot,config:m}}if(!await Fe(n.nativeRoot))throw new Error("Cannot roll back after the old Native root was removed; continue recovery");let l=ES(r.nativeRoot,i.id);!t.native.pending_root_move?.cleanup&&await Fe(r.nativeRoot)&&await Ia(n.nativeRoot,r.nativeRoot,s.file),(!t.native.pending_root_move?.cleanup||t.native.pending_root_move.cleanup.kind==="rollback-destination")&&(t=await Cu({projectRoot:e.projectRoot,config:t,id:i.id,kind:"rollback-destination",stablePaths:n,target:r.nativeRoot,quarantine:l,label:"Native root move rollback destination removal",hooks:e.hooks}));let u=ES(a,i.id);!t.native.pending_root_move?.cleanup&&await Fe(a)&&await Ia(n.nativeRoot,a,s.file),(!t.native.pending_root_move?.cleanup||t.native.pending_root_move.cleanup.kind==="rollback-staging")&&(t=await Cu({projectRoot:e.projectRoot,config:t,id:i.id,kind:"rollback-staging",stablePaths:n,target:a,quarantine:u,label:"Native root move rollback staging removal",hooks:e.hooks}));let d=await ct(n,i.id);await ol(n,d);let f={artifact_root:t.native.artifact_root,language:t.native.language,clarification_mode:t.native.clarification_mode,archive_confirmation:t.native.archive_confirmation,max_verify_failures:t.native.max_verify_failures,snapshot:t.native.snapshot},h={...t,native:{...f,artifact_root:i.fromArtifactRoot}};return await li(e.projectRoot,h),{activeNativeRoot:n.nativeRoot,config:h}}finally{await fi(s)}}var Cs=4096,aD=4096,oD=1024;async function Pr(e,t,i){try{let n=await st({root:e.nativeRoot,directory:t,label:"Native doctor directory",maxEntries:i});return await n.verify(),n.entries}catch(n){if(n.code==="ENOENT")return[];throw n}}async function Pu(e,t){let i=new Map(e.map(n=>[Le.resolve(n.file),{...n,file:Le.resolve(n.file)}]));for(let{paths:n,file:r}of i.values()){let a;try{a=await Po(r)}catch(o){return t.push({severity:"error",code:"lock-invalid",message:`Native recovery lock is invalid: ${o.message}`,path:r}),!1}if(a.status!=="missing"){if(a.status==="stale"){let o=await _f(n,r,a);if(o.status==="removed"){t.push({severity:"info",code:"stale-recovery-lock-removed",message:"Removed stale lock before explicit transaction recovery",path:r});continue}if(o.status==="missing")continue;a=o.diagnosis}return a.status==="stale"?(t.push({severity:"error",code:"lock-takeover-raced",message:"Native recovery lock changed while doctor was preparing stale takeover",path:r}),!1):(t.push({severity:"error",code:a.status==="active"?"lock-active":"lock-owner-unknown",message:a.status==="active"?"Native recovery lock is still owned by a live process":"Native recovery lock owner cannot be proven stale",path:r}),!1)}}return!0}async function sD(e,t){let i=kk(e),n;try{await x(e.projectRoot,i);let r=await ys(e);if(!r)return[];n=r}catch(r){return r.code==="ENOENT"?[]:[{severity:"error",code:"selection-invalid",message:`Native selection is invalid: ${r.message}`,path:i}]}if(n.schema!=="comet.selection.v2"||n.workflow!=="native"||typeof n.change!="string")return[{severity:"error",code:"selection-invalid",message:"Native selection has an invalid schema or change name",path:i}];try{return await G(e,n.change),[]}catch(r){if(r.code!=="ENOENT")return[{severity:"error",code:"selection-target-invalid",message:`Selected Native change is invalid: ${r.message}`,path:i}]}return t?(await rD.rm(i,{force:!0}),[{severity:"info",code:"selection-cleared",message:`Cleared stale Native selection ${n.change}`,path:i}]):[{severity:"warning",code:"selection-stale",message:`Selected Native change does not exist: ${n.change}`,path:i}]}async function cD(e){let t=[];for(let i of[e.specsDir,e.changesDir,e.archiveDir,e.runtimeDir,e.locksDir,e.transactionsDir])try{await x(e.nativeRoot,i)}catch(n){t.push({severity:"error",code:"native-path-unsafe",message:`Managed Native path is unsafe: ${n.message}`,path:i})}return t}async function lD(e,t){let i=[],n=[];for(let r of await Pr(e,e.transactionsDir,aD)){if(!r.isDirectory()||r.isSymbolicLink())continue;let a;try{a=await ct(e,r.name)}catch(o){i.push({severity:"error",code:"transaction-invalid",message:`Native transaction ${r.name} is invalid: ${o.message}`,path:Le.join(e.transactionsDir,r.name)});continue}if(!(a.status==="committed"||a.status==="rolled-back")&&!(t.name&&a.change&&a.change!==t.name)){if(a.kind!=="archive"){n.push(a),i.push({severity:"error",code:"root-move-transaction-orphaned",message:`Root-move transaction ${a.id} is incomplete but project config has no matching pending move`});continue}if(t.repair&&t.recoveryStrategy)try{if(!await Qc([e],`doctor archive recovery ${a.id}`,async()=>await Pu([{paths:e,file:Le.join(e.locksDir,"root-move.lock")},{paths:e,file:Le.join(e.locksDir,"archive.lock")}],i)?(await xk({paths:e,transactionId:a.id,strategy:t.recoveryStrategy}),!0):!1)){n.push(a);continue}i.push({severity:"info",code:"archive-transaction-recovered",message:`${t.recoveryStrategy==="continue"?"Continued":"Rolled back"} archive transaction ${a.id}`})}catch(o){n.push(a),i.push({severity:"error",code:"archive-recovery-failed",message:`Archive recovery failed: ${o.message}`})}else n.push(a),i.push({severity:"error",code:"archive-transaction-incomplete",message:t.repair?`Archive transaction ${a.id} needs an explicit recovery strategy`:`Archive transaction ${a.id} is incomplete`,repair:t.recoveryStrategy??"continue"})}}return{findings:i,unfinished:n}}async function uD(e,t,i){let n=[];for(let r of await Pr(e,e.locksDir,oD)){if(!r.isFile()||r.isSymbolicLink()||!r.name.endsWith(".lock"))continue;let a=Le.join(e.locksDir,r.name);try{let o=await Po(a);if(o.status==="active")n.push({severity:"warning",code:"lock-active",message:`Native lock is active for ${o.owner?.operation??"an operation"}`,path:a});else if(o.status==="unknown")n.push({severity:"warning",code:"lock-owner-unknown",message:"Native lock owner cannot be proven stale",path:a});else if(o.status==="stale")if(t&&i.length===0){let s=await _f(e,a,o);s.status==="removed"?n.push({severity:"info",code:"stale-lock-removed",message:"Removed a Native lock whose local owner process is absent",path:a}):s.status==="changed"&&n.push({severity:s.diagnosis.status==="active"?"warning":"error",code:"lock-takeover-raced",message:"Native lock changed while doctor was preparing stale takeover",path:a})}else n.push({severity:i.length>0?"error":"warning",code:"lock-stale",message:i.length>0?"Native lock is stale but an unfinished transaction still requires recovery":"Native lock owner process is absent",path:a})}catch(o){n.push({severity:"error",code:"lock-invalid",message:`Native lock metadata is invalid: ${o.message}`,path:a})}}return n}async function dD(e,t,i=5){let n=[],r=t?await Np(e,{maxVerifyFailures:i}).then(a=>a.filter(o=>o.name===t)):await Np(e,{maxVerifyFailures:i});if(t&&r.length===0)return[{severity:"error",code:"change-missing",message:`Native change does not exist: ${t}`}];for(let a of r){if(a.migrationRequired)continue;if(a.phase==="invalid"){n.push({severity:"error",code:"change-invalid",message:a.error??`Native change ${a.name} is invalid`,path:Le.join(e.changesDir,a.name,je)});continue}let o=await Ze(e,a.name,{details:!0,maxVerifyFailures:i});for(let s of o.findings??[])s.code==="trajectory-tail-incomplete"||s.code==="checkpoint-progress-incomplete"||n.push({severity:s.severity,code:s.code,message:`${a.name}: ${s.message}`,...s.path?{path:Le.join(e.projectRoot,s.path)}:{}})}return n}async function fD(e,t){let i=[],n=t.name?[t.name]:(await Pr(e,e.changesDir,Cs)).filter(r=>r.isDirectory()&&!r.isSymbolicLink()).map(r=>r.name).sort();for(let r of n)try{let a=await ta(e,r);if(a.status!=="repairable")continue;if(!t.repair){i.push({severity:"error",code:"trajectory-tail-incomplete",message:`Native trajectory for ${r} has an incomplete final line ${a.line}; ${a.discardedBytes} byte(s) are outside the last complete event`,path:a.file,repair:"truncate-tail"});continue}let o=await ey(e,r);o&&i.push({severity:"info",code:"trajectory-tail-repaired",message:`Removed the incomplete Native trajectory tail for ${r} and preserved all complete events`,path:o.file})}catch(a){i.push({severity:"error",code:"trajectory-tail-repair-failed",message:`Native trajectory tail repair failed for ${r}: ${a.message}`,path:Le.join(e.changesDir,r,"runtime","trajectory.jsonl")})}return i}async function hD(e,t){let i=[],n=t.name?[t.name]:(await Pr(e,e.changesDir,Cs)).filter(r=>r.isDirectory()&&!r.isSymbolicLink()).map(r=>r.name).sort();for(let r of n)try{if(!await nh(e,r))continue;if(!t.repair){i.push({severity:"warning",code:"workspace-identity-migration-required",message:`Native workspace identity for ${r} uses legacy external-probe or hash-only metadata`,path:ar(e,r),repair:"migrate"});continue}let a=await G(e,r);await fy({paths:e,name:r,revision:a.revision})&&i.push({severity:"info",code:"workspace-identity-migrated",message:`Replaced legacy workspace metadata for ${r} with process-free root identities`,path:ar(e,r)})}catch(a){i.push({severity:"error",code:"workspace-identity-migration-failed",message:`Native workspace identity migration failed for ${r}: ${a.message}`,path:ar(e,r)})}return i}async function pD(e,t){let i=[],n=t.name?[t.name]:(await Pr(e,e.changesDir,Cs)).filter(r=>r.isDirectory()&&!r.isSymbolicLink()).map(r=>r.name).sort();for(let r of n){let a=ks(e,r);try{let o=await Ss(e,r),s=await ft(e,r);if(!o&&s.status==="current")continue;if(s.status==="runtime-incompatible"){i.push({severity:"error",code:"change-runtime-incompatible",message:s.message??`Native change ${r} requires a newer runtime`,path:Le.join(e.changesDir,r,je)});continue}if(!t.repair){i.push({severity:"error",code:o?"schema-migration-incomplete":"schema-migration-required",message:o?`Native schema migration ${o.id} is incomplete for ${r}`:`Native change ${r} requires migration to the current schema`,path:o?a:Le.join(e.changesDir,r,je),repair:"migrate"});continue}await mS({paths:e,name:r}),i.push({severity:"info",code:o?"schema-migration-recovered":"schema-migrated",message:`Migrated Native change ${r} to the current schema`,path:Le.join(e.changesDir,r,je)})}catch(o){if(o.code==="ENOENT")continue;i.push({severity:"error",code:"schema-migration-failed",message:`Native schema migration failed for ${r}: ${o.message}`,path:a})}}return i}async function mD(e,t){let i=[],n=t.name?[t.name]:(await Pr(e,e.changesDir,Cs)).filter(r=>r.isDirectory()&&!r.isSymbolicLink()).map(r=>r.name).sort();for(let r of n){let a;try{a=await bi(e,r)}catch(o){if(o instanceof os)continue;i.push({severity:"error",code:"transition-invalid",message:`Native transition journal is invalid: ${o.message}`,path:We(e,r)});continue}if(a){if(t.repair&&t.recoveryStrategy==="continue"){try{if(!await Qc([e],`doctor transition recovery ${r}`,async()=>await Pu([{paths:e,file:Le.join(e.locksDir,"root-move.lock")},{paths:e,file:Le.join(e.locksDir,`transition-${r}.lock`)}],i)?(await ub(e,r),!0):!1))continue;i.push({severity:"info",code:"transition-recovered",message:`Continued Native phase transition ${a.id} for ${r}`,path:We(e,r)})}catch(o){i.push({severity:"error",code:"transition-recovery-failed",message:`Native transition recovery failed: ${o.message}`,path:We(e,r)})}continue}i.push({severity:"error",code:"transition-incomplete",message:t.repair&&t.recoveryStrategy==="rollback"?`Native phase transition ${a.id} only supports deterministic continue recovery`:`Native phase transition ${a.id} is incomplete for ${r}`,path:We(e,r),repair:"continue"})}}return i}async function vD(e,t){let i=[],n=t.name?[t.name]:(await Pr(e,e.changesDir,Cs)).filter(r=>r.isDirectory()&&!r.isSymbolicLink()).map(r=>r.name).sort();for(let r of n){let a=zi(e,r),o;try{o=await Gi(e,r)}catch(s){if(s.code==="ENOENT")continue;i.push({severity:"error",code:"checkpoint-progress-invalid",message:`Native progress checkpoint journal is invalid: ${s.message}`,path:a});continue}if(o){if(!t.repair){i.push({severity:"error",code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${o.id} is incomplete for ${r}`,path:a});continue}try{if(!await Qc([e],`doctor checkpoint recovery ${r}`,async()=>await Pu([{paths:e,file:Le.join(e.locksDir,"root-move.lock")},{paths:e,file:Le.join(e.locksDir,`transition-${r}.lock`)}],i)?(await Hb(e,r),!0):!1))continue;i.push({severity:"info",code:"checkpoint-progress-recovered",message:`Continued Native progress checkpoint ${o.id} for ${r}`,path:a})}catch(s){i.push({severity:"error",code:"checkpoint-progress-recovery-failed",message:`Native progress checkpoint recovery failed: ${s.message}`,path:a})}}}return i}async function OS(e){let t=e.repair??!1,i=[],n=e.paths,r;try{r=await re(n.projectRoot)}catch(c){return{healthy:!1,findings:[{severity:"error",code:"config-invalid",message:`Comet project config is invalid: ${c.message}`,path:n.configFile}]}}let a=!!r?.native.pending_root_move;if(r?.native.pending_root_move){let c=r.native.pending_root_move,[l,u]=await Promise.all([Ne(n.projectRoot,c.fromArtifactRoot),Ne(n.projectRoot,c.toArtifactRoot)]);if(t&&e.recoveryStrategy)try{if(!await Pu([{paths:l,file:Le.join(l.locksDir,"root-move.lock")},{paths:u,file:Le.join(u.locksDir,"root-move.lock")}],i))return{healthy:!1,findings:i};let f=await jS({projectRoot:n.projectRoot,strategy:e.recoveryStrategy});n=await Ne(n.projectRoot,f.config.native.artifact_root),a=!1,i.push({severity:"info",code:"root-move-recovered",message:`${e.recoveryStrategy==="continue"?"Continued":"Rolled back"} Native root move ${c.id}`})}catch(d){return i.push({severity:"error",code:"root-move-recovery-failed",message:`Native root recovery failed: ${d.message}`}),{healthy:!1,findings:i}}else i.push({severity:"error",code:"root-move-incomplete",message:`Native root move ${c.id} is ${c.stage}; inspect ${l.nativeRoot} and ${u.nativeRoot}`,repair:e.recoveryStrategy??"continue"})}let o=await cD(n);if(i.push(...o),o.length>0)return{healthy:!1,findings:i};let s=await lD(n,{name:e.name,repair:t,recoveryStrategy:e.recoveryStrategy});return i.push(...s.findings),i.push(...await pD(n,{name:e.name,repair:t})),i.push(...await hD(n,{name:e.name,repair:t})),i.push(...await fD(n,{name:e.name,repair:t})),i.push(...await mD(n,{name:e.name,repair:t,recoveryStrategy:e.recoveryStrategy})),i.push(...await vD(n,{name:e.name,repair:t})),i.push(...await SS({paths:n,name:e.name,repair:t,now:e.now,deferAll:a||s.unfinished.length>0})),i.push(...await uD(n,t,s.unfinished)),i.push(...await sD(n,t)),i.push(...await dD(n,e.name,r?.native.max_verify_failures??5)),{healthy:i.every(c=>c.severity==="info"),findings:i}}async function $S(e,t){let i=gt(e,"--repair"),n=J(e,"--strategy");if(n!==void 0&&n!=="continue"&&n!=="rollback")throw new I("--strategy must be continue or rollback");let r=e[0]?.startsWith("--")?void 0:e.shift();Y(e);let a=await Ik(t),o=await OS({paths:a,...r?{name:r}:{},repair:i,...n?{recoveryStrategy:n}:{}});return o.healthy?Z("doctor",o):{command:"doctor",exitCode:65,data:o,error:{code:"invalid-data",message:"Native project needs attention"}}}import gD from"path";async function HS(e,t){let i=ae(e,"evidence subcommand");if(i==="format"){let n=J(e,"--entries");Y(e);let r;if(n)r=await jk(gD.resolve(n),wi);else{if(process.stdin.isTTY)throw new I("evidence format requires acceptance evidence entries JSON on stdin, or --entries ");r=await Ok(wi)}let a;try{a=JSON.parse(r)}catch(s){throw new Error(`Acceptance evidence entries must be valid JSON: ${s.message}`,{cause:s})}if(!Array.isArray(a))throw new Error("Acceptance evidence entries must be a JSON array");let o=tu(a);return Z("evidence format",{block:o},`${o} +`)}throw new I(`Unknown evidence command: ${i}`)}import{promises as AD}from"fs";import ja from"path";var wD=null;function yD(e,t){let i=e;for(let n of t)i+="\0"+(typeof n=="string"?n:JSON.stringify(n));return i}function DS(e,t){return(...i)=>{let n=wD;if(n===null)return t(...i);let r=yD(`async:${e}`,i),a=n.entries.get(r);if(a)return a.value;let o=t(...i).catch(s=>{throw n.entries.delete(r),s});return n.entries.set(r,{value:o}),o}}import{readFileSync as ND}from"fs";import MS from"path";var bD=new Set(["applypatch","create","createfile","deletefile","edit","editfile","patch","strreplaceeditor","write","writefile","writefiletool"]),kD=new Set(["glob","grep","listfiles","read","readfile","search","view"]),LS=["file_path","filePath","path","target_file","targetFile"],BS=["file_paths","filePaths","paths","files","targets"],qS=["operations","edits"],SD=["patch","diff","patchText","patch_text","changes"];function _p(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function FS(e){return e.toLowerCase().replace(/[^a-z0-9]+/gu,"")}function ED(e){for(let t of["tool_name","toolName","tool","name"]){let i=e[t];if(typeof i=="string"&&i.trim())return i.trim()}return null}function RD(e){for(let t of["cwd","working_directory","workspaceRoot"]){let i=e[t];if(!(typeof i!="string"||!i.trim()||!MS.isAbsolute(i.trim())))return MS.resolve(i.trim())}}function CD(e){if(typeof e!="string")return e;let t=e.trim();if(!t.startsWith("{")&&!t.startsWith("["))return e;try{return JSON.parse(t)}catch{return e}}function PD(e){for(let t of["tool_input","toolInput","toolArgs","tool_args","arguments"])if(e[t]!==void 0)return CD(e[t]);return e}function Tp(e){let t=[],i=[/^\*\*\* (?:Add|Update|Delete) File:\s+(.+?)\s*$/gmu,/^\+\+\+\s+(?:b\/)?(.+?)\s*$/gmu];for(let n of i)for(let r of e.matchAll(n)){let a=r[1]?.trim();a&&a!=="/dev/null"&&t.push(a)}return t}function xr(e,t){if(typeof t=="string"){let i=t.trim();i&&e.push(i);return}if(Array.isArray(t)){for(let i of t)xr(e,i);return}if(_p(t)){for(let i of LS)xr(e,t[i]);for(let i of BS)xr(e,t[i]);for(let i of qS)xr(e,t[i])}}function xD(e,t){let i=[],n=[t,e].filter(_p);for(let r of n){for(let a of LS)xr(i,r[a]);for(let a of BS)xr(i,r[a]);for(let a of qS)xr(i,r[a]);for(let a of SD){let o=r[a];typeof o=="string"&&i.push(...Tp(o))}}return typeof t=="string"&&i.push(...Tp(t)),[...new Set(i)]}function Ps(e,t){if(t?.trim())return{intent:"write",targets:[t.trim()],toolName:null};if(!e.trim())return{intent:"unknown",targets:[],toolName:null};let i;try{i=JSON.parse(e)}catch{let o=Tp(e);return o.length>0?{intent:"write",targets:[...new Set(o)],toolName:"apply_patch"}:{intent:"unknown",targets:[],toolName:null}}if(!_p(i))return{intent:"unknown",targets:[],toolName:null};let n=ED(i),r=xD(i,PD(i)),a=RD(i);return n&&bD.has(FS(n))?{intent:r.length>0?"write":"unknown",targets:r,toolName:n,...a?{cwd:a}:{}}:n&&kD.has(FS(n))?{intent:"non-write",targets:[],toolName:n,...a?{cwd:a}:{}}:n?{intent:"unknown",targets:r,toolName:n,...a?{cwd:a}:{}}:{intent:r.length>0?"write":"unknown",targets:r,toolName:null,...a?{cwd:a}:{}}}function VS(){let e=process.env.FILE_PATH;if(e?.trim()||process.stdin.isTTY)return Ps("",e);try{return Ps(ND(0,"utf8"),e)}catch{return Ps("",e)}}function xu(e,t){let i=ja.relative(e,t);return i===""||!i.startsWith("..")&&!ja.isAbsolute(i)}function TD(e,t,i){return i.targets.length>0&&i.targets.every(n=>{let r=ja.resolve(e,n);return xu(e,r)?ja.relative(e,r).replaceAll("\\","/")===".comet/config.yaml"||xu(t,r):!0})}async function _D(e){let t=await re(e);if(!t||!(t.workflows??[t.default_workflow]).includes("native"))return null;let i=await Ne(e,t.native.artifact_root),n;try{n=await AD.readdir(i.changesDir,{withFileTypes:!0})}catch(a){if(a.code==="ENOENT")return{paths:i,changes:[]};throw a}let r=[];for(let a of n.sort((o,s)=>o.name.localeCompare(s.name))){if(!a.isDirectory()||a.isSymbolicLink())continue;let o=await G(i,a.name);o.archived||r.push(o)}return{paths:i,changes:r}}var ID=DS("nativeActiveContext",e=>_D(e));async function WS(){let{intent:e,targets:t}=await VS();return{intent:e,targets:t}}async function JS(e,t,i){let n=await ID(e);if(!n)return{allowed:!0,reason:"Native workflow is not enabled"};if(t.intent==="non-write")return{allowed:!0,reason:"Hook event is not a write"};if(n.changes.length===0)return{allowed:!0,reason:TD(e,n.paths.nativeRoot,t)?"Native control artifact write":"No Native changes exist"};let r;if(i){if(r=n.changes.find(s=>s.name===i),!r)return{allowed:!1,reason:`Selected Native change ${i} is missing or archived; resume /comet-native before retrying`,workflow:"native",change:i}}else if(n.changes.length===1)r=n.changes[0];else{let s=await Sk(n.paths);if(r=n.changes.find(c=>c.name===s),!r)return{allowed:!1,reason:"Multiple Native changes are active; select the change to resume before writing code",workflow:"native"}}if(r.phase==="build")return{allowed:!0,reason:"Native change is in Build",workflow:"native",phase:r.phase,change:r.name};if(t.intent==="unknown"||t.targets.length===0)return{allowed:!0,reason:"Hook write target was not attributed to the guarded project",workflow:"native",phase:r.phase,change:r.name};let a=!1,o=!1;for(let s of t.targets){let c=ja.resolve(e,s);if(!xu(e,c)){o=!0;continue}if(ja.relative(e,c).replaceAll("\\","/")===".comet/config.yaml"||xu(n.paths.nativeRoot,c)){a=!0;continue}return{allowed:!1,reason:`Native change ${r.name} is in ${r.phase}; implementation writes are only allowed in build. Resume /comet-native to continue safely`,workflow:"native",phase:r.phase,change:r.name}}return{allowed:!0,reason:a?"Native control artifact write":o?"Write target is outside the guarded project":"No guarded write target was provided",workflow:"native",phase:r.phase,change:r.name}}async function zS(e,t){let i=J(e,"--hook-output");if(i!==void 0&&i!=="copilot")throw new I("--hook-output must be copilot");Y(e);let n=await JS(t,await WS());return i==="copilot"?{command:"hook-guard",exitCode:0,data:n,text:n.allowed?`{} `:`${JSON.stringify({permissionDecision:"deny",permissionDecisionReason:n.reason})} `}:n.allowed?{command:"hook-guard",exitCode:0,data:n}:{command:"hook-guard",exitCode:2,data:n,error:{code:"blocked",message:n.reason}}}async function GS(e,t){let i=J(e,"--root"),n=await re(t),r=pu(e,n?.native.language??"en");if(Y(e),n?.native.pending_root_move)throw new Error(`Native root move ${n.native.pending_root_move.id} is incomplete`);let a=pn(i??n?.native.artifact_root??"docs");if(n&&i&&n.native.artifact_root!==a)throw new Error(`Configured Native artifact root is ${n.native.artifact_root}; refusing conflicting root ${a}`);let o=n?{...n,native:{...n.native,language:r}}:tr(a,r),s=await Ne(t,o.native.artifact_root);return await Jc(s),await li(t,o),Z("init",{projectRoot:t,artifactRoot:o.native.artifact_root,nativeRoot:s.nativeRoot,language:r},`Initialized Comet Native at ${s.nativeRoot} -`)}async function US(e,t){let i=ae(e,"change name"),n=await re(t),r=pu(e,n?.native.language??"en"),a=J(e,"--isolation")??"current";if(a!=="current"&&a!=="branch"&&a!=="worktree")throw new I("--isolation must be current, branch, or worktree");let o=J(e,"--change-branch"),s=J(e,"--target-branch");Y(e);let c=n===null?tr("docs",r):void 0;if(n||(n=c),n.native.pending_root_move)throw new Error(`Native root move ${n.native.pending_root_move.id} is incomplete`);let l=await Ne(t,n.native.artifact_root);await Jc(l);let u=ih({projectRoot:t,isolation:a,...o?{changeBranch:o}:{},...s?{targetBranch:s}:{}}),d=await wy({paths:l,name:i,language:r,workspaceBinding:u,...c?{initialProjectConfig:c}:{}});n=await re(t)??n,await hu(l,d.name);let f=await Ve(l,d.name),h=await Ze(l,d.name,{clarificationMode:n.native.clarification_mode,maxVerifyFailures:n.native.max_verify_failures});return Z("new",{...d,workspace:f,continuation:h.continuation},`Created Native change ${d.name} -`)}import{randomUUID as zD}from"crypto";import{promises as jD}from"fs";import KS from"path";function OD(e){return{valid:e.length===0,findings:e}}async function $D(e,t){let i=[];if((t.noCodeReason??"").trim().length>0)return i;if(!t.artifacts||t.artifacts.length===0)return[{code:"build-evidence-missing",message:"Build requires an artifact reference or an explicit no-code reason"}];for(let n of t.artifacts){if(KS.isAbsolute(n)||n.split(/[\\/]/u).includes("..")||/^(?:[A-Za-z]:|~|[\\/])/u.test(n)){i.push({code:"build-artifact-unsafe",message:`Unsafe build artifact: ${n}`});continue}let r=KS.resolve(e.projectRoot,...n.split(/[\\/]/u));if(!$(e.projectRoot,r)){i.push({code:"build-artifact-unsafe",message:`Unsafe build artifact: ${n}`});continue}try{await jD.access(r)}catch{i.push({code:"build-artifact-missing",message:`Build artifact does not exist: ${n}`,path:n})}}return i}async function YS(e){let t=[],i=C(e.paths,e.state.name);if(e.evidence.summary.trim().length===0&&t.push({code:"transition-summary-missing",message:"Phase transition requires a summary"}),e.evidence.confirmed&&e.state.phase!=="shape"&&e.state.phase!=="build"&&t.push({code:"confirmation-not-shape",message:"Explicit confirmation is only valid while leaving Shape or Build"}),t.push(...await vu(e.paths,e.state)),e.state.phase==="shape"||e.state.phase==="build"){let n=await vi(e.paths,e.state.name);if(n===null)t.push({code:"baseline-snapshot-missing",message:"Native baseline is missing; restore a trusted baseline before advancing"});else{let r=await kn(e.paths,n);r.complete||t.push({code:"baseline-snapshot-incomplete",message:`Native baseline is incomplete within the project-owned scope (${r.omittedCount} omitted entries); resolve the omissions before advancing`})}}if(e.state.phase==="shape"){let n=await ur(i,e.state.brief),r=await ca(e.paths,e.state);t.push(...n.findings,...r.findings),t.length===0&&!e.evidence.confirmed&&t.push({code:"shape-confirmation-required",message:"Native clarification requires explicit user confirmation of the shared understanding before Build"})}else if(e.state.phase==="build")t.push(...(await ur(i,e.state.brief)).findings,...(await ca(e.paths,e.state)).findings),t.push(...await $D(e.paths,e.evidence)),t.length===0&&e.state.approval!=="confirmed"&&!e.evidence.confirmed&&t.push({code:"approval-confirmation-required",message:"Native approval is implicit; confirm the current shared understanding before leaving Build"});else if(e.state.phase==="verify"){let n=e.evidence.verificationReport??e.state.verification_report;n?t.push(...(await sa(i,n)).findings):t.push({code:"verification-report-missing",message:"Verify requires a report path"}),e.evidence.verificationResult||t.push({code:"verification-result-missing",message:"Verify requires pass or fail"}),t.push(...(await ca(e.paths,e.state)).findings)}else t.push({code:"archive-command-required",message:"Use comet native archive for the Archive phase"});return OD(t)}import{promises as _p}from"node:fs";import Ip from"node:path";var QS={maxDeclaredArtifacts:128,maxArtifactPathBytes:512};function XS(e,t){if(e.omitted.some(i=>i.reason==="git-selection-changed"))throw new Error(`Native Git selection changed while capturing the ${t}; stabilize the Git index and retry Build evidence`);if(e.omitted.some(i=>i.reason==="physical-enumeration-limit"||i.reason==="physical-selection-changed"))throw new Error(`Native physical selection was incomplete or changed while capturing the ${t}; retry Build evidence with a stable bounded project tree`)}function HD(e,t){let i=t.omitted.slice(0,20).map(a=>a.path),n=t.omitted.reduce((a,o)=>(a[o.reason]=(a[o.reason]??0)+1,a),{}),r=t.omissionOverflow?.count??0;return r>0&&(n.overflow=r),new gi(e,t.omittedCount,n,i,t.omitted.length>i.length||r>0)}function DD(e,t,i){let n=new Set(i.entries.map(a=>a.path)),r=t.entries.filter(a=>!n.has(a.path)).slice(0,20).map(a=>a.path);return new gi(e,i.omittedCount,{"manifest-size":i.omittedCount},r,i.omittedCount>r.length)}function MD(e,t){let i=e.replaceAll("\\","/").trim();if(i.length===0||i!==e.replaceAll("\\","/")||Ip.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(i)||i.split("/").includes("..")||Ip.posix.normalize(i)!==i||i==="."||i.endsWith("/")||Buffer.byteLength(i,"utf8")>QS.maxArtifactPathBytes||Array.from(i).some(n=>{let r=n.codePointAt(0)??0;return r<=31||r===127}))throw new Error(`${t} must be a normalized project-relative path`);return i}function FD(e,t){return e.entries.some(i=>i.path===t)?"file":e.entries.some(i=>i.path.startsWith(`${t}/`))?"directory":null}async function LD(e,t,i){let n=MD(i,"Native build artifact"),r=fo(e,n);if(r)throw new Error(`Native build artifact is excluded as ${r}: ${n}`);let a=Ip.resolve(e.projectRoot,...n.split("/"));if(!$(e.projectRoot,a))throw new Error(`Native build artifact escapes the project: ${n}`);await x(e.projectRoot,a);try{let o=await _p.lstat(a);if(o.isSymbolicLink())throw new Error(`Native build artifact must not be a symlink or junction: ${n}`);let s=await _p.realpath(a),c=await _p.realpath(e.projectRoot);if(!$(c,s))throw new Error(`Native build artifact resolves outside the project: ${n}`);if(o.isFile())return{path:n,kind:"file"};if(o.isDirectory())return{path:n,kind:"directory"};throw new Error(`Native build artifact is not a file or directory: ${n}`)}catch(o){if(o.code!=="ENOENT")throw o;let s=FD(t,n);if(s===null)throw new Error(`Native build artifact does not exist: ${n}`,{cause:o});return{path:n,kind:s}}}async function BD(e){if(e.refs.length>QS.maxDeclaredArtifacts)throw new Error("Native build evidence exceeds its declared-artifact budget");let t=await Promise.all(e.refs.map(i=>LD(e.paths,e.baseline,i)));if(t.sort((i,n)=>i.path.localeCompare(n.path)||i.kind.localeCompare(n.kind)),new Set(t.map(i=>i.path)).size!==t.length)throw new Error("Native build evidence contains duplicate or conflicting artifacts");return t}function qD(e){return e.map(t=>({code:"verification-scope-partial",message:`${t.id}: ${t.reason}`,...t.path===null?{}:{path:t.path}}))}function VD(e){if(!/^[a-f0-9]{64}$/u.test(e))throw new Error("Native partial allowance requires a scope hash");return e}async function ZS(e){if(e.state.phase!=="build")throw new Error(`Native build evidence requires Build, got ${e.state.phase}`);if((e.noCodeReason??"").trim().length>0&&e.artifactRefs.length>0)throw new Error("Native build evidence cannot combine artifacts with a no-code reason");let t=await vi(e.paths,e.state.name);if(t===null)throw new Error("Native change has no baseline content snapshot");let i=await kn(e.paths,t);if(XS(i,"baseline projection"),!i.complete)throw HD(e.state.name,i);let n=await Et({changeDir:C(e.paths,e.state.name),briefRef:e.state.brief,specChanges:e.state.spec_changes}),r=await BD({paths:e.paths,baseline:i,refs:e.artifactRefs}),a=await Sn(e.paths,i,{origin:"explicit",now:e.now});XS(a,"current snapshot");let o=In({baseline:i,current:a,contractHash:n.contract.contractHash,declaredArtifacts:r,noCodeReason:e.noCodeReason??null});if(!o.baseline.complete)throw DD(e.state.name,i,o.baseline);let s=pt("scopes",o.scope.scopeHash);if(o.scope.complete){if(e.allowPartialScopeHash!==void 0&&e.allowPartialScopeHash!==null||e.partialReason!==void 0&&e.partialReason!==null)throw new Error("Complete Native build evidence must not include a partial allowance");return{contract:n,bundle:o,scopeRef:s,allowance:null,allowanceRef:null,findings:[],unresolvedScopes:[]}}if(e.allowPartialScopeHash===void 0||e.allowPartialScopeHash===null)return{contract:n,bundle:o,scopeRef:s,allowance:null,allowanceRef:null,findings:qD(o.scope.unresolvedScopes),unresolvedScopes:o.scope.unresolvedScopes};if(!e.confirmed)throw new Error("Native partial verification requires explicit confirmation");if(VD(e.allowPartialScopeHash)!==o.scope.scopeHash)throw new Error("Native partial allowance does not match the current implementation scope");let l=oN({change:e.state.name,scopeBundle:o,allowedScopeIds:o.scope.unresolvedScopes.map(d=>d.id),reason:e.partialReason??"",confirmedSummary:e.confirmedSummary??"",sourceRevision:e.state.revision,now:e.now}),u=pt("allowances",l.allowanceHash);return{contract:n,bundle:o,scopeRef:s,allowance:l,allowanceRef:u,findings:[],unresolvedScopes:o.scope.unresolvedScopes}}async function Au(e){if(await IN({paths:e.paths,name:e.state.name,bundle:e.preparation.bundle})!==e.preparation.scopeRef)throw new Error("Native implementation scope persistence ref changed");if(e.includeAllowance===!1||e.preparation.allowance===null)return;if(await jN({paths:e.paths,name:e.state.name,allowance:e.preparation.allowance})!==e.preparation.allowanceRef)throw new Error("Native partial allowance persistence ref changed")}import{promises as eE}from"fs";import tE from"path";var iE=Zt.maxSpecs*4;async function Tu(e){try{return await lt(e)}catch(t){if(t.code==="ENOENT")return null;throw t}}async function _u(e,t){let i=tE.join(C(e,t),"specs"),n;try{n=await hi({root:e.nativeRoot,directory:i,label:"Native proposed specs directory"})}catch(s){if(s.code==="ENOENT")return[];throw s}let r=[],a=0,o=await eE.opendir(i);try{for await(let s of o){if(a+=1,a>iE)throw new Error(`Native proposed specs directory exceeds ${iE} entries`);if(s.isSymbolicLink())throw new Error(`Proposed spec capability must not be a symbolic link: ${s.name}`);if(!s.isDirectory())continue;zt(s.name);let c=tE.join(i,s.name,"spec.md");await x(e.nativeRoot,c);let l;try{l=await eE.lstat(c)}catch(u){if(u.code==="ENOENT")continue;throw u}if(l.isSymbolicLink()||!l.isFile())throw new Error(`Proposed spec must be a regular file: ${s.name}`);if(r.push(s.name),r.length>Zt.maxSpecs)throw new Error("Native proposed specs exceed the spec-count budget")}}finally{await o.close().catch(s=>{if(s.code!=="ERR_DIR_CLOSED")throw s})}return await n.verify(),r.sort()}async function nE(e,t){let i=new Map(t.spec_changes.map(a=>[a.capability,a])),n=await _u(e,t.name),r=[];for(let a of n){let o=i.get(a);if(o?.operation==="remove")throw new Error(`Capability ${a} has both a proposed spec and a remove intent`);if(o){r.push({...o,source:`specs/${a}/spec.md`});continue}let s=Gt(e,a);await x(e.nativeRoot,s);let c=await Tu(s);r.push({capability:a,operation:c===null?"create":"replace",source:`specs/${a}/spec.md`,base_hash:c})}for(let a of t.spec_changes)a.operation==="remove"&&!n.includes(a.capability)&&r.push(a);return r.sort((a,o)=>a.capability.localeCompare(o.capability))}async function WD(e,t){let i=await _u(e,t.name),n=[];for(let r of i){if(t.spec_changes.find(c=>c.capability===r)?.operation==="remove")throw new Error(`Capability ${r} has both a proposed spec and a remove intent`);let o=Gt(e,r);await x(e.nativeRoot,o);let s=await Tu(o);n.push({capability:r,operation:s===null?"create":"replace",source:`specs/${r}/spec.md`,base_hash:s})}for(let r of t.spec_changes){if(r.operation!=="remove"||i.includes(r.capability))continue;let a=Gt(e,r.capability);await x(e.nativeRoot,a);let o=await Tu(a);o!==null&&n.push({...r,base_hash:o})}return n.sort((r,a)=>r.capability.localeCompare(a.capability))}async function rE(e){zt(e.name);let t=ke(e.summary);return Mn(t,"Spec rebase summary"),te(e.paths,`rebase specs for ${e.name}`,()=>De(e.paths,e.name,`rebase specs for ${e.name}`,async()=>{await Rt(e.paths,e.name);let i=await G(e.paths,e.name);if(i.phase==="shape")throw new Error("Shape spec metadata is refreshed by the next command");if(i.archived)throw new Error(`Native change ${i.name} is already archived`);let n=C(e.paths,e.name),r=await be(n);if(!r||r.runId!==i.run_id||r.currentStep!==i.phase||r.pending)throw new Error(`Native Run state is missing or inconsistent for ${i.name}`);let a=await WD(e.paths,i),o={...i,revision:i.revision+1,phase:"build",spec_changes:a,verification_result:"pending",verification_report:null,implementation_scope:null,verification_evidence:null,partial_allowance:null},s={...r,currentStep:"build",iteration:r.iteration+1,pending:null,status:"running"},c=D(JSON.stringify({operation:"spec-rebase",change:i.name,summary:t,specChanges:a}));await ss({paths:e.paths,previousState:i,nextState:o,previousRun:r,nextRun:s,evidenceHash:c,eventData:{previousPhase:i.phase,nextPhase:"build",evidenceHash:c,summary:t,artifacts:[],noCodeReason:null,verificationResult:null},operation:"spec-rebase",now:e.now,transitionId:e.transitionId});let l=await ki(e.paths,e.name);if(!l)throw new Error("Native spec rebase journal disappeared before completion");return l}))}async function aE(e,t,i){return zt(t),zt(i),te(e,`remove spec ${i} from ${t}`,()=>De(e,t,`remove spec ${i} from ${t}`,async()=>(await Rt(e,t),JD(e,t,i))))}async function JD(e,t,i){let n=await G(e,t);if(n.phase==="archive"||n.archived)throw new Error(`Native change ${t} no longer accepts spec changes`);if((await _u(e,t)).includes(i))throw new Error(`Capability ${i} has both a proposed spec and a remove intent`);if(n.spec_changes.find(l=>l.capability===i)?.operation==="remove")return n;let o=Gt(e,i);await x(e.nativeRoot,o);let s=await Tu(o);if(s===null)throw new Error(`Canonical spec is missing: ${i}`);let c={...n,spec_changes:[...n.spec_changes.filter(l=>l.capability!==i),{capability:i,operation:"remove",base_hash:s}].sort((l,u)=>l.capability.localeCompare(u.capability))};return await oa(e,c,n.revision),c}async function oE(e,t){let i=C(e,t),n={},r=0;for(let a of await _u(e,t)){let o=await ye({root:i,ref:`specs/${a}/spec.md`,maxBytes:Zt.maxFileBytes});if(r+=o.size,r>Zt.maxTotalBytes)throw new Error("Native proposed specs exceed the total byte budget");n[a]=o.text}return n}function GD(e){return`Native verification receipt binding is invalid: ${e.detail}. Re-issue the affected receipts with \`comet native receipt refresh ${e.change} --apply\`.`}function lE(e){return e.confirmed!==void 0||e.artifacts!==void 0||e.noCodeReason!==void 0||e.allowPartialScopeHash!==void 0||e.partialReason!==void 0||e.verificationResult!==void 0||e.verificationReport!==void 0||e.repairOverrideSignature!==void 0||e.repairOverrideSummary!==void 0}function jp(e){return e.reasonCode==="override-already-used"?{code:"repair-override-exhausted",message:`Native repair already used its override for signature: ${e.signatureHash}`}:e.disposition==="warn"?{code:"repair-stagnation-warning",message:`Native repair repeated the same failure signature: ${e.signatureHash}`}:e.disposition==="manual-stop"?{code:"repair-stagnation-stop",message:`Native repair stopped after repeated failure signature: ${e.signatureHash}`}:{code:"repair-iteration-limit",message:`Native repair reached its total iteration limit at signature: ${e.signatureHash}`}}function sE(e){let t=ni({paths:e.paths,state:e.state,findings:e.preparation.findingCodes.map(i=>{if(i==="verification-receipt-binding-mismatch"&&e.preparation.receiptBindingFailures&&e.preparation.receiptBindingFailures.length>0){let n=e.preparation.receiptBindingFailures.map(r=>`${r.acceptanceId?`${r.ref}[${r.acceptanceId}]`:r.ref} -> ${r.mismatches.join("; ")}`).join(" | ");return{code:i,message:GD({change:e.state.name,detail:n})}}return{code:i,message:`Native verification evidence is not current: ${i}`}})});return{change:e.state,previousPhase:e.previousPhase,next:"manual",nextCommand:null,findings:t,continuation:Me({state:e.state,findings:t,clarificationMode:e.clarificationMode})}}function UD(e){if(Mn(e.summary,"Native transition summary"),e.noCodeReason!==void 0&&Mn(e.noCodeReason,"Native transition no-code reason"),e.repairOverrideSignature!==void 0&&!/^[a-f0-9]{64}$/u.test(e.repairOverrideSignature))throw new Error("Native repair override signature must be a SHA-256 hash");e.repairOverrideSummary!==void 0&&zl(e.repairOverrideSummary)}function KD(e){return{...e,summary:ke(e.summary),...e.noCodeReason===void 0?{}:{noCodeReason:ke(e.noCodeReason)},...e.partialReason===void 0?{}:{partialReason:ke(e.partialReason)},...e.repairOverrideSummary===void 0?{}:{repairOverrideSummary:ke(e.repairOverrideSummary)}}}function YD(e,t){let i=t.repairOverrideSignature!==void 0,n=t.repairOverrideSummary!==void 0;if(i!==n)throw new Error("Native repair override signature and summary must be provided together");if((i||n)&&e.phase!=="build")throw new Error("Native repair override is only valid while leaving Build")}async function cE(e){if(lE(e.transition.evidence))throw new Error("Native evidence retreat only accepts a transition summary");let t=e.state.phase;if(t!=="verify"&&t!=="archive"||e.run.currentStep!==t||e.run.pending!==null)throw new Error("Native Verify/Archive Run cannot retreat evidence safely");if(t==="archive"?["complete","partial"].includes((await br({paths:e.transition.paths,state:e.state,now:e.transition.now})).freshness):(await ms({paths:e.transition.paths,state:e.state,now:e.transition.now})).freshness==="fresh"){let c=ni({paths:e.transition.paths,state:e.state,findings:[t==="archive"?{code:"archive-command-required",message:"Current verification evidence is fresh; use Native Archive preview"}:{code:"verification-result-missing",message:"Current implementation scope is fresh; complete Verify with a result and report"}]});return{change:e.state,previousPhase:t,next:"manual",nextCommand:t==="archive"?`comet native archive ${e.state.name} --dry-run`:null,findings:c,continuation:Me({state:e.state,archiveReady:t==="archive",clarificationMode:e.transition.clarificationMode})}}let n={...e.state,revision:e.state.revision+1,phase:"build",verification_result:"pending",verification_report:null,implementation_scope:null,verification_evidence:null,partial_allowance:null},r={...e.run,currentStep:"build",iteration:e.run.iteration+1,pending:null,status:"running"},a={previousPhase:t,nextPhase:"build",evidenceHash:e.evidenceHash,summary:e.transition.evidence.summary,artifacts:[],noCodeReason:null,verificationResult:null},o=await ss({paths:e.transition.paths,previousState:e.state,nextState:n,previousRun:e.run,nextRun:r,evidenceHash:e.evidenceHash,eventData:a,operation:"evidence-retreat",now:e.transition.now,transitionId:e.transition.transitionId});await e.transition.hooks?.afterPrepared?.(o);let s=await ki(e.transition.paths,e.state.name,e.transition.hooks);if(!s)throw new Error("Native evidence retreat journal disappeared before completion");return{change:s,previousPhase:t,next:"auto",nextCommand:null,findings:[],continuation:Me({state:s,clarificationMode:e.transition.clarificationMode})}}async function uE(e){let t={...e,maxVerifyFailures:e.maxVerifyFailures??Jg,evidence:KD(e.evidence)};return UD(t.evidence),te(e.paths,`advance ${e.name}`,()=>De(e.paths,e.name,`advance ${e.name}`,()=>XD(t)))}async function XD(e){await Rt(e.paths,e.name);let t=await G(e.paths,e.name),i=t.phase,n=C(e.paths,e.name),r=Kl(e.evidence),a=await be(n);if(a){let E=(await qe(n,a.trajectoryRef)).at(-1);if(E?.type==="state_transitioned"&&E.data.evidenceHash===r&&E.data.nextPhase===t.phase&&(E.data.previousPhase==="verify"?["complete","partial"].includes((await br({paths:e.paths,state:t,now:e.now})).freshness):!0)){let B=Object.hasOwn(E.data,"repairStagnation")?await Xk(e.paths,t,e.maxVerifyFailures):null,q=B&&B.disposition!=="continue"?ni({paths:e.paths,state:t,findings:[jp(B)]}):[],U=B?.disposition==="manual-stop"||B?.disposition==="hard-stop";return{change:t,previousPhase:E.data.previousPhase??t.phase,next:U?"manual":"auto",nextCommand:U?null:t.phase==="archive"?`comet native archive ${t.name} --dry-run`:null,findings:q,continuation:Me({state:t,findings:q,archiveReady:t.phase==="archive"&&t.verification_result==="pass",clarificationMode:e.clarificationMode}),...B?{repair:B}:{}}}}if(t.phase==="archive"){if(!a)throw new Error("Native Archive Run state is missing");return cE({transition:e,state:t,run:a,evidenceHash:r})}if(t.phase==="verify"&&!lE(e.evidence)){if(!a)throw new Error("Native Verify Run state is missing");if((await ms({paths:e.paths,state:t,now:e.now})).freshness!=="fresh")return cE({transition:e,state:t,run:a,evidenceHash:r})}let o={...t,spec_changes:await nE(e.paths,t)};YD(t,e.evidence);let s=await YS({paths:e.paths,state:o,evidence:e.evidence,clarificationMode:e.clarificationMode});if(!s.valid){let g=ni({paths:e.paths,state:t,findings:s.findings});return{change:t,previousPhase:i,next:"manual",nextCommand:null,findings:g,continuation:Me({state:t,findings:g,clarificationMode:e.clarificationMode})}}let c=t.phase==="shape"?await Et({changeDir:n,briefRef:o.brief,specChanges:o.spec_changes}):null;if(t.phase!=="build"&&(e.evidence.allowPartialScopeHash!==void 0||e.evidence.partialReason!==void 0))throw new Error("Native partial scope allowance is only valid while leaving Build");let l=t.phase==="build"?await ZS({paths:e.paths,state:o,artifactRefs:e.evidence.artifacts??[],noCodeReason:e.evidence.noCodeReason??null,allowPartialScopeHash:e.evidence.allowPartialScopeHash??null,partialReason:e.evidence.partialReason??null,confirmedSummary:e.evidence.summary,confirmed:e.evidence.confirmed??!1,now:e.now}):null;if(l&&(t.approved_contract_hash??null)!==l.contract.contract.contractHash&&!e.evidence.confirmed){let g=ni({paths:e.paths,state:t,findings:[{code:"contract-changed-after-approval",message:"Native contract changed after approval; re-confirm the current contract before leaving Build"}]});return{change:t,previousPhase:i,next:"manual",nextCommand:null,findings:g,continuation:Me({state:t,findings:g,clarificationMode:e.clarificationMode})}}let u=l?{scopeHash:l.bundle.scope.scopeHash,scopeRef:l.scopeRef,complete:l.bundle.scope.complete,unresolvedScopeCount:l.unresolvedScopes.length,partialAllowanceRef:l.allowanceRef,acceptancePage:Zl({criteria:l.contract.contract.acceptance,acceptanceHash:l.contract.contract.acceptanceHash})}:void 0;if(l&&l.findings.length>0){await Au({paths:e.paths,state:t,preparation:l,includeAllowance:!1});let g=ni({paths:e.paths,state:t,findings:l.findings});return{change:t,previousPhase:i,next:"manual",nextCommand:null,findings:g,continuation:Me({state:t,findings:g,clarificationMode:e.clarificationMode}),preparedScope:u}}let d=null,f=l?ya(l.bundle):null;if(t.phase==="build"&&l){let g=await eS({paths:e.paths,state:t,currentImplementationScope:l.bundle,maxVerifyFailures:e.maxVerifyFailures,...e.evidence.repairOverrideSignature&&e.evidence.repairOverrideSummary?{override:{expectedSignatureHash:e.evidence.repairOverrideSignature,summary:e.evidence.repairOverrideSummary}}:{}});if(g.disposition!=="proceed"){await Au({paths:e.paths,state:t,preparation:l,includeAllowance:!1});let E=ni({paths:e.paths,state:t,findings:[g.disposition==="hard-stop"&&g.overrideRecorded?{code:"repair-override-exhausted",message:`Native repair already used its override for signature: ${g.signatureHash}`}:jp({disposition:g.disposition,reasonCode:g.disposition==="hard-stop"?"repair-iteration-limit":"repeated-failure-stop",signatureHash:g.signatureHash})]});return{change:t,previousPhase:i,next:"manual",nextCommand:null,findings:E,continuation:Me({state:t,findings:E,clarificationMode:e.clarificationMode}),preparedScope:u&&{...u,partialAllowanceRef:null}}}d=g.eventProjection}let h=t.phase==="verify"?await rp({paths:e.paths,state:o,result:e.evidence.verificationResult,reportRef:e.evidence.verificationReport,receiptRef:null,requireReceipt:!1,preflightOnly:e.evidence.verificationResult==="pass",now:e.now}):null;if(h&&!h.ready)return sE({paths:e.paths,state:t,previousPhase:i,clarificationMode:e.clarificationMode,preparation:h});if(t.phase==="verify"&&e.evidence.verificationResult==="pass"){let g=(await vp({paths:e.paths,name:t.name})).ref;h=await rp({paths:e.paths,state:o,result:e.evidence.verificationResult,reportRef:e.evidence.verificationReport,receiptRef:g,preflight:h?.preflight,now:e.now})}if(h&&!h.ready)return sE({paths:e.paths,state:t,previousPhase:i,clarificationMode:e.clarificationMode,preparation:h});let m=null;if(t.phase==="verify"&&e.evidence.verificationResult==="fail"&&h?.ready&&h.envelope){let g=await Zk({paths:e.paths,state:t,envelope:h.envelope,maxVerifyFailures:e.maxVerifyFailures});d=g.eventProjection,f=g.facts.implementationScopeHash,m=Qk(g)}let p=a;if(!p){if(t.run_id!==null||t.phase!=="shape")throw new Error("Native Run state is missing or inconsistent");p=Gw(mt,e.runId?.()??zD(),vr)}if(p.currentStep!==t.phase)throw new Error(`Native Run step ${p.currentStep??"(none)"} does not match ${t.phase}`);let v=_s(mt,p,new Set,Na,void 0);if(!v.action)throw new Error(v.reason??"Native runtime produced no action");let S=Is(mt,v.state,{actionId:v.action.id,status:"succeeded",summary:e.evidence.summary,state:e.evidence.verificationResult?{verification_result:e.evidence.verificationResult}:void 0},Na,void 0);if(!S.currentStep)throw new Error("Archive completion must use the archive command");let k={...o,revision:t.revision+1,phase:S.currentStep,approval:e.evidence.confirmed?"confirmed":t.approval,approved_contract_hash:t.phase==="shape"?c.contract.contractHash:t.phase==="build"&&e.evidence.confirmed?l.contract.contract.contractHash:t.approved_contract_hash??null,run_id:p.runId,...t.phase==="build"?{verification_result:"pending",verification_report:null,implementation_scope:l.scopeRef,partial_allowance:l.allowanceRef,verification_evidence:null}:{},...t.phase==="verify"?{verification_result:e.evidence.verificationResult,verification_report:h.envelope.reportRef,verification_evidence:h.evidenceRef}:{}},N={previousPhase:i,nextPhase:k.phase,evidenceHash:r,summary:e.evidence.summary,artifacts:e.evidence.artifacts??[],noCodeReason:e.evidence.noCodeReason??null,verificationResult:e.evidence.verificationResult??null,...(t.phase==="build"||t.phase==="verify")&&(t.phase==="build"?l.bundle.scope.scopeHash:h.envelope.implementationScopeHash)?{implementationScopeHash:t.phase==="build"?l.bundle.scope.scopeHash:h.envelope.implementationScopeHash}:{},...f?{repairScopeHash:f}:{},...d?{repairStagnation:d}:{}};t.phase==="build"&&l&&await Au({paths:e.paths,state:t,preparation:l}),t.phase==="verify"&&h&&await Zb({paths:e.paths,state:t,preparation:h});let b=await ss({paths:e.paths,previousState:t,nextState:k,previousRun:a,nextRun:S,evidenceHash:r,eventData:N,now:e.now,transitionId:e.transitionId});await e.hooks?.afterPrepared?.(b);let R=await ki(e.paths,e.name,e.hooks);if(!R)throw new Error("Native transition journal disappeared before completion");let y=m&&m.disposition!=="continue"?ni({paths:e.paths,state:R,findings:[jp(m)]}):[],w=m?.disposition==="manual-stop"||m?.disposition==="hard-stop";return{change:R,previousPhase:i,next:w?"manual":"auto",nextCommand:w?null:R.phase==="archive"?`comet native archive ${R.name} --dry-run`:null,findings:y,continuation:Me({state:R,findings:y,archiveReady:R.phase==="archive"&&R.verification_result==="pass",clarificationMode:e.clarificationMode}),...u?{preparedScope:u}:{},...m?{repair:m}:{}}}async function dE(e,t){let i=ae(e,"change name"),n=J(e,"--summary");if(!n)throw new I("--summary is required");let r=gt(e,"--confirmed"),a=Yi(e,"--artifact"),o=J(e,"--no-code-reason"),s=J(e,"--allow-partial-scope"),c=J(e,"--partial-reason"),l=J(e,"--result"),u=J(e,"--report"),d=J(e,"--override-repair"),f=J(e,"--override-summary");if(l!==void 0&&l!=="pass"&&l!=="fail")throw new I("--result must be pass or fail");if(s===void 0!=(c===void 0))throw new I("--allow-partial-scope and --partial-reason must be provided together");if(s&&!/^[a-f0-9]{64}$/u.test(s))throw new I("--allow-partial-scope must be a SHA-256 hash");if(s&&!r)throw new I("--allow-partial-scope requires --confirmed");if(d===void 0!=(f===void 0))throw new I("--override-repair and --override-summary must be provided together");if(d&&!/^[a-f0-9]{64}$/u.test(d))throw new I("--override-repair must be a SHA-256 hash");if(d&&l!==void 0)throw new I("--override-repair cannot be combined with --result");Y(e);let{config:h,paths:m}=await Oe(t),p={summary:n,...r?{confirmed:!0}:{},...a.length>0?{artifacts:a}:{},...o?{noCodeReason:o}:{},...s?{allowPartialScopeHash:s}:{},...c?{partialReason:c}:{},...l?{verificationResult:l}:{},...u?{verificationReport:u}:{},...d?{repairOverrideSignature:d}:{},...f?{repairOverrideSummary:f}:{}},v=await uE({paths:m,name:i,evidence:p,clarificationMode:h.native.clarification_mode,maxVerifyFailures:h.native.max_verify_failures});if(v.next==="manual"){let k=v.repair?.disposition==="manual-stop"||v.repair?.disposition==="hard-stop"||v.findings.some(N=>["repair-stagnation-stop","repair-iteration-limit","repair-override-exhausted"].includes(N.code));return{command:"next",exitCode:k?75:65,data:v,error:{code:k?"blocked":"invalid-data",message:v.findings[0]?.message??"Native phase guard failed"}}}let S=await Ze(m,i,{clarificationMode:h.native.clarification_mode,maxVerifyFailures:h.native.max_verify_failures});return Z("next",{...v,continuation:S.continuation})}import QD from"node:path";var ZD="Native receipt re-issued after revision bump";function eM(e){return!e.ok&&e.mismatches.length===1&&e.mismatches[0]?.startsWith("sourceRevision: ")===!0}function tM(e){return e.kind!=="automated-check"?"":[e.evidence.executable,...e.evidence.args].map(i=>/\s/u.test(i)?JSON.stringify(i):i).join(" ")}function iM(e){return`${ZD} to revision ${e}`}function nM(){return"Manual evidence re-issued via `comet native receipt refresh` to restore revision binding."}async function fE(e){let t=await G(e.paths,e.name);if(t.phase!=="verify")throw new Error(`Native receipt refresh requires Verify, got ${t.phase} for ${e.name}`);let i=t.implementation_scope?await Nr(e.paths,t):null;if(i&&await cu({paths:e.paths,state:t,context:i}),!t.verification_evidence)return{refreshed:[],requiresRerun:[],requiresManual:[],requiresCheck:[],applied:!1,verificationReport:null};if(!i)throw new Error("Native receipt refresh requires an implementation scope");let n=await Dn(e.paths,e.name,t.verification_evidence),r=[],a=[],o=[],s=[],c=new Set,l=[...new Set([...n.requiredReceiptRefs,...n.receiptRefs])];for(let R of l){let y=await Hn(e.paths,e.name,R),w=ps(y,i.bindings);if(!w.ok)if(c.add(R),y.kind==="manual-evidence"){let g={oldRef:R,acceptanceIds:[...y.acceptanceIds]};eM(w)?r.push(g):a.push({...g,mismatches:w.mismatches})}else y.kind==="automated-check"?o.push({oldRef:R,acceptanceIds:[...y.acceptanceIds],command:tM(y),timeoutMs:y.evidence.timeoutMs}):y.kind==="static-inspection"&&s.push({oldRef:R})}if(!(e.apply&&o.length===0&&a.length===0&&r.length>0))return{refreshed:[],requiresRerun:o,requiresManual:a,requiresCheck:s,applied:!1,verificationReport:t.verification_report};let d=[],f=new Map,h=new Map;for(let R of r){let y=[...R.acceptanceIds].sort().join(` +`)}async function US(e,t){let i=ae(e,"change name"),n=await re(t),r=pu(e,n?.native.language??"en"),a=J(e,"--isolation")??"current";if(a!=="current"&&a!=="branch"&&a!=="worktree")throw new I("--isolation must be current, branch, or worktree");let o=J(e,"--change-branch"),s=J(e,"--target-branch");Y(e);let c=n===null?tr("docs",r):void 0;if(n||(n=c),n.native.pending_root_move)throw new Error(`Native root move ${n.native.pending_root_move.id} is incomplete`);let l=await Ne(t,n.native.artifact_root);await Jc(l);let u=ih({projectRoot:t,isolation:a,...o?{changeBranch:o}:{},...s?{targetBranch:s}:{}}),d=await yy({paths:l,name:i,language:r,workspaceBinding:u,...c?{initialProjectConfig:c}:{}});n=await re(t)??n,await hu(l,d.name);let f=await Ve(l,d.name),h=await Ze(l,d.name,{clarificationMode:n.native.clarification_mode,maxVerifyFailures:n.native.max_verify_failures});return Z("new",{...d,workspace:f,continuation:h.continuation},`Created Native change ${d.name} +`)}import{randomUUID as zD}from"crypto";import{promises as jD}from"fs";import KS from"path";function OD(e){return{valid:e.length===0,findings:e}}async function $D(e,t){let i=[];if((t.noCodeReason??"").trim().length>0)return i;if(!t.artifacts||t.artifacts.length===0)return[{code:"build-evidence-missing",message:"Build requires an artifact reference or an explicit no-code reason"}];for(let n of t.artifacts){if(KS.isAbsolute(n)||n.split(/[\\/]/u).includes("..")||/^(?:[A-Za-z]:|~|[\\/])/u.test(n)){i.push({code:"build-artifact-unsafe",message:`Unsafe build artifact: ${n}`});continue}let r=KS.resolve(e.projectRoot,...n.split(/[\\/]/u));if(!$(e.projectRoot,r)){i.push({code:"build-artifact-unsafe",message:`Unsafe build artifact: ${n}`});continue}try{await jD.access(r)}catch{i.push({code:"build-artifact-missing",message:`Build artifact does not exist: ${n}`,path:n})}}return i}async function YS(e){let t=[],i=C(e.paths,e.state.name);if(e.evidence.summary.trim().length===0&&t.push({code:"transition-summary-missing",message:"Phase transition requires a summary"}),e.evidence.confirmed&&e.state.phase!=="shape"&&e.state.phase!=="build"&&t.push({code:"confirmation-not-shape",message:"Explicit confirmation is only valid while leaving Shape or Build"}),t.push(...await vu(e.paths,e.state)),e.state.phase==="shape"||e.state.phase==="build"){let n=await vi(e.paths,e.state.name);if(n===null)t.push({code:"baseline-snapshot-missing",message:"Native baseline is missing; restore a trusted baseline before advancing"});else{let r=await kn(e.paths,n);r.complete||t.push({code:"baseline-snapshot-incomplete",message:`Native baseline is incomplete within the project-owned scope (${r.omittedCount} omitted entries); resolve the omissions before advancing`})}}if(e.state.phase==="shape"){let n=await ur(i,e.state.brief),r=await ca(e.paths,e.state);t.push(...n.findings,...r.findings),t.length===0&&!e.evidence.confirmed&&t.push({code:"shape-confirmation-required",message:"Native clarification requires explicit user confirmation of the shared understanding before Build"})}else if(e.state.phase==="build")t.push(...(await ur(i,e.state.brief)).findings,...(await ca(e.paths,e.state)).findings),t.push(...await $D(e.paths,e.evidence)),t.length===0&&e.state.approval!=="confirmed"&&!e.evidence.confirmed&&t.push({code:"approval-confirmation-required",message:"Native approval is implicit; confirm the current shared understanding before leaving Build"});else if(e.state.phase==="verify"){let n=e.evidence.verificationReport??e.state.verification_report;n?t.push(...(await sa(i,n)).findings):t.push({code:"verification-report-missing",message:"Verify requires a report path"}),e.evidence.verificationResult||t.push({code:"verification-result-missing",message:"Verify requires pass or fail"}),t.push(...(await ca(e.paths,e.state)).findings)}else t.push({code:"archive-command-required",message:"Use comet native archive for the Archive phase"});return OD(t)}import{promises as Ip}from"node:fs";import jp from"node:path";var QS={maxDeclaredArtifacts:128,maxArtifactPathBytes:512};function XS(e,t){if(e.omitted.some(i=>i.reason==="git-selection-changed"))throw new Error(`Native Git selection changed while capturing the ${t}; stabilize the Git index and retry Build evidence`);if(e.omitted.some(i=>i.reason==="physical-enumeration-limit"||i.reason==="physical-selection-changed"))throw new Error(`Native physical selection was incomplete or changed while capturing the ${t}; retry Build evidence with a stable bounded project tree`)}function HD(e,t){let i=t.omitted.slice(0,20).map(a=>a.path),n=t.omitted.reduce((a,o)=>(a[o.reason]=(a[o.reason]??0)+1,a),{}),r=t.omissionOverflow?.count??0;return r>0&&(n.overflow=r),new gi(e,t.omittedCount,n,i,t.omitted.length>i.length||r>0)}function DD(e,t,i){let n=new Set(i.entries.map(a=>a.path)),r=t.entries.filter(a=>!n.has(a.path)).slice(0,20).map(a=>a.path);return new gi(e,i.omittedCount,{"manifest-size":i.omittedCount},r,i.omittedCount>r.length)}function MD(e,t){let i=e.replaceAll("\\","/").trim();if(i.length===0||i!==e.replaceAll("\\","/")||jp.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(i)||i.split("/").includes("..")||jp.posix.normalize(i)!==i||i==="."||i.endsWith("/")||Buffer.byteLength(i,"utf8")>QS.maxArtifactPathBytes||Array.from(i).some(n=>{let r=n.codePointAt(0)??0;return r<=31||r===127}))throw new Error(`${t} must be a normalized project-relative path`);return i}function FD(e,t){return e.entries.some(i=>i.path===t)?"file":e.entries.some(i=>i.path.startsWith(`${t}/`))?"directory":null}async function LD(e,t,i){let n=MD(i,"Native build artifact"),r=fo(e,n);if(r)throw new Error(`Native build artifact is excluded as ${r}: ${n}`);let a=jp.resolve(e.projectRoot,...n.split("/"));if(!$(e.projectRoot,a))throw new Error(`Native build artifact escapes the project: ${n}`);await x(e.projectRoot,a);try{let o=await Ip.lstat(a);if(o.isSymbolicLink())throw new Error(`Native build artifact must not be a symlink or junction: ${n}`);let s=await Ip.realpath(a),c=await Ip.realpath(e.projectRoot);if(!$(c,s))throw new Error(`Native build artifact resolves outside the project: ${n}`);if(o.isFile())return{path:n,kind:"file"};if(o.isDirectory())return{path:n,kind:"directory"};throw new Error(`Native build artifact is not a file or directory: ${n}`)}catch(o){if(o.code!=="ENOENT")throw o;let s=FD(t,n);if(s===null)throw new Error(`Native build artifact does not exist: ${n}`,{cause:o});return{path:n,kind:s}}}async function BD(e){if(e.refs.length>QS.maxDeclaredArtifacts)throw new Error("Native build evidence exceeds its declared-artifact budget");let t=await Promise.all(e.refs.map(i=>LD(e.paths,e.baseline,i)));if(t.sort((i,n)=>i.path.localeCompare(n.path)||i.kind.localeCompare(n.kind)),new Set(t.map(i=>i.path)).size!==t.length)throw new Error("Native build evidence contains duplicate or conflicting artifacts");return t}function qD(e){return e.map(t=>({code:"verification-scope-partial",message:`${t.id}: ${t.reason}`,...t.path===null?{}:{path:t.path}}))}function VD(e){if(!/^[a-f0-9]{64}$/u.test(e))throw new Error("Native partial allowance requires a scope hash");return e}async function ZS(e){if(e.state.phase!=="build")throw new Error(`Native build evidence requires Build, got ${e.state.phase}`);if((e.noCodeReason??"").trim().length>0&&e.artifactRefs.length>0)throw new Error("Native build evidence cannot combine artifacts with a no-code reason");let t=await vi(e.paths,e.state.name);if(t===null)throw new Error("Native change has no baseline content snapshot");let i=await kn(e.paths,t);if(XS(i,"baseline projection"),!i.complete)throw HD(e.state.name,i);let n=await Et({changeDir:C(e.paths,e.state.name),briefRef:e.state.brief,specChanges:e.state.spec_changes}),r=await BD({paths:e.paths,baseline:i,refs:e.artifactRefs}),a=await Sn(e.paths,i,{origin:"explicit",now:e.now});XS(a,"current snapshot");let o=In({baseline:i,current:a,contractHash:n.contract.contractHash,declaredArtifacts:r,noCodeReason:e.noCodeReason??null});if(!o.baseline.complete)throw DD(e.state.name,i,o.baseline);let s=pt("scopes",o.scope.scopeHash);if(o.scope.complete){if(e.allowPartialScopeHash!==void 0&&e.allowPartialScopeHash!==null||e.partialReason!==void 0&&e.partialReason!==null)throw new Error("Complete Native build evidence must not include a partial allowance");return{contract:n,bundle:o,scopeRef:s,allowance:null,allowanceRef:null,findings:[],unresolvedScopes:[]}}if(e.allowPartialScopeHash===void 0||e.allowPartialScopeHash===null)return{contract:n,bundle:o,scopeRef:s,allowance:null,allowanceRef:null,findings:qD(o.scope.unresolvedScopes),unresolvedScopes:o.scope.unresolvedScopes};if(!e.confirmed)throw new Error("Native partial verification requires explicit confirmation");if(VD(e.allowPartialScopeHash)!==o.scope.scopeHash)throw new Error("Native partial allowance does not match the current implementation scope");let l=sN({change:e.state.name,scopeBundle:o,allowedScopeIds:o.scope.unresolvedScopes.map(d=>d.id),reason:e.partialReason??"",confirmedSummary:e.confirmedSummary??"",sourceRevision:e.state.revision,now:e.now}),u=pt("allowances",l.allowanceHash);return{contract:n,bundle:o,scopeRef:s,allowance:l,allowanceRef:u,findings:[],unresolvedScopes:o.scope.unresolvedScopes}}async function Au(e){if(await jN({paths:e.paths,name:e.state.name,bundle:e.preparation.bundle})!==e.preparation.scopeRef)throw new Error("Native implementation scope persistence ref changed");if(e.includeAllowance===!1||e.preparation.allowance===null)return;if(await ON({paths:e.paths,name:e.state.name,allowance:e.preparation.allowance})!==e.preparation.allowanceRef)throw new Error("Native partial allowance persistence ref changed")}import{promises as eE}from"fs";import tE from"path";var iE=Zt.maxSpecs*4;async function Tu(e){try{return await lt(e)}catch(t){if(t.code==="ENOENT")return null;throw t}}async function _u(e,t){let i=tE.join(C(e,t),"specs"),n;try{n=await hi({root:e.nativeRoot,directory:i,label:"Native proposed specs directory"})}catch(s){if(s.code==="ENOENT")return[];throw s}let r=[],a=0,o=await eE.opendir(i);try{for await(let s of o){if(a+=1,a>iE)throw new Error(`Native proposed specs directory exceeds ${iE} entries`);if(s.isSymbolicLink())throw new Error(`Proposed spec capability must not be a symbolic link: ${s.name}`);if(!s.isDirectory())continue;zt(s.name);let c=tE.join(i,s.name,"spec.md");await x(e.nativeRoot,c);let l;try{l=await eE.lstat(c)}catch(u){if(u.code==="ENOENT")continue;throw u}if(l.isSymbolicLink()||!l.isFile())throw new Error(`Proposed spec must be a regular file: ${s.name}`);if(r.push(s.name),r.length>Zt.maxSpecs)throw new Error("Native proposed specs exceed the spec-count budget")}}finally{await o.close().catch(s=>{if(s.code!=="ERR_DIR_CLOSED")throw s})}return await n.verify(),r.sort()}async function nE(e,t){let i=new Map(t.spec_changes.map(a=>[a.capability,a])),n=await _u(e,t.name),r=[];for(let a of n){let o=i.get(a);if(o?.operation==="remove")throw new Error(`Capability ${a} has both a proposed spec and a remove intent`);if(o){r.push({...o,source:`specs/${a}/spec.md`});continue}let s=Gt(e,a);await x(e.nativeRoot,s);let c=await Tu(s);r.push({capability:a,operation:c===null?"create":"replace",source:`specs/${a}/spec.md`,base_hash:c})}for(let a of t.spec_changes)a.operation==="remove"&&!n.includes(a.capability)&&r.push(a);return r.sort((a,o)=>a.capability.localeCompare(o.capability))}async function WD(e,t){let i=await _u(e,t.name),n=[];for(let r of i){if(t.spec_changes.find(c=>c.capability===r)?.operation==="remove")throw new Error(`Capability ${r} has both a proposed spec and a remove intent`);let o=Gt(e,r);await x(e.nativeRoot,o);let s=await Tu(o);n.push({capability:r,operation:s===null?"create":"replace",source:`specs/${r}/spec.md`,base_hash:s})}for(let r of t.spec_changes){if(r.operation!=="remove"||i.includes(r.capability))continue;let a=Gt(e,r.capability);await x(e.nativeRoot,a);let o=await Tu(a);o!==null&&n.push({...r,base_hash:o})}return n.sort((r,a)=>r.capability.localeCompare(a.capability))}async function rE(e){zt(e.name);let t=ke(e.summary);return Mn(t,"Spec rebase summary"),te(e.paths,`rebase specs for ${e.name}`,()=>De(e.paths,e.name,`rebase specs for ${e.name}`,async()=>{await Rt(e.paths,e.name);let i=await G(e.paths,e.name);if(i.phase==="shape")throw new Error("Shape spec metadata is refreshed by the next command");if(i.archived)throw new Error(`Native change ${i.name} is already archived`);let n=C(e.paths,e.name),r=await be(n);if(!r||r.runId!==i.run_id||r.currentStep!==i.phase||r.pending)throw new Error(`Native Run state is missing or inconsistent for ${i.name}`);let a=await WD(e.paths,i),o={...i,revision:i.revision+1,phase:"build",spec_changes:a,verification_result:"pending",verification_report:null,implementation_scope:null,verification_evidence:null,partial_allowance:null},s={...r,currentStep:"build",iteration:r.iteration+1,pending:null,status:"running"},c=D(JSON.stringify({operation:"spec-rebase",change:i.name,summary:t,specChanges:a}));await ss({paths:e.paths,previousState:i,nextState:o,previousRun:r,nextRun:s,evidenceHash:c,eventData:{previousPhase:i.phase,nextPhase:"build",evidenceHash:c,summary:t,artifacts:[],noCodeReason:null,verificationResult:null},operation:"spec-rebase",now:e.now,transitionId:e.transitionId});let l=await ki(e.paths,e.name);if(!l)throw new Error("Native spec rebase journal disappeared before completion");return l}))}async function aE(e,t,i){return zt(t),zt(i),te(e,`remove spec ${i} from ${t}`,()=>De(e,t,`remove spec ${i} from ${t}`,async()=>(await Rt(e,t),JD(e,t,i))))}async function JD(e,t,i){let n=await G(e,t);if(n.phase==="archive"||n.archived)throw new Error(`Native change ${t} no longer accepts spec changes`);if((await _u(e,t)).includes(i))throw new Error(`Capability ${i} has both a proposed spec and a remove intent`);if(n.spec_changes.find(l=>l.capability===i)?.operation==="remove")return n;let o=Gt(e,i);await x(e.nativeRoot,o);let s=await Tu(o);if(s===null)throw new Error(`Canonical spec is missing: ${i}`);let c={...n,spec_changes:[...n.spec_changes.filter(l=>l.capability!==i),{capability:i,operation:"remove",base_hash:s}].sort((l,u)=>l.capability.localeCompare(u.capability))};return await oa(e,c,n.revision),c}async function oE(e,t){let i=C(e,t),n={},r=0;for(let a of await _u(e,t)){let o=await ye({root:i,ref:`specs/${a}/spec.md`,maxBytes:Zt.maxFileBytes});if(r+=o.size,r>Zt.maxTotalBytes)throw new Error("Native proposed specs exceed the total byte budget");n[a]=o.text}return n}function GD(e){return`Native verification receipt binding is invalid: ${e.detail}. Re-issue the affected receipts with \`comet native receipt refresh ${e.change} --apply\`.`}function lE(e){return e.confirmed!==void 0||e.artifacts!==void 0||e.noCodeReason!==void 0||e.allowPartialScopeHash!==void 0||e.partialReason!==void 0||e.verificationResult!==void 0||e.verificationReport!==void 0||e.repairOverrideSignature!==void 0||e.repairOverrideSummary!==void 0}function Op(e){return e.reasonCode==="override-already-used"?{code:"repair-override-exhausted",message:`Native repair already used its override for signature: ${e.signatureHash}`}:e.disposition==="warn"?{code:"repair-stagnation-warning",message:`Native repair repeated the same failure signature: ${e.signatureHash}`}:e.disposition==="manual-stop"?{code:"repair-stagnation-stop",message:`Native repair stopped after repeated failure signature: ${e.signatureHash}`}:{code:"repair-iteration-limit",message:`Native repair reached its total iteration limit at signature: ${e.signatureHash}`}}function sE(e){let t=ni({paths:e.paths,state:e.state,findings:e.preparation.findingCodes.map(i=>{if(i==="verification-receipt-binding-mismatch"&&e.preparation.receiptBindingFailures&&e.preparation.receiptBindingFailures.length>0){let n=e.preparation.receiptBindingFailures.map(r=>`${r.acceptanceId?`${r.ref}[${r.acceptanceId}]`:r.ref} -> ${r.mismatches.join("; ")}`).join(" | ");return{code:i,message:GD({change:e.state.name,detail:n})}}return{code:i,message:`Native verification evidence is not current: ${i}`}})});return{change:e.state,previousPhase:e.previousPhase,next:"manual",nextCommand:null,findings:t,continuation:Me({state:e.state,findings:t,clarificationMode:e.clarificationMode})}}function UD(e){if(Mn(e.summary,"Native transition summary"),e.noCodeReason!==void 0&&Mn(e.noCodeReason,"Native transition no-code reason"),e.repairOverrideSignature!==void 0&&!/^[a-f0-9]{64}$/u.test(e.repairOverrideSignature))throw new Error("Native repair override signature must be a SHA-256 hash");e.repairOverrideSummary!==void 0&&zl(e.repairOverrideSummary)}function KD(e){return{...e,summary:ke(e.summary),...e.noCodeReason===void 0?{}:{noCodeReason:ke(e.noCodeReason)},...e.partialReason===void 0?{}:{partialReason:ke(e.partialReason)},...e.repairOverrideSummary===void 0?{}:{repairOverrideSummary:ke(e.repairOverrideSummary)}}}function YD(e,t){let i=t.repairOverrideSignature!==void 0,n=t.repairOverrideSummary!==void 0;if(i!==n)throw new Error("Native repair override signature and summary must be provided together");if((i||n)&&e.phase!=="build")throw new Error("Native repair override is only valid while leaving Build")}async function cE(e){if(lE(e.transition.evidence))throw new Error("Native evidence retreat only accepts a transition summary");let t=e.state.phase;if(t!=="verify"&&t!=="archive"||e.run.currentStep!==t||e.run.pending!==null)throw new Error("Native Verify/Archive Run cannot retreat evidence safely");if(t==="archive"?["complete","partial"].includes((await br({paths:e.transition.paths,state:e.state,now:e.transition.now})).freshness):(await ms({paths:e.transition.paths,state:e.state,now:e.transition.now})).freshness==="fresh"){let c=ni({paths:e.transition.paths,state:e.state,findings:[t==="archive"?{code:"archive-command-required",message:"Current verification evidence is fresh; use Native Archive preview"}:{code:"verification-result-missing",message:"Current implementation scope is fresh; complete Verify with a result and report"}]});return{change:e.state,previousPhase:t,next:"manual",nextCommand:t==="archive"?`comet native archive ${e.state.name} --dry-run`:null,findings:c,continuation:Me({state:e.state,archiveReady:t==="archive",clarificationMode:e.transition.clarificationMode})}}let n={...e.state,revision:e.state.revision+1,phase:"build",verification_result:"pending",verification_report:null,implementation_scope:null,verification_evidence:null,partial_allowance:null},r={...e.run,currentStep:"build",iteration:e.run.iteration+1,pending:null,status:"running"},a={previousPhase:t,nextPhase:"build",evidenceHash:e.evidenceHash,summary:e.transition.evidence.summary,artifacts:[],noCodeReason:null,verificationResult:null},o=await ss({paths:e.transition.paths,previousState:e.state,nextState:n,previousRun:e.run,nextRun:r,evidenceHash:e.evidenceHash,eventData:a,operation:"evidence-retreat",now:e.transition.now,transitionId:e.transition.transitionId});await e.transition.hooks?.afterPrepared?.(o);let s=await ki(e.transition.paths,e.state.name,e.transition.hooks);if(!s)throw new Error("Native evidence retreat journal disappeared before completion");return{change:s,previousPhase:t,next:"auto",nextCommand:null,findings:[],continuation:Me({state:s,clarificationMode:e.transition.clarificationMode})}}async function uE(e){let t={...e,maxVerifyFailures:e.maxVerifyFailures??zg,evidence:KD(e.evidence)};return UD(t.evidence),te(e.paths,`advance ${e.name}`,()=>De(e.paths,e.name,`advance ${e.name}`,()=>XD(t)))}async function XD(e){await Rt(e.paths,e.name);let t=await G(e.paths,e.name),i=t.phase,n=C(e.paths,e.name),r=Kl(e.evidence),a=await be(n);if(a){let E=(await qe(n,a.trajectoryRef)).at(-1);if(E?.type==="state_transitioned"&&E.data.evidenceHash===r&&E.data.nextPhase===t.phase&&(E.data.previousPhase==="verify"?["complete","partial"].includes((await br({paths:e.paths,state:t,now:e.now})).freshness):!0)){let B=Object.hasOwn(E.data,"repairStagnation")?await Qk(e.paths,t,e.maxVerifyFailures):null,q=B&&B.disposition!=="continue"?ni({paths:e.paths,state:t,findings:[Op(B)]}):[],U=B?.disposition==="manual-stop"||B?.disposition==="hard-stop";return{change:t,previousPhase:E.data.previousPhase??t.phase,next:U?"manual":"auto",nextCommand:U?null:t.phase==="archive"?`comet native archive ${t.name} --dry-run`:null,findings:q,continuation:Me({state:t,findings:q,archiveReady:t.phase==="archive"&&t.verification_result==="pass",clarificationMode:e.clarificationMode}),...B?{repair:B}:{}}}}if(t.phase==="archive"){if(!a)throw new Error("Native Archive Run state is missing");return cE({transition:e,state:t,run:a,evidenceHash:r})}if(t.phase==="verify"&&!lE(e.evidence)){if(!a)throw new Error("Native Verify Run state is missing");if((await ms({paths:e.paths,state:t,now:e.now})).freshness!=="fresh")return cE({transition:e,state:t,run:a,evidenceHash:r})}let o={...t,spec_changes:await nE(e.paths,t)};YD(t,e.evidence);let s=await YS({paths:e.paths,state:o,evidence:e.evidence,clarificationMode:e.clarificationMode});if(!s.valid){let g=ni({paths:e.paths,state:t,findings:s.findings});return{change:t,previousPhase:i,next:"manual",nextCommand:null,findings:g,continuation:Me({state:t,findings:g,clarificationMode:e.clarificationMode})}}let c=t.phase==="shape"?await Et({changeDir:n,briefRef:o.brief,specChanges:o.spec_changes}):null;if(t.phase!=="build"&&(e.evidence.allowPartialScopeHash!==void 0||e.evidence.partialReason!==void 0))throw new Error("Native partial scope allowance is only valid while leaving Build");let l=t.phase==="build"?await ZS({paths:e.paths,state:o,artifactRefs:e.evidence.artifacts??[],noCodeReason:e.evidence.noCodeReason??null,allowPartialScopeHash:e.evidence.allowPartialScopeHash??null,partialReason:e.evidence.partialReason??null,confirmedSummary:e.evidence.summary,confirmed:e.evidence.confirmed??!1,now:e.now}):null;if(l&&(t.approved_contract_hash??null)!==l.contract.contract.contractHash&&!e.evidence.confirmed){let g=ni({paths:e.paths,state:t,findings:[{code:"contract-changed-after-approval",message:"Native contract changed after approval; re-confirm the current contract before leaving Build"}]});return{change:t,previousPhase:i,next:"manual",nextCommand:null,findings:g,continuation:Me({state:t,findings:g,clarificationMode:e.clarificationMode})}}let u=l?{scopeHash:l.bundle.scope.scopeHash,scopeRef:l.scopeRef,complete:l.bundle.scope.complete,unresolvedScopeCount:l.unresolvedScopes.length,partialAllowanceRef:l.allowanceRef,acceptancePage:Zl({criteria:l.contract.contract.acceptance,acceptanceHash:l.contract.contract.acceptanceHash})}:void 0;if(l&&l.findings.length>0){await Au({paths:e.paths,state:t,preparation:l,includeAllowance:!1});let g=ni({paths:e.paths,state:t,findings:l.findings});return{change:t,previousPhase:i,next:"manual",nextCommand:null,findings:g,continuation:Me({state:t,findings:g,clarificationMode:e.clarificationMode}),preparedScope:u}}let d=null,f=l?ya(l.bundle):null;if(t.phase==="build"&&l){let g=await tS({paths:e.paths,state:t,currentImplementationScope:l.bundle,maxVerifyFailures:e.maxVerifyFailures,...e.evidence.repairOverrideSignature&&e.evidence.repairOverrideSummary?{override:{expectedSignatureHash:e.evidence.repairOverrideSignature,summary:e.evidence.repairOverrideSummary}}:{}});if(g.disposition!=="proceed"){await Au({paths:e.paths,state:t,preparation:l,includeAllowance:!1});let E=ni({paths:e.paths,state:t,findings:[g.disposition==="hard-stop"&&g.overrideRecorded?{code:"repair-override-exhausted",message:`Native repair already used its override for signature: ${g.signatureHash}`}:Op({disposition:g.disposition,reasonCode:g.disposition==="hard-stop"?"repair-iteration-limit":"repeated-failure-stop",signatureHash:g.signatureHash})]});return{change:t,previousPhase:i,next:"manual",nextCommand:null,findings:E,continuation:Me({state:t,findings:E,clarificationMode:e.clarificationMode}),preparedScope:u&&{...u,partialAllowanceRef:null}}}d=g.eventProjection}let h=t.phase==="verify"?await rp({paths:e.paths,state:o,result:e.evidence.verificationResult,reportRef:e.evidence.verificationReport,receiptRef:null,requireReceipt:!1,preflightOnly:e.evidence.verificationResult==="pass",now:e.now}):null;if(h&&!h.ready)return sE({paths:e.paths,state:t,previousPhase:i,clarificationMode:e.clarificationMode,preparation:h});if(t.phase==="verify"&&e.evidence.verificationResult==="pass"){let g=(await vp({paths:e.paths,name:t.name})).ref;h=await rp({paths:e.paths,state:o,result:e.evidence.verificationResult,reportRef:e.evidence.verificationReport,receiptRef:g,preflight:h?.preflight,now:e.now})}if(h&&!h.ready)return sE({paths:e.paths,state:t,previousPhase:i,clarificationMode:e.clarificationMode,preparation:h});let m=null;if(t.phase==="verify"&&e.evidence.verificationResult==="fail"&&h?.ready&&h.envelope){let g=await eS({paths:e.paths,state:t,envelope:h.envelope,maxVerifyFailures:e.maxVerifyFailures});d=g.eventProjection,f=g.facts.implementationScopeHash,m=Zk(g)}let p=a;if(!p){if(t.run_id!==null||t.phase!=="shape")throw new Error("Native Run state is missing or inconsistent");p=Uw(mt,e.runId?.()??zD(),vr)}if(p.currentStep!==t.phase)throw new Error(`Native Run step ${p.currentStep??"(none)"} does not match ${t.phase}`);let v=_s(mt,p,new Set,Na,void 0);if(!v.action)throw new Error(v.reason??"Native runtime produced no action");let S=Is(mt,v.state,{actionId:v.action.id,status:"succeeded",summary:e.evidence.summary,state:e.evidence.verificationResult?{verification_result:e.evidence.verificationResult}:void 0},Na,void 0);if(!S.currentStep)throw new Error("Archive completion must use the archive command");let k={...o,revision:t.revision+1,phase:S.currentStep,approval:e.evidence.confirmed?"confirmed":t.approval,approved_contract_hash:t.phase==="shape"?c.contract.contractHash:t.phase==="build"&&e.evidence.confirmed?l.contract.contract.contractHash:t.approved_contract_hash??null,run_id:p.runId,...t.phase==="build"?{verification_result:"pending",verification_report:null,implementation_scope:l.scopeRef,partial_allowance:l.allowanceRef,verification_evidence:null}:{},...t.phase==="verify"?{verification_result:e.evidence.verificationResult,verification_report:h.envelope.reportRef,verification_evidence:h.evidenceRef}:{}},N={previousPhase:i,nextPhase:k.phase,evidenceHash:r,summary:e.evidence.summary,artifacts:e.evidence.artifacts??[],noCodeReason:e.evidence.noCodeReason??null,verificationResult:e.evidence.verificationResult??null,...(t.phase==="build"||t.phase==="verify")&&(t.phase==="build"?l.bundle.scope.scopeHash:h.envelope.implementationScopeHash)?{implementationScopeHash:t.phase==="build"?l.bundle.scope.scopeHash:h.envelope.implementationScopeHash}:{},...f?{repairScopeHash:f}:{},...d?{repairStagnation:d}:{}};t.phase==="build"&&l&&await Au({paths:e.paths,state:t,preparation:l}),t.phase==="verify"&&h&&await ek({paths:e.paths,state:t,preparation:h});let b=await ss({paths:e.paths,previousState:t,nextState:k,previousRun:a,nextRun:S,evidenceHash:r,eventData:N,now:e.now,transitionId:e.transitionId});await e.hooks?.afterPrepared?.(b);let R=await ki(e.paths,e.name,e.hooks);if(!R)throw new Error("Native transition journal disappeared before completion");let y=m&&m.disposition!=="continue"?ni({paths:e.paths,state:R,findings:[Op(m)]}):[],w=m?.disposition==="manual-stop"||m?.disposition==="hard-stop";return{change:R,previousPhase:i,next:w?"manual":"auto",nextCommand:w?null:R.phase==="archive"?`comet native archive ${R.name} --dry-run`:null,findings:y,continuation:Me({state:R,findings:y,archiveReady:R.phase==="archive"&&R.verification_result==="pass",clarificationMode:e.clarificationMode}),...u?{preparedScope:u}:{},...m?{repair:m}:{}}}async function dE(e,t){let i=ae(e,"change name"),n=J(e,"--summary");if(!n)throw new I("--summary is required");let r=gt(e,"--confirmed"),a=Yi(e,"--artifact"),o=J(e,"--no-code-reason"),s=J(e,"--allow-partial-scope"),c=J(e,"--partial-reason"),l=J(e,"--result"),u=J(e,"--report"),d=J(e,"--override-repair"),f=J(e,"--override-summary");if(l!==void 0&&l!=="pass"&&l!=="fail")throw new I("--result must be pass or fail");if(s===void 0!=(c===void 0))throw new I("--allow-partial-scope and --partial-reason must be provided together");if(s&&!/^[a-f0-9]{64}$/u.test(s))throw new I("--allow-partial-scope must be a SHA-256 hash");if(s&&!r)throw new I("--allow-partial-scope requires --confirmed");if(d===void 0!=(f===void 0))throw new I("--override-repair and --override-summary must be provided together");if(d&&!/^[a-f0-9]{64}$/u.test(d))throw new I("--override-repair must be a SHA-256 hash");if(d&&l!==void 0)throw new I("--override-repair cannot be combined with --result");Y(e);let{config:h,paths:m}=await Oe(t),p={summary:n,...r?{confirmed:!0}:{},...a.length>0?{artifacts:a}:{},...o?{noCodeReason:o}:{},...s?{allowPartialScopeHash:s}:{},...c?{partialReason:c}:{},...l?{verificationResult:l}:{},...u?{verificationReport:u}:{},...d?{repairOverrideSignature:d}:{},...f?{repairOverrideSummary:f}:{}},v=await uE({paths:m,name:i,evidence:p,clarificationMode:h.native.clarification_mode,maxVerifyFailures:h.native.max_verify_failures});if(v.next==="manual"){let k=v.repair?.disposition==="manual-stop"||v.repair?.disposition==="hard-stop"||v.findings.some(N=>["repair-stagnation-stop","repair-iteration-limit","repair-override-exhausted"].includes(N.code));return{command:"next",exitCode:k?75:65,data:v,error:{code:k?"blocked":"invalid-data",message:v.findings[0]?.message??"Native phase guard failed"}}}let S=await Ze(m,i,{clarificationMode:h.native.clarification_mode,maxVerifyFailures:h.native.max_verify_failures});return Z("next",{...v,continuation:S.continuation})}import QD from"node:path";var ZD="Native receipt re-issued after revision bump";function eM(e){return!e.ok&&e.mismatches.length===1&&e.mismatches[0]?.startsWith("sourceRevision: ")===!0}function tM(e){return e.kind!=="automated-check"?"":[e.evidence.executable,...e.evidence.args].map(i=>/\s/u.test(i)?JSON.stringify(i):i).join(" ")}function iM(e){return`${ZD} to revision ${e}`}function nM(){return"Manual evidence re-issued via `comet native receipt refresh` to restore revision binding."}async function fE(e){let t=await G(e.paths,e.name);if(t.phase!=="verify")throw new Error(`Native receipt refresh requires Verify, got ${t.phase} for ${e.name}`);let i=t.implementation_scope?await Nr(e.paths,t):null;if(i&&await cu({paths:e.paths,state:t,context:i}),!t.verification_evidence)return{refreshed:[],requiresRerun:[],requiresManual:[],requiresCheck:[],applied:!1,verificationReport:null};if(!i)throw new Error("Native receipt refresh requires an implementation scope");let n=await Dn(e.paths,e.name,t.verification_evidence),r=[],a=[],o=[],s=[],c=new Set,l=[...new Set([...n.requiredReceiptRefs,...n.receiptRefs])];for(let R of l){let y=await Hn(e.paths,e.name,R),w=ps(y,i.bindings);if(!w.ok)if(c.add(R),y.kind==="manual-evidence"){let g={oldRef:R,acceptanceIds:[...y.acceptanceIds]};eM(w)?r.push(g):a.push({...g,mismatches:w.mismatches})}else y.kind==="automated-check"?o.push({oldRef:R,acceptanceIds:[...y.acceptanceIds],command:tM(y),timeoutMs:y.evidence.timeoutMs}):y.kind==="static-inspection"&&s.push({oldRef:R})}if(!(e.apply&&o.length===0&&a.length===0&&r.length>0))return{refreshed:[],requiresRerun:o,requiresManual:a,requiresCheck:s,applied:!1,verificationReport:t.verification_report};let d=[],f=new Map,h=new Map;for(let R of r){let y=[...R.acceptanceIds].sort().join(` `),w=h.get(y);w?w.push(R.oldRef):h.set(y,[R.oldRef])}for(let[R,y]of h){let w=R.split(` `),g=await su({paths:e.paths,name:e.name,acceptanceIds:w,steps:[iM(t.revision)],observations:[nM()]});for(let E of w)f.set(E,g.ref);for(let E of y){let O=r.find(B=>B.oldRef===E)?.acceptanceIds[0];O&&d.push({acceptanceId:O,oldRef:E,newRef:g.ref})}}let m=t.verification_report;if(!m)throw new Error(`Native receipt refresh cannot rewrite verification report: ${e.name} has no report ref`);let p=C(e.paths,e.name),v=await ye({root:p,ref:m}),S=eu(v.text),k=rM(n.acceptanceTrace.entries,S,c,f),N=tu(k),b=aM(v.text,N);return await $e(QD.join(p,...m.split("/")),b),{refreshed:d,requiresRerun:[],requiresManual:[],requiresCheck:s,applied:!0,verificationReport:m}}function rM(e,t,i,n){let r=new Map;for(let o of t)r.set(o.acceptance_id,o);let a=[];for(let o of e){let s=r.get(o.acceptanceId);if(!s)continue;if(o.status==="failed"){a.push(s);continue}let c=s.evidence_refs.filter(f=>!i.has(f)),l=n.get(o.acceptanceId),u=l!==void 0?[...c,l]:c;if(u.length===0){a.push(s);continue}let d={acceptance_id:s.acceptance_id,status:s.status,evidence_refs:[...new Set(u)].sort()};s.skipped_reason!==void 0&&(d.skipped_reason=s.skipped_reason),a.push(d)}return a}function aM(e,t){let i=e.indexOf(cs);if(i<0)throw new Error("Native verification report is missing the acceptance-evidence start marker");let n=e.indexOf(ba,i);if(n<0)throw new Error("Native verification report is missing the acceptance-evidence end marker");let r=e.slice(0,i),a=e.slice(n+ba.length);return`${r}${t}${a}`}async function hE(e,t){let i=ae(e,"receipt subcommand"),n=ae(e,"change name"),{paths:r}=await Oe(t);if(i==="manual"){let a=Yi(e,"--acceptance"),o=Yi(e,"--step"),s=Yi(e,"--observation");Y(e);let c=await su({paths:r,name:n,acceptanceIds:a,steps:o,observations:s});return Z("receipt manual",c,`Native manual receipt: ${c.ref} -`)}if(i==="automated"){let a=e.indexOf("--");if(a<0||a===e.length-1)throw new I("receipt automated requires -- [args...]");let o=e.splice(a+1);e.splice(a,1);let s=Yi(e,"--acceptance"),c=J(e,"--timeout-ms");Y(e);let l=c===void 0?void 0:/^[1-9]\d*$/u.test(c)&&Number.isSafeInteger(Number(c))&&Number(c)<=hs?Number(c):null;if(l===null)throw new I(`--timeout-ms must be an integer from 1 through ${hs}`);let u=await Ub({paths:r,name:n,acceptanceIds:s,command:o[0],args:o.slice(1),...l===void 0?{}:{timeoutMs:l}}),d=[`Native automated receipt ${u.receipt.status}: ${u.ref}`];if(u.recovery){let f=u.recovery.changedPaths.map(h=>` ${h.kind}: ${h.path}`).join(` +`)}if(i==="automated"){let a=e.indexOf("--");if(a<0||a===e.length-1)throw new I("receipt automated requires -- [args...]");let o=e.splice(a+1);e.splice(a,1);let s=Yi(e,"--acceptance"),c=J(e,"--timeout-ms");Y(e);let l=c===void 0?void 0:/^[1-9]\d*$/u.test(c)&&Number.isSafeInteger(Number(c))&&Number(c)<=hs?Number(c):null;if(l===null)throw new I(`--timeout-ms must be an integer from 1 through ${hs}`);let u=await Kb({paths:r,name:n,acceptanceIds:s,command:o[0],args:o.slice(1),...l===void 0?{}:{timeoutMs:l}}),d=[`Native automated receipt ${u.receipt.status}: ${u.ref}`];if(u.recovery){let f=u.recovery.changedPaths.map(h=>` ${h.kind}: ${h.path}`).join(` `);d.push("Implementation changed while the verification command was running."),f&&d.push(f),u.recovery.changedPathsTruncated&&d.push(` ... ${u.recovery.changedPathCount-u.recovery.changedPaths.length} more path(s)`),d.push(`Recover with: ${u.recovery.nextCommand}`)}return{command:"receipt automated",exitCode:u.receipt.status==="passed"?0:1,data:u,text:`${d.join(` `)} `}}if(i==="refresh"){let a=gt(e,"--apply"),o=gt(e,"--dry-run");if(Y(e),a&&o)throw new I("receipt refresh --apply and --dry-run cannot be combined");let s=await fE({paths:r,name:n,apply:a}),c=[];if(s.refreshed.length>0){c.push(`Re-issued ${s.refreshed.length} manual receipt(s) at the current revision:`);for(let l of s.refreshed)c.push(` ${l.acceptanceId}: ${l.oldRef} -> ${l.newRef}`)}if(s.requiresRerun.length>0){c.push(`Re-run ${s.requiresRerun.length} stale automated receipt(s) (they cannot be re-issued without a real execution):`);for(let l of s.requiresRerun){let u=l.acceptanceIds.join(", ");c.push(` [${u}] ${l.command}`)}}if(s.requiresManual.length>0){c.push(`Re-run manual verification for ${s.requiresManual.length} receipt(s); contract, scope, snapshot, or artifact bindings changed:`);for(let l of s.requiresManual)c.push(` [${l.acceptanceIds.join(", ")}] ${l.mismatches.join("; ")}`)}return s.requiresCheck.length>0&&c.push(`Re-run \`comet native check ${n}\` to refresh ${s.requiresCheck.length} required-check receipt(s).`),s.applied?c.push(`Updated acceptance evidence in ${s.verificationReport}.`):s.refreshed.length===0&&s.requiresRerun.length===0&&s.requiresManual.length===0&&s.requiresCheck.length===0?c.push("No stale receipts found."):a?s.requiresManual.length>0&&c.push("Fresh manual verification is required before these receipts can be refreshed."):c.push("Dry run only. Re-run with --apply to re-issue manual receipts."),Z("receipt refresh",s,`${c.join(` `)} -`)}throw new I(`Unknown receipt command: ${i}`)}async function pE(e,t){let i=ae(e,"root subcommand");if(i==="show"){Y(e);let n=await re(t);if(!n)throw new Error(".comet/config.yaml was not found");let r=await Ne(t,n.native.artifact_root);return Z("root show",{projectRoot:t,artifactRoot:n.native.artifact_root,language:n.native.language,nativeRoot:r.nativeRoot,pendingRootMove:n.native.pending_root_move??null})}if(i==="move"){let n=ae(e,"artifact root");Y(e);let r=await _S({projectRoot:t,toArtifactRoot:n});return Z("root move",r,`Moved Comet Native to ${r.toNativeRoot} +`)}throw new I(`Unknown receipt command: ${i}`)}async function pE(e,t){let i=ae(e,"root subcommand");if(i==="show"){Y(e);let n=await re(t);if(!n)throw new Error(".comet/config.yaml was not found");let r=await Ne(t,n.native.artifact_root);return Z("root show",{projectRoot:t,artifactRoot:n.native.artifact_root,language:n.native.language,nativeRoot:r.nativeRoot,pendingRootMove:n.native.pending_root_move??null})}if(i==="move"){let n=ae(e,"artifact root");Y(e);let r=await IS({projectRoot:t,toArtifactRoot:n});return Z("root move",r,`Moved Comet Native to ${r.toNativeRoot} `)}throw new I(`Unknown root command: ${i}`)}async function mE(e,t){let i=ae(e,"change name");Y(e);let{config:n,paths:r}=await Oe(t);await hu(r,i);let a=await Ze(r,i,{clarificationMode:n.native.clarification_mode,maxVerifyFailures:n.native.max_verify_failures});return Z("select",{selected:i,continuation:a.continuation},`Selected Native change ${i} -`)}async function vE(e,t){let i=ae(e,"change name");Y(e);let{paths:n}=await Oe(t),r=await ft(n,i);if(r.status==="migration-required")return Z("show",{name:i,schema:r.schema,minimumRuntimeVersion:r.minimumRuntimeVersion,migrationRequired:!0,message:r.message});if(r.status!=="current"||!r.state)throw new Hi(r.schema,r.minimumRuntimeVersion);let a=r.state,o=C(n,i),s=await oE(n,i),c=await ye({root:o,ref:a.brief,maxBytes:Zt.maxFileBytes}),l={state:a,brief:c.text,proposedSpecs:s};if(Buffer.byteLength(JSON.stringify(l),"utf8")>xk)throw new Error("Native show output exceeds its serialized byte budget");return Z("show",l)}async function gE(e,t){let i=ae(e,"spec subcommand");if(i==="remove"){let n=ae(e,"change name"),r=ae(e,"capability");Y(e);let{config:a,paths:o}=await Oe(t),s=await aE(o,n,r),c=await Ze(o,s.name,{clarificationMode:a.native.clarification_mode,maxVerifyFailures:a.native.max_verify_failures});return Z("spec remove",{...s,continuation:c.continuation},`Marked Native capability ${r} for removal in ${n} +`)}async function vE(e,t){let i=ae(e,"change name");Y(e);let{paths:n}=await Oe(t),r=await ft(n,i);if(r.status==="migration-required")return Z("show",{name:i,schema:r.schema,minimumRuntimeVersion:r.minimumRuntimeVersion,migrationRequired:!0,message:r.message});if(r.status!=="current"||!r.state)throw new Hi(r.schema,r.minimumRuntimeVersion);let a=r.state,o=C(n,i),s=await oE(n,i),c=await ye({root:o,ref:a.brief,maxBytes:Zt.maxFileBytes}),l={state:a,brief:c.text,proposedSpecs:s};if(Buffer.byteLength(JSON.stringify(l),"utf8")>Ak)throw new Error("Native show output exceeds its serialized byte budget");return Z("show",l)}async function gE(e,t){let i=ae(e,"spec subcommand");if(i==="remove"){let n=ae(e,"change name"),r=ae(e,"capability");Y(e);let{config:a,paths:o}=await Oe(t),s=await aE(o,n,r),c=await Ze(o,s.name,{clarificationMode:a.native.clarification_mode,maxVerifyFailures:a.native.max_verify_failures});return Z("spec remove",{...s,continuation:c.continuation},`Marked Native capability ${r} for removal in ${n} `)}if(i==="rebase"){let n=ae(e,"change name"),r=J(e,"--summary");if(!r)throw new I("--summary is required");Y(e);let{config:a,paths:o}=await Oe(t),s=await rE({paths:o,name:n,summary:r}),c=await Ze(o,s.name,{clarificationMode:a.native.clarification_mode,maxVerifyFailures:a.native.max_verify_failures});return Z("spec rebase",{...s,continuation:c.continuation},`Rebased Native specs for ${n} -`)}throw new I(`Unknown spec command: ${i}`)}async function wE(e,t){let i=gt(e,"--details"),n=J(e,"--cursor"),r=J(e,"--acceptance-cursor"),a=e[0]?.startsWith("--")?void 0:e.shift();if(i&&!a)throw new I("status --details requires a change name");if(n&&a)throw new I("--cursor is only valid for status lists");if(n&&i)throw new I("--cursor cannot be combined with --details");if(r&&!i)throw new I("--acceptance-cursor requires status --details");if(r&&!a)throw new I("--acceptance-cursor requires a change name");Y(e);let{config:o,paths:s}=await Oe(t),c=a?await Ze(s,a,{details:i,...r?{acceptanceCursor:r}:{},clarificationMode:o.native.clarification_mode,maxVerifyFailures:o.native.max_verify_failures}):await yp(s,{...n?{cursor:n}:{},clarificationMode:o.native.clarification_mode,maxVerifyFailures:o.native.max_verify_failures});return Z("status",c)}var oM={"hook-guard":zS,init:GS,root:pE,new:US,spec:gE,show:vE,status:wE,select:mE,checkpoint:oS,check:qk,evidence:$S,receipt:hE,next:dE,archive:$k,doctor:OS};async function sM(e,t){if(e.length===0||e[0]==="--help"||e[0]==="help")return{command:e[0]??null,exitCode:0,data:{usage:hp},text:hp};let i=e.shift(),n=await Tk(t),r=oM[i];if(!r)throw new I(`Unknown Native command: ${i}`);return r(e,n)}async function yE(e){let t=[...e],i=t.indexOf("--"),n=i<0?t:t.slice(0,i),r=i<0?[]:t.slice(i),a=n.includes("--json"),o,s=n[0]??null;try{gt(n,"--json"),o=J(n,"--project-root");let c=[...n,...r];return s=c[0]??null,pp(await sM(c,o),a)}catch(c){return pp(Ok(s,c),a)}}async function lM(e=process.argv.slice(2)){let t=await yE(e);return t.stdout&&process.stdout.write(t.stdout),t.stderr&&process.stderr.write(t.stderr+(t.stderr.endsWith(` +`)}throw new I(`Unknown spec command: ${i}`)}async function wE(e,t){let i=gt(e,"--details"),n=J(e,"--cursor"),r=J(e,"--acceptance-cursor"),a=e[0]?.startsWith("--")?void 0:e.shift();if(i&&!a)throw new I("status --details requires a change name");if(n&&a)throw new I("--cursor is only valid for status lists");if(n&&i)throw new I("--cursor cannot be combined with --details");if(r&&!i)throw new I("--acceptance-cursor requires status --details");if(r&&!a)throw new I("--acceptance-cursor requires a change name");Y(e);let{config:o,paths:s}=await Oe(t),c=a?await Ze(s,a,{details:i,...r?{acceptanceCursor:r}:{},clarificationMode:o.native.clarification_mode,maxVerifyFailures:o.native.max_verify_failures}):await yp(s,{...n?{cursor:n}:{},clarificationMode:o.native.clarification_mode,maxVerifyFailures:o.native.max_verify_failures});return Z("status",c)}var oM={"hook-guard":zS,init:GS,root:pE,new:US,spec:gE,show:vE,status:wE,select:mE,checkpoint:sS,check:Vk,evidence:HS,receipt:hE,next:dE,archive:Hk,doctor:$S};async function sM(e,t){if(e.length===0||e[0]==="--help"||e[0]==="help")return{command:e[0]??null,exitCode:0,data:{usage:hp},text:hp};let i=e.shift(),n=await _k(t),r=oM[i];if(!r)throw new I(`Unknown Native command: ${i}`);return r(e,n)}async function yE(e){let t=[...e],i=t.indexOf("--"),n=i<0?t:t.slice(0,i),r=i<0?[]:t.slice(i),a=n.includes("--json"),o,s=n[0]??null;try{gt(n,"--json"),o=J(n,"--project-root");let c=[...n,...r];return s=c[0]??null,pp(await sM(c,o),a)}catch(c){return pp($k(s,c),a)}}async function lM(e=process.argv.slice(2)){let t=await yE(e);return t.stdout&&process.stdout.write(t.stdout),t.stderr&&process.stderr.write(t.stderr+(t.stderr.endsWith(` `)?"":` `)),t.exitCode}var NE=process.argv[1];NE&&import.meta.url===cM(NE).href&&lM().then(e=>{process.exitCode=e});export{lM as main}; diff --git a/assets/skills/comet/scripts/comet-archive.mjs b/assets/skills/comet/scripts/comet-archive.mjs index 094d79fe7..92abe4760 100644 --- a/assets/skills/comet/scripts/comet-archive.mjs +++ b/assets/skills/comet/scripts/comet-archive.mjs @@ -1,40 +1,40 @@ #!/usr/bin/env node import { createRequire as __cometCreateRequire } from 'module'; const require = __cometCreateRequire(import.meta.url); -var Wu=Object.create;var sr=Object.defineProperty;var Bu=Object.getOwnPropertyDescriptor;var Ku=Object.getOwnPropertyNames;var Yu=Object.getPrototypeOf,Uu=Object.prototype.hasOwnProperty;var kn=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var K=(t,e,n)=>()=>{if(n)throw n[0];try{return t&&(e=t(t=0)),e}catch(i){throw n=[i],i}};var v=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(n){throw e=0,n}},Ju=(t,e)=>{for(var n in e)sr(t,n,{get:e[n],enumerable:!0})},Vu=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Ku(e))!Uu.call(t,r)&&r!==n&&sr(t,r,{get:()=>e[r],enumerable:!(i=Bu(e,r))||i.enumerable});return t};var nt=(t,e,n)=>(n=t!=null?Wu(Yu(t)):{},Vu(e||!t||!t.__esModule?sr(n,"default",{value:t,enumerable:!0}):n,t));var _=v(M=>{"use strict";var or=Symbol.for("yaml.alias"),Po=Symbol.for("yaml.document"),Sn=Symbol.for("yaml.map"),Ro=Symbol.for("yaml.pair"),ar=Symbol.for("yaml.scalar"),Cn=Symbol.for("yaml.seq"),he=Symbol.for("yaml.node.type"),Qu=t=>!!t&&typeof t=="object"&&t[he]===or,Xu=t=>!!t&&typeof t=="object"&&t[he]===Po,Zu=t=>!!t&&typeof t=="object"&&t[he]===Sn,ef=t=>!!t&&typeof t=="object"&&t[he]===Ro,Oo=t=>!!t&&typeof t=="object"&&t[he]===ar,tf=t=>!!t&&typeof t=="object"&&t[he]===Cn;function Ao(t){if(t&&typeof t=="object")switch(t[he]){case Sn:case Cn:return!0}return!1}function nf(t){if(t&&typeof t=="object")switch(t[he]){case or:case Sn:case ar:case Cn:return!0}return!1}var rf=t=>(Oo(t)||Ao(t))&&!!t.anchor;M.ALIAS=or;M.DOC=Po;M.MAP=Sn;M.NODE_TYPE=he;M.PAIR=Ro;M.SCALAR=ar;M.SEQ=Cn;M.hasAnchor=rf;M.isAlias=Qu;M.isCollection=Ao;M.isDocument=Xu;M.isMap=Zu;M.isNode=nf;M.isPair=ef;M.isScalar=Oo;M.isSeq=tf});var St=v(cr=>{"use strict";var L=_(),J=Symbol("break visit"),No=Symbol("skip children"),le=Symbol("remove node");function En(t,e){let n=To(e);L.isDocument(t)?it(null,t.contents,n,Object.freeze([t]))===le&&(t.contents=null):it(null,t,n,Object.freeze([]))}En.BREAK=J;En.SKIP=No;En.REMOVE=le;function it(t,e,n,i){let r=jo(t,e,n,i);if(L.isNode(r)||L.isPair(r))return Io(t,i,r),it(t,r,n,i);if(typeof r!="symbol"){if(L.isCollection(e)){i=Object.freeze(i.concat(e));for(let s=0;s{"use strict";var qo=_(),sf=St(),of={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},af=t=>t.replace(/[!,[\]{}]/g,e=>of[e]),Ct=class t{constructor(e,n){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},t.defaultYaml,e),this.tags=Object.assign({},t.defaultTags,n)}clone(){let e=new t(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){let e=new t(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:t.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},t.defaultTags);break}return e}add(e,n){this.atNextDocument&&(this.yaml={explicit:t.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},t.defaultTags),this.atNextDocument=!1);let i=e.trim().split(/[ \t]+/),r=i.shift();switch(r){case"%TAG":{if(i.length!==2&&(n(0,"%TAG directive should contain exactly two parts"),i.length<2))return!1;let[s,o]=i;return this.tags[s]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,i.length!==1)return n(0,"%YAML directive should contain exactly one part"),!1;let[s]=i;if(s==="1.1"||s==="1.2")return this.yaml.version=s,!0;{let o=/^\d+\.\d+$/.test(s);return n(6,`Unsupported YAML version ${s}`,o),!1}}default:return n(0,`Unknown directive ${r}`,!0),!1}}tagName(e,n){if(e==="!")return"!";if(e[0]!=="!")return n(`Not a valid tag: ${e}`),null;if(e[1]==="<"){let o=e.slice(2,-1);return o==="!"||o==="!!"?(n(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&n("Verbatim tags must end with a >"),o)}let[,i,r]=e.match(/^(.*!)([^!]*)$/s);r||n(`The ${e} tag has no suffix`);let s=this.tags[i];if(s)try{return s+decodeURIComponent(r)}catch(o){return n(String(o)),null}return i==="!"?e:(n(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[n,i]of Object.entries(this.tags))if(e.startsWith(i))return n+af(e.substring(i.length));return e[0]==="!"?e:`!<${e}>`}toString(e){let n=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],i=Object.entries(this.tags),r;if(e&&i.length>0&&qo.isNode(e.contents)){let s={};sf.visit(e.contents,(o,a)=>{qo.isNode(a)&&a.tag&&(s[a.tag]=!0)}),r=Object.keys(s)}else r=[];for(let[s,o]of i)s==="!!"&&o==="tag:yaml.org,2002:"||(!e||r.some(a=>a.startsWith(o)))&&n.push(`%TAG ${s} ${o}`);return n.join(` -`)}};Ct.defaultYaml={explicit:!1,version:"1.2"};Ct.defaultTags={"!!":"tag:yaml.org,2002:"};$o.Directives=Ct});var _n=v(Et=>{"use strict";var Lo=_(),cf=St();function lf(t){if(/[\x00-\x19\s,[\]{}]/.test(t)){let n=`Anchor must not contain whitespace or control characters: ${JSON.stringify(t)}`;throw new Error(n)}return!0}function Do(t){let e=new Set;return cf.visit(t,{Value(n,i){i.anchor&&e.add(i.anchor)}}),e}function Fo(t,e){for(let n=1;;++n){let i=`${t}${n}`;if(!e.has(i))return i}}function uf(t,e){let n=[],i=new Map,r=null;return{onAnchor:s=>{n.push(s),r??(r=Do(t));let o=Fo(e,r);return r.add(o),o},setAnchors:()=>{for(let s of n){let o=i.get(s);if(typeof o=="object"&&o.anchor&&(Lo.isScalar(o.node)||Lo.isCollection(o.node)))o.node.anchor=o.anchor;else{let a=new Error("Failed to resolve repeated object (this should not happen)");throw a.source=s,a}}},sourceObjects:i}}Et.anchorIsValid=lf;Et.anchorNames=Do;Et.createNodeAnchors=uf;Et.findNewAnchor=Fo});var ur=v(Mo=>{"use strict";function xt(t,e,n,i){if(i&&typeof i=="object")if(Array.isArray(i))for(let r=0,s=i.length;r{"use strict";var ff=_();function Wo(t,e,n){if(Array.isArray(t))return t.map((i,r)=>Wo(i,String(r),n));if(t&&typeof t.toJSON=="function"){if(!n||!ff.hasAnchor(t))return t.toJSON(e,n);let i={aliasCount:0,count:1,res:void 0};n.anchors.set(t,i),n.onCreate=s=>{i.res=s,delete n.onCreate};let r=t.toJSON(e,n);return n.onCreate&&n.onCreate(r),r}return typeof t=="bigint"&&!n?.keep?Number(t):t}Bo.toJS=Wo});var Pn=v(Yo=>{"use strict";var df=ur(),Ko=_(),pf=Ee(),fr=class{constructor(e){Object.defineProperty(this,Ko.NODE_TYPE,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:n,maxAliasCount:i,onAnchor:r,reviver:s}={}){if(!Ko.isDocument(e))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:e,keep:!0,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},a=pf.toJS(this,"",o);if(typeof r=="function")for(let{count:c,res:l}of o.anchors.values())r(l,c);return typeof s=="function"?df.applyReviver(s,{"":a},"",a):a}};Yo.NodeBase=fr});var _t=v(Uo=>{"use strict";var mf=_n(),hf=St(),st=_(),gf=Pn(),wf=Ee(),dr=class extends gf.NodeBase{constructor(e){super(st.ALIAS),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,n){if(n?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let i;n?.aliasResolveCache?i=n.aliasResolveCache:(i=[],hf.visit(e,{Node:(s,o)=>{(st.isAlias(o)||st.hasAnchor(o))&&i.push(o)}}),n&&(n.aliasResolveCache=i));let r;for(let s of i){if(s===this)break;s.anchor===this.source&&(r=s)}return r}toJSON(e,n){if(!n)return{source:this.source};let{anchors:i,doc:r,maxAliasCount:s}=n,o=this.resolve(r,n);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let a=i.get(o);if(a||(wf.toJS(o,null,n),a=i.get(o)),a?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(s>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=Rn(r,o,i)),a.count*a.aliasCount>s)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return a.res}toString(e,n,i){let r=`*${this.source}`;if(e){if(mf.anchorIsValid(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let s=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(s)}if(e.implicitKey)return`${r} `}return r}};function Rn(t,e,n){if(st.isAlias(e)){let i=e.resolve(t),r=n&&i&&n.get(i);return r?r.count*r.aliasCount:0}else if(st.isCollection(e)){let i=0;for(let r of e.items){let s=Rn(t,r,n);s>i&&(i=s)}return i}else if(st.isPair(e)){let i=Rn(t,e.key,n),r=Rn(t,e.value,n);return Math.max(i,r)}return 1}Uo.Alias=dr});var I=v(pr=>{"use strict";var yf=_(),vf=Pn(),bf=Ee(),kf=t=>!t||typeof t!="function"&&typeof t!="object",xe=class extends vf.NodeBase{constructor(e){super(yf.SCALAR),this.value=e}toJSON(e,n){return n?.keep?this.value:bf.toJS(this.value,e,n)}toString(){return String(this.value)}};xe.BLOCK_FOLDED="BLOCK_FOLDED";xe.BLOCK_LITERAL="BLOCK_LITERAL";xe.PLAIN="PLAIN";xe.QUOTE_DOUBLE="QUOTE_DOUBLE";xe.QUOTE_SINGLE="QUOTE_SINGLE";pr.Scalar=xe;pr.isScalarValue=kf});var Pt=v(Vo=>{"use strict";var Sf=_t(),Ye=_(),Jo=I(),Cf="tag:yaml.org,2002:";function Ef(t,e,n){if(e){let i=n.filter(s=>s.tag===e),r=i.find(s=>!s.format)??i[0];if(!r)throw new Error(`Tag ${e} not found`);return r}return n.find(i=>i.identify?.(t)&&!i.format)}function xf(t,e,n){if(Ye.isDocument(t)&&(t=t.contents),Ye.isNode(t))return t;if(Ye.isPair(t)){let u=n.schema[Ye.MAP].createNode?.(n.schema,null,n);return u.items.push(t),u}(t instanceof String||t instanceof Number||t instanceof Boolean||typeof BigInt<"u"&&t instanceof BigInt)&&(t=t.valueOf());let{aliasDuplicateObjects:i,onAnchor:r,onTagObj:s,schema:o,sourceObjects:a}=n,c;if(i&&t&&typeof t=="object"){if(c=a.get(t),c)return c.anchor??(c.anchor=r(t)),new Sf.Alias(c.anchor);c={anchor:null,node:null},a.set(t,c)}e?.startsWith("!!")&&(e=Cf+e.slice(2));let l=Ef(t,e,o.tags);if(!l){if(t&&typeof t.toJSON=="function"&&(t=t.toJSON()),!t||typeof t!="object"){let u=new Jo.Scalar(t);return c&&(c.node=u),u}l=t instanceof Map?o[Ye.MAP]:Symbol.iterator in Object(t)?o[Ye.SEQ]:o[Ye.MAP]}s&&(s(l),delete n.onTagObj);let f=l?.createNode?l.createNode(n.schema,t,n):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(n.schema,t,n):new Jo.Scalar(t);return e?f.tag=e:l.default||(f.tag=l.tag),c&&(c.node=f),f}Vo.createNode=xf});var An=v(On=>{"use strict";var _f=Pt(),ue=_(),Pf=Pn();function mr(t,e,n){let i=n;for(let r=e.length-1;r>=0;--r){let s=e[r];if(typeof s=="number"&&Number.isInteger(s)&&s>=0){let o=[];o[s]=i,i=o}else i=new Map([[s,i]])}return _f.createNode(i,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:t,sourceObjects:new Map})}var Ho=t=>t==null||typeof t=="object"&&!!t[Symbol.iterator]().next().done,hr=class extends Pf.NodeBase{constructor(e,n){super(e),Object.defineProperty(this,"schema",{value:n,configurable:!0,enumerable:!1,writable:!0})}clone(e){let n=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(n.schema=e),n.items=n.items.map(i=>ue.isNode(i)||ue.isPair(i)?i.clone(e):i),this.range&&(n.range=this.range.slice()),n}addIn(e,n){if(Ho(e))this.add(n);else{let[i,...r]=e,s=this.get(i,!0);if(ue.isCollection(s))s.addIn(r,n);else if(s===void 0&&this.schema)this.set(i,mr(this.schema,r,n));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${r}`)}}deleteIn(e){let[n,...i]=e;if(i.length===0)return this.delete(n);let r=this.get(n,!0);if(ue.isCollection(r))return r.deleteIn(i);throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}getIn(e,n){let[i,...r]=e,s=this.get(i,!0);return r.length===0?!n&&ue.isScalar(s)?s.value:s:ue.isCollection(s)?s.getIn(r,n):void 0}hasAllNullValues(e){return this.items.every(n=>{if(!ue.isPair(n))return!1;let i=n.value;return i==null||e&&ue.isScalar(i)&&i.value==null&&!i.commentBefore&&!i.comment&&!i.tag})}hasIn(e){let[n,...i]=e;if(i.length===0)return this.has(n);let r=this.get(n,!0);return ue.isCollection(r)?r.hasIn(i):!1}setIn(e,n){let[i,...r]=e;if(r.length===0)this.set(i,n);else{let s=this.get(i,!0);if(ue.isCollection(s))s.setIn(r,n);else if(s===void 0&&this.schema)this.set(i,mr(this.schema,r,n));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${r}`)}}};On.Collection=hr;On.collectionFromPath=mr;On.isEmptyPath=Ho});var Rt=v(Nn=>{"use strict";var Rf=t=>t.replace(/^(?!$)(?: $)?/gm,"#");function gr(t,e){return/^\n+$/.test(t)?t.substring(1):e?t.replace(/^(?! *$)/gm,e):t}var Of=(t,e,n)=>t.endsWith(` -`)?gr(n,e):n.includes(` +var Bu=Object.create;var or=Object.defineProperty;var Ku=Object.getOwnPropertyDescriptor;var Yu=Object.getOwnPropertyNames;var Uu=Object.getPrototypeOf,Ju=Object.prototype.hasOwnProperty;var kn=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var K=(t,e,n)=>()=>{if(n)throw n[0];try{return t&&(e=t(t=0)),e}catch(i){throw n=[i],i}};var v=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(n){throw e=0,n}},Vu=(t,e)=>{for(var n in e)or(t,n,{get:e[n],enumerable:!0})},Hu=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Yu(e))!Ju.call(t,r)&&r!==n&&or(t,r,{get:()=>e[r],enumerable:!(i=Ku(e,r))||i.enumerable});return t};var nt=(t,e,n)=>(n=t!=null?Bu(Uu(t)):{},Hu(e||!t||!t.__esModule?or(n,"default",{value:t,enumerable:!0}):n,t));var _=v(M=>{"use strict";var ar=Symbol.for("yaml.alias"),Po=Symbol.for("yaml.document"),Sn=Symbol.for("yaml.map"),Ro=Symbol.for("yaml.pair"),cr=Symbol.for("yaml.scalar"),Cn=Symbol.for("yaml.seq"),he=Symbol.for("yaml.node.type"),Xu=t=>!!t&&typeof t=="object"&&t[he]===ar,Zu=t=>!!t&&typeof t=="object"&&t[he]===Po,ef=t=>!!t&&typeof t=="object"&&t[he]===Sn,tf=t=>!!t&&typeof t=="object"&&t[he]===Ro,Oo=t=>!!t&&typeof t=="object"&&t[he]===cr,nf=t=>!!t&&typeof t=="object"&&t[he]===Cn;function Ao(t){if(t&&typeof t=="object")switch(t[he]){case Sn:case Cn:return!0}return!1}function rf(t){if(t&&typeof t=="object")switch(t[he]){case ar:case Sn:case cr:case Cn:return!0}return!1}var sf=t=>(Oo(t)||Ao(t))&&!!t.anchor;M.ALIAS=ar;M.DOC=Po;M.MAP=Sn;M.NODE_TYPE=he;M.PAIR=Ro;M.SCALAR=cr;M.SEQ=Cn;M.hasAnchor=sf;M.isAlias=Xu;M.isCollection=Ao;M.isDocument=Zu;M.isMap=ef;M.isNode=rf;M.isPair=tf;M.isScalar=Oo;M.isSeq=nf});var St=v(lr=>{"use strict";var L=_(),J=Symbol("break visit"),No=Symbol("skip children"),ue=Symbol("remove node");function En(t,e){let n=To(e);L.isDocument(t)?it(null,t.contents,n,Object.freeze([t]))===ue&&(t.contents=null):it(null,t,n,Object.freeze([]))}En.BREAK=J;En.SKIP=No;En.REMOVE=ue;function it(t,e,n,i){let r=jo(t,e,n,i);if(L.isNode(r)||L.isPair(r))return Io(t,i,r),it(t,r,n,i);if(typeof r!="symbol"){if(L.isCollection(e)){i=Object.freeze(i.concat(e));for(let s=0;s{"use strict";var $o=_(),of=St(),af={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},cf=t=>t.replace(/[!,[\]{}]/g,e=>af[e]),Ct=class t{constructor(e,n){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},t.defaultYaml,e),this.tags=Object.assign({},t.defaultTags,n)}clone(){let e=new t(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){let e=new t(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:t.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},t.defaultTags);break}return e}add(e,n){this.atNextDocument&&(this.yaml={explicit:t.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},t.defaultTags),this.atNextDocument=!1);let i=e.trim().split(/[ \t]+/),r=i.shift();switch(r){case"%TAG":{if(i.length!==2&&(n(0,"%TAG directive should contain exactly two parts"),i.length<2))return!1;let[s,o]=i;return this.tags[s]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,i.length!==1)return n(0,"%YAML directive should contain exactly one part"),!1;let[s]=i;if(s==="1.1"||s==="1.2")return this.yaml.version=s,!0;{let o=/^\d+\.\d+$/.test(s);return n(6,`Unsupported YAML version ${s}`,o),!1}}default:return n(0,`Unknown directive ${r}`,!0),!1}}tagName(e,n){if(e==="!")return"!";if(e[0]!=="!")return n(`Not a valid tag: ${e}`),null;if(e[1]==="<"){let o=e.slice(2,-1);return o==="!"||o==="!!"?(n(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&n("Verbatim tags must end with a >"),o)}let[,i,r]=e.match(/^(.*!)([^!]*)$/s);r||n(`The ${e} tag has no suffix`);let s=this.tags[i];if(s)try{return s+decodeURIComponent(r)}catch(o){return n(String(o)),null}return i==="!"?e:(n(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[n,i]of Object.entries(this.tags))if(e.startsWith(i))return n+cf(e.substring(i.length));return e[0]==="!"?e:`!<${e}>`}toString(e){let n=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],i=Object.entries(this.tags),r;if(e&&i.length>0&&$o.isNode(e.contents)){let s={};of.visit(e.contents,(o,a)=>{$o.isNode(a)&&a.tag&&(s[a.tag]=!0)}),r=Object.keys(s)}else r=[];for(let[s,o]of i)s==="!!"&&o==="tag:yaml.org,2002:"||(!e||r.some(a=>a.startsWith(o)))&&n.push(`%TAG ${s} ${o}`);return n.join(` +`)}};Ct.defaultYaml={explicit:!1,version:"1.2"};Ct.defaultTags={"!!":"tag:yaml.org,2002:"};qo.Directives=Ct});var _n=v(Et=>{"use strict";var Lo=_(),lf=St();function uf(t){if(/[\x00-\x19\s,[\]{}]/.test(t)){let n=`Anchor must not contain whitespace or control characters: ${JSON.stringify(t)}`;throw new Error(n)}return!0}function Do(t){let e=new Set;return lf.visit(t,{Value(n,i){i.anchor&&e.add(i.anchor)}}),e}function Fo(t,e){for(let n=1;;++n){let i=`${t}${n}`;if(!e.has(i))return i}}function ff(t,e){let n=[],i=new Map,r=null;return{onAnchor:s=>{n.push(s),r??(r=Do(t));let o=Fo(e,r);return r.add(o),o},setAnchors:()=>{for(let s of n){let o=i.get(s);if(typeof o=="object"&&o.anchor&&(Lo.isScalar(o.node)||Lo.isCollection(o.node)))o.node.anchor=o.anchor;else{let a=new Error("Failed to resolve repeated object (this should not happen)");throw a.source=s,a}}},sourceObjects:i}}Et.anchorIsValid=uf;Et.anchorNames=Do;Et.createNodeAnchors=ff;Et.findNewAnchor=Fo});var fr=v(Mo=>{"use strict";function xt(t,e,n,i){if(i&&typeof i=="object")if(Array.isArray(i))for(let r=0,s=i.length;r{"use strict";var df=_();function Wo(t,e,n){if(Array.isArray(t))return t.map((i,r)=>Wo(i,String(r),n));if(t&&typeof t.toJSON=="function"){if(!n||!df.hasAnchor(t))return t.toJSON(e,n);let i={aliasCount:0,count:1,res:void 0};n.anchors.set(t,i),n.onCreate=s=>{i.res=s,delete n.onCreate};let r=t.toJSON(e,n);return n.onCreate&&n.onCreate(r),r}return typeof t=="bigint"&&!n?.keep?Number(t):t}Bo.toJS=Wo});var Pn=v(Yo=>{"use strict";var pf=fr(),Ko=_(),mf=Ee(),dr=class{constructor(e){Object.defineProperty(this,Ko.NODE_TYPE,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:n,maxAliasCount:i,onAnchor:r,reviver:s}={}){if(!Ko.isDocument(e))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:e,keep:!0,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},a=mf.toJS(this,"",o);if(typeof r=="function")for(let{count:c,res:l}of o.anchors.values())r(l,c);return typeof s=="function"?pf.applyReviver(s,{"":a},"",a):a}};Yo.NodeBase=dr});var _t=v(Uo=>{"use strict";var hf=_n(),gf=St(),st=_(),wf=Pn(),yf=Ee(),pr=class extends wf.NodeBase{constructor(e){super(st.ALIAS),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,n){if(n?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let i;n?.aliasResolveCache?i=n.aliasResolveCache:(i=[],gf.visit(e,{Node:(s,o)=>{(st.isAlias(o)||st.hasAnchor(o))&&i.push(o)}}),n&&(n.aliasResolveCache=i));let r;for(let s of i){if(s===this)break;s.anchor===this.source&&(r=s)}return r}toJSON(e,n){if(!n)return{source:this.source};let{anchors:i,doc:r,maxAliasCount:s}=n,o=this.resolve(r,n);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let a=i.get(o);if(a||(yf.toJS(o,null,n),a=i.get(o)),a?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(s>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=Rn(r,o,i)),a.count*a.aliasCount>s)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return a.res}toString(e,n,i){let r=`*${this.source}`;if(e){if(hf.anchorIsValid(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let s=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(s)}if(e.implicitKey)return`${r} `}return r}};function Rn(t,e,n){if(st.isAlias(e)){let i=e.resolve(t),r=n&&i&&n.get(i);return r?r.count*r.aliasCount:0}else if(st.isCollection(e)){let i=0;for(let r of e.items){let s=Rn(t,r,n);s>i&&(i=s)}return i}else if(st.isPair(e)){let i=Rn(t,e.key,n),r=Rn(t,e.value,n);return Math.max(i,r)}return 1}Uo.Alias=pr});var j=v(mr=>{"use strict";var vf=_(),bf=Pn(),kf=Ee(),Sf=t=>!t||typeof t!="function"&&typeof t!="object",xe=class extends bf.NodeBase{constructor(e){super(vf.SCALAR),this.value=e}toJSON(e,n){return n?.keep?this.value:kf.toJS(this.value,e,n)}toString(){return String(this.value)}};xe.BLOCK_FOLDED="BLOCK_FOLDED";xe.BLOCK_LITERAL="BLOCK_LITERAL";xe.PLAIN="PLAIN";xe.QUOTE_DOUBLE="QUOTE_DOUBLE";xe.QUOTE_SINGLE="QUOTE_SINGLE";mr.Scalar=xe;mr.isScalarValue=Sf});var Pt=v(Vo=>{"use strict";var Cf=_t(),Ye=_(),Jo=j(),Ef="tag:yaml.org,2002:";function xf(t,e,n){if(e){let i=n.filter(s=>s.tag===e),r=i.find(s=>!s.format)??i[0];if(!r)throw new Error(`Tag ${e} not found`);return r}return n.find(i=>i.identify?.(t)&&!i.format)}function _f(t,e,n){if(Ye.isDocument(t)&&(t=t.contents),Ye.isNode(t))return t;if(Ye.isPair(t)){let u=n.schema[Ye.MAP].createNode?.(n.schema,null,n);return u.items.push(t),u}(t instanceof String||t instanceof Number||t instanceof Boolean||typeof BigInt<"u"&&t instanceof BigInt)&&(t=t.valueOf());let{aliasDuplicateObjects:i,onAnchor:r,onTagObj:s,schema:o,sourceObjects:a}=n,c;if(i&&t&&typeof t=="object"){if(c=a.get(t),c)return c.anchor??(c.anchor=r(t)),new Cf.Alias(c.anchor);c={anchor:null,node:null},a.set(t,c)}e?.startsWith("!!")&&(e=Ef+e.slice(2));let l=xf(t,e,o.tags);if(!l){if(t&&typeof t.toJSON=="function"&&(t=t.toJSON()),!t||typeof t!="object"){let u=new Jo.Scalar(t);return c&&(c.node=u),u}l=t instanceof Map?o[Ye.MAP]:Symbol.iterator in Object(t)?o[Ye.SEQ]:o[Ye.MAP]}s&&(s(l),delete n.onTagObj);let f=l?.createNode?l.createNode(n.schema,t,n):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(n.schema,t,n):new Jo.Scalar(t);return e?f.tag=e:l.default||(f.tag=l.tag),c&&(c.node=f),f}Vo.createNode=_f});var An=v(On=>{"use strict";var Pf=Pt(),fe=_(),Rf=Pn();function hr(t,e,n){let i=n;for(let r=e.length-1;r>=0;--r){let s=e[r];if(typeof s=="number"&&Number.isInteger(s)&&s>=0){let o=[];o[s]=i,i=o}else i=new Map([[s,i]])}return Pf.createNode(i,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:t,sourceObjects:new Map})}var Ho=t=>t==null||typeof t=="object"&&!!t[Symbol.iterator]().next().done,gr=class extends Rf.NodeBase{constructor(e,n){super(e),Object.defineProperty(this,"schema",{value:n,configurable:!0,enumerable:!1,writable:!0})}clone(e){let n=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(n.schema=e),n.items=n.items.map(i=>fe.isNode(i)||fe.isPair(i)?i.clone(e):i),this.range&&(n.range=this.range.slice()),n}addIn(e,n){if(Ho(e))this.add(n);else{let[i,...r]=e,s=this.get(i,!0);if(fe.isCollection(s))s.addIn(r,n);else if(s===void 0&&this.schema)this.set(i,hr(this.schema,r,n));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${r}`)}}deleteIn(e){let[n,...i]=e;if(i.length===0)return this.delete(n);let r=this.get(n,!0);if(fe.isCollection(r))return r.deleteIn(i);throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}getIn(e,n){let[i,...r]=e,s=this.get(i,!0);return r.length===0?!n&&fe.isScalar(s)?s.value:s:fe.isCollection(s)?s.getIn(r,n):void 0}hasAllNullValues(e){return this.items.every(n=>{if(!fe.isPair(n))return!1;let i=n.value;return i==null||e&&fe.isScalar(i)&&i.value==null&&!i.commentBefore&&!i.comment&&!i.tag})}hasIn(e){let[n,...i]=e;if(i.length===0)return this.has(n);let r=this.get(n,!0);return fe.isCollection(r)?r.hasIn(i):!1}setIn(e,n){let[i,...r]=e;if(r.length===0)this.set(i,n);else{let s=this.get(i,!0);if(fe.isCollection(s))s.setIn(r,n);else if(s===void 0&&this.schema)this.set(i,hr(this.schema,r,n));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${r}`)}}};On.Collection=gr;On.collectionFromPath=hr;On.isEmptyPath=Ho});var Rt=v(Nn=>{"use strict";var Of=t=>t.replace(/^(?!$)(?: $)?/gm,"#");function wr(t,e){return/^\n+$/.test(t)?t.substring(1):e?t.replace(/^(?! *$)/gm,e):t}var Af=(t,e,n)=>t.endsWith(` +`)?wr(n,e):n.includes(` `)?` -`+gr(n,e):(t.endsWith(" ")?"":" ")+n;Nn.indentComment=gr;Nn.lineComment=Of;Nn.stringifyComment=Rf});var zo=v(Ot=>{"use strict";var Af="flow",wr="block",Tn="quoted";function Nf(t,e,n="flow",{indentAtStart:i,lineWidth:r=80,minContentWidth:s=20,onFold:o,onOverflow:a}={}){if(!r||r<0)return t;rr-Math.max(2,s)?l.push(0):u=r-i);let d,h,g=!1,p=-1,m=-1,w=-1;n===wr&&(p=Go(t,p,e.length),p!==-1&&(u=p+c));for(let S;S=t[p+=1];){if(n===Tn&&S==="\\"){switch(m=p,t[p+1]){case"x":p+=3;break;case"u":p+=5;break;case"U":p+=9;break;default:p+=1}w=p}if(S===` -`)n===wr&&(p=Go(t,p,e.length)),u=p+e.length+c,d=void 0;else{if(S===" "&&h&&h!==" "&&h!==` +`+wr(n,e):(t.endsWith(" ")?"":" ")+n;Nn.indentComment=wr;Nn.lineComment=Af;Nn.stringifyComment=Of});var zo=v(Ot=>{"use strict";var Nf="flow",yr="block",Tn="quoted";function Tf(t,e,n="flow",{indentAtStart:i,lineWidth:r=80,minContentWidth:s=20,onFold:o,onOverflow:a}={}){if(!r||r<0)return t;rr-Math.max(2,s)?l.push(0):u=r-i);let d,h,g=!1,p=-1,m=-1,w=-1;n===yr&&(p=Go(t,p,e.length),p!==-1&&(u=p+c));for(let S;S=t[p+=1];){if(n===Tn&&S==="\\"){switch(m=p,t[p+1]){case"x":p+=3;break;case"u":p+=5;break;case"U":p+=9;break;default:p+=1}w=p}if(S===` +`)n===yr&&(p=Go(t,p,e.length)),u=p+e.length+c,d=void 0;else{if(S===" "&&h&&h!==" "&&h!==` `&&h!==" "){let k=t[p+1];k&&k!==" "&&k!==` `&&k!==" "&&(d=p)}if(p>=u)if(d)l.push(d),u=d+c,d=void 0;else if(n===Tn){for(;h===" "||h===" ";)h=S,S=t[p+=1],g=!0;let k=p>w+1?p-2:m-1;if(f[k])return t;l.push(k),f[k]=!0,u=k+c,d=void 0}else g=!0}h=S}if(g&&a&&a(),l.length===0)return t;o&&o();let y=t.slice(0,l[0]);for(let S=0;S{"use strict";var re=I(),_e=zo(),In=(t,e)=>({indentAtStart:e?t.indent.length:t.indentAtStart,lineWidth:t.options.lineWidth,minContentWidth:t.options.minContentWidth}),qn=t=>/^(%|---|\.\.\.)/m.test(t);function Tf(t,e,n){if(!e||e<0)return!1;let i=e-n,r=t.length;if(r<=i)return!1;for(let s=0,o=0;si)return!0;if(o=s+1,r-o<=i)return!1}return!0}function At(t,e){let n=JSON.stringify(t);if(e.options.doubleQuotedAsJSON)return n;let{implicitKey:i}=e,r=e.options.doubleQuotedMinMultiLineLength,s=e.indent||(qn(t)?" ":""),o="",a=0;for(let c=0,l=n[c];l;l=n[++c])if(l===" "&&n[c+1]==="\\"&&n[c+2]==="n"&&(o+=n.slice(a,c)+"\\ ",c+=1,a=c,l="\\"),l==="\\")switch(n[c+1]){case"u":{o+=n.slice(a,c);let f=n.substr(c+2,4);switch(f){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:f.substr(0,2)==="00"?o+="\\x"+f.substr(2):o+=n.substr(c,6)}c+=5,a=c+1}break;case"n":if(i||n[c+2]==='"'||n.length{"use strict";var re=j(),_e=zo(),In=(t,e)=>({indentAtStart:e?t.indent.length:t.indentAtStart,lineWidth:t.options.lineWidth,minContentWidth:t.options.minContentWidth}),$n=t=>/^(%|---|\.\.\.)/m.test(t);function jf(t,e,n){if(!e||e<0)return!1;let i=e-n,r=t.length;if(r<=i)return!1;for(let s=0,o=0;si)return!0;if(o=s+1,r-o<=i)return!1}return!0}function At(t,e){let n=JSON.stringify(t);if(e.options.doubleQuotedAsJSON)return n;let{implicitKey:i}=e,r=e.options.doubleQuotedMinMultiLineLength,s=e.indent||($n(t)?" ":""),o="",a=0;for(let c=0,l=n[c];l;l=n[++c])if(l===" "&&n[c+1]==="\\"&&n[c+2]==="n"&&(o+=n.slice(a,c)+"\\ ",c+=1,a=c,l="\\"),l==="\\")switch(n[c+1]){case"u":{o+=n.slice(a,c);let f=n.substr(c+2,4);switch(f){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:f.substr(0,2)==="00"?o+="\\x"+f.substr(2):o+=n.substr(c,6)}c+=5,a=c+1}break;case"n":if(i||n[c+2]==='"'||n.length `;let u,d;for(d=n.length;d>0;--d){let C=n[d-1];if(C!==` `&&C!==" "&&C!==" ")break}let h=n.substring(d),g=h.indexOf(` `);g===-1?u="-":n===h||g!==h.length-1?(u="+",s&&s()):u="",h&&(n=n.slice(0,-h.length),h[h.length-1]===` -`&&(h=h.slice(0,-1)),h=h.replace(vr,`$&${l}`));let p=!1,m,w=-1;for(m=0;m{E=!0});let b=_e.foldFlowLines(`${y}${C}${h}`,l,_e.FOLD_BLOCK,R);if(!E)return`>${k} ${l}${b}`}return n=n.replace(/\n+/g,`$&${l}`),`|${k} -${l}${y}${n}${h}`}function jf(t,e,n,i){let{type:r,value:s}=t,{actualString:o,implicitKey:a,indent:c,indentStep:l,inFlow:f}=e;if(a&&s.includes(` +${l}${y}${n}${h}`}function If(t,e,n,i){let{type:r,value:s}=t,{actualString:o,implicitKey:a,indent:c,indentStep:l,inFlow:f}=e;if(a&&s.includes(` `)||f&&/[[\]{},]/.test(s))return ot(s,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(s))return a||f||!s.includes(` `)?ot(s,e):jn(t,e,n,i);if(!a&&!f&&r!==re.Scalar.PLAIN&&s.includes(` -`))return jn(t,e,n,i);if(qn(s)){if(c==="")return e.forceBlockIndent=!0,jn(t,e,n,i);if(a&&c===l)return ot(s,e)}let u=s.replace(/\n+/g,`$& -${c}`);if(o){let d=p=>p.default&&p.tag!=="tag:yaml.org,2002:str"&&p.test?.test(u),{compat:h,tags:g}=e.doc.schema;if(g.some(d)||h?.some(d))return ot(s,e)}return a?u:_e.foldFlowLines(u,c,_e.FOLD_FLOW,In(e,!1))}function If(t,e,n,i){let{implicitKey:r,inFlow:s}=e,o=typeof t.value=="string"?t:Object.assign({},t,{value:String(t.value)}),{type:a}=t;a!==re.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=re.Scalar.QUOTE_DOUBLE);let c=f=>{switch(f){case re.Scalar.BLOCK_FOLDED:case re.Scalar.BLOCK_LITERAL:return r||s?ot(o.value,e):jn(o,e,n,i);case re.Scalar.QUOTE_DOUBLE:return At(o.value,e);case re.Scalar.QUOTE_SINGLE:return yr(o.value,e);case re.Scalar.PLAIN:return jf(o,e,n,i);default:return null}},l=c(a);if(l===null){let{defaultKeyType:f,defaultStringType:u}=e.options,d=r&&f||u;if(l=c(d),l===null)throw new Error(`Unsupported default string type ${d}`)}return l}Qo.stringifyString=If});var Tt=v(br=>{"use strict";var qf=_n(),Pe=_(),$f=Rt(),Lf=Nt();function Df(t,e){let n=Object.assign({blockQuote:!0,commentString:$f.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},t.schema.toStringOptions,e),i;switch(n.collectionStyle){case"block":i=!1;break;case"flow":i=!0;break;default:i=null}return{anchors:new Set,doc:t,flowCollectionPadding:n.flowCollectionPadding?" ":"",indent:"",indentStep:typeof n.indent=="number"?" ".repeat(n.indent):" ",inFlow:i,options:n}}function Ff(t,e){if(e.tag){let r=t.filter(s=>s.tag===e.tag);if(r.length>0)return r.find(s=>s.format===e.format)??r[0]}let n,i;if(Pe.isScalar(e)){i=e.value;let r=t.filter(s=>s.identify?.(i));if(r.length>1){let s=r.filter(o=>o.test);s.length>0&&(r=s)}n=r.find(s=>s.format===e.format)??r.find(s=>!s.format)}else i=e,n=t.find(r=>r.nodeClass&&i instanceof r.nodeClass);if(!n){let r=i?.constructor?.name??(i===null?"null":typeof i);throw new Error(`Tag not resolved for ${r} value`)}return n}function Mf(t,e,{anchors:n,doc:i}){if(!i.directives)return"";let r=[],s=(Pe.isScalar(t)||Pe.isCollection(t))&&t.anchor;s&&qf.anchorIsValid(s)&&(n.add(s),r.push(`&${s}`));let o=t.tag??(e.default?null:e.tag);return o&&r.push(i.directives.tagString(o)),r.join(" ")}function Wf(t,e,n,i){if(Pe.isPair(t))return t.toString(e,n,i);if(Pe.isAlias(t)){if(e.doc.directives)return t.toString(e);if(e.resolvedAliases?.has(t))throw new TypeError("Cannot stringify circular structure without alias nodes");e.resolvedAliases?e.resolvedAliases.add(t):e.resolvedAliases=new Set([t]),t=t.resolve(e.doc)}let r,s=Pe.isNode(t)?t:e.doc.createNode(t,{onTagObj:c=>r=c});r??(r=Ff(e.doc.schema.tags,s));let o=Mf(s,r,e);o.length>0&&(e.indentAtStart=(e.indentAtStart??0)+o.length+1);let a=typeof r.stringify=="function"?r.stringify(s,e,n,i):Pe.isScalar(s)?Lf.stringifyString(s,e,n,i):s.toString(e,n,i);return o?Pe.isScalar(s)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o} -${e.indent}${a}`:a}br.createStringifyContext=Df;br.stringify=Wf});var ta=v(ea=>{"use strict";var ge=_(),Xo=I(),Zo=Tt(),jt=Rt();function Bf({key:t,value:e},n,i,r){let{allNullValues:s,doc:o,indent:a,indentStep:c,options:{commentString:l,indentSeq:f,simpleKeys:u}}=n,d=ge.isNode(t)&&t.comment||null;if(u){if(d)throw new Error("With simple keys, key nodes cannot have comments");if(ge.isCollection(t)||!ge.isNode(t)&&typeof t=="object"){let R="With simple keys, collection cannot be used as a key value";throw new Error(R)}}let h=!u&&(!t||d&&e==null&&!n.inFlow||ge.isCollection(t)||(ge.isScalar(t)?t.type===Xo.Scalar.BLOCK_FOLDED||t.type===Xo.Scalar.BLOCK_LITERAL:typeof t=="object"));n=Object.assign({},n,{allNullValues:!1,implicitKey:!h&&(u||!s),indent:a+c});let g=!1,p=!1,m=Zo.stringify(t,n,()=>g=!0,()=>p=!0);if(!h&&!n.inFlow&&m.length>1024){if(u)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");h=!0}if(n.inFlow){if(s||e==null)return g&&i&&i(),m===""?"?":h?`? ${m}`:m}else if(s&&!u||e==null&&h)return m=`? ${m}`,d&&!g?m+=jt.lineComment(m,n.indent,l(d)):p&&r&&r(),m;g&&(d=null),h?(d&&(m+=jt.lineComment(m,n.indent,l(d))),m=`? ${m} +`))return jn(t,e,n,i);if($n(s)){if(c==="")return e.forceBlockIndent=!0,jn(t,e,n,i);if(a&&c===l)return ot(s,e)}let u=s.replace(/\n+/g,`$& +${c}`);if(o){let d=p=>p.default&&p.tag!=="tag:yaml.org,2002:str"&&p.test?.test(u),{compat:h,tags:g}=e.doc.schema;if(g.some(d)||h?.some(d))return ot(s,e)}return a?u:_e.foldFlowLines(u,c,_e.FOLD_FLOW,In(e,!1))}function $f(t,e,n,i){let{implicitKey:r,inFlow:s}=e,o=typeof t.value=="string"?t:Object.assign({},t,{value:String(t.value)}),{type:a}=t;a!==re.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=re.Scalar.QUOTE_DOUBLE);let c=f=>{switch(f){case re.Scalar.BLOCK_FOLDED:case re.Scalar.BLOCK_LITERAL:return r||s?ot(o.value,e):jn(o,e,n,i);case re.Scalar.QUOTE_DOUBLE:return At(o.value,e);case re.Scalar.QUOTE_SINGLE:return vr(o.value,e);case re.Scalar.PLAIN:return If(o,e,n,i);default:return null}},l=c(a);if(l===null){let{defaultKeyType:f,defaultStringType:u}=e.options,d=r&&f||u;if(l=c(d),l===null)throw new Error(`Unsupported default string type ${d}`)}return l}Qo.stringifyString=$f});var Tt=v(kr=>{"use strict";var qf=_n(),Pe=_(),Lf=Rt(),Df=Nt();function Ff(t,e){let n=Object.assign({blockQuote:!0,commentString:Lf.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},t.schema.toStringOptions,e),i;switch(n.collectionStyle){case"block":i=!1;break;case"flow":i=!0;break;default:i=null}return{anchors:new Set,doc:t,flowCollectionPadding:n.flowCollectionPadding?" ":"",indent:"",indentStep:typeof n.indent=="number"?" ".repeat(n.indent):" ",inFlow:i,options:n}}function Mf(t,e){if(e.tag){let r=t.filter(s=>s.tag===e.tag);if(r.length>0)return r.find(s=>s.format===e.format)??r[0]}let n,i;if(Pe.isScalar(e)){i=e.value;let r=t.filter(s=>s.identify?.(i));if(r.length>1){let s=r.filter(o=>o.test);s.length>0&&(r=s)}n=r.find(s=>s.format===e.format)??r.find(s=>!s.format)}else i=e,n=t.find(r=>r.nodeClass&&i instanceof r.nodeClass);if(!n){let r=i?.constructor?.name??(i===null?"null":typeof i);throw new Error(`Tag not resolved for ${r} value`)}return n}function Wf(t,e,{anchors:n,doc:i}){if(!i.directives)return"";let r=[],s=(Pe.isScalar(t)||Pe.isCollection(t))&&t.anchor;s&&qf.anchorIsValid(s)&&(n.add(s),r.push(`&${s}`));let o=t.tag??(e.default?null:e.tag);return o&&r.push(i.directives.tagString(o)),r.join(" ")}function Bf(t,e,n,i){if(Pe.isPair(t))return t.toString(e,n,i);if(Pe.isAlias(t)){if(e.doc.directives)return t.toString(e);if(e.resolvedAliases?.has(t))throw new TypeError("Cannot stringify circular structure without alias nodes");e.resolvedAliases?e.resolvedAliases.add(t):e.resolvedAliases=new Set([t]),t=t.resolve(e.doc)}let r,s=Pe.isNode(t)?t:e.doc.createNode(t,{onTagObj:c=>r=c});r??(r=Mf(e.doc.schema.tags,s));let o=Wf(s,r,e);o.length>0&&(e.indentAtStart=(e.indentAtStart??0)+o.length+1);let a=typeof r.stringify=="function"?r.stringify(s,e,n,i):Pe.isScalar(s)?Df.stringifyString(s,e,n,i):s.toString(e,n,i);return o?Pe.isScalar(s)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o} +${e.indent}${a}`:a}kr.createStringifyContext=Ff;kr.stringify=Bf});var ta=v(ea=>{"use strict";var ge=_(),Xo=j(),Zo=Tt(),jt=Rt();function Kf({key:t,value:e},n,i,r){let{allNullValues:s,doc:o,indent:a,indentStep:c,options:{commentString:l,indentSeq:f,simpleKeys:u}}=n,d=ge.isNode(t)&&t.comment||null;if(u){if(d)throw new Error("With simple keys, key nodes cannot have comments");if(ge.isCollection(t)||!ge.isNode(t)&&typeof t=="object"){let R="With simple keys, collection cannot be used as a key value";throw new Error(R)}}let h=!u&&(!t||d&&e==null&&!n.inFlow||ge.isCollection(t)||(ge.isScalar(t)?t.type===Xo.Scalar.BLOCK_FOLDED||t.type===Xo.Scalar.BLOCK_LITERAL:typeof t=="object"));n=Object.assign({},n,{allNullValues:!1,implicitKey:!h&&(u||!s),indent:a+c});let g=!1,p=!1,m=Zo.stringify(t,n,()=>g=!0,()=>p=!0);if(!h&&!n.inFlow&&m.length>1024){if(u)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");h=!0}if(n.inFlow){if(s||e==null)return g&&i&&i(),m===""?"?":h?`? ${m}`:m}else if(s&&!u||e==null&&h)return m=`? ${m}`,d&&!g?m+=jt.lineComment(m,n.indent,l(d)):p&&r&&r(),m;g&&(d=null),h?(d&&(m+=jt.lineComment(m,n.indent,l(d))),m=`? ${m} ${a}:`):(m=`${m}:`,d&&(m+=jt.lineComment(m,n.indent,l(d))));let w,y,S;ge.isNode(e)?(w=!!e.spaceBefore,y=e.commentBefore,S=e.comment):(w=!1,y=null,S=null,e&&typeof e=="object"&&(e=o.createNode(e))),n.implicitKey=!1,!h&&!d&&ge.isScalar(e)&&(n.indentAtStart=m.length+1),p=!1,!f&&c.length>=2&&!n.inFlow&&!h&&ge.isSeq(e)&&!e.flow&&!e.tag&&!e.anchor&&(n.indent=n.indent.substring(2));let k=!1,C=Zo.stringify(e,n,()=>k=!0,()=>p=!0),E=" ";if(d||w||y){if(E=w?` `:"",y){let R=l(y);E+=` ${jt.indentComment(R,n.indent)}`}C===""&&!n.inFlow?E===` @@ -44,34 +44,34 @@ ${jt.indentComment(R,n.indent)}`}C===""&&!n.inFlow?E===` ${n.indent}`}else if(!h&&ge.isCollection(e)){let R=C[0],b=C.indexOf(` `),P=b!==-1,ne=n.inFlow??e.flow??e.items.length===0;if(P||!ne){let z=!1;if(P&&(R==="&"||R==="!")){let A=C.indexOf(" ");R==="&"&&A!==-1&&A{"use strict";var na=kn("process");function Kf(t,...e){t==="debug"&&console.log(...e)}function Yf(t,e){(t==="debug"||t==="warn")&&(typeof na.emitWarning=="function"?na.emitWarning(e):console.warn(e))}kr.debug=Kf;kr.warn=Yf});var Mn=v(Fn=>{"use strict";var Dn=_(),ia=I(),$n="<<",Ln={identify:t=>t===$n||typeof t=="symbol"&&t.description===$n,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new ia.Scalar(Symbol($n)),{addToJSMap:ra}),stringify:()=>$n},Uf=(t,e)=>(Ln.identify(e)||Dn.isScalar(e)&&(!e.type||e.type===ia.Scalar.PLAIN)&&Ln.identify(e.value))&&t?.doc.schema.tags.some(n=>n.tag===Ln.tag&&n.default);function ra(t,e,n){let i=sa(t,n);if(Dn.isSeq(i))for(let r of i.items)Cr(t,e,r);else if(Array.isArray(i))for(let r of i)Cr(t,e,r);else Cr(t,e,i)}function Cr(t,e,n){let i=sa(t,n);if(!Dn.isMap(i))throw new Error("Merge sources must be maps or map aliases");let r=i.toJSON(null,t,Map);for(let[s,o]of r)e instanceof Map?e.has(s)||e.set(s,o):e instanceof Set?e.add(s):Object.prototype.hasOwnProperty.call(e,s)||Object.defineProperty(e,s,{value:o,writable:!0,enumerable:!0,configurable:!0});return e}function sa(t,e){return t&&Dn.isAlias(e)?e.resolve(t.doc,t):e}Fn.addMergeToJSMap=ra;Fn.isMergeKey=Uf;Fn.merge=Ln});var xr=v(ca=>{"use strict";var Jf=Sr(),oa=Mn(),Vf=Tt(),aa=_(),Er=Ee();function Hf(t,e,{key:n,value:i}){if(aa.isNode(n)&&n.addToJSMap)n.addToJSMap(t,e,i);else if(oa.isMergeKey(t,n))oa.addMergeToJSMap(t,e,i);else{let r=Er.toJS(n,"",t);if(e instanceof Map)e.set(r,Er.toJS(i,r,t));else if(e instanceof Set)e.add(r);else{let s=Gf(n,r,t),o=Er.toJS(i,s,t);s in e?Object.defineProperty(e,s,{value:o,writable:!0,enumerable:!0,configurable:!0}):e[s]=o}}return e}function Gf(t,e,n){if(e===null)return"";if(typeof e!="object")return String(e);if(aa.isNode(t)&&n?.doc){let i=Vf.createStringifyContext(n.doc,{});i.anchors=new Set;for(let s of n.anchors.keys())i.anchors.add(s.anchor);i.inFlow=!0,i.inStringifyKey=!0;let r=t.toString(i);if(!n.mapKeyWarned){let s=JSON.stringify(r);s.length>40&&(s=s.substring(0,36)+'..."'),Jf.warn(n.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${s}. Set mapAsMap: true to use object keys.`),n.mapKeyWarned=!0}return r}return JSON.stringify(e)}ca.addPairToJSMap=Hf});var Re=v(_r=>{"use strict";var la=Pt(),zf=ta(),Qf=xr(),Wn=_();function Xf(t,e,n){let i=la.createNode(t,void 0,n),r=la.createNode(e,void 0,n);return new Bn(i,r)}var Bn=class t{constructor(e,n=null){Object.defineProperty(this,Wn.NODE_TYPE,{value:Wn.PAIR}),this.key=e,this.value=n}clone(e){let{key:n,value:i}=this;return Wn.isNode(n)&&(n=n.clone(e)),Wn.isNode(i)&&(i=i.clone(e)),new t(n,i)}toJSON(e,n){let i=n?.mapAsMap?new Map:{};return Qf.addPairToJSMap(n,i,this)}toString(e,n,i){return e?.doc?zf.stringifyPair(this,e,n,i):JSON.stringify(this)}};_r.Pair=Bn;_r.createPair=Xf});var Pr=v(fa=>{"use strict";var Ue=_(),ua=Tt(),Kn=Rt();function Zf(t,e,n){return(e.inFlow??t.flow?td:ed)(t,e,n)}function ed({comment:t,items:e},n,{blockItemPrefix:i,flowChars:r,itemIndent:s,onChompKeep:o,onComment:a}){let{indent:c,options:{commentString:l}}=n,f=Object.assign({},n,{indent:s,type:null}),u=!1,d=[];for(let g=0;gm=null,()=>u=!0);m&&(w+=Kn.lineComment(w,s,l(m))),u&&m&&(u=!1),d.push(i+w)}let h;if(d.length===0)h=r.start+r.end;else{h=d[0];for(let g=1;g{"use strict";var na=kn("process");function Yf(t,...e){t==="debug"&&console.log(...e)}function Uf(t,e){(t==="debug"||t==="warn")&&(typeof na.emitWarning=="function"?na.emitWarning(e):console.warn(e))}Sr.debug=Yf;Sr.warn=Uf});var Mn=v(Fn=>{"use strict";var Dn=_(),ia=j(),qn="<<",Ln={identify:t=>t===qn||typeof t=="symbol"&&t.description===qn,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new ia.Scalar(Symbol(qn)),{addToJSMap:ra}),stringify:()=>qn},Jf=(t,e)=>(Ln.identify(e)||Dn.isScalar(e)&&(!e.type||e.type===ia.Scalar.PLAIN)&&Ln.identify(e.value))&&t?.doc.schema.tags.some(n=>n.tag===Ln.tag&&n.default);function ra(t,e,n){let i=sa(t,n);if(Dn.isSeq(i))for(let r of i.items)Er(t,e,r);else if(Array.isArray(i))for(let r of i)Er(t,e,r);else Er(t,e,i)}function Er(t,e,n){let i=sa(t,n);if(!Dn.isMap(i))throw new Error("Merge sources must be maps or map aliases");let r=i.toJSON(null,t,Map);for(let[s,o]of r)e instanceof Map?e.has(s)||e.set(s,o):e instanceof Set?e.add(s):Object.prototype.hasOwnProperty.call(e,s)||Object.defineProperty(e,s,{value:o,writable:!0,enumerable:!0,configurable:!0});return e}function sa(t,e){return t&&Dn.isAlias(e)?e.resolve(t.doc,t):e}Fn.addMergeToJSMap=ra;Fn.isMergeKey=Jf;Fn.merge=Ln});var _r=v(ca=>{"use strict";var Vf=Cr(),oa=Mn(),Hf=Tt(),aa=_(),xr=Ee();function Gf(t,e,{key:n,value:i}){if(aa.isNode(n)&&n.addToJSMap)n.addToJSMap(t,e,i);else if(oa.isMergeKey(t,n))oa.addMergeToJSMap(t,e,i);else{let r=xr.toJS(n,"",t);if(e instanceof Map)e.set(r,xr.toJS(i,r,t));else if(e instanceof Set)e.add(r);else{let s=zf(n,r,t),o=xr.toJS(i,s,t);s in e?Object.defineProperty(e,s,{value:o,writable:!0,enumerable:!0,configurable:!0}):e[s]=o}}return e}function zf(t,e,n){if(e===null)return"";if(typeof e!="object")return String(e);if(aa.isNode(t)&&n?.doc){let i=Hf.createStringifyContext(n.doc,{});i.anchors=new Set;for(let s of n.anchors.keys())i.anchors.add(s.anchor);i.inFlow=!0,i.inStringifyKey=!0;let r=t.toString(i);if(!n.mapKeyWarned){let s=JSON.stringify(r);s.length>40&&(s=s.substring(0,36)+'..."'),Vf.warn(n.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${s}. Set mapAsMap: true to use object keys.`),n.mapKeyWarned=!0}return r}return JSON.stringify(e)}ca.addPairToJSMap=Gf});var Re=v(Pr=>{"use strict";var la=Pt(),Qf=ta(),Xf=_r(),Wn=_();function Zf(t,e,n){let i=la.createNode(t,void 0,n),r=la.createNode(e,void 0,n);return new Bn(i,r)}var Bn=class t{constructor(e,n=null){Object.defineProperty(this,Wn.NODE_TYPE,{value:Wn.PAIR}),this.key=e,this.value=n}clone(e){let{key:n,value:i}=this;return Wn.isNode(n)&&(n=n.clone(e)),Wn.isNode(i)&&(i=i.clone(e)),new t(n,i)}toJSON(e,n){let i=n?.mapAsMap?new Map:{};return Xf.addPairToJSMap(n,i,this)}toString(e,n,i){return e?.doc?Qf.stringifyPair(this,e,n,i):JSON.stringify(this)}};Pr.Pair=Bn;Pr.createPair=Zf});var Rr=v(fa=>{"use strict";var Ue=_(),ua=Tt(),Kn=Rt();function ed(t,e,n){return(e.inFlow??t.flow?nd:td)(t,e,n)}function td({comment:t,items:e},n,{blockItemPrefix:i,flowChars:r,itemIndent:s,onChompKeep:o,onComment:a}){let{indent:c,options:{commentString:l}}=n,f=Object.assign({},n,{indent:s,type:null}),u=!1,d=[];for(let g=0;gm=null,()=>u=!0);m&&(w+=Kn.lineComment(w,s,l(m))),u&&m&&(u=!1),d.push(i+w)}let h;if(d.length===0)h=r.start+r.end;else{h=d[0];for(let g=1;gm=null);l||(l=u.length>f||w.includes(` +`+Kn.indentComment(l(t),c),a&&a()):u&&o&&o(),h}function nd({items:t},e,{flowChars:n,itemIndent:i}){let{indent:r,indentStep:s,flowCollectionPadding:o,options:{commentString:a}}=e;i+=s;let c=Object.assign({},e,{indent:i,inFlow:!0,type:null}),l=!1,f=0,u=[];for(let g=0;gm=null);l||(l=u.length>f||w.includes(` `)),g0&&(l||(l=u.reduce((y,S)=>y+S.length+2,2)+(w.length+2)>e.options.lineWidth)),l&&(w+=",")),m&&(w+=Kn.lineComment(w,i,a(m))),u.push(w),f=u.length}let{start:d,end:h}=n;if(u.length===0)return d+h;if(!l){let g=u.reduce((p,m)=>p+m.length+2,2);l=e.options.lineWidth>0&&g>e.options.lineWidth}if(l){let g=d;for(let p of u)g+=p?` ${s}${r}${p}`:` `;return`${g} -${r}${h}`}else return`${d}${o}${u.join(" ")}${o}${h}`}function Yn({indent:t,options:{commentString:e}},n,i,r){if(i&&r&&(i=i.replace(/^\n+/,"")),i){let s=Kn.indentComment(e(i),t);n.push(s.trimStart())}}fa.stringifyCollection=Zf});var Ae=v(Or=>{"use strict";var nd=Pr(),id=xr(),rd=An(),Oe=_(),Un=Re(),sd=I();function It(t,e){let n=Oe.isScalar(e)?e.value:e;for(let i of t)if(Oe.isPair(i)&&(i.key===e||i.key===n||Oe.isScalar(i.key)&&i.key.value===n))return i}var Rr=class extends rd.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(Oe.MAP,e),this.items=[]}static from(e,n,i){let{keepUndefined:r,replacer:s}=i,o=new this(e),a=(c,l)=>{if(typeof s=="function")l=s.call(n,c,l);else if(Array.isArray(s)&&!s.includes(c))return;(l!==void 0||r)&&o.items.push(Un.createPair(c,l,i))};if(n instanceof Map)for(let[c,l]of n)a(c,l);else if(n&&typeof n=="object")for(let c of Object.keys(n))a(c,n[c]);return typeof e.sortMapEntries=="function"&&o.items.sort(e.sortMapEntries),o}add(e,n){let i;Oe.isPair(e)?i=e:!e||typeof e!="object"||!("key"in e)?i=new Un.Pair(e,e?.value):i=new Un.Pair(e.key,e.value);let r=It(this.items,i.key),s=this.schema?.sortMapEntries;if(r){if(!n)throw new Error(`Key ${i.key} already set`);Oe.isScalar(r.value)&&sd.isScalarValue(i.value)?r.value.value=i.value:r.value=i.value}else if(s){let o=this.items.findIndex(a=>s(i,a)<0);o===-1?this.items.push(i):this.items.splice(o,0,i)}else this.items.push(i)}delete(e){let n=It(this.items,e);return n?this.items.splice(this.items.indexOf(n),1).length>0:!1}get(e,n){let r=It(this.items,e)?.value;return(!n&&Oe.isScalar(r)?r.value:r)??void 0}has(e){return!!It(this.items,e)}set(e,n){this.add(new Un.Pair(e,n),!0)}toJSON(e,n,i){let r=i?new i:n?.mapAsMap?new Map:{};n?.onCreate&&n.onCreate(r);for(let s of this.items)id.addPairToJSMap(n,r,s);return r}toString(e,n,i){if(!e)return JSON.stringify(this);for(let r of this.items)if(!Oe.isPair(r))throw new Error(`Map items must all be pairs; found ${JSON.stringify(r)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),nd.stringifyCollection(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:i,onComment:n})}};Or.YAMLMap=Rr;Or.findPair=It});var at=v(pa=>{"use strict";var od=_(),da=Ae(),ad={collection:"map",default:!0,nodeClass:da.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(t,e){return od.isMap(t)||e("Expected a mapping for this tag"),t},createNode:(t,e,n)=>da.YAMLMap.from(t,e,n)};pa.map=ad});var Ne=v(ma=>{"use strict";var cd=Pt(),ld=Pr(),ud=An(),Vn=_(),fd=I(),dd=Ee(),Ar=class extends ud.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(Vn.SEQ,e),this.items=[]}add(e){this.items.push(e)}delete(e){let n=Jn(e);return typeof n!="number"?!1:this.items.splice(n,1).length>0}get(e,n){let i=Jn(e);if(typeof i!="number")return;let r=this.items[i];return!n&&Vn.isScalar(r)?r.value:r}has(e){let n=Jn(e);return typeof n=="number"&&n=0?e:null}ma.YAMLSeq=Ar});var ct=v(ga=>{"use strict";var pd=_(),ha=Ne(),md={collection:"seq",default:!0,nodeClass:ha.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(t,e){return pd.isSeq(t)||e("Expected a sequence for this tag"),t},createNode:(t,e,n)=>ha.YAMLSeq.from(t,e,n)};ga.seq=md});var qt=v(wa=>{"use strict";var hd=Nt(),gd={identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify(t,e,n,i){return e=Object.assign({actualString:!0},e),hd.stringifyString(t,e,n,i)}};wa.string=gd});var Hn=v(ba=>{"use strict";var ya=I(),va={identify:t=>t==null,createNode:()=>new ya.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new ya.Scalar(null),stringify:({source:t},e)=>typeof t=="string"&&va.test.test(t)?t:e.options.nullStr};ba.nullTag=va});var Nr=v(Sa=>{"use strict";var wd=I(),ka={identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:t=>new wd.Scalar(t[0]==="t"||t[0]==="T"),stringify({source:t,value:e},n){if(t&&ka.test.test(t)){let i=t[0]==="t"||t[0]==="T";if(e===i)return t}return e?n.options.trueStr:n.options.falseStr}};Sa.boolTag=ka});var lt=v(Ca=>{"use strict";function yd({format:t,minFractionDigits:e,tag:n,value:i}){if(typeof i=="bigint")return String(i);let r=typeof i=="number"?i:Number(i);if(!isFinite(r))return isNaN(r)?".nan":r<0?"-.inf":".inf";let s=Object.is(i,-0)?"-0":JSON.stringify(i);if(!t&&e&&(!n||n==="tag:yaml.org,2002:float")&&/^-?\d/.test(s)&&!s.includes("e")){let o=s.indexOf(".");o<0&&(o=s.length,s+=".");let a=e-(s.length-o-1);for(;a-- >0;)s+="0"}return s}Ca.stringifyNumber=yd});var jr=v(Gn=>{"use strict";var vd=I(),Tr=lt(),bd={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:t=>t.slice(-3).toLowerCase()==="nan"?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Tr.stringifyNumber},kd={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t),stringify(t){let e=Number(t.value);return isFinite(e)?e.toExponential():Tr.stringifyNumber(t)}},Sd={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(t){let e=new vd.Scalar(parseFloat(t)),n=t.indexOf(".");return n!==-1&&t[t.length-1]==="0"&&(e.minFractionDigits=t.length-n-1),e},stringify:Tr.stringifyNumber};Gn.float=Sd;Gn.floatExp=kd;Gn.floatNaN=bd});var qr=v(Qn=>{"use strict";var Ea=lt(),zn=t=>typeof t=="bigint"||Number.isInteger(t),Ir=(t,e,n,{intAsBigInt:i})=>i?BigInt(t):parseInt(t.substring(e),n);function xa(t,e,n){let{value:i}=t;return zn(i)&&i>=0?n+i.toString(e):Ea.stringifyNumber(t)}var Cd={identify:t=>zn(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(t,e,n)=>Ir(t,2,8,n),stringify:t=>xa(t,8,"0o")},Ed={identify:zn,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(t,e,n)=>Ir(t,0,10,n),stringify:Ea.stringifyNumber},xd={identify:t=>zn(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(t,e,n)=>Ir(t,2,16,n),stringify:t=>xa(t,16,"0x")};Qn.int=Ed;Qn.intHex=xd;Qn.intOct=Cd});var Pa=v(_a=>{"use strict";var _d=at(),Pd=Hn(),Rd=ct(),Od=qt(),Ad=Nr(),$r=jr(),Lr=qr(),Nd=[_d.map,Rd.seq,Od.string,Pd.nullTag,Ad.boolTag,Lr.intOct,Lr.int,Lr.intHex,$r.floatNaN,$r.floatExp,$r.float];_a.schema=Nd});var Aa=v(Oa=>{"use strict";var Td=I(),jd=at(),Id=ct();function Ra(t){return typeof t=="bigint"||Number.isInteger(t)}var Xn=({value:t})=>JSON.stringify(t),qd=[{identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify:Xn},{identify:t=>t==null,createNode:()=>new Td.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Xn},{identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:t=>t==="true",stringify:Xn},{identify:Ra,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(t,e,{intAsBigInt:n})=>n?BigInt(t):parseInt(t,10),stringify:({value:t})=>Ra(t)?t.toString():JSON.stringify(t)},{identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:t=>parseFloat(t),stringify:Xn}],$d={default:!0,tag:"",test:/^/,resolve(t,e){return e(`Unresolved plain scalar ${JSON.stringify(t)}`),t}},Ld=[jd.map,Id.seq].concat(qd,$d);Oa.schema=Ld});var Fr=v(Na=>{"use strict";var $t=kn("buffer"),Dr=I(),Dd=Nt(),Fd={identify:t=>t instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(t,e){if(typeof $t.Buffer=="function")return $t.Buffer.from(t,"base64");if(typeof atob=="function"){let n=atob(t.replace(/[\n\r]/g,"")),i=new Uint8Array(n.length);for(let r=0;r{"use strict";var Zn=_(),Mr=Re(),Md=I(),Wd=Ne();function Ta(t,e){if(Zn.isSeq(t))for(let n=0;n1&&e("Each pair must have its own sequence indicator");let r=i.items[0]||new Mr.Pair(new Md.Scalar(null));if(i.commentBefore&&(r.key.commentBefore=r.key.commentBefore?`${i.commentBefore} +${r}${h}`}else return`${d}${o}${u.join(" ")}${o}${h}`}function Yn({indent:t,options:{commentString:e}},n,i,r){if(i&&r&&(i=i.replace(/^\n+/,"")),i){let s=Kn.indentComment(e(i),t);n.push(s.trimStart())}}fa.stringifyCollection=ed});var Ae=v(Ar=>{"use strict";var id=Rr(),rd=_r(),sd=An(),Oe=_(),Un=Re(),od=j();function It(t,e){let n=Oe.isScalar(e)?e.value:e;for(let i of t)if(Oe.isPair(i)&&(i.key===e||i.key===n||Oe.isScalar(i.key)&&i.key.value===n))return i}var Or=class extends sd.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(Oe.MAP,e),this.items=[]}static from(e,n,i){let{keepUndefined:r,replacer:s}=i,o=new this(e),a=(c,l)=>{if(typeof s=="function")l=s.call(n,c,l);else if(Array.isArray(s)&&!s.includes(c))return;(l!==void 0||r)&&o.items.push(Un.createPair(c,l,i))};if(n instanceof Map)for(let[c,l]of n)a(c,l);else if(n&&typeof n=="object")for(let c of Object.keys(n))a(c,n[c]);return typeof e.sortMapEntries=="function"&&o.items.sort(e.sortMapEntries),o}add(e,n){let i;Oe.isPair(e)?i=e:!e||typeof e!="object"||!("key"in e)?i=new Un.Pair(e,e?.value):i=new Un.Pair(e.key,e.value);let r=It(this.items,i.key),s=this.schema?.sortMapEntries;if(r){if(!n)throw new Error(`Key ${i.key} already set`);Oe.isScalar(r.value)&&od.isScalarValue(i.value)?r.value.value=i.value:r.value=i.value}else if(s){let o=this.items.findIndex(a=>s(i,a)<0);o===-1?this.items.push(i):this.items.splice(o,0,i)}else this.items.push(i)}delete(e){let n=It(this.items,e);return n?this.items.splice(this.items.indexOf(n),1).length>0:!1}get(e,n){let r=It(this.items,e)?.value;return(!n&&Oe.isScalar(r)?r.value:r)??void 0}has(e){return!!It(this.items,e)}set(e,n){this.add(new Un.Pair(e,n),!0)}toJSON(e,n,i){let r=i?new i:n?.mapAsMap?new Map:{};n?.onCreate&&n.onCreate(r);for(let s of this.items)rd.addPairToJSMap(n,r,s);return r}toString(e,n,i){if(!e)return JSON.stringify(this);for(let r of this.items)if(!Oe.isPair(r))throw new Error(`Map items must all be pairs; found ${JSON.stringify(r)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),id.stringifyCollection(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:i,onComment:n})}};Ar.YAMLMap=Or;Ar.findPair=It});var at=v(pa=>{"use strict";var ad=_(),da=Ae(),cd={collection:"map",default:!0,nodeClass:da.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(t,e){return ad.isMap(t)||e("Expected a mapping for this tag"),t},createNode:(t,e,n)=>da.YAMLMap.from(t,e,n)};pa.map=cd});var Ne=v(ma=>{"use strict";var ld=Pt(),ud=Rr(),fd=An(),Vn=_(),dd=j(),pd=Ee(),Nr=class extends fd.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(Vn.SEQ,e),this.items=[]}add(e){this.items.push(e)}delete(e){let n=Jn(e);return typeof n!="number"?!1:this.items.splice(n,1).length>0}get(e,n){let i=Jn(e);if(typeof i!="number")return;let r=this.items[i];return!n&&Vn.isScalar(r)?r.value:r}has(e){let n=Jn(e);return typeof n=="number"&&n=0?e:null}ma.YAMLSeq=Nr});var ct=v(ga=>{"use strict";var md=_(),ha=Ne(),hd={collection:"seq",default:!0,nodeClass:ha.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(t,e){return md.isSeq(t)||e("Expected a sequence for this tag"),t},createNode:(t,e,n)=>ha.YAMLSeq.from(t,e,n)};ga.seq=hd});var $t=v(wa=>{"use strict";var gd=Nt(),wd={identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify(t,e,n,i){return e=Object.assign({actualString:!0},e),gd.stringifyString(t,e,n,i)}};wa.string=wd});var Hn=v(ba=>{"use strict";var ya=j(),va={identify:t=>t==null,createNode:()=>new ya.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new ya.Scalar(null),stringify:({source:t},e)=>typeof t=="string"&&va.test.test(t)?t:e.options.nullStr};ba.nullTag=va});var Tr=v(Sa=>{"use strict";var yd=j(),ka={identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:t=>new yd.Scalar(t[0]==="t"||t[0]==="T"),stringify({source:t,value:e},n){if(t&&ka.test.test(t)){let i=t[0]==="t"||t[0]==="T";if(e===i)return t}return e?n.options.trueStr:n.options.falseStr}};Sa.boolTag=ka});var lt=v(Ca=>{"use strict";function vd({format:t,minFractionDigits:e,tag:n,value:i}){if(typeof i=="bigint")return String(i);let r=typeof i=="number"?i:Number(i);if(!isFinite(r))return isNaN(r)?".nan":r<0?"-.inf":".inf";let s=Object.is(i,-0)?"-0":JSON.stringify(i);if(!t&&e&&(!n||n==="tag:yaml.org,2002:float")&&/^-?\d/.test(s)&&!s.includes("e")){let o=s.indexOf(".");o<0&&(o=s.length,s+=".");let a=e-(s.length-o-1);for(;a-- >0;)s+="0"}return s}Ca.stringifyNumber=vd});var Ir=v(Gn=>{"use strict";var bd=j(),jr=lt(),kd={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:t=>t.slice(-3).toLowerCase()==="nan"?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:jr.stringifyNumber},Sd={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t),stringify(t){let e=Number(t.value);return isFinite(e)?e.toExponential():jr.stringifyNumber(t)}},Cd={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(t){let e=new bd.Scalar(parseFloat(t)),n=t.indexOf(".");return n!==-1&&t[t.length-1]==="0"&&(e.minFractionDigits=t.length-n-1),e},stringify:jr.stringifyNumber};Gn.float=Cd;Gn.floatExp=Sd;Gn.floatNaN=kd});var qr=v(Qn=>{"use strict";var Ea=lt(),zn=t=>typeof t=="bigint"||Number.isInteger(t),$r=(t,e,n,{intAsBigInt:i})=>i?BigInt(t):parseInt(t.substring(e),n);function xa(t,e,n){let{value:i}=t;return zn(i)&&i>=0?n+i.toString(e):Ea.stringifyNumber(t)}var Ed={identify:t=>zn(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(t,e,n)=>$r(t,2,8,n),stringify:t=>xa(t,8,"0o")},xd={identify:zn,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(t,e,n)=>$r(t,0,10,n),stringify:Ea.stringifyNumber},_d={identify:t=>zn(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(t,e,n)=>$r(t,2,16,n),stringify:t=>xa(t,16,"0x")};Qn.int=xd;Qn.intHex=_d;Qn.intOct=Ed});var Pa=v(_a=>{"use strict";var Pd=at(),Rd=Hn(),Od=ct(),Ad=$t(),Nd=Tr(),Lr=Ir(),Dr=qr(),Td=[Pd.map,Od.seq,Ad.string,Rd.nullTag,Nd.boolTag,Dr.intOct,Dr.int,Dr.intHex,Lr.floatNaN,Lr.floatExp,Lr.float];_a.schema=Td});var Aa=v(Oa=>{"use strict";var jd=j(),Id=at(),$d=ct();function Ra(t){return typeof t=="bigint"||Number.isInteger(t)}var Xn=({value:t})=>JSON.stringify(t),qd=[{identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify:Xn},{identify:t=>t==null,createNode:()=>new jd.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Xn},{identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:t=>t==="true",stringify:Xn},{identify:Ra,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(t,e,{intAsBigInt:n})=>n?BigInt(t):parseInt(t,10),stringify:({value:t})=>Ra(t)?t.toString():JSON.stringify(t)},{identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:t=>parseFloat(t),stringify:Xn}],Ld={default:!0,tag:"",test:/^/,resolve(t,e){return e(`Unresolved plain scalar ${JSON.stringify(t)}`),t}},Dd=[Id.map,$d.seq].concat(qd,Ld);Oa.schema=Dd});var Mr=v(Na=>{"use strict";var qt=kn("buffer"),Fr=j(),Fd=Nt(),Md={identify:t=>t instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(t,e){if(typeof qt.Buffer=="function")return qt.Buffer.from(t,"base64");if(typeof atob=="function"){let n=atob(t.replace(/[\n\r]/g,"")),i=new Uint8Array(n.length);for(let r=0;r{"use strict";var Zn=_(),Wr=Re(),Wd=j(),Bd=Ne();function Ta(t,e){if(Zn.isSeq(t))for(let n=0;n1&&e("Each pair must have its own sequence indicator");let r=i.items[0]||new Wr.Pair(new Wd.Scalar(null));if(i.commentBefore&&(r.key.commentBefore=r.key.commentBefore?`${i.commentBefore} ${r.key.commentBefore}`:i.commentBefore),i.comment){let s=r.value??r.key;s.comment=s.comment?`${i.comment} -${s.comment}`:i.comment}i=r}t.items[n]=Zn.isPair(i)?i:new Mr.Pair(i)}}else e("Expected a sequence for this tag");return t}function ja(t,e,n){let{replacer:i}=n,r=new Wd.YAMLSeq(t);r.tag="tag:yaml.org,2002:pairs";let s=0;if(e&&Symbol.iterator in Object(e))for(let o of e){typeof i=="function"&&(o=i.call(e,String(s++),o));let a,c;if(Array.isArray(o))if(o.length===2)a=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)a=l[0],c=o[a];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else a=o;r.items.push(Mr.createPair(a,c,n))}return r}var Bd={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Ta,createNode:ja};ei.createPairs=ja;ei.pairs=Bd;ei.resolvePairs=Ta});var Kr=v(Br=>{"use strict";var Ia=_(),Wr=Ee(),Lt=Ae(),Kd=Ne(),qa=ti(),Je=class t extends Kd.YAMLSeq{constructor(){super(),this.add=Lt.YAMLMap.prototype.add.bind(this),this.delete=Lt.YAMLMap.prototype.delete.bind(this),this.get=Lt.YAMLMap.prototype.get.bind(this),this.has=Lt.YAMLMap.prototype.has.bind(this),this.set=Lt.YAMLMap.prototype.set.bind(this),this.tag=t.tag}toJSON(e,n){if(!n)return super.toJSON(e);let i=new Map;n?.onCreate&&n.onCreate(i);for(let r of this.items){let s,o;if(Ia.isPair(r)?(s=Wr.toJS(r.key,"",n),o=Wr.toJS(r.value,s,n)):s=Wr.toJS(r,"",n),i.has(s))throw new Error("Ordered maps must not include duplicate keys");i.set(s,o)}return i}static from(e,n,i){let r=qa.createPairs(e,n,i),s=new this;return s.items=r.items,s}};Je.tag="tag:yaml.org,2002:omap";var Yd={collection:"seq",identify:t=>t instanceof Map,nodeClass:Je,default:!1,tag:"tag:yaml.org,2002:omap",resolve(t,e){let n=qa.resolvePairs(t,e),i=[];for(let{key:r}of n.items)Ia.isScalar(r)&&(i.includes(r.value)?e(`Ordered maps must not include duplicate keys: ${r.value}`):i.push(r.value));return Object.assign(new Je,n)},createNode:(t,e,n)=>Je.from(t,e,n)};Br.YAMLOMap=Je;Br.omap=Yd});var Ma=v(Yr=>{"use strict";var $a=I();function La({value:t,source:e},n){return e&&(t?Da:Fa).test.test(e)?e:t?n.options.trueStr:n.options.falseStr}var Da={identify:t=>t===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new $a.Scalar(!0),stringify:La},Fa={identify:t=>t===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new $a.Scalar(!1),stringify:La};Yr.falseTag=Fa;Yr.trueTag=Da});var Wa=v(ni=>{"use strict";var Ud=I(),Ur=lt(),Jd={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:t=>t.slice(-3).toLowerCase()==="nan"?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Ur.stringifyNumber},Vd={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t.replace(/_/g,"")),stringify(t){let e=Number(t.value);return isFinite(e)?e.toExponential():Ur.stringifyNumber(t)}},Hd={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(t){let e=new Ud.Scalar(parseFloat(t.replace(/_/g,""))),n=t.indexOf(".");if(n!==-1){let i=t.substring(n+1).replace(/_/g,"");i[i.length-1]==="0"&&(e.minFractionDigits=i.length)}return e},stringify:Ur.stringifyNumber};ni.float=Hd;ni.floatExp=Vd;ni.floatNaN=Jd});var Ka=v(Ft=>{"use strict";var Ba=lt(),Dt=t=>typeof t=="bigint"||Number.isInteger(t);function ii(t,e,n,{intAsBigInt:i}){let r=t[0];if((r==="-"||r==="+")&&(e+=1),t=t.substring(e).replace(/_/g,""),i){switch(n){case 2:t=`0b${t}`;break;case 8:t=`0o${t}`;break;case 16:t=`0x${t}`;break}let o=BigInt(t);return r==="-"?BigInt(-1)*o:o}let s=parseInt(t,n);return r==="-"?-1*s:s}function Jr(t,e,n){let{value:i}=t;if(Dt(i)){let r=i.toString(e);return i<0?"-"+n+r.substr(1):n+r}return Ba.stringifyNumber(t)}var Gd={identify:Dt,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(t,e,n)=>ii(t,2,2,n),stringify:t=>Jr(t,2,"0b")},zd={identify:Dt,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(t,e,n)=>ii(t,1,8,n),stringify:t=>Jr(t,8,"0")},Qd={identify:Dt,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(t,e,n)=>ii(t,0,10,n),stringify:Ba.stringifyNumber},Xd={identify:Dt,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(t,e,n)=>ii(t,2,16,n),stringify:t=>Jr(t,16,"0x")};Ft.int=Qd;Ft.intBin=Gd;Ft.intHex=Xd;Ft.intOct=zd});var Hr=v(Vr=>{"use strict";var oi=_(),ri=Re(),si=Ae(),Ve=class t extends si.YAMLMap{constructor(e){super(e),this.tag=t.tag}add(e){let n;oi.isPair(e)?n=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?n=new ri.Pair(e.key,null):n=new ri.Pair(e,null),si.findPair(this.items,n.key)||this.items.push(n)}get(e,n){let i=si.findPair(this.items,e);return!n&&oi.isPair(i)?oi.isScalar(i.key)?i.key.value:i.key:i}set(e,n){if(typeof n!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof n}`);let i=si.findPair(this.items,e);i&&!n?this.items.splice(this.items.indexOf(i),1):!i&&n&&this.items.push(new ri.Pair(e))}toJSON(e,n){return super.toJSON(e,n,Set)}toString(e,n,i){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),n,i);throw new Error("Set items must all have null values")}static from(e,n,i){let{replacer:r}=i,s=new this(e);if(n&&Symbol.iterator in Object(n))for(let o of n)typeof r=="function"&&(o=r.call(n,o,o)),s.items.push(ri.createPair(o,null,i));return s}};Ve.tag="tag:yaml.org,2002:set";var Zd={collection:"map",identify:t=>t instanceof Set,nodeClass:Ve,default:!1,tag:"tag:yaml.org,2002:set",createNode:(t,e,n)=>Ve.from(t,e,n),resolve(t,e){if(oi.isMap(t)){if(t.hasAllNullValues(!0))return Object.assign(new Ve,t);e("Set items must all have null values")}else e("Expected a mapping for this tag");return t}};Vr.YAMLSet=Ve;Vr.set=Zd});var zr=v(ai=>{"use strict";var ep=lt();function Gr(t,e){let n=t[0],i=n==="-"||n==="+"?t.substring(1):t,r=o=>e?BigInt(o):Number(o),s=i.replace(/_/g,"").split(":").reduce((o,a)=>o*r(60)+r(a),r(0));return n==="-"?r(-1)*s:s}function Ya(t){let{value:e}=t,n=o=>o;if(typeof e=="bigint")n=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return ep.stringifyNumber(t);let i="";e<0&&(i="-",e*=n(-1));let r=n(60),s=[e%r];return e<60?s.unshift(0):(e=(e-s[0])/r,s.unshift(e%r),e>=60&&(e=(e-s[0])/r,s.unshift(e))),i+s.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var tp={identify:t=>typeof t=="bigint"||Number.isInteger(t),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(t,e,{intAsBigInt:n})=>Gr(t,n),stringify:Ya},np={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:t=>Gr(t,!1),stringify:Ya},Ua={identify:t=>t instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(t){let e=t.match(Ua.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,n,i,r,s,o,a]=e.map(Number),c=e[7]?Number((e[7]+"00").substr(1,3)):0,l=Date.UTC(n,i-1,r,s||0,o||0,a||0,c),f=e[8];if(f&&f!=="Z"){let u=Gr(f,!1);Math.abs(u)<30&&(u*=60),l-=6e4*u}return new Date(l)},stringify:({value:t})=>t?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};ai.floatTime=np;ai.intTime=tp;ai.timestamp=Ua});var Ha=v(Va=>{"use strict";var ip=at(),rp=Hn(),sp=ct(),op=qt(),ap=Fr(),Ja=Ma(),Qr=Wa(),ci=Ka(),cp=Mn(),lp=Kr(),up=ti(),fp=Hr(),Xr=zr(),dp=[ip.map,sp.seq,op.string,rp.nullTag,Ja.trueTag,Ja.falseTag,ci.intBin,ci.intOct,ci.int,ci.intHex,Qr.floatNaN,Qr.floatExp,Qr.float,ap.binary,cp.merge,lp.omap,up.pairs,fp.set,Xr.intTime,Xr.floatTime,Xr.timestamp];Va.schema=dp});var rc=v(ts=>{"use strict";var Xa=at(),pp=Hn(),Za=ct(),mp=qt(),hp=Nr(),Zr=jr(),es=qr(),gp=Pa(),wp=Aa(),ec=Fr(),Mt=Mn(),tc=Kr(),nc=ti(),Ga=Ha(),ic=Hr(),li=zr(),za=new Map([["core",gp.schema],["failsafe",[Xa.map,Za.seq,mp.string]],["json",wp.schema],["yaml11",Ga.schema],["yaml-1.1",Ga.schema]]),Qa={binary:ec.binary,bool:hp.boolTag,float:Zr.float,floatExp:Zr.floatExp,floatNaN:Zr.floatNaN,floatTime:li.floatTime,int:es.int,intHex:es.intHex,intOct:es.intOct,intTime:li.intTime,map:Xa.map,merge:Mt.merge,null:pp.nullTag,omap:tc.omap,pairs:nc.pairs,seq:Za.seq,set:ic.set,timestamp:li.timestamp},yp={"tag:yaml.org,2002:binary":ec.binary,"tag:yaml.org,2002:merge":Mt.merge,"tag:yaml.org,2002:omap":tc.omap,"tag:yaml.org,2002:pairs":nc.pairs,"tag:yaml.org,2002:set":ic.set,"tag:yaml.org,2002:timestamp":li.timestamp};function vp(t,e,n){let i=za.get(e);if(i&&!t)return n&&!i.includes(Mt.merge)?i.concat(Mt.merge):i.slice();let r=i;if(!r)if(Array.isArray(t))r=[];else{let s=Array.from(za.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${e}"; use one of ${s} or define customTags array`)}if(Array.isArray(t))for(let s of t)r=r.concat(s);else typeof t=="function"&&(r=t(r.slice()));return n&&(r=r.concat(Mt.merge)),r.reduce((s,o)=>{let a=typeof o=="string"?Qa[o]:o;if(!a){let c=JSON.stringify(o),l=Object.keys(Qa).map(f=>JSON.stringify(f)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return s.includes(a)||s.push(a),s},[])}ts.coreKnownTags=yp;ts.getTags=vp});var rs=v(sc=>{"use strict";var ns=_(),bp=at(),kp=ct(),Sp=qt(),ui=rc(),Cp=(t,e)=>t.keye.key?1:0,is=class t{constructor({compat:e,customTags:n,merge:i,resolveKnownTags:r,schema:s,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?ui.getTags(e,"compat"):e?ui.getTags(null,e):null,this.name=typeof s=="string"&&s||"core",this.knownTags=r?ui.coreKnownTags:{},this.tags=ui.getTags(n,this.name,i),this.toStringOptions=a??null,Object.defineProperty(this,ns.MAP,{value:bp.map}),Object.defineProperty(this,ns.SCALAR,{value:Sp.string}),Object.defineProperty(this,ns.SEQ,{value:kp.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?Cp:null}clone(){let e=Object.create(t.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};sc.Schema=is});var ac=v(oc=>{"use strict";var Ep=_(),ss=Tt(),Wt=Rt();function xp(t,e){let n=[],i=e.directives===!0;if(e.directives!==!1&&t.directives){let c=t.directives.toString(t);c?(n.push(c),i=!0):t.directives.docStart&&(i=!0)}i&&n.push("---");let r=ss.createStringifyContext(t,e),{commentString:s}=r.options;if(t.commentBefore){n.length!==1&&n.unshift("");let c=s(t.commentBefore);n.unshift(Wt.indentComment(c,""))}let o=!1,a=null;if(t.contents){if(Ep.isNode(t.contents)){if(t.contents.spaceBefore&&i&&n.push(""),t.contents.commentBefore){let f=s(t.contents.commentBefore);n.push(Wt.indentComment(f,""))}r.forceBlockIndent=!!t.comment,a=t.contents.comment}let c=a?void 0:()=>o=!0,l=ss.stringify(t.contents,r,()=>a=null,c);a&&(l+=Wt.lineComment(l,"",s(a))),(l[0]==="|"||l[0]===">")&&n[n.length-1]==="---"?n[n.length-1]=`--- ${l}`:n.push(l)}else n.push(ss.stringify(t.contents,r));if(t.directives?.docEnd)if(t.comment){let c=s(t.comment);c.includes(` +${s.comment}`:i.comment}i=r}t.items[n]=Zn.isPair(i)?i:new Wr.Pair(i)}}else e("Expected a sequence for this tag");return t}function ja(t,e,n){let{replacer:i}=n,r=new Bd.YAMLSeq(t);r.tag="tag:yaml.org,2002:pairs";let s=0;if(e&&Symbol.iterator in Object(e))for(let o of e){typeof i=="function"&&(o=i.call(e,String(s++),o));let a,c;if(Array.isArray(o))if(o.length===2)a=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)a=l[0],c=o[a];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else a=o;r.items.push(Wr.createPair(a,c,n))}return r}var Kd={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Ta,createNode:ja};ei.createPairs=ja;ei.pairs=Kd;ei.resolvePairs=Ta});var Yr=v(Kr=>{"use strict";var Ia=_(),Br=Ee(),Lt=Ae(),Yd=Ne(),$a=ti(),Je=class t extends Yd.YAMLSeq{constructor(){super(),this.add=Lt.YAMLMap.prototype.add.bind(this),this.delete=Lt.YAMLMap.prototype.delete.bind(this),this.get=Lt.YAMLMap.prototype.get.bind(this),this.has=Lt.YAMLMap.prototype.has.bind(this),this.set=Lt.YAMLMap.prototype.set.bind(this),this.tag=t.tag}toJSON(e,n){if(!n)return super.toJSON(e);let i=new Map;n?.onCreate&&n.onCreate(i);for(let r of this.items){let s,o;if(Ia.isPair(r)?(s=Br.toJS(r.key,"",n),o=Br.toJS(r.value,s,n)):s=Br.toJS(r,"",n),i.has(s))throw new Error("Ordered maps must not include duplicate keys");i.set(s,o)}return i}static from(e,n,i){let r=$a.createPairs(e,n,i),s=new this;return s.items=r.items,s}};Je.tag="tag:yaml.org,2002:omap";var Ud={collection:"seq",identify:t=>t instanceof Map,nodeClass:Je,default:!1,tag:"tag:yaml.org,2002:omap",resolve(t,e){let n=$a.resolvePairs(t,e),i=[];for(let{key:r}of n.items)Ia.isScalar(r)&&(i.includes(r.value)?e(`Ordered maps must not include duplicate keys: ${r.value}`):i.push(r.value));return Object.assign(new Je,n)},createNode:(t,e,n)=>Je.from(t,e,n)};Kr.YAMLOMap=Je;Kr.omap=Ud});var Ma=v(Ur=>{"use strict";var qa=j();function La({value:t,source:e},n){return e&&(t?Da:Fa).test.test(e)?e:t?n.options.trueStr:n.options.falseStr}var Da={identify:t=>t===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new qa.Scalar(!0),stringify:La},Fa={identify:t=>t===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new qa.Scalar(!1),stringify:La};Ur.falseTag=Fa;Ur.trueTag=Da});var Wa=v(ni=>{"use strict";var Jd=j(),Jr=lt(),Vd={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:t=>t.slice(-3).toLowerCase()==="nan"?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Jr.stringifyNumber},Hd={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t.replace(/_/g,"")),stringify(t){let e=Number(t.value);return isFinite(e)?e.toExponential():Jr.stringifyNumber(t)}},Gd={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(t){let e=new Jd.Scalar(parseFloat(t.replace(/_/g,""))),n=t.indexOf(".");if(n!==-1){let i=t.substring(n+1).replace(/_/g,"");i[i.length-1]==="0"&&(e.minFractionDigits=i.length)}return e},stringify:Jr.stringifyNumber};ni.float=Gd;ni.floatExp=Hd;ni.floatNaN=Vd});var Ka=v(Ft=>{"use strict";var Ba=lt(),Dt=t=>typeof t=="bigint"||Number.isInteger(t);function ii(t,e,n,{intAsBigInt:i}){let r=t[0];if((r==="-"||r==="+")&&(e+=1),t=t.substring(e).replace(/_/g,""),i){switch(n){case 2:t=`0b${t}`;break;case 8:t=`0o${t}`;break;case 16:t=`0x${t}`;break}let o=BigInt(t);return r==="-"?BigInt(-1)*o:o}let s=parseInt(t,n);return r==="-"?-1*s:s}function Vr(t,e,n){let{value:i}=t;if(Dt(i)){let r=i.toString(e);return i<0?"-"+n+r.substr(1):n+r}return Ba.stringifyNumber(t)}var zd={identify:Dt,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(t,e,n)=>ii(t,2,2,n),stringify:t=>Vr(t,2,"0b")},Qd={identify:Dt,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(t,e,n)=>ii(t,1,8,n),stringify:t=>Vr(t,8,"0")},Xd={identify:Dt,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(t,e,n)=>ii(t,0,10,n),stringify:Ba.stringifyNumber},Zd={identify:Dt,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(t,e,n)=>ii(t,2,16,n),stringify:t=>Vr(t,16,"0x")};Ft.int=Xd;Ft.intBin=zd;Ft.intHex=Zd;Ft.intOct=Qd});var Gr=v(Hr=>{"use strict";var oi=_(),ri=Re(),si=Ae(),Ve=class t extends si.YAMLMap{constructor(e){super(e),this.tag=t.tag}add(e){let n;oi.isPair(e)?n=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?n=new ri.Pair(e.key,null):n=new ri.Pair(e,null),si.findPair(this.items,n.key)||this.items.push(n)}get(e,n){let i=si.findPair(this.items,e);return!n&&oi.isPair(i)?oi.isScalar(i.key)?i.key.value:i.key:i}set(e,n){if(typeof n!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof n}`);let i=si.findPair(this.items,e);i&&!n?this.items.splice(this.items.indexOf(i),1):!i&&n&&this.items.push(new ri.Pair(e))}toJSON(e,n){return super.toJSON(e,n,Set)}toString(e,n,i){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),n,i);throw new Error("Set items must all have null values")}static from(e,n,i){let{replacer:r}=i,s=new this(e);if(n&&Symbol.iterator in Object(n))for(let o of n)typeof r=="function"&&(o=r.call(n,o,o)),s.items.push(ri.createPair(o,null,i));return s}};Ve.tag="tag:yaml.org,2002:set";var ep={collection:"map",identify:t=>t instanceof Set,nodeClass:Ve,default:!1,tag:"tag:yaml.org,2002:set",createNode:(t,e,n)=>Ve.from(t,e,n),resolve(t,e){if(oi.isMap(t)){if(t.hasAllNullValues(!0))return Object.assign(new Ve,t);e("Set items must all have null values")}else e("Expected a mapping for this tag");return t}};Hr.YAMLSet=Ve;Hr.set=ep});var Qr=v(ai=>{"use strict";var tp=lt();function zr(t,e){let n=t[0],i=n==="-"||n==="+"?t.substring(1):t,r=o=>e?BigInt(o):Number(o),s=i.replace(/_/g,"").split(":").reduce((o,a)=>o*r(60)+r(a),r(0));return n==="-"?r(-1)*s:s}function Ya(t){let{value:e}=t,n=o=>o;if(typeof e=="bigint")n=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return tp.stringifyNumber(t);let i="";e<0&&(i="-",e*=n(-1));let r=n(60),s=[e%r];return e<60?s.unshift(0):(e=(e-s[0])/r,s.unshift(e%r),e>=60&&(e=(e-s[0])/r,s.unshift(e))),i+s.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var np={identify:t=>typeof t=="bigint"||Number.isInteger(t),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(t,e,{intAsBigInt:n})=>zr(t,n),stringify:Ya},ip={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:t=>zr(t,!1),stringify:Ya},Ua={identify:t=>t instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(t){let e=t.match(Ua.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,n,i,r,s,o,a]=e.map(Number),c=e[7]?Number((e[7]+"00").substr(1,3)):0,l=Date.UTC(n,i-1,r,s||0,o||0,a||0,c),f=e[8];if(f&&f!=="Z"){let u=zr(f,!1);Math.abs(u)<30&&(u*=60),l-=6e4*u}return new Date(l)},stringify:({value:t})=>t?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};ai.floatTime=ip;ai.intTime=np;ai.timestamp=Ua});var Ha=v(Va=>{"use strict";var rp=at(),sp=Hn(),op=ct(),ap=$t(),cp=Mr(),Ja=Ma(),Xr=Wa(),ci=Ka(),lp=Mn(),up=Yr(),fp=ti(),dp=Gr(),Zr=Qr(),pp=[rp.map,op.seq,ap.string,sp.nullTag,Ja.trueTag,Ja.falseTag,ci.intBin,ci.intOct,ci.int,ci.intHex,Xr.floatNaN,Xr.floatExp,Xr.float,cp.binary,lp.merge,up.omap,fp.pairs,dp.set,Zr.intTime,Zr.floatTime,Zr.timestamp];Va.schema=pp});var rc=v(ns=>{"use strict";var Xa=at(),mp=Hn(),Za=ct(),hp=$t(),gp=Tr(),es=Ir(),ts=qr(),wp=Pa(),yp=Aa(),ec=Mr(),Mt=Mn(),tc=Yr(),nc=ti(),Ga=Ha(),ic=Gr(),li=Qr(),za=new Map([["core",wp.schema],["failsafe",[Xa.map,Za.seq,hp.string]],["json",yp.schema],["yaml11",Ga.schema],["yaml-1.1",Ga.schema]]),Qa={binary:ec.binary,bool:gp.boolTag,float:es.float,floatExp:es.floatExp,floatNaN:es.floatNaN,floatTime:li.floatTime,int:ts.int,intHex:ts.intHex,intOct:ts.intOct,intTime:li.intTime,map:Xa.map,merge:Mt.merge,null:mp.nullTag,omap:tc.omap,pairs:nc.pairs,seq:Za.seq,set:ic.set,timestamp:li.timestamp},vp={"tag:yaml.org,2002:binary":ec.binary,"tag:yaml.org,2002:merge":Mt.merge,"tag:yaml.org,2002:omap":tc.omap,"tag:yaml.org,2002:pairs":nc.pairs,"tag:yaml.org,2002:set":ic.set,"tag:yaml.org,2002:timestamp":li.timestamp};function bp(t,e,n){let i=za.get(e);if(i&&!t)return n&&!i.includes(Mt.merge)?i.concat(Mt.merge):i.slice();let r=i;if(!r)if(Array.isArray(t))r=[];else{let s=Array.from(za.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${e}"; use one of ${s} or define customTags array`)}if(Array.isArray(t))for(let s of t)r=r.concat(s);else typeof t=="function"&&(r=t(r.slice()));return n&&(r=r.concat(Mt.merge)),r.reduce((s,o)=>{let a=typeof o=="string"?Qa[o]:o;if(!a){let c=JSON.stringify(o),l=Object.keys(Qa).map(f=>JSON.stringify(f)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return s.includes(a)||s.push(a),s},[])}ns.coreKnownTags=vp;ns.getTags=bp});var ss=v(sc=>{"use strict";var is=_(),kp=at(),Sp=ct(),Cp=$t(),ui=rc(),Ep=(t,e)=>t.keye.key?1:0,rs=class t{constructor({compat:e,customTags:n,merge:i,resolveKnownTags:r,schema:s,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?ui.getTags(e,"compat"):e?ui.getTags(null,e):null,this.name=typeof s=="string"&&s||"core",this.knownTags=r?ui.coreKnownTags:{},this.tags=ui.getTags(n,this.name,i),this.toStringOptions=a??null,Object.defineProperty(this,is.MAP,{value:kp.map}),Object.defineProperty(this,is.SCALAR,{value:Cp.string}),Object.defineProperty(this,is.SEQ,{value:Sp.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?Ep:null}clone(){let e=Object.create(t.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};sc.Schema=rs});var ac=v(oc=>{"use strict";var xp=_(),os=Tt(),Wt=Rt();function _p(t,e){let n=[],i=e.directives===!0;if(e.directives!==!1&&t.directives){let c=t.directives.toString(t);c?(n.push(c),i=!0):t.directives.docStart&&(i=!0)}i&&n.push("---");let r=os.createStringifyContext(t,e),{commentString:s}=r.options;if(t.commentBefore){n.length!==1&&n.unshift("");let c=s(t.commentBefore);n.unshift(Wt.indentComment(c,""))}let o=!1,a=null;if(t.contents){if(xp.isNode(t.contents)){if(t.contents.spaceBefore&&i&&n.push(""),t.contents.commentBefore){let f=s(t.contents.commentBefore);n.push(Wt.indentComment(f,""))}r.forceBlockIndent=!!t.comment,a=t.contents.comment}let c=a?void 0:()=>o=!0,l=os.stringify(t.contents,r,()=>a=null,c);a&&(l+=Wt.lineComment(l,"",s(a))),(l[0]==="|"||l[0]===">")&&n[n.length-1]==="---"?n[n.length-1]=`--- ${l}`:n.push(l)}else n.push(os.stringify(t.contents,r));if(t.directives?.docEnd)if(t.comment){let c=s(t.comment);c.includes(` `)?(n.push("..."),n.push(Wt.indentComment(c,""))):n.push(`... ${c}`)}else n.push("...");else{let c=t.comment;c&&o&&(c=c.replace(/^\n+/,"")),c&&((!o||a)&&n[n.length-1]!==""&&n.push(""),n.push(Wt.indentComment(s(c),"")))}return n.join(` `)+` -`}oc.stringifyDocument=xp});var Bt=v(cc=>{"use strict";var _p=_t(),ut=An(),X=_(),Pp=Re(),Rp=Ee(),Op=rs(),Ap=ac(),os=_n(),Np=ur(),Tp=Pt(),as=lr(),cs=class t{constructor(e,n,i){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,X.NODE_TYPE,{value:X.DOC});let r=null;typeof n=="function"||Array.isArray(n)?r=n:i===void 0&&n&&(i=n,n=void 0);let s=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},i);this.options=s;let{version:o}=s;i?._directives?(this.directives=i._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new as.Directives({version:o}),this.setSchema(o,i),this.contents=e===void 0?null:this.createNode(e,r,i)}clone(){let e=Object.create(t.prototype,{[X.NODE_TYPE]:{value:X.DOC}});return e.commentBefore=this.commentBefore,e.comment=this.comment,e.errors=this.errors.slice(),e.warnings=this.warnings.slice(),e.options=Object.assign({},this.options),this.directives&&(e.directives=this.directives.clone()),e.schema=this.schema.clone(),e.contents=X.isNode(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){ft(this.contents)&&this.contents.add(e)}addIn(e,n){ft(this.contents)&&this.contents.addIn(e,n)}createAlias(e,n){if(!e.anchor){let i=os.anchorNames(this);e.anchor=!n||i.has(n)?os.findNewAnchor(n||"a",i):n}return new _p.Alias(e.anchor)}createNode(e,n,i){let r;if(typeof n=="function")e=n.call({"":e},"",e),r=n;else if(Array.isArray(n)){let m=y=>typeof y=="number"||y instanceof String||y instanceof Number,w=n.filter(m).map(String);w.length>0&&(n=n.concat(w)),r=n}else i===void 0&&n&&(i=n,n=void 0);let{aliasDuplicateObjects:s,anchorPrefix:o,flow:a,keepUndefined:c,onTagObj:l,tag:f}=i??{},{onAnchor:u,setAnchors:d,sourceObjects:h}=os.createNodeAnchors(this,o||"a"),g={aliasDuplicateObjects:s??!0,keepUndefined:c??!1,onAnchor:u,onTagObj:l,replacer:r,schema:this.schema,sourceObjects:h},p=Tp.createNode(e,f,g);return a&&X.isCollection(p)&&(p.flow=!0),d(),p}createPair(e,n,i={}){let r=this.createNode(e,null,i),s=this.createNode(n,null,i);return new Pp.Pair(r,s)}delete(e){return ft(this.contents)?this.contents.delete(e):!1}deleteIn(e){return ut.isEmptyPath(e)?this.contents==null?!1:(this.contents=null,!0):ft(this.contents)?this.contents.deleteIn(e):!1}get(e,n){return X.isCollection(this.contents)?this.contents.get(e,n):void 0}getIn(e,n){return ut.isEmptyPath(e)?!n&&X.isScalar(this.contents)?this.contents.value:this.contents:X.isCollection(this.contents)?this.contents.getIn(e,n):void 0}has(e){return X.isCollection(this.contents)?this.contents.has(e):!1}hasIn(e){return ut.isEmptyPath(e)?this.contents!==void 0:X.isCollection(this.contents)?this.contents.hasIn(e):!1}set(e,n){this.contents==null?this.contents=ut.collectionFromPath(this.schema,[e],n):ft(this.contents)&&this.contents.set(e,n)}setIn(e,n){ut.isEmptyPath(e)?this.contents=n:this.contents==null?this.contents=ut.collectionFromPath(this.schema,Array.from(e),n):ft(this.contents)&&this.contents.setIn(e,n)}setSchema(e,n={}){typeof e=="number"&&(e=String(e));let i;switch(e){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new as.Directives({version:"1.1"}),i={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=e:this.directives=new as.Directives({version:e}),i={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,i=null;break;default:{let r=JSON.stringify(e);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${r}`)}}if(n.schema instanceof Object)this.schema=n.schema;else if(i)this.schema=new Op.Schema(Object.assign(i,n));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:e,jsonArg:n,mapAsMap:i,maxAliasCount:r,onAnchor:s,reviver:o}={}){let a={anchors:new Map,doc:this,keep:!e,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},c=Rp.toJS(this.contents,n??"",a);if(typeof s=="function")for(let{count:l,res:f}of a.anchors.values())s(f,l);return typeof o=="function"?Np.applyReviver(o,{"":c},"",c):c}toJSON(e,n){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:n})}toString(e={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let n=JSON.stringify(e.indent);throw new Error(`"indent" option must be a positive integer, not ${n}`)}return Ap.stringifyDocument(this,e)}};function ft(t){if(X.isCollection(t))return!0;throw new Error("Expected a YAML collection as document contents")}cc.Document=cs});var Ut=v(Yt=>{"use strict";var Kt=class extends Error{constructor(e,n,i,r){super(),this.name=e,this.code=i,this.message=r,this.pos=n}},ls=class extends Kt{constructor(e,n,i){super("YAMLParseError",e,n,i)}},us=class extends Kt{constructor(e,n,i){super("YAMLWarning",e,n,i)}},jp=(t,e)=>n=>{if(n.pos[0]===-1)return;n.linePos=n.pos.map(a=>e.linePos(a));let{line:i,col:r}=n.linePos[0];n.message+=` at line ${i}, column ${r}`;let s=r-1,o=t.substring(e.lineStarts[i-1],e.lineStarts[i]).replace(/[\n\r]+$/,"");if(s>=60&&o.length>80){let a=Math.min(s-39,o.length-79);o="…"+o.substring(a),s-=a-1}if(o.length>80&&(o=o.substring(0,79)+"…"),i>1&&/^ *$/.test(o.substring(0,s))){let a=t.substring(e.lineStarts[i-2],e.lineStarts[i-1]);a.length>80&&(a=a.substring(0,79)+`… +`}oc.stringifyDocument=_p});var Bt=v(cc=>{"use strict";var Pp=_t(),ut=An(),X=_(),Rp=Re(),Op=Ee(),Ap=ss(),Np=ac(),as=_n(),Tp=fr(),jp=Pt(),cs=ur(),ls=class t{constructor(e,n,i){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,X.NODE_TYPE,{value:X.DOC});let r=null;typeof n=="function"||Array.isArray(n)?r=n:i===void 0&&n&&(i=n,n=void 0);let s=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},i);this.options=s;let{version:o}=s;i?._directives?(this.directives=i._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new cs.Directives({version:o}),this.setSchema(o,i),this.contents=e===void 0?null:this.createNode(e,r,i)}clone(){let e=Object.create(t.prototype,{[X.NODE_TYPE]:{value:X.DOC}});return e.commentBefore=this.commentBefore,e.comment=this.comment,e.errors=this.errors.slice(),e.warnings=this.warnings.slice(),e.options=Object.assign({},this.options),this.directives&&(e.directives=this.directives.clone()),e.schema=this.schema.clone(),e.contents=X.isNode(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){ft(this.contents)&&this.contents.add(e)}addIn(e,n){ft(this.contents)&&this.contents.addIn(e,n)}createAlias(e,n){if(!e.anchor){let i=as.anchorNames(this);e.anchor=!n||i.has(n)?as.findNewAnchor(n||"a",i):n}return new Pp.Alias(e.anchor)}createNode(e,n,i){let r;if(typeof n=="function")e=n.call({"":e},"",e),r=n;else if(Array.isArray(n)){let m=y=>typeof y=="number"||y instanceof String||y instanceof Number,w=n.filter(m).map(String);w.length>0&&(n=n.concat(w)),r=n}else i===void 0&&n&&(i=n,n=void 0);let{aliasDuplicateObjects:s,anchorPrefix:o,flow:a,keepUndefined:c,onTagObj:l,tag:f}=i??{},{onAnchor:u,setAnchors:d,sourceObjects:h}=as.createNodeAnchors(this,o||"a"),g={aliasDuplicateObjects:s??!0,keepUndefined:c??!1,onAnchor:u,onTagObj:l,replacer:r,schema:this.schema,sourceObjects:h},p=jp.createNode(e,f,g);return a&&X.isCollection(p)&&(p.flow=!0),d(),p}createPair(e,n,i={}){let r=this.createNode(e,null,i),s=this.createNode(n,null,i);return new Rp.Pair(r,s)}delete(e){return ft(this.contents)?this.contents.delete(e):!1}deleteIn(e){return ut.isEmptyPath(e)?this.contents==null?!1:(this.contents=null,!0):ft(this.contents)?this.contents.deleteIn(e):!1}get(e,n){return X.isCollection(this.contents)?this.contents.get(e,n):void 0}getIn(e,n){return ut.isEmptyPath(e)?!n&&X.isScalar(this.contents)?this.contents.value:this.contents:X.isCollection(this.contents)?this.contents.getIn(e,n):void 0}has(e){return X.isCollection(this.contents)?this.contents.has(e):!1}hasIn(e){return ut.isEmptyPath(e)?this.contents!==void 0:X.isCollection(this.contents)?this.contents.hasIn(e):!1}set(e,n){this.contents==null?this.contents=ut.collectionFromPath(this.schema,[e],n):ft(this.contents)&&this.contents.set(e,n)}setIn(e,n){ut.isEmptyPath(e)?this.contents=n:this.contents==null?this.contents=ut.collectionFromPath(this.schema,Array.from(e),n):ft(this.contents)&&this.contents.setIn(e,n)}setSchema(e,n={}){typeof e=="number"&&(e=String(e));let i;switch(e){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new cs.Directives({version:"1.1"}),i={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=e:this.directives=new cs.Directives({version:e}),i={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,i=null;break;default:{let r=JSON.stringify(e);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${r}`)}}if(n.schema instanceof Object)this.schema=n.schema;else if(i)this.schema=new Ap.Schema(Object.assign(i,n));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:e,jsonArg:n,mapAsMap:i,maxAliasCount:r,onAnchor:s,reviver:o}={}){let a={anchors:new Map,doc:this,keep:!e,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},c=Op.toJS(this.contents,n??"",a);if(typeof s=="function")for(let{count:l,res:f}of a.anchors.values())s(f,l);return typeof o=="function"?Tp.applyReviver(o,{"":c},"",c):c}toJSON(e,n){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:n})}toString(e={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let n=JSON.stringify(e.indent);throw new Error(`"indent" option must be a positive integer, not ${n}`)}return Np.stringifyDocument(this,e)}};function ft(t){if(X.isCollection(t))return!0;throw new Error("Expected a YAML collection as document contents")}cc.Document=ls});var Ut=v(Yt=>{"use strict";var Kt=class extends Error{constructor(e,n,i,r){super(),this.name=e,this.code=i,this.message=r,this.pos=n}},us=class extends Kt{constructor(e,n,i){super("YAMLParseError",e,n,i)}},fs=class extends Kt{constructor(e,n,i){super("YAMLWarning",e,n,i)}},Ip=(t,e)=>n=>{if(n.pos[0]===-1)return;n.linePos=n.pos.map(a=>e.linePos(a));let{line:i,col:r}=n.linePos[0];n.message+=` at line ${i}, column ${r}`;let s=r-1,o=t.substring(e.lineStarts[i-1],e.lineStarts[i]).replace(/[\n\r]+$/,"");if(s>=60&&o.length>80){let a=Math.min(s-39,o.length-79);o="…"+o.substring(a),s-=a-1}if(o.length>80&&(o=o.substring(0,79)+"…"),i>1&&/^ *$/.test(o.substring(0,s))){let a=t.substring(e.lineStarts[i-2],e.lineStarts[i-1]);a.length>80&&(a=a.substring(0,79)+`… `),o=a+o}if(/[^ ]/.test(o)){let a=1,c=n.linePos[1];c?.line===i&&c.col>r&&(a=Math.max(1,Math.min(c.col-r,80-s)));let l=" ".repeat(s)+"^".repeat(a);n.message+=`: ${o} ${l} -`}};Yt.YAMLError=Kt;Yt.YAMLParseError=ls;Yt.YAMLWarning=us;Yt.prettifyError=jp});var Jt=v(lc=>{"use strict";function Ip(t,{flow:e,indicator:n,next:i,offset:r,onError:s,parentIndent:o,startOnNewline:a}){let c=!1,l=a,f=a,u="",d="",h=!1,g=!1,p=null,m=null,w=null,y=null,S=null,k=null,C=null;for(let b of t)switch(g&&(b.type!=="space"&&b.type!=="newline"&&b.type!=="comma"&&s(b.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),g=!1),p&&(l&&b.type!=="comment"&&b.type!=="newline"&&s(p,"TAB_AS_INDENT","Tabs are not allowed as indentation"),p=null),b.type){case"space":!e&&(n!=="doc-start"||i?.type!=="flow-collection")&&b.source.includes(" ")&&(p=b),f=!0;break;case"comment":{f||s(b,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let P=b.source.substring(1)||" ";u?u+=d+P:u=P,d="",l=!1;break}case"newline":l?u?u+=b.source:(!k||n!=="seq-item-ind")&&(c=!0):d+=b.source,l=!0,h=!0,(m||w)&&(y=b),f=!0;break;case"anchor":m&&s(b,"MULTIPLE_ANCHORS","A node can have at most one anchor"),b.source.endsWith(":")&&s(b.offset+b.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),m=b,C??(C=b.offset),l=!1,f=!1,g=!0;break;case"tag":{w&&s(b,"MULTIPLE_TAGS","A node can have at most one tag"),w=b,C??(C=b.offset),l=!1,f=!1,g=!0;break}case n:(m||w)&&s(b,"BAD_PROP_ORDER",`Anchors and tags must be after the ${b.source} indicator`),k&&s(b,"UNEXPECTED_TOKEN",`Unexpected ${b.source} in ${e??"collection"}`),k=b,l=n==="seq-item-ind"||n==="explicit-key-ind",f=!1;break;case"comma":if(e){S&&s(b,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),S=b,l=!1,f=!1;break}default:s(b,"UNEXPECTED_TOKEN",`Unexpected ${b.type} token`),l=!1,f=!1}let E=t[t.length-1],R=E?E.offset+E.source.length:r;return g&&i&&i.type!=="space"&&i.type!=="newline"&&i.type!=="comma"&&(i.type!=="scalar"||i.source!=="")&&s(i.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),p&&(l&&p.indent<=o||i?.type==="block-map"||i?.type==="block-seq")&&s(p,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:S,found:k,spaceBefore:c,comment:u,hasNewline:h,anchor:m,tag:w,newlineAfterProp:y,end:R,start:C??R}}lc.resolveProps=Ip});var fi=v(uc=>{"use strict";function fs(t){if(!t)return null;switch(t.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(t.source.includes(` -`))return!0;if(t.end){for(let e of t.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(let e of t.items){for(let n of e.start)if(n.type==="newline")return!0;if(e.sep){for(let n of e.sep)if(n.type==="newline")return!0}if(fs(e.key)||fs(e.value))return!0}return!1;default:return!0}}uc.containsNewline=fs});var ds=v(fc=>{"use strict";var qp=fi();function $p(t,e,n){if(e?.type==="flow-collection"){let i=e.end[0];i.indent===t&&(i.source==="]"||i.source==="}")&&qp.containsNewline(e)&&n(i,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}fc.flowIndentCheck=$p});var ps=v(pc=>{"use strict";var dc=_();function Lp(t,e,n){let{uniqueKeys:i}=t.options;if(i===!1)return!1;let r=typeof i=="function"?i:(s,o)=>s===o||dc.isScalar(s)&&dc.isScalar(o)&&s.value===o.value;return e.some(s=>r(s.key,n))}pc.mapIncludes=Lp});var vc=v(yc=>{"use strict";var mc=Re(),Dp=Ae(),hc=Jt(),Fp=fi(),gc=ds(),Mp=ps(),wc="All mapping items must start at the same column";function Wp({composeNode:t,composeEmptyNode:e},n,i,r,s){let o=s?.nodeClass??Dp.YAMLMap,a=new o(n.schema);n.atRoot&&(n.atRoot=!1);let c=i.offset,l=null;for(let f of i.items){let{start:u,key:d,sep:h,value:g}=f,p=hc.resolveProps(u,{indicator:"explicit-key-ind",next:d??h?.[0],offset:c,onError:r,parentIndent:i.indent,startOnNewline:!0}),m=!p.found;if(m){if(d&&(d.type==="block-seq"?r(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in d&&d.indent!==i.indent&&r(c,"BAD_INDENT",wc)),!p.anchor&&!p.tag&&!h){l=p.end,p.comment&&(a.comment?a.comment+=` -`+p.comment:a.comment=p.comment);continue}(p.newlineAfterProp||Fp.containsNewline(d))&&r(d??u[u.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else p.found?.indent!==i.indent&&r(c,"BAD_INDENT",wc);n.atKey=!0;let w=p.end,y=d?t(n,d,p,r):e(n,w,u,null,p,r);n.schema.compat&&gc.flowIndentCheck(i.indent,d,r),n.atKey=!1,Mp.mapIncludes(n,a.items,y)&&r(w,"DUPLICATE_KEY","Map keys must be unique");let S=hc.resolveProps(h??[],{indicator:"map-value-ind",next:g,offset:y.range[2],onError:r,parentIndent:i.indent,startOnNewline:!d||d.type==="block-scalar"});if(c=S.end,S.found){m&&(g?.type==="block-map"&&!S.hasNewline&&r(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),n.options.strict&&p.start{"use strict";var Bp=Ne(),Kp=Jt(),Yp=ds();function Up({composeNode:t,composeEmptyNode:e},n,i,r,s){let o=s?.nodeClass??Bp.YAMLSeq,a=new o(n.schema);n.atRoot&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let c=i.offset,l=null;for(let{start:f,value:u}of i.items){let d=Kp.resolveProps(f,{indicator:"seq-item-ind",next:u,offset:c,onError:r,parentIndent:i.indent,startOnNewline:!0});if(!d.found)if(d.anchor||d.tag||u)u?.type==="block-seq"?r(d.end,"BAD_INDENT","All sequence items must start at the same column"):r(c,"MISSING_CHAR","Sequence item without - indicator");else{l=d.end,d.comment&&(a.comment=d.comment);continue}let h=u?t(n,u,d,r):e(n,d.end,f,null,d,r);n.schema.compat&&Yp.flowIndentCheck(i.indent,u,r),c=h.range[2],a.items.push(h)}return a.range=[i.offset,c,l??c],a}bc.resolveBlockSeq=Up});var dt=v(Sc=>{"use strict";function Jp(t,e,n,i){let r="";if(t){let s=!1,o="";for(let a of t){let{source:c,type:l}=a;switch(l){case"space":s=!0;break;case"comment":{n&&!s&&i(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let f=c.substring(1)||" ";r?r+=o+f:r=f,o="";break}case"newline":r&&(o+=c),s=!0;break;default:i(a,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}e+=c.length}}return{comment:r,offset:e}}Sc.resolveEnd=Jp});var _c=v(xc=>{"use strict";var Vp=_(),Hp=Re(),Cc=Ae(),Gp=Ne(),zp=dt(),Ec=Jt(),Qp=fi(),Xp=ps(),ms="Block collections are not allowed within flow collections",hs=t=>t&&(t.type==="block-map"||t.type==="block-seq");function Zp({composeNode:t,composeEmptyNode:e},n,i,r,s){let o=i.start.source==="{",a=o?"flow map":"flow sequence",c=s?.nodeClass??(o?Cc.YAMLMap:Gp.YAMLSeq),l=new c(n.schema);l.flow=!0;let f=n.atRoot;f&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let u=i.offset+i.start.source.length;for(let m=0;m0){let m=zp.resolveEnd(g,p,n.options.strict,r);m.comment&&(l.comment?l.comment+=` -`+m.comment:l.comment=m.comment),l.range=[i.offset,p,m.offset]}else l.range=[i.offset,p,p];return l}xc.resolveFlowCollection=Zp});var Rc=v(Pc=>{"use strict";var em=_(),tm=I(),nm=Ae(),im=Ne(),rm=vc(),sm=kc(),om=_c();function gs(t,e,n,i,r,s){let o=n.type==="block-map"?rm.resolveBlockMap(t,e,n,i,s):n.type==="block-seq"?sm.resolveBlockSeq(t,e,n,i,s):om.resolveFlowCollection(t,e,n,i,s),a=o.constructor;return r==="!"||r===a.tagName?(o.tag=a.tagName,o):(r&&(o.tag=r),o)}function am(t,e,n,i,r){let s=i.tag,o=s?e.directives.tagName(s.source,d=>r(s,"TAG_RESOLVE_FAILED",d)):null;if(n.type==="block-seq"){let{anchor:d,newlineAfterProp:h}=i,g=d&&s?d.offset>s.offset?d:s:d??s;g&&(!h||h.offsetd.tag===o&&d.collection===a);if(!c){let d=e.schema.knownTags[o];if(d?.collection===a)e.schema.tags.push(Object.assign({},d,{default:!1})),c=d;else return d?r(s,"BAD_COLLECTION_TYPE",`${d.tag} used for ${a} collection, but expects ${d.collection??"scalar"}`,!0):r(s,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),gs(t,e,n,r,o)}let l=gs(t,e,n,r,o,c),f=c.resolve?.(l,d=>r(s,"TAG_RESOLVE_FAILED",d),e.options)??l,u=em.isNode(f)?f:new tm.Scalar(f);return u.range=l.range,u.tag=o,c?.format&&(u.format=c.format),u}Pc.composeCollection=am});var ys=v(Oc=>{"use strict";var ws=I();function cm(t,e,n){let i=e.offset,r=lm(e,t.options.strict,n);if(!r)return{value:"",type:null,comment:"",range:[i,i,i]};let s=r.mode===">"?ws.Scalar.BLOCK_FOLDED:ws.Scalar.BLOCK_LITERAL,o=e.source?um(e.source):[],a=o.length;for(let p=o.length-1;p>=0;--p){let m=o[p][1];if(m===""||m==="\r")a=p;else break}if(a===0){let p=r.chomp==="+"&&o.length>0?` +`}};Yt.YAMLError=Kt;Yt.YAMLParseError=us;Yt.YAMLWarning=fs;Yt.prettifyError=Ip});var Jt=v(lc=>{"use strict";function $p(t,{flow:e,indicator:n,next:i,offset:r,onError:s,parentIndent:o,startOnNewline:a}){let c=!1,l=a,f=a,u="",d="",h=!1,g=!1,p=null,m=null,w=null,y=null,S=null,k=null,C=null;for(let b of t)switch(g&&(b.type!=="space"&&b.type!=="newline"&&b.type!=="comma"&&s(b.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),g=!1),p&&(l&&b.type!=="comment"&&b.type!=="newline"&&s(p,"TAB_AS_INDENT","Tabs are not allowed as indentation"),p=null),b.type){case"space":!e&&(n!=="doc-start"||i?.type!=="flow-collection")&&b.source.includes(" ")&&(p=b),f=!0;break;case"comment":{f||s(b,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let P=b.source.substring(1)||" ";u?u+=d+P:u=P,d="",l=!1;break}case"newline":l?u?u+=b.source:(!k||n!=="seq-item-ind")&&(c=!0):d+=b.source,l=!0,h=!0,(m||w)&&(y=b),f=!0;break;case"anchor":m&&s(b,"MULTIPLE_ANCHORS","A node can have at most one anchor"),b.source.endsWith(":")&&s(b.offset+b.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),m=b,C??(C=b.offset),l=!1,f=!1,g=!0;break;case"tag":{w&&s(b,"MULTIPLE_TAGS","A node can have at most one tag"),w=b,C??(C=b.offset),l=!1,f=!1,g=!0;break}case n:(m||w)&&s(b,"BAD_PROP_ORDER",`Anchors and tags must be after the ${b.source} indicator`),k&&s(b,"UNEXPECTED_TOKEN",`Unexpected ${b.source} in ${e??"collection"}`),k=b,l=n==="seq-item-ind"||n==="explicit-key-ind",f=!1;break;case"comma":if(e){S&&s(b,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),S=b,l=!1,f=!1;break}default:s(b,"UNEXPECTED_TOKEN",`Unexpected ${b.type} token`),l=!1,f=!1}let E=t[t.length-1],R=E?E.offset+E.source.length:r;return g&&i&&i.type!=="space"&&i.type!=="newline"&&i.type!=="comma"&&(i.type!=="scalar"||i.source!=="")&&s(i.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),p&&(l&&p.indent<=o||i?.type==="block-map"||i?.type==="block-seq")&&s(p,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:S,found:k,spaceBefore:c,comment:u,hasNewline:h,anchor:m,tag:w,newlineAfterProp:y,end:R,start:C??R}}lc.resolveProps=$p});var fi=v(uc=>{"use strict";function ds(t){if(!t)return null;switch(t.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(t.source.includes(` +`))return!0;if(t.end){for(let e of t.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(let e of t.items){for(let n of e.start)if(n.type==="newline")return!0;if(e.sep){for(let n of e.sep)if(n.type==="newline")return!0}if(ds(e.key)||ds(e.value))return!0}return!1;default:return!0}}uc.containsNewline=ds});var ps=v(fc=>{"use strict";var qp=fi();function Lp(t,e,n){if(e?.type==="flow-collection"){let i=e.end[0];i.indent===t&&(i.source==="]"||i.source==="}")&&qp.containsNewline(e)&&n(i,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}fc.flowIndentCheck=Lp});var ms=v(pc=>{"use strict";var dc=_();function Dp(t,e,n){let{uniqueKeys:i}=t.options;if(i===!1)return!1;let r=typeof i=="function"?i:(s,o)=>s===o||dc.isScalar(s)&&dc.isScalar(o)&&s.value===o.value;return e.some(s=>r(s.key,n))}pc.mapIncludes=Dp});var vc=v(yc=>{"use strict";var mc=Re(),Fp=Ae(),hc=Jt(),Mp=fi(),gc=ps(),Wp=ms(),wc="All mapping items must start at the same column";function Bp({composeNode:t,composeEmptyNode:e},n,i,r,s){let o=s?.nodeClass??Fp.YAMLMap,a=new o(n.schema);n.atRoot&&(n.atRoot=!1);let c=i.offset,l=null;for(let f of i.items){let{start:u,key:d,sep:h,value:g}=f,p=hc.resolveProps(u,{indicator:"explicit-key-ind",next:d??h?.[0],offset:c,onError:r,parentIndent:i.indent,startOnNewline:!0}),m=!p.found;if(m){if(d&&(d.type==="block-seq"?r(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in d&&d.indent!==i.indent&&r(c,"BAD_INDENT",wc)),!p.anchor&&!p.tag&&!h){l=p.end,p.comment&&(a.comment?a.comment+=` +`+p.comment:a.comment=p.comment);continue}(p.newlineAfterProp||Mp.containsNewline(d))&&r(d??u[u.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else p.found?.indent!==i.indent&&r(c,"BAD_INDENT",wc);n.atKey=!0;let w=p.end,y=d?t(n,d,p,r):e(n,w,u,null,p,r);n.schema.compat&&gc.flowIndentCheck(i.indent,d,r),n.atKey=!1,Wp.mapIncludes(n,a.items,y)&&r(w,"DUPLICATE_KEY","Map keys must be unique");let S=hc.resolveProps(h??[],{indicator:"map-value-ind",next:g,offset:y.range[2],onError:r,parentIndent:i.indent,startOnNewline:!d||d.type==="block-scalar"});if(c=S.end,S.found){m&&(g?.type==="block-map"&&!S.hasNewline&&r(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),n.options.strict&&p.start{"use strict";var Kp=Ne(),Yp=Jt(),Up=ps();function Jp({composeNode:t,composeEmptyNode:e},n,i,r,s){let o=s?.nodeClass??Kp.YAMLSeq,a=new o(n.schema);n.atRoot&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let c=i.offset,l=null;for(let{start:f,value:u}of i.items){let d=Yp.resolveProps(f,{indicator:"seq-item-ind",next:u,offset:c,onError:r,parentIndent:i.indent,startOnNewline:!0});if(!d.found)if(d.anchor||d.tag||u)u?.type==="block-seq"?r(d.end,"BAD_INDENT","All sequence items must start at the same column"):r(c,"MISSING_CHAR","Sequence item without - indicator");else{l=d.end,d.comment&&(a.comment=d.comment);continue}let h=u?t(n,u,d,r):e(n,d.end,f,null,d,r);n.schema.compat&&Up.flowIndentCheck(i.indent,u,r),c=h.range[2],a.items.push(h)}return a.range=[i.offset,c,l??c],a}bc.resolveBlockSeq=Jp});var dt=v(Sc=>{"use strict";function Vp(t,e,n,i){let r="";if(t){let s=!1,o="";for(let a of t){let{source:c,type:l}=a;switch(l){case"space":s=!0;break;case"comment":{n&&!s&&i(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let f=c.substring(1)||" ";r?r+=o+f:r=f,o="";break}case"newline":r&&(o+=c),s=!0;break;default:i(a,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}e+=c.length}}return{comment:r,offset:e}}Sc.resolveEnd=Vp});var _c=v(xc=>{"use strict";var Hp=_(),Gp=Re(),Cc=Ae(),zp=Ne(),Qp=dt(),Ec=Jt(),Xp=fi(),Zp=ms(),hs="Block collections are not allowed within flow collections",gs=t=>t&&(t.type==="block-map"||t.type==="block-seq");function em({composeNode:t,composeEmptyNode:e},n,i,r,s){let o=i.start.source==="{",a=o?"flow map":"flow sequence",c=s?.nodeClass??(o?Cc.YAMLMap:zp.YAMLSeq),l=new c(n.schema);l.flow=!0;let f=n.atRoot;f&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let u=i.offset+i.start.source.length;for(let m=0;m0){let m=Qp.resolveEnd(g,p,n.options.strict,r);m.comment&&(l.comment?l.comment+=` +`+m.comment:l.comment=m.comment),l.range=[i.offset,p,m.offset]}else l.range=[i.offset,p,p];return l}xc.resolveFlowCollection=em});var Rc=v(Pc=>{"use strict";var tm=_(),nm=j(),im=Ae(),rm=Ne(),sm=vc(),om=kc(),am=_c();function ws(t,e,n,i,r,s){let o=n.type==="block-map"?sm.resolveBlockMap(t,e,n,i,s):n.type==="block-seq"?om.resolveBlockSeq(t,e,n,i,s):am.resolveFlowCollection(t,e,n,i,s),a=o.constructor;return r==="!"||r===a.tagName?(o.tag=a.tagName,o):(r&&(o.tag=r),o)}function cm(t,e,n,i,r){let s=i.tag,o=s?e.directives.tagName(s.source,d=>r(s,"TAG_RESOLVE_FAILED",d)):null;if(n.type==="block-seq"){let{anchor:d,newlineAfterProp:h}=i,g=d&&s?d.offset>s.offset?d:s:d??s;g&&(!h||h.offsetd.tag===o&&d.collection===a);if(!c){let d=e.schema.knownTags[o];if(d?.collection===a)e.schema.tags.push(Object.assign({},d,{default:!1})),c=d;else return d?r(s,"BAD_COLLECTION_TYPE",`${d.tag} used for ${a} collection, but expects ${d.collection??"scalar"}`,!0):r(s,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),ws(t,e,n,r,o)}let l=ws(t,e,n,r,o,c),f=c.resolve?.(l,d=>r(s,"TAG_RESOLVE_FAILED",d),e.options)??l,u=tm.isNode(f)?f:new nm.Scalar(f);return u.range=l.range,u.tag=o,c?.format&&(u.format=c.format),u}Pc.composeCollection=cm});var vs=v(Oc=>{"use strict";var ys=j();function lm(t,e,n){let i=e.offset,r=um(e,t.options.strict,n);if(!r)return{value:"",type:null,comment:"",range:[i,i,i]};let s=r.mode===">"?ys.Scalar.BLOCK_FOLDED:ys.Scalar.BLOCK_LITERAL,o=e.source?fm(e.source):[],a=o.length;for(let p=o.length-1;p>=0;--p){let m=o[p][1];if(m===""||m==="\r")a=p;else break}if(a===0){let p=r.chomp==="+"&&o.length>0?` `.repeat(Math.max(1,o.length-1)):"",m=i+r.length;return e.source&&(m+=e.source.length),{value:p,type:s,comment:r.comment,range:[i,m,m]}}let c=e.indent+r.indent,l=e.offset+r.length,f=0;for(let p=0;pc&&(c=m.length);else{m.length=a;--p)o[p][0].length>c&&(a=p+1);let u="",d="",h=!1;for(let p=0;pc||w[0]===" "?(d===" "?d=` `:!h&&d===` `&&(d=` @@ -84,46 +84,46 @@ ${l} `+o[p][0].slice(c);u[u.length-1]!==` `&&(u+=` `);break;default:u+=` -`}let g=i+r.length+e.source.length;return{value:u,type:s,comment:r.comment,range:[i,g,g]}}function lm({offset:t,props:e},n,i){if(e[0].type!=="block-scalar-header")return i(e[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:r}=e[0],s=r[0],o=0,a="",c=-1;for(let d=1;d{"use strict";var vs=I(),fm=dt();function dm(t,e,n){let{offset:i,type:r,source:s,end:o}=t,a,c,l=(d,h,g)=>n(i+d,h,g);switch(r){case"scalar":a=vs.Scalar.PLAIN,c=pm(s,l);break;case"single-quoted-scalar":a=vs.Scalar.QUOTE_SINGLE,c=mm(s,l);break;case"double-quoted-scalar":a=vs.Scalar.QUOTE_DOUBLE,c=hm(s,l);break;default:return n(t,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${r}`),{value:"",type:null,comment:"",range:[i,i+s.length,i+s.length]}}let f=i+s.length,u=fm.resolveEnd(o,f,e,n);return{value:c,type:a,comment:u.comment,range:[i,f,u.offset]}}function pm(t,e){let n="";switch(t[0]){case" ":n="a tab character";break;case",":n="flow indicator character ,";break;case"%":n="directive indicator character %";break;case"|":case">":{n=`block scalar indicator ${t[0]}`;break}case"@":case"`":{n=`reserved character ${t[0]}`;break}}return n&&e(0,"BAD_SCALAR_START",`Plain value cannot start with ${n}`),Ac(t)}function mm(t,e){return(t[t.length-1]!=="'"||t.length===1)&&e(t.length,"MISSING_CHAR","Missing closing 'quote"),Ac(t.slice(1,-1)).replace(/''/g,"'")}function Ac(t){let e,n;try{e=new RegExp(`(.*?)(?{"use strict";var bs=j(),dm=dt();function pm(t,e,n){let{offset:i,type:r,source:s,end:o}=t,a,c,l=(d,h,g)=>n(i+d,h,g);switch(r){case"scalar":a=bs.Scalar.PLAIN,c=mm(s,l);break;case"single-quoted-scalar":a=bs.Scalar.QUOTE_SINGLE,c=hm(s,l);break;case"double-quoted-scalar":a=bs.Scalar.QUOTE_DOUBLE,c=gm(s,l);break;default:return n(t,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${r}`),{value:"",type:null,comment:"",range:[i,i+s.length,i+s.length]}}let f=i+s.length,u=dm.resolveEnd(o,f,e,n);return{value:c,type:a,comment:u.comment,range:[i,f,u.offset]}}function mm(t,e){let n="";switch(t[0]){case" ":n="a tab character";break;case",":n="flow indicator character ,";break;case"%":n="directive indicator character %";break;case"|":case">":{n=`block scalar indicator ${t[0]}`;break}case"@":case"`":{n=`reserved character ${t[0]}`;break}}return n&&e(0,"BAD_SCALAR_START",`Plain value cannot start with ${n}`),Ac(t)}function hm(t,e){return(t[t.length-1]!=="'"||t.length===1)&&e(t.length,"MISSING_CHAR","Missing closing 'quote"),Ac(t.slice(1,-1)).replace(/''/g,"'")}function Ac(t){let e,n;try{e=new RegExp(`(.*?)(?s?t.slice(s,i+1):r)}else n+=r}return(t[t.length-1]!=='"'||t.length===1)&&e(t.length,"MISSING_CHAR",'Missing closing "quote'),n}function gm(t,e){let n="",i=t[e+1];for(;(i===" "||i===" "||i===` +`)&&(n+=i>s?t.slice(s,i+1):r)}else n+=r}return(t[t.length-1]!=='"'||t.length===1)&&e(t.length,"MISSING_CHAR",'Missing closing "quote'),n}function wm(t,e){let n="",i=t[e+1];for(;(i===" "||i===" "||i===` `||i==="\r")&&!(i==="\r"&&t[e+2]!==` `);)i===` `&&(n+=` -`),e+=1,i=t[e+1];return n||(n=" "),{fold:n,offset:e}}var wm={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:` -`,r:"\r",t:" ",v:"\v",N:"…",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function ym(t,e,n,i){let r=t.substr(e,n),o=r.length===n&&/^[0-9a-fA-F]+$/.test(r)?parseInt(r,16):NaN;try{return String.fromCodePoint(o)}catch{let a=t.substr(e-2,n+2);return i(e-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),a}}Nc.resolveFlowScalar=dm});var Ic=v(jc=>{"use strict";var He=_(),Tc=I(),vm=ys(),bm=bs();function km(t,e,n,i){let{value:r,type:s,comment:o,range:a}=e.type==="block-scalar"?vm.resolveBlockScalar(t,e,i):bm.resolveFlowScalar(e,t.options.strict,i),c=n?t.directives.tagName(n.source,u=>i(n,"TAG_RESOLVE_FAILED",u)):null,l;t.options.stringKeys&&t.atKey?l=t.schema[He.SCALAR]:c?l=Sm(t.schema,r,c,n,i):e.type==="scalar"?l=Cm(t,r,e,i):l=t.schema[He.SCALAR];let f;try{let u=l.resolve(r,d=>i(n??e,"TAG_RESOLVE_FAILED",d),t.options);f=He.isScalar(u)?u:new Tc.Scalar(u)}catch(u){let d=u instanceof Error?u.message:String(u);i(n??e,"TAG_RESOLVE_FAILED",d),f=new Tc.Scalar(r)}return f.range=a,f.source=r,s&&(f.type=s),c&&(f.tag=c),l.format&&(f.format=l.format),o&&(f.comment=o),f}function Sm(t,e,n,i,r){if(n==="!")return t[He.SCALAR];let s=[];for(let a of t.tags)if(!a.collection&&a.tag===n)if(a.default&&a.test)s.push(a);else return a;for(let a of s)if(a.test?.test(e))return a;let o=t.knownTags[n];return o&&!o.collection?(t.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(r(i,"TAG_RESOLVE_FAILED",`Unresolved tag: ${n}`,n!=="tag:yaml.org,2002:str"),t[He.SCALAR])}function Cm({atKey:t,directives:e,schema:n},i,r,s){let o=n.tags.find(a=>(a.default===!0||t&&a.default==="key")&&a.test?.test(i))||n[He.SCALAR];if(n.compat){let a=n.compat.find(c=>c.default&&c.test?.test(i))??n[He.SCALAR];if(o.tag!==a.tag){let c=e.tagString(o.tag),l=e.tagString(a.tag),f=`Value may be parsed as either ${c} or ${l}`;s(r,"TAG_RESOLVE_FAILED",f,!0)}}return o}jc.composeScalar=km});var $c=v(qc=>{"use strict";function Em(t,e,n){if(e){n??(n=e.length);for(let i=n-1;i>=0;--i){let r=e[i];switch(r.type){case"space":case"comment":case"newline":t-=r.source.length;continue}for(r=e[++i];r?.type==="space";)t+=r.source.length,r=e[++i];break}}return t}qc.emptyScalarPosition=Em});var Fc=v(Ss=>{"use strict";var xm=_t(),_m=_(),Pm=Rc(),Lc=Ic(),Rm=dt(),Om=$c(),Am={composeNode:Dc,composeEmptyNode:ks};function Dc(t,e,n,i){let r=t.atKey,{spaceBefore:s,comment:o,anchor:a,tag:c}=n,l,f=!0;switch(e.type){case"alias":l=Nm(t,e,i),(a||c)&&i(e,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=Lc.composeScalar(t,e,c,i),a&&(l.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=Pm.composeCollection(Am,t,e,n,i),a&&(l.anchor=a.source.substring(1))}catch(u){let d=u instanceof Error?u.message:String(u);i(e,"RESOURCE_EXHAUSTION",d)}break;default:{let u=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;i(e,"UNEXPECTED_TOKEN",u),f=!1}}return l??(l=ks(t,e.offset,void 0,null,n,i)),a&&l.anchor===""&&i(a,"BAD_ALIAS","Anchor cannot be an empty string"),r&&t.options.stringKeys&&(!_m.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&i(c??e,"NON_STRING_KEY","With stringKeys, all keys must be strings"),s&&(l.spaceBefore=!0),o&&(e.type==="scalar"&&e.source===""?l.comment=o:l.commentBefore=o),t.options.keepSourceTokens&&f&&(l.srcToken=e),l}function ks(t,e,n,i,{spaceBefore:r,comment:s,anchor:o,tag:a,end:c},l){let f={type:"scalar",offset:Om.emptyScalarPosition(e,n,i),indent:-1,source:""},u=Lc.composeScalar(t,f,a,l);return o&&(u.anchor=o.source.substring(1),u.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),r&&(u.spaceBefore=!0),s&&(u.comment=s,u.range[2]=c),u}function Nm({options:t},{offset:e,source:n,end:i},r){let s=new xm.Alias(n.substring(1));s.source===""&&r(e,"BAD_ALIAS","Alias cannot be an empty string"),s.source.endsWith(":")&&r(e+n.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=e+n.length,a=Rm.resolveEnd(i,o,t.strict,r);return s.range=[e,o,a.offset],a.comment&&(s.comment=a.comment),s}Ss.composeEmptyNode=ks;Ss.composeNode=Dc});var Bc=v(Wc=>{"use strict";var Tm=Bt(),Mc=Fc(),jm=dt(),Im=Jt();function qm(t,e,{offset:n,start:i,value:r,end:s},o){let a=Object.assign({_directives:e},t),c=new Tm.Document(void 0,a),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},f=Im.resolveProps(i,{indicator:"doc-start",next:r??s?.[0],offset:n,onError:o,parentIndent:0,startOnNewline:!0});f.found&&(c.directives.docStart=!0,r&&(r.type==="block-map"||r.type==="block-seq")&&!f.hasNewline&&o(f.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=r?Mc.composeNode(l,r,f,o):Mc.composeEmptyNode(l,f.end,i,null,f,o);let u=c.contents.range[2],d=jm.resolveEnd(s,u,!1,o);return d.comment&&(c.comment=d.comment),c.range=[n,u,d.offset],c}Wc.composeDoc=qm});var Es=v(Uc=>{"use strict";var $m=kn("process"),Lm=lr(),Dm=Bt(),Vt=Ut(),Kc=_(),Fm=Bc(),Mm=dt();function Ht(t){if(typeof t=="number")return[t,t+1];if(Array.isArray(t))return t.length===2?t:[t[0],t[1]];let{offset:e,source:n}=t;return[e,e+(typeof n=="string"?n.length:1)]}function Yc(t){let e="",n=!1,i=!1;for(let r=0;r{"use strict";var He=_(),Tc=j(),bm=vs(),km=ks();function Sm(t,e,n,i){let{value:r,type:s,comment:o,range:a}=e.type==="block-scalar"?bm.resolveBlockScalar(t,e,i):km.resolveFlowScalar(e,t.options.strict,i),c=n?t.directives.tagName(n.source,u=>i(n,"TAG_RESOLVE_FAILED",u)):null,l;t.options.stringKeys&&t.atKey?l=t.schema[He.SCALAR]:c?l=Cm(t.schema,r,c,n,i):e.type==="scalar"?l=Em(t,r,e,i):l=t.schema[He.SCALAR];let f;try{let u=l.resolve(r,d=>i(n??e,"TAG_RESOLVE_FAILED",d),t.options);f=He.isScalar(u)?u:new Tc.Scalar(u)}catch(u){let d=u instanceof Error?u.message:String(u);i(n??e,"TAG_RESOLVE_FAILED",d),f=new Tc.Scalar(r)}return f.range=a,f.source=r,s&&(f.type=s),c&&(f.tag=c),l.format&&(f.format=l.format),o&&(f.comment=o),f}function Cm(t,e,n,i,r){if(n==="!")return t[He.SCALAR];let s=[];for(let a of t.tags)if(!a.collection&&a.tag===n)if(a.default&&a.test)s.push(a);else return a;for(let a of s)if(a.test?.test(e))return a;let o=t.knownTags[n];return o&&!o.collection?(t.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(r(i,"TAG_RESOLVE_FAILED",`Unresolved tag: ${n}`,n!=="tag:yaml.org,2002:str"),t[He.SCALAR])}function Em({atKey:t,directives:e,schema:n},i,r,s){let o=n.tags.find(a=>(a.default===!0||t&&a.default==="key")&&a.test?.test(i))||n[He.SCALAR];if(n.compat){let a=n.compat.find(c=>c.default&&c.test?.test(i))??n[He.SCALAR];if(o.tag!==a.tag){let c=e.tagString(o.tag),l=e.tagString(a.tag),f=`Value may be parsed as either ${c} or ${l}`;s(r,"TAG_RESOLVE_FAILED",f,!0)}}return o}jc.composeScalar=Sm});var qc=v($c=>{"use strict";function xm(t,e,n){if(e){n??(n=e.length);for(let i=n-1;i>=0;--i){let r=e[i];switch(r.type){case"space":case"comment":case"newline":t-=r.source.length;continue}for(r=e[++i];r?.type==="space";)t+=r.source.length,r=e[++i];break}}return t}$c.emptyScalarPosition=xm});var Fc=v(Cs=>{"use strict";var _m=_t(),Pm=_(),Rm=Rc(),Lc=Ic(),Om=dt(),Am=qc(),Nm={composeNode:Dc,composeEmptyNode:Ss};function Dc(t,e,n,i){let r=t.atKey,{spaceBefore:s,comment:o,anchor:a,tag:c}=n,l,f=!0;switch(e.type){case"alias":l=Tm(t,e,i),(a||c)&&i(e,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=Lc.composeScalar(t,e,c,i),a&&(l.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=Rm.composeCollection(Nm,t,e,n,i),a&&(l.anchor=a.source.substring(1))}catch(u){let d=u instanceof Error?u.message:String(u);i(e,"RESOURCE_EXHAUSTION",d)}break;default:{let u=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;i(e,"UNEXPECTED_TOKEN",u),f=!1}}return l??(l=Ss(t,e.offset,void 0,null,n,i)),a&&l.anchor===""&&i(a,"BAD_ALIAS","Anchor cannot be an empty string"),r&&t.options.stringKeys&&(!Pm.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&i(c??e,"NON_STRING_KEY","With stringKeys, all keys must be strings"),s&&(l.spaceBefore=!0),o&&(e.type==="scalar"&&e.source===""?l.comment=o:l.commentBefore=o),t.options.keepSourceTokens&&f&&(l.srcToken=e),l}function Ss(t,e,n,i,{spaceBefore:r,comment:s,anchor:o,tag:a,end:c},l){let f={type:"scalar",offset:Am.emptyScalarPosition(e,n,i),indent:-1,source:""},u=Lc.composeScalar(t,f,a,l);return o&&(u.anchor=o.source.substring(1),u.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),r&&(u.spaceBefore=!0),s&&(u.comment=s,u.range[2]=c),u}function Tm({options:t},{offset:e,source:n,end:i},r){let s=new _m.Alias(n.substring(1));s.source===""&&r(e,"BAD_ALIAS","Alias cannot be an empty string"),s.source.endsWith(":")&&r(e+n.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=e+n.length,a=Om.resolveEnd(i,o,t.strict,r);return s.range=[e,o,a.offset],a.comment&&(s.comment=a.comment),s}Cs.composeEmptyNode=Ss;Cs.composeNode=Dc});var Bc=v(Wc=>{"use strict";var jm=Bt(),Mc=Fc(),Im=dt(),$m=Jt();function qm(t,e,{offset:n,start:i,value:r,end:s},o){let a=Object.assign({_directives:e},t),c=new jm.Document(void 0,a),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},f=$m.resolveProps(i,{indicator:"doc-start",next:r??s?.[0],offset:n,onError:o,parentIndent:0,startOnNewline:!0});f.found&&(c.directives.docStart=!0,r&&(r.type==="block-map"||r.type==="block-seq")&&!f.hasNewline&&o(f.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=r?Mc.composeNode(l,r,f,o):Mc.composeEmptyNode(l,f.end,i,null,f,o);let u=c.contents.range[2],d=Im.resolveEnd(s,u,!1,o);return d.comment&&(c.comment=d.comment),c.range=[n,u,d.offset],c}Wc.composeDoc=qm});var xs=v(Uc=>{"use strict";var Lm=kn("process"),Dm=ur(),Fm=Bt(),Vt=Ut(),Kc=_(),Mm=Bc(),Wm=dt();function Ht(t){if(typeof t=="number")return[t,t+1];if(Array.isArray(t))return t.length===2?t:[t[0],t[1]];let{offset:e,source:n}=t;return[e,e+(typeof n=="string"?n.length:1)]}function Yc(t){let e="",n=!1,i=!1;for(let r=0;r{let o=Ht(n);s?this.warnings.push(new Vt.YAMLWarning(o,i,r)):this.errors.push(new Vt.YAMLParseError(o,i,r))},this.directives=new Lm.Directives({version:e.version||"1.2"}),this.options=e}decorate(e,n){let{comment:i,afterEmptyLine:r}=Yc(this.prelude);if(i){let s=e.contents;if(n)e.comment=e.comment?`${e.comment} +`)+(s.substring(1)||" "),n=!0,i=!1;break;case"%":t[r+1]?.[0]!=="#"&&(r+=1),n=!1;break;default:n||(i=!0),n=!1}}return{comment:e,afterEmptyLine:i}}var Es=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(n,i,r,s)=>{let o=Ht(n);s?this.warnings.push(new Vt.YAMLWarning(o,i,r)):this.errors.push(new Vt.YAMLParseError(o,i,r))},this.directives=new Dm.Directives({version:e.version||"1.2"}),this.options=e}decorate(e,n){let{comment:i,afterEmptyLine:r}=Yc(this.prelude);if(i){let s=e.contents;if(n)e.comment=e.comment?`${e.comment} ${i}`:i;else if(r||e.directives.docStart||!s)e.commentBefore=i;else if(Kc.isCollection(s)&&!s.flow&&s.items.length>0){let o=s.items[0];Kc.isPair(o)&&(o=o.key);let a=o.commentBefore;o.commentBefore=a?`${i} ${a}`:i}else{let o=s.commentBefore;s.commentBefore=o?`${i} -${o}`:i}}if(n){for(let s=0;s{let s=Ht(e);s[0]+=n,this.onError(s,"BAD_DIRECTIVE",i,r)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let n=Fm.composeDoc(this.options,this.directives,e,this.onError);this.atDirectives&&!n.directives.docStart&&this.onError(e,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(n,!1),this.doc&&(yield this.doc),this.doc=n,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(e.source);break;case"error":{let n=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,i=new Vt.YAMLParseError(Ht(e),"UNEXPECTED_TOKEN",n);this.atDirectives||!this.doc?this.errors.push(i):this.doc.errors.push(i);break}case"doc-end":{if(!this.doc){let i="Unexpected doc-end without preceding document";this.errors.push(new Vt.YAMLParseError(Ht(e),"UNEXPECTED_TOKEN",i));break}this.doc.directives.docEnd=!0;let n=Mm.resolveEnd(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),n.comment){let i=this.doc.comment;this.doc.comment=i?`${i} -${n.comment}`:n.comment}this.doc.range[2]=n.offset;break}default:this.errors.push(new Vt.YAMLParseError(Ht(e),"UNEXPECTED_TOKEN",`Unsupported token ${e.type}`))}}*end(e=!1,n=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let i=Object.assign({_directives:this.directives},this.options),r=new Dm.Document(void 0,i);this.atDirectives&&this.onError(n,"MISSING_CHAR","Missing directives-end indicator line"),r.range=[0,n,n],this.decorate(r,!1),yield r}}};Uc.Composer=Cs});var Hc=v(di=>{"use strict";var Wm=ys(),Bm=bs(),Km=Ut(),Jc=Nt();function Ym(t,e=!0,n){if(t){let i=(r,s,o)=>{let a=typeof r=="number"?r:Array.isArray(r)?r[0]:r.offset;if(n)n(a,s,o);else throw new Km.YAMLParseError([a,a+1],s,o)};switch(t.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return Bm.resolveFlowScalar(t,e,i);case"block-scalar":return Wm.resolveBlockScalar({options:{strict:e}},t,i)}}return null}function Um(t,e){let{implicitKey:n=!1,indent:i,inFlow:r=!1,offset:s=-1,type:o="PLAIN"}=e,a=Jc.stringifyString({type:o,value:t},{implicitKey:n,indent:i>0?" ".repeat(i):"",inFlow:r,options:{blockQuote:!0,lineWidth:-1}}),c=e.end??[{type:"newline",offset:-1,indent:i,source:` +${o}`:i}}if(n){for(let s=0;s{let s=Ht(e);s[0]+=n,this.onError(s,"BAD_DIRECTIVE",i,r)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let n=Mm.composeDoc(this.options,this.directives,e,this.onError);this.atDirectives&&!n.directives.docStart&&this.onError(e,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(n,!1),this.doc&&(yield this.doc),this.doc=n,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(e.source);break;case"error":{let n=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,i=new Vt.YAMLParseError(Ht(e),"UNEXPECTED_TOKEN",n);this.atDirectives||!this.doc?this.errors.push(i):this.doc.errors.push(i);break}case"doc-end":{if(!this.doc){let i="Unexpected doc-end without preceding document";this.errors.push(new Vt.YAMLParseError(Ht(e),"UNEXPECTED_TOKEN",i));break}this.doc.directives.docEnd=!0;let n=Wm.resolveEnd(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),n.comment){let i=this.doc.comment;this.doc.comment=i?`${i} +${n.comment}`:n.comment}this.doc.range[2]=n.offset;break}default:this.errors.push(new Vt.YAMLParseError(Ht(e),"UNEXPECTED_TOKEN",`Unsupported token ${e.type}`))}}*end(e=!1,n=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let i=Object.assign({_directives:this.directives},this.options),r=new Fm.Document(void 0,i);this.atDirectives&&this.onError(n,"MISSING_CHAR","Missing directives-end indicator line"),r.range=[0,n,n],this.decorate(r,!1),yield r}}};Uc.Composer=Es});var Hc=v(di=>{"use strict";var Bm=vs(),Km=ks(),Ym=Ut(),Jc=Nt();function Um(t,e=!0,n){if(t){let i=(r,s,o)=>{let a=typeof r=="number"?r:Array.isArray(r)?r[0]:r.offset;if(n)n(a,s,o);else throw new Ym.YAMLParseError([a,a+1],s,o)};switch(t.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return Km.resolveFlowScalar(t,e,i);case"block-scalar":return Bm.resolveBlockScalar({options:{strict:e}},t,i)}}return null}function Jm(t,e){let{implicitKey:n=!1,indent:i,inFlow:r=!1,offset:s=-1,type:o="PLAIN"}=e,a=Jc.stringifyString({type:o,value:t},{implicitKey:n,indent:i>0?" ".repeat(i):"",inFlow:r,options:{blockQuote:!0,lineWidth:-1}}),c=e.end??[{type:"newline",offset:-1,indent:i,source:` `}];switch(a[0]){case"|":case">":{let l=a.indexOf(` `),f=a.substring(0,l),u=a.substring(l+1)+` `,d=[{type:"block-scalar-header",offset:s,indent:i,source:f}];return Vc(d,c)||d.push({type:"newline",offset:-1,indent:i,source:` -`}),{type:"block-scalar",offset:s,indent:i,props:d,source:u}}case'"':return{type:"double-quoted-scalar",offset:s,indent:i,source:a,end:c};case"'":return{type:"single-quoted-scalar",offset:s,indent:i,source:a,end:c};default:return{type:"scalar",offset:s,indent:i,source:a,end:c}}}function Jm(t,e,n={}){let{afterKey:i=!1,implicitKey:r=!1,inFlow:s=!1,type:o}=n,a="indent"in t?t.indent:null;if(i&&typeof a=="number"&&(a+=2),!o)switch(t.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let l=t.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let c=Jc.stringifyString({type:o,value:e},{implicitKey:r||a===null,indent:a!==null&&a>0?" ".repeat(a):"",inFlow:s,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":Vm(t,c);break;case'"':xs(t,c,"double-quoted-scalar");break;case"'":xs(t,c,"single-quoted-scalar");break;default:xs(t,c,"scalar")}}function Vm(t,e){let n=e.indexOf(` +`}),{type:"block-scalar",offset:s,indent:i,props:d,source:u}}case'"':return{type:"double-quoted-scalar",offset:s,indent:i,source:a,end:c};case"'":return{type:"single-quoted-scalar",offset:s,indent:i,source:a,end:c};default:return{type:"scalar",offset:s,indent:i,source:a,end:c}}}function Vm(t,e,n={}){let{afterKey:i=!1,implicitKey:r=!1,inFlow:s=!1,type:o}=n,a="indent"in t?t.indent:null;if(i&&typeof a=="number"&&(a+=2),!o)switch(t.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let l=t.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let c=Jc.stringifyString({type:o,value:e},{implicitKey:r||a===null,indent:a!==null&&a>0?" ".repeat(a):"",inFlow:s,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":Hm(t,c);break;case'"':_s(t,c,"double-quoted-scalar");break;case"'":_s(t,c,"single-quoted-scalar");break;default:_s(t,c,"scalar")}}function Hm(t,e){let n=e.indexOf(` `),i=e.substring(0,n),r=e.substring(n+1)+` `;if(t.type==="block-scalar"){let s=t.props[0];if(s.type!=="block-scalar-header")throw new Error("Invalid block scalar header");s.source=i,t.source=r}else{let{offset:s}=t,o="indent"in t?t.indent:-1,a=[{type:"block-scalar-header",offset:s,indent:o,source:i}];Vc(a,"end"in t?t.end:void 0)||a.push({type:"newline",offset:-1,indent:o,source:` -`});for(let c of Object.keys(t))c!=="type"&&c!=="offset"&&delete t[c];Object.assign(t,{type:"block-scalar",indent:o,props:a,source:r})}}function Vc(t,e){if(e)for(let n of e)switch(n.type){case"space":case"comment":t.push(n);break;case"newline":return t.push(n),!0}return!1}function xs(t,e,n){switch(t.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":t.type=n,t.source=e;break;case"block-scalar":{let i=t.props.slice(1),r=e.length;t.props[0].type==="block-scalar-header"&&(r-=t.props[0].source.length);for(let s of i)s.offset+=r;delete t.props,Object.assign(t,{type:n,source:e,end:i});break}case"block-map":case"block-seq":{let r={type:"newline",offset:t.offset+e.length,indent:t.indent,source:` -`};delete t.items,Object.assign(t,{type:n,source:e,end:[r]});break}default:{let i="indent"in t?t.indent:-1,r="end"in t&&Array.isArray(t.end)?t.end.filter(s=>s.type==="space"||s.type==="comment"||s.type==="newline"):[];for(let s of Object.keys(t))s!=="type"&&s!=="offset"&&delete t[s];Object.assign(t,{type:n,indent:i,source:e,end:r})}}}di.createScalarToken=Um;di.resolveAsScalar=Ym;di.setScalarValue=Jm});var zc=v(Gc=>{"use strict";var Hm=t=>"type"in t?mi(t):pi(t);function mi(t){switch(t.type){case"block-scalar":{let e="";for(let n of t.props)e+=mi(n);return e+t.source}case"block-map":case"block-seq":{let e="";for(let n of t.items)e+=pi(n);return e}case"flow-collection":{let e=t.start.source;for(let n of t.items)e+=pi(n);for(let n of t.end)e+=n.source;return e}case"document":{let e=pi(t);if(t.end)for(let n of t.end)e+=n.source;return e}default:{let e=t.source;if("end"in t&&t.end)for(let n of t.end)e+=n.source;return e}}}function pi({start:t,key:e,sep:n,value:i}){let r="";for(let s of t)r+=s.source;if(e&&(r+=mi(e)),n)for(let s of n)r+=s.source;return i&&(r+=mi(i)),r}Gc.stringify=Hm});var el=v(Zc=>{"use strict";var _s=Symbol("break visit"),Gm=Symbol("skip children"),Qc=Symbol("remove item");function Ge(t,e){"type"in t&&t.type==="document"&&(t={start:t.start,value:t.value}),Xc(Object.freeze([]),t,e)}Ge.BREAK=_s;Ge.SKIP=Gm;Ge.REMOVE=Qc;Ge.itemAtPath=(t,e)=>{let n=t;for(let[i,r]of e){let s=n?.[i];if(s&&"items"in s)n=s.items[r];else return}return n};Ge.parentCollection=(t,e)=>{let n=Ge.itemAtPath(t,e.slice(0,-1)),i=e[e.length-1][0],r=n?.[i];if(r&&"items"in r)return r;throw new Error("Parent collection not found")};function Xc(t,e,n){let i=n(e,t);if(typeof i=="symbol")return i;for(let r of["key","value"]){let s=e[r];if(s&&"items"in s){for(let o=0;o{"use strict";var Ps=Hc(),zm=zc(),Qm=el(),Rs="\uFEFF",Os="",As="",Ns="",Xm=t=>!!t&&"items"in t,Zm=t=>!!t&&(t.type==="scalar"||t.type==="single-quoted-scalar"||t.type==="double-quoted-scalar"||t.type==="block-scalar");function eh(t){switch(t){case Rs:return"";case Os:return"";case As:return"";case Ns:return"";default:return JSON.stringify(t)}}function th(t){switch(t){case Rs:return"byte-order-mark";case Os:return"doc-mode";case As:return"flow-error-end";case Ns:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case` +`});for(let c of Object.keys(t))c!=="type"&&c!=="offset"&&delete t[c];Object.assign(t,{type:"block-scalar",indent:o,props:a,source:r})}}function Vc(t,e){if(e)for(let n of e)switch(n.type){case"space":case"comment":t.push(n);break;case"newline":return t.push(n),!0}return!1}function _s(t,e,n){switch(t.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":t.type=n,t.source=e;break;case"block-scalar":{let i=t.props.slice(1),r=e.length;t.props[0].type==="block-scalar-header"&&(r-=t.props[0].source.length);for(let s of i)s.offset+=r;delete t.props,Object.assign(t,{type:n,source:e,end:i});break}case"block-map":case"block-seq":{let r={type:"newline",offset:t.offset+e.length,indent:t.indent,source:` +`};delete t.items,Object.assign(t,{type:n,source:e,end:[r]});break}default:{let i="indent"in t?t.indent:-1,r="end"in t&&Array.isArray(t.end)?t.end.filter(s=>s.type==="space"||s.type==="comment"||s.type==="newline"):[];for(let s of Object.keys(t))s!=="type"&&s!=="offset"&&delete t[s];Object.assign(t,{type:n,indent:i,source:e,end:r})}}}di.createScalarToken=Jm;di.resolveAsScalar=Um;di.setScalarValue=Vm});var zc=v(Gc=>{"use strict";var Gm=t=>"type"in t?mi(t):pi(t);function mi(t){switch(t.type){case"block-scalar":{let e="";for(let n of t.props)e+=mi(n);return e+t.source}case"block-map":case"block-seq":{let e="";for(let n of t.items)e+=pi(n);return e}case"flow-collection":{let e=t.start.source;for(let n of t.items)e+=pi(n);for(let n of t.end)e+=n.source;return e}case"document":{let e=pi(t);if(t.end)for(let n of t.end)e+=n.source;return e}default:{let e=t.source;if("end"in t&&t.end)for(let n of t.end)e+=n.source;return e}}}function pi({start:t,key:e,sep:n,value:i}){let r="";for(let s of t)r+=s.source;if(e&&(r+=mi(e)),n)for(let s of n)r+=s.source;return i&&(r+=mi(i)),r}Gc.stringify=Gm});var el=v(Zc=>{"use strict";var Ps=Symbol("break visit"),zm=Symbol("skip children"),Qc=Symbol("remove item");function Ge(t,e){"type"in t&&t.type==="document"&&(t={start:t.start,value:t.value}),Xc(Object.freeze([]),t,e)}Ge.BREAK=Ps;Ge.SKIP=zm;Ge.REMOVE=Qc;Ge.itemAtPath=(t,e)=>{let n=t;for(let[i,r]of e){let s=n?.[i];if(s&&"items"in s)n=s.items[r];else return}return n};Ge.parentCollection=(t,e)=>{let n=Ge.itemAtPath(t,e.slice(0,-1)),i=e[e.length-1][0],r=n?.[i];if(r&&"items"in r)return r;throw new Error("Parent collection not found")};function Xc(t,e,n){let i=n(e,t);if(typeof i=="symbol")return i;for(let r of["key","value"]){let s=e[r];if(s&&"items"in s){for(let o=0;o{"use strict";var Rs=Hc(),Qm=zc(),Xm=el(),Os="\uFEFF",As="",Ns="",Ts="",Zm=t=>!!t&&"items"in t,eh=t=>!!t&&(t.type==="scalar"||t.type==="single-quoted-scalar"||t.type==="double-quoted-scalar"||t.type==="block-scalar");function th(t){switch(t){case Os:return"";case As:return"";case Ns:return"";case Ts:return"";default:return JSON.stringify(t)}}function nh(t){switch(t){case Os:return"byte-order-mark";case As:return"doc-mode";case Ns:return"flow-error-end";case Ts:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case` `:case`\r -`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(t[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}V.createScalarToken=Ps.createScalarToken;V.resolveAsScalar=Ps.resolveAsScalar;V.setScalarValue=Ps.setScalarValue;V.stringify=zm.stringify;V.visit=Qm.visit;V.BOM=Rs;V.DOCUMENT=Os;V.FLOW_END=As;V.SCALAR=Ns;V.isCollection=Xm;V.isScalar=Zm;V.prettyToken=eh;V.tokenType=th});var Is=v(nl=>{"use strict";var Gt=hi();function se(t){switch(t){case void 0:case" ":case` -`:case"\r":case" ":return!0;default:return!1}}var tl=new Set("0123456789ABCDEFabcdef"),nh=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),gi=new Set(",[]{}"),ih=new Set(` ,[]{} -\r `),Ts=t=>!t||ih.has(t),js=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,n=!1){if(e){if(typeof e!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!n;let i=this.next??"stream";for(;i&&(n||this.hasChars(1));)i=yield*this.parseNext(i)}atLineEnd(){let e=this.pos,n=this.buffer[e];for(;n===" "||n===" ";)n=this.buffer[++e];return!n||n==="#"||n===` +`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(t[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}V.createScalarToken=Rs.createScalarToken;V.resolveAsScalar=Rs.resolveAsScalar;V.setScalarValue=Rs.setScalarValue;V.stringify=Qm.stringify;V.visit=Xm.visit;V.BOM=Os;V.DOCUMENT=As;V.FLOW_END=Ns;V.SCALAR=Ts;V.isCollection=Zm;V.isScalar=eh;V.prettyToken=th;V.tokenType=nh});var $s=v(nl=>{"use strict";var Gt=hi();function se(t){switch(t){case void 0:case" ":case` +`:case"\r":case" ":return!0;default:return!1}}var tl=new Set("0123456789ABCDEFabcdef"),ih=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),gi=new Set(",[]{}"),rh=new Set(` ,[]{} +\r `),js=t=>!t||rh.has(t),Is=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,n=!1){if(e){if(typeof e!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!n;let i=this.next??"stream";for(;i&&(n||this.hasChars(1));)i=yield*this.parseNext(i)}atLineEnd(){let e=this.pos,n=this.buffer[e];for(;n===" "||n===" ";)n=this.buffer[++e];return!n||n==="#"||n===` `?!0:n==="\r"?this.buffer[e+1]===` `:!1}charAt(e){return this.buffer[this.pos+e]}continueScalar(e){let n=this.buffer[e];if(this.indentNext>0){let i=0;for(;n===" ";)n=this.buffer[++i+e];if(n==="\r"){let r=this.buffer[i+e+1];if(r===` `||!r&&!this.atEnd)return e+i+1}return n===` `||i>=this.indentNext||!n&&!this.atEnd?e+i:-1}if(n==="-"||n==="."){let i=this.buffer.substr(e,3);if((i==="---"||i==="...")&&se(this.buffer[e+3]))return-1}return e}getLine(){let e=this.lineEndPos;return(typeof e!="number"||e!==-1&&ethis.indentValue&&!se(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[e,n]=this.peek(2);if(!n&&!this.atEnd)return this.setNext("block-start");if((e==="-"||e==="?"||e===":")&&se(n)){let i=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=i,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let e=this.getLine();if(e===null)return this.setNext("doc");let n=yield*this.pushIndicators();switch(e[n]){case"#":yield*this.pushCount(e.length-n);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(Ts),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return n+=yield*this.parseBlockScalarHeader(),n+=yield*this.pushSpaces(!0),yield*this.pushCount(e.length-n),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,n,i=-1;do e=yield*this.pushNewline(),e>0?(n=yield*this.pushSpaces(!1),this.indentValue=i=n):n=0,n+=yield*this.pushSpaces(!0);while(e+n>0);let r=this.getLine();if(r===null)return this.setNext("flow");if((i!==-1&&ithis.indentValue&&!se(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[e,n]=this.peek(2);if(!n&&!this.atEnd)return this.setNext("block-start");if((e==="-"||e==="?"||e===":")&&se(n)){let i=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=i,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let e=this.getLine();if(e===null)return this.setNext("doc");let n=yield*this.pushIndicators();switch(e[n]){case"#":yield*this.pushCount(e.length-n);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(js),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return n+=yield*this.parseBlockScalarHeader(),n+=yield*this.pushSpaces(!0),yield*this.pushCount(e.length-n),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,n,i=-1;do e=yield*this.pushNewline(),e>0?(n=yield*this.pushSpaces(!1),this.indentValue=i=n):n=0,n+=yield*this.pushSpaces(!0);while(e+n>0);let r=this.getLine();if(r===null)return this.setNext("flow");if((i!==-1&&i"0"&&n<="9")this.blockScalarIndent=Number(n)-1;else if(n!=="-")break}return yield*this.pushUntil(n=>se(n)||n==="#")}*parseBlockScalar(){let e=this.pos-1,n=0,i;e:for(let s=this.pos;i=this.buffer[s];++s)switch(i){case" ":n+=1;break;case` `:e=s,n=0;break;case"\r":{let o=this.buffer[s+1];if(!o&&!this.atEnd)return this.setNext("block-scalar");if(o===` @@ -133,34 +133,34 @@ ${n.comment}`:n.comment}this.doc.range[2]=n.offset;break}default:this.errors.pus `&&s>=this.pos&&s+1+n>a)e=s;else break}while(!0);return yield Gt.SCALAR,yield*this.pushToIndex(e+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let e=this.flowLevel>0,n=this.pos-1,i=this.pos-1,r;for(;r=this.buffer[++i];)if(r===":"){let s=this.buffer[i+1];if(se(s)||e&&gi.has(s))break;n=i}else if(se(r)){let s=this.buffer[i+1];if(r==="\r"&&(s===` `?(i+=1,r=` `,s=this.buffer[i+1]):n=i),s==="#"||e&&gi.has(s))break;if(r===` -`){let o=this.continueScalar(i+1);if(o===-1)break;i=Math.max(i,o-2)}}else{if(e&&gi.has(r))break;n=i}return!r&&!this.atEnd?this.setNext("plain-scalar"):(yield Gt.SCALAR,yield*this.pushToIndex(n+1,!0),e?"flow":"doc")}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,n){let i=this.buffer.slice(this.pos,e);return i?(yield i,this.pos+=i.length,i.length):(n&&(yield""),0)}*pushIndicators(){let e=0;e:for(;;){switch(this.charAt(0)){case"!":e+=yield*this.pushTag(),e+=yield*this.pushSpaces(!0);continue e;case"&":e+=yield*this.pushUntil(Ts),e+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let n=this.flowLevel>0,i=this.charAt(1);if(se(i)||n&&gi.has(i)){n?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,e+=yield*this.pushCount(1),e+=yield*this.pushSpaces(!0);continue e}}}break e}return e}*pushTag(){if(this.charAt(1)==="<"){let e=this.pos+2,n=this.buffer[e];for(;!se(n)&&n!==">";)n=this.buffer[++e];return yield*this.pushToIndex(n===">"?e+1:e,!1)}else{let e=this.pos+1,n=this.buffer[e];for(;n;)if(nh.has(n))n=this.buffer[++e];else if(n==="%"&&tl.has(this.buffer[e+1])&&tl.has(this.buffer[e+2]))n=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];return e===` +`){let o=this.continueScalar(i+1);if(o===-1)break;i=Math.max(i,o-2)}}else{if(e&&gi.has(r))break;n=i}return!r&&!this.atEnd?this.setNext("plain-scalar"):(yield Gt.SCALAR,yield*this.pushToIndex(n+1,!0),e?"flow":"doc")}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,n){let i=this.buffer.slice(this.pos,e);return i?(yield i,this.pos+=i.length,i.length):(n&&(yield""),0)}*pushIndicators(){let e=0;e:for(;;){switch(this.charAt(0)){case"!":e+=yield*this.pushTag(),e+=yield*this.pushSpaces(!0);continue e;case"&":e+=yield*this.pushUntil(js),e+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let n=this.flowLevel>0,i=this.charAt(1);if(se(i)||n&&gi.has(i)){n?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,e+=yield*this.pushCount(1),e+=yield*this.pushSpaces(!0);continue e}}}break e}return e}*pushTag(){if(this.charAt(1)==="<"){let e=this.pos+2,n=this.buffer[e];for(;!se(n)&&n!==">";)n=this.buffer[++e];return yield*this.pushToIndex(n===">"?e+1:e,!1)}else{let e=this.pos+1,n=this.buffer[e];for(;n;)if(ih.has(n))n=this.buffer[++e];else if(n==="%"&&tl.has(this.buffer[e+1])&&tl.has(this.buffer[e+2]))n=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];return e===` `?yield*this.pushCount(1):e==="\r"&&this.charAt(1)===` -`?yield*this.pushCount(2):0}*pushSpaces(e){let n=this.pos-1,i;do i=this.buffer[++n];while(i===" "||e&&i===" ");let r=n-this.pos;return r>0&&(yield this.buffer.substr(this.pos,r),this.pos=n),r}*pushUntil(e){let n=this.pos,i=this.buffer[n];for(;!e(i);)i=this.buffer[++n];return yield*this.pushToIndex(n,!1)}};nl.Lexer=js});var $s=v(il=>{"use strict";var qs=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let n=0,i=this.lineStarts.length;for(;n>1;this.lineStarts[s]{"use strict";var rh=kn("process"),rl=hi(),sh=Is();function Te(t,e){for(let n=0;n=0;)switch(t[e].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;t[++e]?.type==="space";);return t.splice(e,t.length)}function yi(t,e){if(e.length<1e5)Array.prototype.push.apply(t,e);else for(let n=0;n0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let e=this.peek(1);if(this.type==="doc-end"&&e?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!e)return yield*this.stream();switch(e.type){case"document":return yield*this.document(e);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(e);case"block-scalar":return yield*this.blockScalar(e);case"block-map":return yield*this.blockMap(e);case"block-seq":return yield*this.blockSequence(e);case"flow-collection":return yield*this.flowCollection(e);case"doc-end":return yield*this.documentEnd(e)}yield*this.pop()}peek(e){return this.stack[this.stack.length-e]}*pop(e){let n=e??this.stack.pop();if(!n)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield n;else{let i=this.peek(1);switch(n.type==="block-scalar"?n.indent="indent"in i?i.indent:0:n.type==="flow-collection"&&i.type==="document"&&(n.indent=0),n.type==="flow-collection"&&ol(n),i.type){case"document":i.value=n;break;case"block-scalar":i.props.push(n);break;case"block-map":{let r=i.items[i.items.length-1];if(r.value){i.items.push({start:[],key:n,sep:[]}),this.onKeyLine=!0;return}else if(r.sep)r.value=n;else{Object.assign(r,{key:n,sep:[]}),this.onKeyLine=!r.explicitKey;return}break}case"block-seq":{let r=i.items[i.items.length-1];r.value?i.items.push({start:[],value:n}):r.value=n;break}case"flow-collection":{let r=i.items[i.items.length-1];!r||r.value?i.items.push({start:[],key:n,sep:[]}):r.sep?r.value=n:Object.assign(r,{key:n,sep:[]});return}default:yield*this.pop(),yield*this.pop(n)}if((i.type==="document"||i.type==="block-map"||i.type==="block-seq")&&(n.type==="block-map"||n.type==="block-seq")){let r=n.items[n.items.length-1];r&&!r.sep&&!r.value&&r.start.length>0&&sl(r.start)===-1&&(n.indent===0||r.start.every(s=>s.type!=="comment"||s.indent0&&(yield this.buffer.substr(this.pos,r),this.pos=n),r}*pushUntil(e){let n=this.pos,i=this.buffer[n];for(;!e(i);)i=this.buffer[++n];return yield*this.pushToIndex(n,!1)}};nl.Lexer=Is});var Ls=v(il=>{"use strict";var qs=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let n=0,i=this.lineStarts.length;for(;n>1;this.lineStarts[s]{"use strict";var sh=kn("process"),rl=hi(),oh=$s();function Te(t,e){for(let n=0;n=0;)switch(t[e].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;t[++e]?.type==="space";);return t.splice(e,t.length)}function yi(t,e){if(e.length<1e5)Array.prototype.push.apply(t,e);else for(let n=0;n0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let e=this.peek(1);if(this.type==="doc-end"&&e?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!e)return yield*this.stream();switch(e.type){case"document":return yield*this.document(e);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(e);case"block-scalar":return yield*this.blockScalar(e);case"block-map":return yield*this.blockMap(e);case"block-seq":return yield*this.blockSequence(e);case"flow-collection":return yield*this.flowCollection(e);case"doc-end":return yield*this.documentEnd(e)}yield*this.pop()}peek(e){return this.stack[this.stack.length-e]}*pop(e){let n=e??this.stack.pop();if(!n)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield n;else{let i=this.peek(1);switch(n.type==="block-scalar"?n.indent="indent"in i?i.indent:0:n.type==="flow-collection"&&i.type==="document"&&(n.indent=0),n.type==="flow-collection"&&ol(n),i.type){case"document":i.value=n;break;case"block-scalar":i.props.push(n);break;case"block-map":{let r=i.items[i.items.length-1];if(r.value){i.items.push({start:[],key:n,sep:[]}),this.onKeyLine=!0;return}else if(r.sep)r.value=n;else{Object.assign(r,{key:n,sep:[]}),this.onKeyLine=!r.explicitKey;return}break}case"block-seq":{let r=i.items[i.items.length-1];r.value?i.items.push({start:[],value:n}):r.value=n;break}case"flow-collection":{let r=i.items[i.items.length-1];!r||r.value?i.items.push({start:[],key:n,sep:[]}):r.sep?r.value=n:Object.assign(r,{key:n,sep:[]});return}default:yield*this.pop(),yield*this.pop(n)}if((i.type==="document"||i.type==="block-map"||i.type==="block-seq")&&(n.type==="block-map"||n.type==="block-seq")){let r=n.items[n.items.length-1];r&&!r.sep&&!r.value&&r.start.length>0&&sl(r.start)===-1&&(n.indent===0||r.start.every(s=>s.type!=="comment"||s.indent=e.indent){let i=!this.onKeyLine&&this.indent===e.indent,r=i&&(n.sep||n.explicitKey)&&this.type!=="seq-item-ind",s=[];if(r&&n.sep&&!n.value){let o=[];for(let a=0;ae.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(s=n.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":r||n.value?(s.push(this.sourceToken),e.items.push({start:s}),this.onKeyLine=!0):n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"explicit-key-ind":!n.sep&&!n.explicitKey?(n.start.push(this.sourceToken),n.explicitKey=!0):r||n.value?(s.push(this.sourceToken),e.items.push({start:s,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(n.explicitKey)if(n.sep)if(n.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(Te(n.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:s,key:null,sep:[this.sourceToken]}]});else if(al(n.key)&&!Te(n.sep,"newline")){let o=pt(n.start),a=n.key,c=n.sep;c.push(this.sourceToken),delete n.key,delete n.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:a,sep:c}]})}else s.length>0?n.sep=n.sep.concat(s,this.sourceToken):n.sep.push(this.sourceToken);else if(Te(n.start,"newline"))Object.assign(n,{key:null,sep:[this.sourceToken]});else{let o=pt(n.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else n.sep?n.value||r?e.items.push({start:s,key:null,sep:[this.sourceToken]}):Te(n.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):n.sep.push(this.sourceToken):Object.assign(n,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);r||n.value?(e.items.push({start:s,key:o,sep:[]}),this.onKeyLine=!0):n.sep?this.stack.push(o):(Object.assign(n,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(e);if(o){if(o.type==="block-seq"){if(!n.explicitKey&&n.sep&&!Te(n.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else i&&e.items.push({start:s});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let n=e.items[e.items.length-1];switch(this.type){case"newline":if(n.value){let i="end"in n.value?n.value.end:void 0;(Array.isArray(i)?i[i.length-1]:void 0)?.type==="comment"?i?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else n.start.push(this.sourceToken);return;case"space":case"comment":if(n.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(n.start,e.indent)){let r=e.items[e.items.length-2]?.value?.end;if(Array.isArray(r)){yi(r,n.start),r.push(this.sourceToken),e.items.pop();return}}n.start.push(this.sourceToken)}return;case"anchor":case"tag":if(n.value||this.indent<=e.indent)break;n.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;n.value||Te(n.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):n.start.push(this.sourceToken);return}if(this.indent>e.indent){let i=this.startBlockValue(e);if(i){this.stack.push(i);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let n=e.items[e.items.length-1];if(this.type==="flow-error-end"){let i;do yield*this.pop(),i=this.peek(1);while(i?.type==="flow-collection")}else if(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!n||n.sep?e.items.push({start:[this.sourceToken]}):n.start.push(this.sourceToken);return;case"map-value-ind":!n||n.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):n.sep?n.sep.push(this.sourceToken):Object.assign(n,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!n||n.value?e.items.push({start:[this.sourceToken]}):n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let r=this.flowScalar(this.type);!n||n.value?e.items.push({start:[],key:r,sep:[]}):n.sep?this.stack.push(r):Object.assign(n,{key:r,sep:[]});return}case"flow-map-end":case"flow-seq-end":e.end.push(this.sourceToken);return}let i=this.startBlockValue(e);i?this.stack.push(i):(yield*this.pop(),yield*this.step())}else{let i=this.peek(2);if(i.type==="block-map"&&(this.type==="map-value-ind"&&i.indent===e.indent||this.type==="newline"&&!i.items[i.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&i.type!=="flow-collection"){let r=wi(i),s=pt(r);ol(e);let o=e.end.splice(1,e.end.length);o.push(this.sourceToken);let a={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:s,key:e,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let n=this.source.indexOf(` `)+1;for(;n!==0;)this.onNewLine(this.offset+n),n=this.source.indexOf(` -`,n)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let n=wi(e),i=pt(n);return i.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let n=wi(e),i=pt(n);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,n){return this.type!=="comment"||this.indent<=n?!1:e.every(i=>i.type==="newline"||i.type==="space")}*documentEnd(e){this.type!=="doc-mode"&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};cl.Parser=Ls});var pl=v(Qt=>{"use strict";var ll=Es(),oh=Bt(),zt=Ut(),ah=Sr(),ch=_(),lh=$s(),ul=Ds();function fl(t){let e=t.prettyErrors!==!1;return{lineCounter:t.lineCounter||e&&new lh.LineCounter||null,prettyErrors:e}}function uh(t,e={}){let{lineCounter:n,prettyErrors:i}=fl(e),r=new ul.Parser(n?.addNewLine),s=new ll.Composer(e),o=Array.from(s.compose(r.parse(t)));if(i&&n)for(let a of o)a.errors.forEach(zt.prettifyError(t,n)),a.warnings.forEach(zt.prettifyError(t,n));return o.length>0?o:Object.assign([],{empty:!0},s.streamInfo())}function dl(t,e={}){let{lineCounter:n,prettyErrors:i}=fl(e),r=new ul.Parser(n?.addNewLine),s=new ll.Composer(e),o=null;for(let a of s.compose(r.parse(t),!0,t.length))if(!o)o=a;else if(o.options.logLevel!=="silent"){o.errors.push(new zt.YAMLParseError(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return i&&n&&(o.errors.forEach(zt.prettifyError(t,n)),o.warnings.forEach(zt.prettifyError(t,n))),o}function fh(t,e,n){let i;typeof e=="function"?i=e:n===void 0&&e&&typeof e=="object"&&(n=e);let r=dl(t,n);if(!r)return null;if(r.warnings.forEach(s=>ah.warn(r.options.logLevel,s)),r.errors.length>0){if(r.options.logLevel!=="silent")throw r.errors[0];r.errors=[]}return r.toJS(Object.assign({reviver:i},n))}function dh(t,e,n){let i=null;if(typeof e=="function"||Array.isArray(e)?i=e:n===void 0&&e&&(n=e),typeof n=="string"&&(n=n.length),typeof n=="number"){let r=Math.round(n);n=r<1?void 0:r>8?{indent:8}:{indent:r}}if(t===void 0){let{keepUndefined:r}=n??e??{};if(!r)return}return ch.isDocument(t)&&!i?t.toString(n):new oh.Document(t,i,n).toString(n)}Qt.parse=fh;Qt.parseAllDocuments=uh;Qt.parseDocument=dl;Qt.stringify=dh});var ze=v(O=>{"use strict";var ph=Es(),mh=Bt(),hh=rs(),Fs=Ut(),gh=_t(),je=_(),wh=Re(),yh=I(),vh=Ae(),bh=Ne(),kh=hi(),Sh=Is(),Ch=$s(),Eh=Ds(),vi=pl(),ml=St();O.Composer=ph.Composer;O.Document=mh.Document;O.Schema=hh.Schema;O.YAMLError=Fs.YAMLError;O.YAMLParseError=Fs.YAMLParseError;O.YAMLWarning=Fs.YAMLWarning;O.Alias=gh.Alias;O.isAlias=je.isAlias;O.isCollection=je.isCollection;O.isDocument=je.isDocument;O.isMap=je.isMap;O.isNode=je.isNode;O.isPair=je.isPair;O.isScalar=je.isScalar;O.isSeq=je.isSeq;O.Pair=wh.Pair;O.Scalar=yh.Scalar;O.YAMLMap=vh.YAMLMap;O.YAMLSeq=bh.YAMLSeq;O.CST=kh;O.Lexer=Sh.Lexer;O.LineCounter=Ch.LineCounter;O.Parser=Eh.Parser;O.parse=vi.parse;O.parseAllDocuments=vi.parseAllDocuments;O.parseDocument=vi.parseDocument;O.stringify=vi.stringify;O.visit=ml.visit;O.visitAsync=ml.visitAsync});import bi from"path";function Ph(t,e){if(typeof t!="string")throw new Error(`${e} must be a string`);let n=t.trim();if(n.length===0||bi.posix.isAbsolute(n)||bi.win32.isAbsolute(n)||/^(?:~|[\\/])/u.test(n))throw new Error(`${e} must be a project-relative path`);if(n===".")return[];let i=n.replaceAll("\\","/").split("/");if(i.some(r=>r===".."))throw new Error(`${e} must stay inside the project root`);if(i.some(r=>r===""||r==="."))throw new Error(`${e} must not contain empty or dot path segments`);return i}function ki(t){let e=Ph(t,"native.artifact_root");return e.length===0?".":e.join("/")}function gl(t,e="docs"){let n=t??e;if(n!=="legacy"&&n!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return n}function Ie(t,e,n=!1){if(typeof t!="string")throw new Error(`${e} must be a string`);let i=t.trim().replaceAll("\\","/");if(i.length===0||bi.posix.isAbsolute(i)||bi.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${e} must be relative to its declared path base`);let r=i.split("/");if(r.some(s=>s===".."))throw new Error(`${e} must stay inside its declared path base`);if(r.some(s=>s===""||s==="."))throw new Error(`${e} must not contain empty or dot path segments`);if(!n&&/[*?]/u.test(i))throw new Error(`${e} cannot contain wildcards`);return r.join("/")}function Xt(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function wl(t,e,n){let i=t??e;if(i!=="en"&&i!=="zh-CN")throw new Error(`${n} must be en or zh-CN`);return i}function yl(t,e){if(typeof t!="string"||t.length===0||t.includes("\\")||t.includes("\0")||t.startsWith("/")||t.split("/").includes(".."))throw new Error(`${e} contains an unsafe pattern`);if(t.length>Ws)throw new Error(`${e} exceeds ${Ws} characters`);let n=0;for(let i=0;iBs)throw new Error(`${e} contains more than ${Bs} wildcard tokens`);return t}function hl(t,e,n){if(t===void 0)return[...n];if(!Array.isArray(t))throw new Error(`${e} contains an unsafe pattern`);return[...new Set(t.map(i=>yl(i,e)))].sort((i,r)=>i.localeCompare(r,"en"))}function Ms(t,e,n){let i=t??e;if(!Number.isSafeInteger(i)||i<1)throw new Error(`${n} must be a positive integer`);return i}function Rh(t){if(t===void 0)return{...we,include:[...we.include],exclude:[...we.exclude]};let e=Xt(t,"native.snapshot");return{include:hl(e.include,"native.snapshot.include",we.include),exclude:hl(e.exclude,"native.snapshot.exclude",we.exclude),max_files:Ms(e.max_files,we.max_files,"native.snapshot.max_files"),max_total_bytes:Ms(e.max_total_bytes,we.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:Ms(e.max_duration_ms,we.max_duration_ms,"native.snapshot.max_duration_ms")}}function Oh(t){if(t===void 0)return;let e=Xt(t,"native.pending_root_move"),n=e.id,i=e.from_artifact_root,r=e.to_artifact_root,s=e.stage;if(typeof n!="string"||!/^[a-f0-9-]{8,}$/u.test(n))throw new Error("native.pending_root_move.id is invalid");if(typeof i!="string"||typeof r!="string")throw new Error("native.pending_root_move roots must be strings");if(s!=="copying"&&s!=="ready"&&s!=="switched")throw new Error("native.pending_root_move.stage is invalid");let o;if(e.cleanup!==void 0){let a=Xt(e.cleanup,"native.pending_root_move.cleanup"),c=a.kind,l=a.state,f=a.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof f!="string"||!/^[a-f0-9]{64}$/u.test(f))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:f}}return{id:n,fromArtifactRoot:ki(i),toArtifactRoot:ki(r),stage:s,...o?{cleanup:o}:{}}}function Ah(t,e={}){let n=Xt(t,"native"),i=n.artifact_root??(e.allowMissingArtifactRoot?"docs":void 0);if(typeof i!="string")throw new Error("native.artifact_root must be a string");let r=n.clarification_mode??"sequential";if(r!=="sequential"&&r!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let s=n.archive_confirmation??"automatic";if(s!=="automatic"&&s!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=n.max_verify_failures??xh;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let a=Oh(n.pending_root_move);return{artifact_root:ki(i),language:wl(n.language,"en","native.language"),clarification_mode:r,archive_confirmation:s,max_verify_failures:o,snapshot:Rh(n.snapshot),...a?{pending_root_move:a}:{}}}function Nh(t){let e=Xt(t,"classic"),n=e.context_compression??"off";if(n!=="off"&&n!=="beta")throw new Error("classic.context_compression must be off or beta");let i=e.review_mode??"standard";if(i!=="off"&&i!=="standard"&&i!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let r=e.auto_transition??!0;if(typeof r!="boolean")throw new Error("classic.auto_transition must be true or false");return{artifact_layout:gl(e.artifact_layout),language:wl(e.language,"zh-CN","classic.language"),context_compression:n,review_mode:i,auto_transition:r}}function Th(t){let e=t??!0;if(typeof e!="boolean")throw new Error("ambient_resume must be true or false");return e}function jh(t,e,n,i,r){let s=t.schema!==void 0;if(!(s||t.default_workflow!==void 0||t.workflows!==void 0||!r.allowPartialProject&&t.native!==void 0)||r.allowPartialProject&&!s)return null;if(t.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(t.default_workflow!=="native"&&t.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let a=t.workflows??[t.default_workflow];if(!Array.isArray(a)||a.length===0||a.some(l=>l!=="native"&&l!=="classic"))throw new Error("workflows must contain native and/or classic");let c=[...new Set(a)];if(!c.includes(t.default_workflow))throw new Error("workflows must include default_workflow");if(c.includes("native")&&!e)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:t.default_workflow,workflows:c,ambient_resume:i,...e?{native:e}:{},...n?{classic:n}:{}}}function mt(t,e={}){let n=(0,Ks.parseDocument)(t,{uniqueKeys:!0});if(n.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${n.errors[0].message}`);let i=n.toJS();if(i==null)return{value:{},config:null,ambient_resume:!0};if(typeof i!="object"||Array.isArray(i))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let r=i,s=Th(r.ambient_resume),o=r.native===void 0?void 0:Ah(r.native,{allowMissingArtifactRoot:e.allowMissingNativeFields}),a=r.classic===void 0?void 0:Nh(r.classic),c=jh(r,o,a,s,{allowPartialProject:e.allowPartialProject??!1});return{value:r,config:c,ambient_resume:s,...o?{native:o}:{},...a?{classic:a}:{}}}var Ks,Zt,Ws,Bs,xh,_h,we,ye=K(()=>{"use strict";Ks=nt(ze(),1),Zt=64*1024,Ws=1024,Bs=64,xh=5,_h=[".agents/skills/**",".amazonq/skills/**",".augment/skills/**",".bob/skills/**",".claude/skills/**",".cline/skills/**",".codebuddy/skills/**",".continue/skills/**",".cospec/skills/**",".crush/skills/**",".cursor/skills/**",".factory/skills/**",".forge/skills/**",".gemini/skills/**",".github/skills/**",".iflow/skills/**",".junie/skills/**",".kilocode/skills/**",".kimi-code/skills/**",".kiro/skills/**",".lingma/skills/**",".mimocode/skills/**",".opencode/skills/**",".pi/skills/**",".qoder/skills/**",".qwen/skills/**",".roo/skills/**",".trae-cn/skills/**",".trae/skills/**",".windsurf/skills/**",".zcode/skills/**"],we={include:["**/*"],exclude:[..._h],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4}});function qe(t){return t!==0&&t!==0n&&t!=="0"}function Si(t,e){return qe(t.dev)&&qe(e.dev)&&qe(t.ino)&&qe(e.ino)}function ve(t,e){let n=qe(t.dev)&&qe(e.dev);if(n&&t.dev!==e.dev)return!1;let i=qe(t.ino)&&qe(e.ino);return i&&t.ino!==e.ino?!1:n&&i?!0:t.birthtime===e.birthtime}var Ci=K(()=>{"use strict"});import{constants as Ei,promises as Qe}from"fs";function Ys(t){return"birthtimeNs"in t&&typeof t.birthtimeNs=="bigint"?t.birthtimeNs:t.birthtimeMs}function vl(t){return"ctimeNs"in t&&typeof t.ctimeNs=="bigint"?t.ctimeNs:t.ctimeMs}function en(t){return{dev:t.dev,ino:t.ino,birthtime:Ys(t)}}function xi(t,e){let n=en(t),i=en(e);return Si(n,i)?ve(n,i):ve(n,i)&&Ys(t)===Ys(e)&&vl(t)===vl(e)&&t.size===e.size}async function _i(t,e,n={}){if(!Number.isSafeInteger(e)||e<1)throw new Error("race-safe read byte limit must be a positive integer");let i=n.label??"file",r=n.bigint===!0,s=await Qe.lstat(t,{bigint:r});if(!s.isFile()||s.isSymbolicLink())throw new $e("not-regular-file",`${i} must be a regular file`);if(BigInt(s.size)>BigInt(e))throw new $e("too-large",`${i} exceeds ${e} bytes`);let o=await Qe.realpath(t);await n.verify?.("pre-open",{realPath:o,identity:en(s)});let a=process.platform==="win32"?Ei.O_RDONLY:Ei.O_RDONLY|Ei.O_NOFOLLOW|Ei.O_NONBLOCK,c;try{c=await Qe.open(t,a)}catch(l){throw l.code==="ELOOP"?new $e("not-regular-file",`${i} must be a regular file`,{cause:l}):l}try{let[l,f,u]=await Promise.all([c.stat({bigint:r}),Qe.lstat(t,{bigint:r}),Qe.realpath(t)]);if(!l.isFile()||!f.isFile()||f.isSymbolicLink()||u!==o||!xi(s,l)||!xi(s,f))throw new $e("changed",`${i} changed while opening`);await n.verify?.("post-open",{realPath:u,identity:en(l)}),await n.hooks?.afterOpen?.();let d=[],h=0,g=Buffer.allocUnsafe(Math.min(64*1024,e+1));for(;;){let y=e+1-h,{bytesRead:S}=await c.read(g,0,Math.min(g.length,y),null);if(S===0)break;if(h+=S,h>e)throw new $e("too-large",`${i} exceeds ${e} bytes`);d.push(Buffer.from(g.subarray(0,S)))}await n.hooks?.beforeFinalCheck?.();let[p,m,w]=await Promise.all([c.stat({bigint:r}),Qe.lstat(t,{bigint:r}),Qe.realpath(t)]);if(!m.isFile()||m.isSymbolicLink()||w!==o||!xi(s,p)||!xi(s,m))throw new $e("changed",`${i} changed while reading`);return await n.verify?.("post-read",{realPath:w,identity:en(p)}),{bytes:Buffer.concat(d,h),stat:p,realPath:w}}finally{await c.close()}}var $e,Us=K(()=>{"use strict";Ci();$e=class extends Error{reason;constructor(e,n,i){super(n,i),this.name="RaceSafeReadError",this.reason=e}}});import{promises as Le}from"fs";import oe from"path";function bl(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}function Pi(t,e){let n=oe.relative(t,e);return n===""||!oe.isAbsolute(n)&&n!==".."&&!n.startsWith(`..${oe.sep}`)}async function Js(t,e){let n=oe.resolve(t),i=await Le.lstat(n);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${e} project root must be a real directory`);return Le.realpath(n)}async function Vs(t,e,n,i){let r=t;for(let s=0;s{if(!Pi(s,a.realPath))throw new Error(`${i.label} resolves outside the project root`);await Vs(r.projectRoot,s,r.relative.split("/"),{label:i.label,expected:"file"})}})}var Z=K(()=>{"use strict";Us();ye()});import{createHash as Ih}from"crypto";function qh(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function Oi(t,e={}){return(await Ai(t,e)).document}async function $h(t){try{return(await F(t,tn,Zt,{label:tn})).bytes}catch(e){if(qh(e))return null;throw e}}function Lh(t){return t?{exists:!0,sha256:Ih("sha256").update(t).digest("hex")}:{exists:!1,sha256:null}}async function Ai(t,e={}){let n=await $h(t);return{document:n?mt(n.toString("utf8"),e):null,identity:Lh(n)}}var tn,nn=K(()=>{"use strict";ye();Z();tn=".comet/config.yaml"});import{randomUUID as Dh}from"crypto";import{constants as Fh,promises as q}from"fs";import W from"path";async function Gs(t,e){try{return await q.link(t,e),{linked:!0}}catch(n){let i=n.code;if(i!=="ENOTSUP"&&i!=="EOPNOTSUPP")throw n}return await q.copyFile(t,e,Fh.COPYFILE_EXCL),{linked:!1}}function ht(t,e){let n=W.relative(t,e);return n===""||!W.isAbsolute(n)&&n!==".."&&!n.startsWith(`..${W.sep}`)}function Ti(t){return{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs}}function Mh(t,e){return ve(t,Ti(e))}function Ni(t,e){let n=Ti(t),i=Ti(e);return Si(n,i)?ve(n,i):ve(n,i)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.size===e.size}async function ji(t){let e=await q.lstat(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Contained atomic write parent must be a real directory: ${t}`);return{path:t,realPath:await q.realpath(t),...Ti(e)}}async function De(t){for(let e of t){let n=await q.lstat(e.path);if(!n.isDirectory()||n.isSymbolicLink()||!Mh(e,n)||await q.realpath(e.path)!==e.realPath)throw new Error(`Contained atomic write parent changed before commit: ${e.path}`)}}async function Wh(t,e){let n=W.resolve(t),i=W.resolve(e);if(!ht(n,i))throw new Error(`Contained atomic write parent is outside its managed root: ${e}`);let r=[await ji(n)],s=W.relative(n,i).split(W.sep).filter(Boolean),o=n;for(let a of s){await De(r),o=W.join(o,a);try{await q.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await ji(o);if(!ht(r[0].realPath,c.realPath))throw new Error(`Contained atomic write parent resolves outside its managed root: ${o}`);r.push(c)}return await De(r),r}async function Bh(t,e){let n=W.resolve(t),i=W.resolve(e);if(!ht(n,i))throw new Error(`Contained file parent is outside its managed root: ${e}`);let r=[await ji(n)],s=W.relative(n,i).split(W.sep).filter(Boolean),o=n;for(let a of s){o=W.join(o,a);try{let c=await ji(o);if(!ht(r[0].realPath,c.realPath))throw new Error(`Contained file parent resolves outside its managed root: ${o}`);r.push(c)}catch(c){if(c.code==="ENOENT")return null;throw c}}return await De(r),r}async function kl(t){let e;try{e=await q.open(t,"r"),await e.sync()}catch(n){let i=n.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(i??""))throw n}finally{await e?.close()}}async function Kh(t,e,n){let i=W.dirname(t),r=await Wh(n.containedRoot,i),s=W.join(i,`.${W.basename(t)}.${Dh()}.tmp`),o,a;try{await n.beforeTemporaryOpen?.(),o=await q.open(s,"wx"),a=await o.stat();let[c,l]=await Promise.all([q.lstat(s),q.realpath(s)]);if(await De(r),!c.isFile()||c.isSymbolicLink()||!Ni(a,c)||!ht(r[0].realPath,l))throw new Error("Contained atomic write temporary file opened outside its managed parent");if(typeof e=="string"?await o.writeFile(e,"utf8"):await o.writeFile(e),await o.sync(),!Ni(a,await o.stat()))throw new Error("Contained atomic write temporary file changed while writing");await o.close(),o=void 0,await n.beforeCommit?.(),await De(r);let f=await q.lstat(s);if(!f.isFile()||f.isSymbolicLink()||!Ni(f,a))throw new Error("Contained atomic write temporary file changed before commit");n.exclusive?(await Gs(s,t),await q.unlink(s)):await q.rename(s,t),await kl(i)}catch(c){await o?.close();try{await De(r),await q.rm(s,{force:!0})}catch{}throw c}}async function ae(t,e,n){await Kh(t,e,n)}async function zs(t,e){let n=W.dirname(t),i=await Bh(e.containedRoot,n);if(!i)return!1;let r,s;try{r=await q.lstat(t),s=await q.realpath(t)}catch(c){if(c.code==="ENOENT")return!1;throw c}if(!r.isFile()||r.isSymbolicLink()||!ht(i[0].realPath,s))throw new Error("Contained file removal target must be a regular file inside its managed root");await e.beforeRemove?.(),await De(i);let[o,a]=await Promise.all([q.lstat(t),q.realpath(t)]);if(!o.isFile()||o.isSymbolicLink()||!Ni(r,o)||a!==s)throw new Error("Contained file removal target changed before removal");return await q.unlink(t),await De(i),await kl(n),!0}var Xe=K(()=>{"use strict";Ci()});var tb,Qs=K(()=>{"use strict";Xe();nn();Z();tb=16*1024});var Zs=K(()=>{"use strict";Xe();ye();nn();Z();Qs()});var Fi=K(()=>{"use strict"});var Il=K(()=>{"use strict"});var ro=K(()=>{"use strict";Fi()});var ql=K(()=>{"use strict";Fi();ro()});var _g,$l=K(()=>{"use strict";_g=nt(ze(),1);Xe();ye();Z()});var Ll=K(()=>{"use strict";Fi();Xe();Il();ql();ye();$l();Z();nn();Zs();Qs();ro()});import{TextDecoder as Pg}from"util";function Dl(t){return{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs}}function Rg(t,e){try{return new Pg("utf-8",{fatal:!0}).decode(t.bytes)}catch(n){throw new Error(`${e} is not valid UTF-8`,{cause:n})}}async function so(t,e,n,i,r={}){try{let s=await F(t,e,n,{label:i,hooks:r.hooks});return{result:s,text:Rg(s,i)}}catch(s){let o=s.code;if(o==="ENOENT"||o==="ENOTDIR")return null;throw s}}async function Me(t,e,n,i,r={}){return(await so(t,e,n,i,r))?.text??null}async function We(t,e,n,i,r,s={}){if(Buffer.byteLength(n,"utf8")>i)throw new Error(`${r} exceeds ${i} bytes`);let o=await so(t,e,i,r),a=await T(t,e,{label:r,expected:"file"});await ae(a.target,n,{containedRoot:a.projectRoot,beforeCommit:async()=>{await s.beforeCommit?.();let c=await so(t,e,i,r);if(!(!o&&!c)){if(!o||!c)throw new Error(`${r} changed before commit`);if(o.result.realPath!==c.result.realPath||!ve(Dl(o.result.stat),Dl(c.result.stat))||o.text!==c.text)throw new Error(`${r} changed before commit`)}}})}async function Mi(t,e,n,i,r,s={}){let o=await Me(t,e,i,r);await We(t,e,`${o??""}${n}`,i,r,s)}async function Wi(t,e,n,i={}){let r=await T(t,e,{label:n,expected:"file"});return r.exists?zs(r.target,{containedRoot:r.projectRoot,beforeRemove:i.beforeRemove}):!1}var Bi=K(()=>{"use strict";Ll();Ci()});var Wl={};Ju(Wl,{RUN_STATE_FILE:()=>Yi,applyRunStateToDocument:()=>oo,readRunState:()=>ao,removeRunState:()=>co,runStateFromDocument:()=>Ki,writeRunState:()=>Ui});import Og from"path";function gn(t,e){let n=t[e];if(typeof n!="string"||n.length===0)throw new Error(`Invalid Run state: ${e} must be a non-empty string`);return n}function hn(t,e){let n=gn(t,e);if(Og.isAbsolute(n)||/^(?:[A-Za-z]:|[\\/]|~)/u.test(n)||n.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Run state: ${e} must stay inside the change directory`);return n}function Ag(t){let e=t.run_retries??"{}",n;try{n=typeof e=="string"?JSON.parse(e):e}catch(i){throw new Error("Invalid Run state: run_retries must be a JSON object",{cause:i})}if(!n||typeof n!="object"||Array.isArray(n))throw new Error("Invalid Run state: run_retries must be a JSON object");for(let i of Object.values(n))if(!Number.isInteger(i)||Number(i)<0)throw new Error("Invalid Run state: retry counts must be non-negative integers");return n}function Ki(t){if(!t.run_id)return null;let e=gn(t,"run_id"),n=gn(t,"skill"),i=gn(t,"skill_version"),r=gn(t,"skill_hash"),s=hn(t,"pending_ref"),o=hn(t,"trajectory_ref"),a=hn(t,"context_ref"),c=hn(t,"artifacts_ref"),l=hn(t,"checkpoint_ref"),f=Number(t.iteration);if(!Number.isInteger(f)||f<0)throw new Error("Invalid Run state: iteration must be a non-negative integer");if(t.orchestration!=="deterministic"&&t.orchestration!=="adaptive")throw new Error("Invalid Run state: orchestration must be deterministic or adaptive");if(t.run_status!=="running"&&t.run_status!=="waiting"&&t.run_status!=="completed"&&t.run_status!=="failed")throw new Error("Invalid Run state: run_status is invalid");return{runId:e,skill:n,skillVersion:i,skillHash:r,orchestration:t.orchestration,currentStep:Fl(t,"current_step"),iteration:f,pending:Fl(t,"pending"),pendingRef:s,trajectoryRef:o,contextRef:a,artifactsRef:c,checkpointRef:l,status:t.run_status,retries:Ag(t)}}function oo(t,e){e?t.run_id=e.runId:delete t.run_id}function Ng(t){return{runId:t.runId,skill:t.skill,skillVersion:t.skillVersion,skillHash:t.skillHash,orchestration:t.orchestration,currentStep:t.currentStep,iteration:t.iteration,pending:t.pending,pendingRef:t.pendingRef,trajectoryRef:t.trajectoryRef,contextRef:t.contextRef,artifactsRef:t.artifactsRef,checkpointRef:t.checkpointRef,status:t.status,retries:t.retries}}function Tg(t){let e={run_id:t.runId,skill:t.skill,skill_version:t.skillVersion,skill_hash:t.skillHash,orchestration:t.orchestration,current_step:t.currentStep,iteration:t.iteration,pending:t.pending,pending_ref:t.pendingRef,trajectory_ref:t.trajectoryRef,context_ref:t.contextRef,artifacts_ref:t.artifactsRef,checkpoint_ref:t.checkpointRef,run_status:t.status,run_retries:JSON.stringify(t.retries)};return Ki(e)}async function ao(t,e={}){let n=await Me(t,Yi,Ml,"Run state",e);if(n===null)return null;let i=JSON.parse(n);return Tg(i)}async function Ui(t,e,n={}){await We(t,Yi,JSON.stringify(Ng(e),null,2),Ml,"Run state",n)}async function co(t,e={}){await Wi(t,Yi,"Run state",e)}var Fl,Yi,Ml,Ji=K(()=>{"use strict";Bi();Fl=(t,e)=>{let n=t[e];return n==null?null:String(n)};Yi=".comet/run-state.json",Ml=256*1024});import{createHash as zw}from"crypto";import{promises as Qw}from"fs";import me from"path";import{spawnSync as ng}from"child_process";function Hu(t){return t.length>0&&/^[A-Za-z0-9@+=:,./\\_-]+$/.test(t)?t:`"${t.replace(/"/g,'""')}"`}function _o(t){return t.map(e=>Hu(e))}import{promises as Hh}from"fs";import N from"path";import{promises as Gu}from"fs";async function kt(t){try{return await Gu.access(t),!0}catch(e){if(zu(e))return!1;throw e}}function zu(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}ye();nn();Zs();Z();var rn=class extends Error{code="classic-layout-unavailable";constructor(e="Classic artifact layout is unavailable from .comet/config.yaml"){super(e),this.name="ClassicLayoutUnavailableError"}},eo=class extends Error{constructor(n,i,r){let s=j(r,n),o=j(r,i);super(`Classic layout conflict: both ${s}/ and ${o}/ exist; run comet doctor and resolve the conflict before writing`);this.configuredRoot=n;this.alternateRoot=i;this.name="ClassicLayoutConflictError"}configuredRoot;alternateRoot;code="classic-layout-conflict"},El=".comet/config.yaml";function Gh(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function xl(t){await T(t,El,{label:El,expected:"file"})}function _l(t,e){let n=N.resolve(t),i=e==="docs"?N.join(n,"docs"):n,r=N.join(i,"openspec"),s=N.join(n,"docs","superpowers");return{projectRoot:n,artifactLayout:e,openSpecBase:i,openSpecRoot:r,changesDir:N.join(r,"changes"),archiveDir:N.join(r,"changes","archive"),specsDir:N.join(r,"specs"),superpowersRoot:s,superpowersSpecsDir:N.join(s,"specs"),superpowersPlansDir:N.join(s,"plans"),superpowersReportsDir:N.join(s,"reports")}}async function zh(t){await xl(t);let e=await Oi(t,{allowPartialProject:!0,allowMissingNativeFields:!0});if(!e?.config)throw new rn;if(!(e.config.workflows??[e.config.default_workflow]).includes("classic"))throw new rn("Classic artifact layout is unavailable because Classic is not enabled");return e.classic?.artifact_layout??"legacy"}async function Qh(t,e){return _l(t,e??await zh(t))}async function Xh(t,e){let n=await Qh(t,e),i=n.artifactLayout==="legacy"?"docs":"legacy",r=_l(t,i).openSpecRoot,[s,o]=await Promise.all([T(n.projectRoot,j(n.projectRoot,n.openSpecRoot),{label:"Configured Classic OpenSpec root",expected:"directory"}),T(n.projectRoot,j(n.projectRoot,r),{label:"Alternate Classic OpenSpec root",expected:"directory"})]),a=s.exists,c=o.exists;return{paths:n,configuredRootExists:a,alternateRoot:r,alternateRootExists:c,dualRoots:a&&c}}async function Zh(t,e){let n=[t.openSpecRoot,t.changesDir,t.archiveDir,t.specsDir,e,t.superpowersRoot,t.superpowersSpecsDir,t.superpowersPlansDir,t.superpowersReportsDir];for(let i of n){let r=j(t.projectRoot,i);await T(t.projectRoot,r,{label:`Classic managed physical path ${r}`,expected:"directory"})}}async function fe(t,e,n={}){let i=await Xh(t,e);if(await Zh(i.paths,i.alternateRoot),i.dualRoots&&!n.allowAlternateRoot)throw new eo(i.paths.openSpecRoot,i.alternateRoot,i.paths.projectRoot);if(!i.configuredRootExists){let r=j(i.paths.projectRoot,i.paths.openSpecRoot),s=j(i.paths.projectRoot,i.alternateRoot);throw new rn(`Configured Classic OpenSpec root is missing: ${r} (alternate ${s} is ${i.alternateRootExists?"present":"missing"})`)}return i.paths}async function sn(t,e,n={}){let i=N.join(N.resolve(t),".comet","classic-root-move.json");if(await kt(i))throw new Error("Classic root move transaction is incomplete; inspect it with comet doctor and recover it explicitly before writing");let r=await fe(t,e,n);if(!await kt(r.openSpecRoot))throw new Error(`Configured Classic OpenSpec root is missing: ${j(r.projectRoot,r.openSpecRoot)}`);return r}async function be(t){let e=N.resolve(t),n=null;try{(await Hh.lstat(e)).isDirectory()||(e=N.dirname(e))}catch(i){if(!Gh(i))throw i}for(;;){N.basename(e)==="openspec"&&(n=N.dirname(e));let i=N.join(e,".comet","config.yaml"),r=!1;if(await kt(i))try{await xl(e);let o=(await Oi(e))?.value;r=!!o&&typeof o=="object"&&!Array.isArray(o)&&(o.schema==="comet.project.v1"||o.default_workflow!==void 0||o.native!==void 0)}catch{}if(r||await kt(N.join(e,".git")))return e;let s=N.dirname(e);if(s===e)return n??N.resolve(t);e=s}}function j(t,e){return N.relative(N.resolve(t),e).replaceAll("\\","/")}var Pl=nt(ze(),1);Z();import eg from"path";var tg=1024*1024;async function Rl(t,e){let n=e??await fe(t),i=eg.join(n.openSpecRoot,"config.yaml"),r=j(n.projectRoot,i),s;try{s=(await F(n.projectRoot,r,tg,{label:"Classic OpenSpec project config",bigint:!0})).bytes.toString("utf8")}catch(l){throw l.code==="ENOENT"?new Error(`Classic OpenSpec root is unhealthy: ${r} is missing; rerun OpenSpec initialization for the configured Classic layout`,{cause:l}):new Error(`Classic OpenSpec root is unhealthy: ${l instanceof Error?l.message:String(l)}`,{cause:l})}let o=(0,Pl.parseDocument)(s,{uniqueKeys:!0});if(o.errors.length>0)throw new Error(`Classic OpenSpec root is unhealthy: ${r} is invalid YAML (${o.errors[0].message})`);let a=o.toJS();if(!a||typeof a!="object"||Array.isArray(a))throw new Error(`Classic OpenSpec root is unhealthy: ${r} must contain a mapping`);let c=a.schema;if(typeof c!="string"||c.trim()==="")throw new Error(`Classic OpenSpec root is unhealthy: ${r} must declare a non-empty schema`);return{layout:n,configPath:r,schema:c}}function ig(t){return t[0]==="--"?t.slice(1):[...t]}async function Ol(t,e=process.cwd()){let n=ig(t);if(n.length===0)return{exitCode:64,stderr:"Usage: comet classic openspec -- "};let i=await be(e),r=await sn(i);await Rl(i,r);let s=process.env.COMET_OPENSPEC||"openspec",o=process.platform==="win32",a=ng(s,o?_o(n):n,{cwd:r.openSpecBase,encoding:"utf8",shell:o,windowsHide:!0});if(a.error){let c=a.error.code;return{exitCode:c==="ENOENT"?127:70,stdout:a.stdout||void 0,stderr:a.stderr||(c==="ENOENT"?`OpenSpec CLI not found: ${s}`:a.error.message)}}return{exitCode:a.status??1,stdout:a.stdout||void 0,stderr:a.stderr||void 0}}import{promises as og}from"fs";import ln from"path";Xe();ye();Z();import on from"path";var rg=2*1024*1024;function Ii(t,e,n){let i=on.resolve(t),r=on.isAbsolute(e)?on.resolve(e):on.resolve(i,e),s=on.relative(i,r).replaceAll("\\","/");return{root:i,relative:Ie(s,n),target:r}}async function Fe(t,e,n){let i=Ii(t,e,n.label);return T(i.root,i.relative,n)}async function an(t,e,n){return(await Fe(t,e,{label:n.label,expected:n.expected??"any"})).exists}async function cn(t,e,n){return(await sg(t,e,n)).toString("utf8")}async function sg(t,e,n){let i=Ii(t,e,n.label);return(await F(i.root,i.relative,n.maxBytes??rg,{label:n.label,hooks:n.hooks})).bytes}async function to(t,e,n){let i=Ii(t,e,n);return Hs(i.root,i.relative,{label:n})}async function Al(t,e,n,i){let r=Ii(t,e,i.label);await T(r.root,r.relative,{label:i.label,expected:"file"}),await ae(r.target,n,{containedRoot:r.root,beforeTemporaryOpen:i.beforeTemporaryOpen,beforeCommit:i.beforeCommit,exclusive:i.exclusive})}function no(t){return t?/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t)?t.includes("..")?"Change name cannot contain '..' (path traversal not allowed)":null:`Invalid change name: '${t}' -Valid format: lowercase kebab-case (a-z, 0-9, single hyphens)`:"Change name cannot be empty"}function un(t){let e=no(t);if(e)throw new Error(e)}function ag(t,e){return{label:j(t,e),directory:e}}async function qi(t,e,n){let i=ag(t,e);if(!(await Fe(t,e,{label:n,expected:"directory"})).exists)return{change:i,exists:!1,stateExists:!1};let s=await Fe(t,ln.join(e,".comet.yaml"),{label:`${n} state`,expected:"file"});return{change:i,exists:!0,stateExists:s.exists}}function Nl(t,e){let n=e.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&");return new RegExp(`^\\d{4}-\\d{2}-\\d{2}-${n}$`,"u").test(t)}async function cg(t,e,n,i={}){if(!i.skipExactCompatibility){let o=await qi(t,ln.join(e,n),`Classic archived change ${n}`);if(o.exists)return o.change}if(!(await Fe(t,e,{label:"Classic archive directory",expected:"directory"})).exists)return null;let s=[];for(let o of await og.readdir(e,{withFileTypes:!0})){if(!Nl(o.name,n))continue;let a=await qi(t,ln.join(e,o.name),`Classic archived change ${o.name}`);a.exists&&a.stateExists&&s.push(a.change)}return s.sort((o,a)=>a.directory.localeCompare(o.directory))[0]??null}async function io(t,e=process.cwd()){un(t);let n=await fe(e),i=await qi(n.projectRoot,ln.join(n.changesDir,t),`Classic active change ${t}`);return{...i.change,exists:i.exists,stateExists:i.stateExists}}async function $i(t,e=process.cwd(),n={}){un(t);let i=await fe(e);if(n.preferredArchiveName!==void 0){let r=n.preferredArchiveName;if(r!==t&&!Nl(r,t))throw new Error(`Classic preferred archive name '${r}' does not belong to change '${t}'`);let s=await qi(i.projectRoot,ln.join(i.archiveDir,r),`Classic preferred archived change ${r}`);return s.exists&&s.stateExists?s.change:null}return cg(i.projectRoot,i.archiveDir,t,n)}import{promises as ku}from"fs";import Q from"path";import{fileURLToPath as Su}from"url";import{promises as ug}from"fs";import ke from"path";Z();ye();import fn from"path";function lg(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function Tl(t,e,n,i){let r=Ie(n,"Classic handoff artifact pointer");if((await T(t,r,{label:"Classic handoff artifact",expected:"file"})).exists)return null;let o=await fe(t),a=`${j(t,o.changesDir)}/`,l=(o.artifactLayout==="docs"?[a,"openspec/changes/"]:[a]).find(y=>r.startsWith(y));if(!l)return null;let f=r.slice(l.length).split("/");if(f.length<4||f[1]!==".comet"||f.slice(2).some(y=>y.length===0))return null;let u=f[0];un(u);let d=f.slice(2),h=fn.resolve(e);if(fn.dirname(h)!==fn.resolve(o.archiveDir))return null;let g=fn.basename(h),p=/^\d{4}-\d{2}-\d{2}-(.+)$/u.exec(g);if(g!==u&&p?.[1]!==u)return null;await T(t,j(t,h),{label:"Classic archived change directory",expected:"directory"});let m=fn.join(h,".comet",...d),w=j(t,m);try{return await F(t,w,i,{label:"Historical Classic archived handoff artifact"}),w}catch(y){if(lg(y))return null;throw y}}Z();var jl=2*1024*1024;function dn(t,e){return ke.relative(t,e).split(ke.sep).join("/")}async function pn(t,e,n){if(!n)return{code:e,satisfied:!1};let i=n.replaceAll("\\","/");try{let r=await Ri(t,i,{label:`${e} artifact`});return{code:e,satisfied:r,source:i,...r?{resolvedSource:i}:{}}}catch(r){return{code:e,satisfied:!1,source:i,detail:`unsafe artifact pointer outside the project or through a special path: ${r instanceof Error?r.message:String(r)}`}}}async function fg(t,e,n){try{await fe(t)}catch(r){return{code:"design.handoff",satisfied:!1,...n?{source:n.replaceAll("\\","/")}:{},detail:`Classic layout is unsafe or unavailable for handoff evidence: ${r instanceof Error?r.message:String(r)}`}}let i=await pn(t,"design.handoff",n);if(!n||i.satisfied||i.detail)return i;try{let r=await Tl(t,e,n,jl);return r?{...i,satisfied:!0,resolvedSource:r,detail:`resolved historical legacy pointer from archived change: ${r}`}:i}catch(r){return{...i,satisfied:!1,detail:`unsafe archived handoff fallback: ${r instanceof Error?r.message:String(r)}`}}}async function Li(t,e,n){return pn(t,e,dn(t,n))}async function dg(t,e){let n=ke.join(e,"specs"),i;try{let o=dn(t,n);if(!(await T(t,o,{label:"OpenSpec delta-spec directory",expected:"directory"})).exists)return{code:"openspec.delta-spec",satisfied:!1};i=await ug.readdir(n)}catch(o){return o.code==="ENOENT"?{code:"openspec.delta-spec",satisfied:!1}:{code:"openspec.delta-spec",satisfied:!1,detail:`unsafe delta-spec path: ${o instanceof Error?o.message:String(o)}`}}let r=i.map(o=>ke.join(n,o,"spec.md")),s=(await Promise.all(r.map(async o=>{try{return await Ri(t,dn(t,o),{label:"OpenSpec delta spec"})?o:null}catch{return null}}))).filter(o=>o!==null);return{code:"openspec.delta-spec",satisfied:s.length>0,source:s[0]?dn(t,s[0]):void 0,detail:`${s.length} delta spec${s.length===1?"":"s"}`}}async function pg(t,e){let n,i=dn(t,e);try{n=(await F(t,i,jl,{label:"Classic tasks artifact"})).bytes.toString("utf8")}catch(o){return o.code==="ENOENT"?{code:"build.tasks-complete",satisfied:!1}:{code:"build.tasks-complete",satisfied:!1,source:i,detail:`unsafe tasks artifact: ${o instanceof Error?o.message:String(o)}`}}let r=[...n.matchAll(/^\s*[-*]\s+\[([ xX])\]\s+/gmu)],s=r.filter(o=>o[1].toLowerCase()==="x").length;return{code:"build.tasks-complete",satisfied:r.length>0&&s===r.length,source:i,detail:`${s} of ${r.length} tasks complete`}}function mn(t,e){return t.some(n=>n.code===e&&n.satisfied)}async function gt(t,e){let n=await be(t),i=e.classic,r=ke.join(t,"proposal.md"),s=ke.join(t,"design.md"),o=ke.join(t,"tasks.md"),a=e.run?ke.resolve(t,e.run.checkpointRef):ke.join(t,".comet","checkpoint.json"),c=await Promise.all([Li(n,"openspec.proposal",r),Li(n,"openspec.design",s),Li(n,"openspec.tasks",o),dg(n,t),pn(n,"design.document",i?.designDoc??null),pn(n,"build.plan",i?.plan??null),pg(n,o),pn(n,"verification.report",i?.verificationReport??null),fg(n,t,i?.handoffContext??null),Li(n,"run.checkpoint",a)]),l=c.find(f=>f.code==="design.handoff");return l&&!i?.handoffHash&&(l.satisfied=!1,l.detail="handoff hash is missing"),c.push({code:"archive.confirmed",satisfied:i?.archiveConfirmation==="confirmed"}),c}import{createHash as xw,randomUUID as _w}from"crypto";import{promises as wo}from"fs";import Ce from"path";function mg(t){return t.classicProfile??t.workflow}function hg(t){return!t.buildMode||!t.tddMode||!t.isolation||!t.verifyMode?!1:t.buildMode==="subagent-driven-development"?t.subagentDispatch==="confirmed":t.buildMode==="direct"?t.directOverride===!0:!0}function gg(t){return t.buildMode==="direct"&&t.tddMode==="direct"&&t.isolation!==null&&t.verifyMode==="light"}function wg(t,e,n){if(e.verifyResult==="fail")return t==="full"?"full.build.fix":`${t}.build.execute`;if(t==="full"){if(!mn(n,"build.plan"))return"full.build.plan";if(e.buildPause==="plan-ready")return"full.build.plan-ready";if(!hg(e))return"full.build.configure"}else if(!gg(e))throw new Error(`${t} build configuration is incomplete`);return mn(n,"build.tasks-complete")?`${t}.build.complete`:`${t}.build.execute`}function yg(t,e,n){return e.verifyResult!=="pass"||!mn(n,"verification.report")?`${t}.verify.run`:`${t}.verify.branch`}function vg(t,e){if(e.verifyResult!=="pass")throw new Error("archive requires verify_result=pass");return e.archiveConfirmation==="confirmed"?`${t}.archive.execute`:`${t}.archive.confirm`}function Di(t,e){let n=mg(t);if(t.archived&&t.phase!=="archive")throw new Error("archived=true requires phase=archive");if(t.archived)return"completed";if(n!=="full"&&t.phase==="design")throw new Error(`${n} workflow cannot enter design`);switch(t.phase){case"open":return`${n}.open`;case"design":return mn(e,"design.handoff")?"full.design.document":"full.design.handoff";case"build":return wg(n,t,e);case"verify":return yg(n,t,e);case"archive":return vg(n,t)}}var zi=nt(ze(),1);Xe();Z();import Gi from"path";Ji();var Bl=["full","hotfix","tweak"],Ze=1,jg=["open","design","build","verify","archive"],Ig=["en","zh-CN"],qg=["off","beta"],$g=["subagent-driven-development","executing-plans","direct"],Lg=["plan-ready"],Dg=["confirmed"],Fg=["tdd","direct"],Mg=["off","standard","thorough"],Wg=["current","branch","worktree"],Bg=["light","full"],Kg=["pending","pass","fail"],Yg=["pending","handled"],Ug=["pending","confirmed"],Hi=["workflow","language","phase","context_compression","build_mode","build_pause","subagent_dispatch","tdd_mode","review_mode","isolation","bound_branch","verify_mode","auto_transition","base_ref","design_doc","plan","verify_result","verify_failures","verification_report","branch_status","created_at","verified_at","archive_confirmation","archived","direct_override","handoff_context","handoff_hash","classic_profile","classic_migration"],Jg=["run_id"],Vg=new Set([...Hi,...Jg]),Hg=["workflow","phase","design_doc","plan","build_mode","isolation","verify_mode","verify_result","verified_at","archived"];function Kl(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function wt(t,e){let n=t[e];if(n==null||n==="")return null;if(typeof n!="string")throw new Error(`Invalid Classic state: ${e} must be a string or null`);return n}function Y(t,e,n,i=!0){let r=t[e];if(r==null||r===""){if(i)return null;throw new Error(`Invalid Classic state: ${e} is required`)}if(typeof r!="string"||!n.includes(r))throw new Error(`Invalid Classic state: ${e} must be one of ${n.join(", ")}${i?" or null":""}`);return r}function lo(t,e,n=!0){let i=t[e];if(i==null||i===""){if(n)return null;throw new Error(`Invalid Classic state: ${e} is required`)}if(typeof i!="boolean")throw new Error(`Invalid Classic state: ${e} must be true or false`);return i}function Gg(t,e,n=0){let i=t[e];if(i==null||i==="")return n;if(typeof i!="number"||!Number.isInteger(i)||i<0)throw new Error(`Invalid Classic state: ${e} must be a non-negative integer`);return i}function Vi(t,e){let n=wt(t,e);if(n===null)return null;if(/^(?:[A-Za-z]:|[\\/]|~)/u.test(n)||n.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Classic state: ${e} must be a relative repository path`);return n}function zg(t,e){let n=wt(t,e);if(n!==null&&!/^[a-f0-9]{64}$/u.test(n))throw new Error(`Invalid Classic state: ${e} must be a sha256 hex digest`);return n}function Qg(t){let e=t.classic_migration;if(e==null||e==="")return null;if(e!==Ze)throw new Error(`Invalid Classic state: classic_migration must be ${Ze}`);return e}function Xg(t){if(!Hi.some(n=>Kl(t,n)))return null;for(let n of Hg)if(!Kl(t,n))return null;return{workflow:Y(t,"workflow",Bl,!1),language:Y(t,"language",Ig),phase:Y(t,"phase",jg,!1),contextCompression:Y(t,"context_compression",qg),buildMode:Y(t,"build_mode",$g),buildPause:Y(t,"build_pause",Lg),subagentDispatch:Y(t,"subagent_dispatch",Dg),tddMode:Y(t,"tdd_mode",Fg),reviewMode:Y(t,"review_mode",Mg),isolation:Y(t,"isolation",Wg),boundBranch:wt(t,"bound_branch"),verifyMode:Y(t,"verify_mode",Bg),autoTransition:lo(t,"auto_transition"),baseRef:wt(t,"base_ref"),designDoc:Vi(t,"design_doc"),plan:Vi(t,"plan"),verifyResult:Y(t,"verify_result",Kg,!1),verifyFailures:Gg(t,"verify_failures"),verificationReport:Vi(t,"verification_report"),branchStatus:Y(t,"branch_status",Yg),createdAt:wt(t,"created_at"),verifiedAt:wt(t,"verified_at"),archiveConfirmation:Y(t,"archive_confirmation",Ug),archived:lo(t,"archived",!1),directOverride:lo(t,"direct_override"),handoffContext:Vi(t,"handoff_context"),handoffHash:zg(t,"handoff_hash"),classicProfile:Y(t,"classic_profile",Bl),classicMigration:Qg(t)}}function uo(t,e){let n=e??null;if(n===null&&e===void 0&&t.run_id&&t.skill)try{n=Ki(t)}catch(i){let r=i instanceof Error?i.message:String(i);throw new Error(r.replace(/^Invalid Run state:/u,"Invalid Classic state:"),{cause:i})}return{classic:Xg(t),run:n,unknownKeys:Object.keys(t).filter(i=>!Vg.has(i))}}function Yl(t){return{workflow:t.workflow,language:t.language,phase:t.phase,context_compression:t.contextCompression,build_mode:t.buildMode,build_pause:t.buildPause,subagent_dispatch:t.subagentDispatch,tdd_mode:t.tddMode,review_mode:t.reviewMode,isolation:t.isolation,bound_branch:t.boundBranch,verify_mode:t.verifyMode,auto_transition:t.autoTransition,base_ref:t.baseRef,design_doc:t.designDoc,plan:t.plan,verify_result:t.verifyResult,verify_failures:t.verifyFailures,verification_report:t.verificationReport,branch_status:t.branchStatus,created_at:t.createdAt,verified_at:t.verifiedAt,archive_confirmation:t.archiveConfirmation,archived:t.archived,direct_override:t.directOverride,handoff_context:t.handoffContext,handoff_hash:t.handoffHash,classic_profile:t.classicProfile,classic_migration:t.classicMigration}}Ji();var Zg=2*1024*1024;function wn(t){let e=t.toJS();if(e===null)return{};if(typeof e!="object"||Array.isArray(e))throw new Error("Invalid Classic state document: root must be a mapping");return e}function Ul(t,e,n){t.get(e)!==n&&t.set(e,n)}function ew(t,e){if(e.classic)for(let[n,i]of Object.entries(Yl(e.classic)))Ul(t,n,i);else for(let n of Hi)t.delete(n);oo(t.toJS(),e.run),e.run?Ul(t,"run_id",e.run.runId):t.delete("run_id")}function tw(t){let e=["skill","skill_version","skill_hash","orchestration","current_step","iteration","pending","pending_ref","trajectory_ref","context_ref","artifacts_ref","checkpoint_ref","run_status","run_retries"];for(let n of e)t.delete(n)}function nw(t){let e=!1;for(let n of["build_command","verify_command"])t.has(n)&&(t.delete(n),e=!0);return e}async function Jl(t){let e;try{e=(await F(Gi.dirname(t),Gi.basename(t),Zg,{label:"Classic state document"})).bytes.toString("utf8")}catch(i){if(i.code!=="ENOENT")throw i;return new zi.Document({})}let n=(0,zi.parseDocument)(e);if(n.errors.length>0)throw new Error(`Invalid Classic state document: ${n.errors[0].message}`);return wn(n),n}async function de(t,e={}){let n=e.migrate!==!1,i=Gi.join(t,".comet.yaml"),r=await Jl(i),s=wn(r),o=nw(r);o&&(s=wn(r));let a=await ao(t);if(!a&&s.run_id&&s.skill){let{runStateFromDocument:c}=await Promise.resolve().then(()=>(Ji(),Wl));a=c(s),a&&n&&(await Ui(t,a),tw(r),o=!0)}return o&&n&&await ae(i,r.toString(),{containedRoot:t}),uo(wn(r),a)}async function et(t,e,n={}){let i=Gi.join(t,".comet.yaml"),r=await Jl(i);ew(r,{...e,unknownKeys:e.unknownKeys??[]}),uo(wn(r),e.run??null),await ae(i,r.toString(),{containedRoot:t,beforeCommit:n.beforeCommit}),e.run?await Ui(t,e.run):await co(t)}function Vl(t,e,n){return{runId:e,skill:t.definition.metadata.name,skillVersion:t.definition.metadata.version,skillHash:n,orchestration:t.definition.orchestration.mode,currentStep:t.definition.orchestration.entry??null,iteration:0,pending:null,pendingRef:".comet/pending-action.json",trajectoryRef:".comet/trajectory.jsonl",contextRef:".comet/context.md",artifactsRef:".comet/artifacts.json",checkpointRef:".comet/checkpoint.json",status:"running",retries:{}}}Bi();import Qi from"path";var Se={trajectory:8*1024*1024,artifacts:1024*1024,context:1024*1024,pendingAction:256*1024,checkpoint:256*1024};function pe(t,e){if(Qi.isAbsolute(e))throw new Error("Run path must stay inside the change directory");let n=Qi.resolve(t),i=Qi.resolve(n,e);if(i!==n&&!i.startsWith(n+Qi.sep))throw new Error("Run path must stay inside the change directory")}async function yt(t,e,n,i={}){pe(t,e),await Mi(t,e,`${JSON.stringify(n)} -`,Se.trajectory,"Run trajectory",i)}async function yn(t,e,n={}){pe(t,e);let i=await Me(t,e,Se.trajectory,"Run trajectory",n);return i===null?[]:i.split(/\r?\n/).map((r,s)=>({line:r,number:s+1})).filter(({line:r})=>r.length>0).map(({line:r,number:s})=>{try{return JSON.parse(r)}catch(o){throw new Error(`Invalid Trajectory event at line ${s}`,{cause:o})}})}async function fo(t,e,n={}){pe(t,e);let i=await Me(t,e,Se.artifacts,"Run artifacts",n);return i===null?{}:JSON.parse(i)}async function Xi(t,e,n,i={}){pe(t,e),await We(t,e,JSON.stringify(n,null,2)+` -`,Se.artifacts,"Run artifacts",i)}async function Hl(t,e,n,i={}){pe(t,e),await We(t,e,n,Se.context,"Run context",i)}async function Gl(t,e,n={}){return pe(t,e),Me(t,e,Se.context,"Run context",n)}async function zl(t,e,n,i={}){pe(t,e),await We(t,e,JSON.stringify(n,null,2)+` -`,Se.pendingAction,"Run pending action",i)}async function Ql(t,e,n={}){pe(t,e);let i=await Me(t,e,Se.pendingAction,"Run pending action",n);return i===null?null:JSON.parse(i)}async function Xl(t,e,n={}){pe(t,e),await Wi(t,e,"Run pending action",n)}async function Zi(t,e,n,i={}){pe(t,e),await We(t,e,JSON.stringify(n,null,2)+` -`,Se.checkpoint,"Run checkpoint",i)}import{createHash as du,randomUUID as bw}from"crypto";import{promises as D}from"fs";import $ from"path";var tu=nt(ze(),1);import{promises as po}from"fs";import ee from"path";var iw=["invoke_skill","call_tool","handoff","ask_user","checkpoint"],rw=["deterministic","adaptive"],sw=["function","mcp","script","agent"],ow=["none","read","write","external"],aw=["progress","step","completion"],cw=["artifact_exists","state_equals"];function tt(t,e,n){return new Error(`${t}: ${e} ${n}`)}function H(t,e,n="document"){if(t===null||typeof t!="object"||Array.isArray(t))throw tt(e,n,"must be an object")}function Be(t,e,n){if(!Array.isArray(t))throw tt(e,n,"must be an array")}function U(t,e,n){if(typeof t!="string")throw tt(e,n,"must be a string")}function ce(t,e,n,i){e in t&&U(t[e],n,`${i}.${e}`)}function nu(t,e,n,i){if(e in t&&typeof t[e]!="boolean")throw tt(n,`${i}.${e}`,"must be a boolean")}function Ke(t,e,n,i){if(typeof t!="string"||!e.includes(t))throw tt(n,i,`must be one of ${e.join(", ")}`)}function er(t,e,n){Be(t,e,n),t.forEach((i,r)=>{U(i,e,`${n}[${r}]`)})}function Zl(t,e,n){H(t,e,n),U(t.name,e,`${n}.name`),U(t.description,e,`${n}.description`),nu(t,"required",e,n)}function lw(t,e,n){H(t,e,n),U(t.id,e,`${n}.id`),ce(t,"source",e,n),ce(t,"version",e,n)}function uw(t,e,n){H(t,e,n),U(t.id,e,`${n}.id`),U(t.role,e,`${n}.role`),ce(t,"instructions",e,n)}function fw(t,e,n){H(t,e,n),U(t.id,e,`${n}.id`),Ke(t.kind,sw,e,`${n}.kind`),U(t.source,e,`${n}.source`),Ke(t.sideEffect,ow,e,`${n}.sideEffect`),nu(t,"requiresConfirmation",e,n)}function dw(t,e,n){H(t,e,n),Ke(t.type,iw,e,`${n}.type`),ce(t,"ref",e,n),ce(t,"prompt",e,n),ce(t,"question",e,n),"options"in t&&er(t.options,e,`${n}.options`)}function pw(t,e,n){H(t,e,n),U(t.id,e,`${n}.id`),dw(t.action,e,`${n}.action`),ce(t,"next",e,n),"completionEvals"in t&&er(t.completionEvals,e,`${n}.completionEvals`)}function mw(t,e){let n="goal";H(t,e,n),U(t.statement,e,`${n}.statement`),Be(t.inputs,e,`${n}.inputs`),t.inputs.forEach((i,r)=>{Zl(i,e,`${n}.inputs[${r}]`)}),Be(t.outputs,e,`${n}.outputs`),t.outputs.forEach((i,r)=>{Zl(i,e,`${n}.outputs[${r}]`)}),er(t.success,e,`${n}.success`)}function hw(t,e){let n="orchestration";H(t,e,n),Ke(t.mode,rw,e,`${n}.mode`),ce(t,"entry",e,n),"steps"in t&&(Be(t.steps,e,`${n}.steps`),t.steps.forEach((i,r)=>{pw(i,e,`${n}.steps[${r}]`)}))}function iu(t,e){return H(t,e),Ke(t.apiVersion,["comet/v1alpha1"],e,"apiVersion"),Ke(t.kind,["Skill"],e,"kind"),H(t.metadata,e,"metadata"),U(t.metadata.name,e,"metadata.name"),U(t.metadata.version,e,"metadata.version"),U(t.metadata.description,e,"metadata.description"),mw(t.goal,e),hw(t.orchestration,e),Be(t.skills,e,"skills"),t.skills.forEach((n,i)=>{lw(n,e,`skills[${i}]`)}),Be(t.agents,e,"agents"),t.agents.forEach((n,i)=>{uw(n,e,`agents[${i}]`)}),Be(t.tools,e,"tools"),t.tools.forEach((n,i)=>{fw(n,e,`tools[${i}]`)}),t}function ru(t,e){H(t,e);for(let n of["allowedSkills","allowedAgents","allowedTools","confirmationRequiredFor"])n in t&&er(t[n],e,n);for(let n of["maxIterations","maxRetriesPerAction"])if(n in t&&(typeof t[n]!="number"||!Number.isFinite(t[n])))throw tt(e,n,"must be a finite number");return t}function gw(t,e){return H(t,e),"runtime"in t&&su(t.runtime,e,"runtime"),t}function su(t,e,n){return Be(t,e,n),t.forEach((i,r)=>{let s=`${n}[${r}]`;H(i,e,s),U(i.id,e,`${s}.id`),Ke(i.scope,aw,e,`${s}.scope`),Ke(i.type,cw,e,`${s}.type`),ce(i,"artifact",e,s),ce(i,"field",e,s),ce(i,"equals",e,s)}),t}async function mo(t){let e=await po.readFile(t,"utf8");try{return(0,tu.parse)(e)}catch(n){let i=n instanceof Error?n.message:String(n);throw tt(t,"document",i)}}async function ww(t){try{return await mo(t)}catch(e){if(e.code==="ENOENT")return null;throw e}}async function eu(t){try{return await po.access(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function yw(t){let e=ee.join(t,"checks.yaml"),n=ee.join(t,"evals.yaml"),[i,r]=await Promise.all([eu(e),eu(n)]);if(r)throw new Error(`${n}: evals.yaml is no longer supported; use checks.yaml`);return i?{document:gw(await mo(e),e)}:{document:null}}async function ou(t){let e=ee.resolve(t.root),n=ee.resolve(t.controlRoot);t.requireSkillMarkdown&&await po.access(ee.join(e,"SKILL.md"));let i=ee.join(n,"skill.yaml"),r=ee.join(n,"guardrails.yaml"),s=iu(await mo(i),i),o=await ww(r),a=o===null?null:ru(o,r),c=await yw(n),l={allowedSkills:s.skills.map(f=>f.id),allowedAgents:s.agents.map(f=>f.id),allowedTools:s.tools.map(f=>f.id),maxIterations:50,maxRetriesPerAction:3,confirmationRequiredFor:s.tools.filter(f=>f.requiresConfirmation).map(f=>f.id)};return{root:e,packageKind:t.packageKind==="runtime"?"runtime":void 0,definition:s,guardrails:{...l,...a},evals:c.document?.runtime??[]}}async function au(t){let e=ee.resolve(t);return ou({root:e,controlRoot:ee.join(e,"comet"),packageKind:"skill",requireSkillMarkdown:!0})}async function cu(t){let e=ee.resolve(t);return ou({root:e,controlRoot:e,packageKind:"runtime",requireSkillMarkdown:!1})}function lu(t,e,n=ee.join(e,"package.json")){H(t,n);let i=t.packageKind==="runtime"?"runtime":void 0,r=iu(t.definition,n),s=ru(t.guardrails,n),o=su(t.evals,n,"evals"),a={allowedSkills:r.skills.map(c=>c.id),allowedAgents:r.agents.map(c=>c.id),allowedTools:r.tools.map(c=>c.id),maxIterations:50,maxRetriesPerAction:3,confirmationRequiredFor:r.tools.filter(c=>c.requiresConfirmation).map(c=>c.id)};return{root:ee.resolve(e),packageKind:i,definition:r,guardrails:{...a,...s},evals:o}}import uu from"path";function vw(t,e,n,i){t.type==="invoke_skill"&&!e.definition.skills.some(r=>r.id===t.ref)&&n.push(`step ${i} references undeclared skill: ${t.ref??"(missing)"}`),t.type==="call_tool"&&!e.definition.tools.some(r=>r.id===t.ref)&&n.push(`step ${i} references undeclared tool: ${t.ref??"(missing)"}`),t.type==="handoff"&&!e.definition.agents.some(r=>r.id===t.ref)&&n.push(`step ${i} references undeclared agent: ${t.ref??"(missing)"}`),t.type==="ask_user"&&!t.question&&n.push(`step ${i} ask_user action requires question`)}function fu(t){let e=[],{definition:n,guardrails:i,evals:r}=t;n.apiVersion!=="comet/v1alpha1"&&e.push("unsupported apiVersion"),n.kind!=="Skill"&&e.push("kind must be Skill"),n.metadata.name||e.push("metadata.name is required"),n.goal.statement||e.push("goal.statement is required"),i.maxIterations<1&&e.push("maxIterations must be at least 1"),i.maxRetriesPerAction<0&&e.push("maxRetriesPerAction must not be negative");let s=n.orchestration.steps??[];if(n.orchestration.mode==="adaptive")(n.orchestration.entry||s.length>0)&&e.push("adaptive orchestration must not define entry or steps");else{let o=new Set;for(let a of s)o.has(a.id)&&e.push(`duplicate step id: ${a.id}`),o.add(a.id),vw(a.action,t,e,a.id);(!n.orchestration.entry||!o.has(n.orchestration.entry))&&e.push(`orchestration.entry references unknown step: ${n.orchestration.entry??"(missing)"}`);for(let a of s){a.next&&!o.has(a.next)&&e.push(`step ${a.id} has unknown next step: ${a.next}`);for(let c of a.completionEvals??[])r.some(l=>l.id===c)||e.push(`step ${a.id} references unknown eval: ${c}`)}}for(let o of n.tools){if(o.kind!=="script")continue;let a=uu.posix.normalize(o.source.replaceAll("\\","/"));(uu.isAbsolute(o.source)||a===".."||a.startsWith("../"))&&e.push(`script tool ${o.id} must reference a relative path inside the Skill package`)}for(let o of i.allowedSkills)n.skills.some(a=>a.id===o)||e.push(`guardrails allow undeclared skill: ${o}`);for(let o of i.allowedAgents)n.agents.some(a=>a.id===o)||e.push(`guardrails allow undeclared agent: ${o}`);for(let o of i.allowedTools)n.tools.some(a=>a.id===o)||e.push(`guardrails allow undeclared tool: ${o}`);return e}function tr(t){return Array.isArray(t)?t.map(tr):t&&typeof t=="object"?Object.fromEntries(Object.entries(t).sort(([e],[n])=>e.localeCompare(n)).map(([e,n])=>[e,tr(n)])):t}function kw(t){return tr({...t.packageKind==="runtime"?{packageKind:"runtime"}:{},definition:t.definition,guardrails:t.guardrails,evals:t.evals})}function Sw(t){return $.posix.normalize(t.replaceAll("\\","/"))}function vt(t,e,n){let i=$.relative(t,e);if(!(i===""||!$.isAbsolute(i)&&!i.startsWith(`..${$.sep}`)))throw new Error(`${n} resolves outside the Skill package`)}async function pu(t,e,n){let i=Sw(e);if($.posix.isAbsolute(i)||i===".."||i.startsWith("../"))throw new Error(`${n} resolves outside the Skill package`);let r=$.resolve(t,...i.split("/"));vt(t,r,n);let s;try{s=await D.realpath(r)}catch(o){throw o.code==="ENOENT"?new Error(`${n} does not exist: ${e}`,{cause:o}):o}if(vt(t,s,n),!(await D.stat(s)).isFile())throw new Error(`${n} is not a file: ${e}`);return{path:i,content:await D.readFile(s)}}async function Cw(t){let e=await D.realpath(t.root),n=t.packageKind==="runtime"?[]:[await pu(e,"SKILL.md","SKILL.md")];for(let i of t.definition.tools)i.kind==="script"&&n.push(await pu(e,i.source,`Script tool ${i.id}`));return n.sort((i,r)=>i.path.localeCompare(r.path))}function Ew(t,e){let n=e.map(i=>({path:i.path,sha256:du("sha256").update(i.content).digest("hex")}));return du("sha256").update(JSON.stringify(tr({package:t,files:n}))).digest("hex")}function gu(t){return JSON.stringify(t,null,2)+` -`}async function wu(t){let e=kw(t),n=await Cw(t);return{document:e,files:n,hash:Ew(e,n)}}async function nr(t){return(await wu(t)).hash}async function mu(t){try{return await D.access(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function hu(t,e){try{if((await D.readFile($.join(t,"sha256"),"utf8")).trim()!==e.hash)throw new Error("hash mismatch");if(await D.readFile($.join(t,"package.json"),"utf8")!==gu(e.document))throw new Error("package mismatch");for(let r of e.files)if(!(await D.readFile($.join(t,...r.path.split("/")))).equals(r.content))throw new Error(`file mismatch: ${r.path}`)}catch(n){throw new Error(`Existing Skill snapshot is invalid: ${e.hash}`,{cause:n})}}async function ho(t,e){let n=await wu(t),i=$.resolve(e,".comet","skill-snapshots"),r=$.join(i,n.hash);if(await D.mkdir(i,{recursive:!0}),await mu(r))return await hu(r,n),{hash:n.hash,snapshotDir:r};let s=$.join(i,`.tmp-${bw()}`);vt(i,s,"Temporary snapshot"),vt(i,r,"Published snapshot");try{await D.mkdir(s);for(let o of n.files){let a=$.join(s,...o.path.split("/"));vt(s,a,`Snapshot file ${o.path}`),await D.mkdir($.dirname(a),{recursive:!0}),await D.writeFile(a,o.content)}await D.writeFile($.join(s,"package.json"),gu(n.document)),await D.writeFile($.join(s,"sha256"),n.hash+` -`),await D.rename(s,r)}catch(o){if(await mu(r)){try{await hu(r,n)}finally{await D.rm(s,{recursive:!0,force:!0})}return{hash:n.hash,snapshotDir:r}}throw await D.rm(s,{recursive:!0,force:!0}),o}return{hash:n.hash,snapshotDir:r}}async function go(t,e){if(!/^[a-f0-9]{64}$/u.test(e))throw new Error(`Invalid Skill snapshot hash: ${e}`);let n=$.resolve(t,".comet","skill-snapshots"),i=$.join(n,e);vt(n,i,"Skill snapshot");try{let r=(await D.readFile($.join(i,"sha256"),"utf8")).trim();if(r!==e)throw new Error(`stored hash is ${r||"(empty)"}`);let s=$.join(i,"package.json"),o=JSON.parse(await D.readFile(s,"utf8")),a=lu(o,i,s),c=fu(a);if(c.length>0)throw new Error(c.map(f=>` - ${f}`).join(` -`));let l=await nr(a);if(l!==e)throw new Error(`calculated hash is ${l}`);return a}catch(r){throw new Error(`Skill snapshot is invalid or missing: ${e}`,{cause:r})}}async function yu(t){try{return await wo.access(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}function vu(t){return xw("sha256").update(t).digest("hex")}function Pw(t){return vu(JSON.stringify(Object.fromEntries(Object.entries(t).sort(([e],[n])=>e.localeCompare(n)))))}function Rw(t){return t.replaceAll(".","_").replaceAll("-","_")}async function Ow(t,e){let n=await be(t),i=Object.fromEntries(e.filter(o=>o.satisfied&&o.source).map(o=>[Rw(o.code),o.source])),r=Ce.join(t,"subagent-progress.md");await yu(r)&&(i.subagent_progress=Ce.relative(n,r).split(Ce.sep).join("/"));let s=e.find(o=>o.code==="design.handoff"&&o.satisfied);return s?.source&&(i.handoff_context=s.source),i}function Aw(t,e,n){return[{sequence:1,timestamp:n,type:"run_started",runId:t.runId,data:{skill:t.skill,skillVersion:t.skillVersion,skillHash:t.skillHash}},{sequence:2,timestamp:n,type:"state_migrated",runId:t.runId,data:{kind:"classic",migrationVersion:Ze,profile:e,source:"pre-migration"}}]}async function Nw(t){await Promise.all(t.map(e=>wo.rm(e,{recursive:!0,force:!0})))}async function bu(t,e){let n=await de(t);if(!n.classic)throw new Error("Classic migration requires a legacy state projection");let i=n.classic,r=i.classicProfile??i.workflow;if(n.run){if(i.classicMigration!==Ze)throw new Error("Classic Run exists without a supported classic_migration marker");if(n.run.skill!==e.skillPackage.definition.metadata.name)throw new Error(`Classic Run skill mismatch: expected ${e.skillPackage.definition.metadata.name}, got ${n.run.skill}`);if(await nr(e.skillPackage)!==n.run.skillHash)return await go(t,n.run.skillHash),{classic:i,run:n.run,evidence:await gt(t,n),migrated:!1,snapshotDir:Ce.join(t,".comet","skill-snapshots",n.run.skillHash)};let d=await ho(e.skillPackage,t);return{classic:i,run:n.run,evidence:await gt(t,n),migrated:!1,snapshotDir:d.snapshotDir}}let s=await gt(t,n),o=Di(i,s);if(!e.skillPackage.definition.orchestration.steps?.some(u=>u.id===o))throw new Error(`Classic Skill package does not define resolved step: ${o}`);let a=await nr(e.skillPackage),c=Ce.join(t,".comet","skill-snapshots",a),l=await yu(c),f=[];try{let u=await ho(e.skillPackage,t),d=Vl(e.skillPackage,e.runId?.()??_w(),u.hash);d.currentStep=o,o==="completed"&&(d.status="completed");let h={...i,classicProfile:r,classicMigration:Ze},g=await Ow(t,s),p=await be(t),m=s.find(k=>k.code==="design.handoff"&&k.satisfied),w=null;m?.source&&(w=await cn(p,m.resolvedSource??m.source,{label:"Classic migration handoff context",hooks:e.handoffReadHooks}),await Hl(t,d.contextRef,w),f.push(Ce.resolve(t,d.contextRef))),await Xi(t,d.artifactsRef,g),f.push(Ce.resolve(t,d.artifactsRef));let y=(e.now?.()??new Date).toISOString(),S={runId:d.runId,stateVersion:1,trajectoryOffset:2,contextHash:w===null?null:vu(w),artifactsHash:Pw(g),createdAt:y};await Zi(t,d.checkpointRef,S),f.push(Ce.resolve(t,d.checkpointRef)),f.push(Ce.resolve(t,d.trajectoryRef));for(let k of Aw(d,r,y))await yt(t,d.trajectoryRef,k);return await et(t,{classic:h,run:d,unknownKeys:n.unknownKeys}),{classic:h,run:d,evidence:s,migrated:!0,snapshotDir:u.snapshotDir}}catch(u){throw await Nw(f),l||await wo.rm(c,{recursive:!0,force:!0}),u}}async function Tw(t){try{return(await ku.stat(t)).isDirectory()}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function ir(t){try{return(await ku.stat(t)).isFile()}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function jw(t){return await Tw(t)?await ir(Q.join(t,"skill.yaml"))?!0:await ir(Q.join(t,"SKILL.md"))&&await ir(Q.join(t,"comet","skill.yaml")):!1}function Iw(t){return{root:t,packageKind:"runtime",definition:{apiVersion:"comet/v1alpha1",kind:"Skill",metadata:{name:"comet-classic",version:"1",description:"Internal compatibility orchestration for classic Comet full, hotfix, and tweak workflows"},goal:{statement:"Advance or restore a classic Comet Run without changing the user command surface",inputs:[{name:"classic-state",description:"Validated ClassicState consistent with the Run projection",required:!0},{name:"evidence",description:"Structured evidence produced by the Classic Evidence collector",required:!0}],outputs:[{name:"run-state",description:"Atomically synchronized Classic and Run state",required:!0}],success:["Legacy fields and Run fields remain consistent","Every step invokes only a declared public Comet Skill","The completed state passes its completion eval"]},orchestration:{mode:"deterministic",entry:"full.open",steps:[{id:"full.open",action:{type:"invoke_skill",ref:"comet-open"},next:"full.design.handoff"},{id:"full.design.handoff",action:{type:"invoke_skill",ref:"comet-design"},next:"full.design.document"},{id:"full.design.document",action:{type:"invoke_skill",ref:"comet-design"},next:"full.build.plan"},{id:"full.build.plan",action:{type:"invoke_skill",ref:"comet-build"},next:"full.build.plan-ready"},{id:"full.build.plan-ready",action:{type:"invoke_skill",ref:"comet-build"},next:"full.build.configure"},{id:"full.build.configure",action:{type:"invoke_skill",ref:"comet-build"},next:"full.build.execute"},{id:"full.build.execute",action:{type:"invoke_skill",ref:"comet-build"},next:"full.build.complete"},{id:"full.build.complete",action:{type:"invoke_skill",ref:"comet-build"},next:"full.verify.run"},{id:"full.build.fix",action:{type:"invoke_skill",ref:"comet-build"},next:"full.build.execute"},{id:"full.verify.run",action:{type:"invoke_skill",ref:"comet-verify"},next:"full.verify.branch"},{id:"full.verify.branch",action:{type:"invoke_skill",ref:"comet-verify"},next:"full.archive.confirm"},{id:"full.archive.confirm",action:{type:"invoke_skill",ref:"comet-archive"},next:"full.archive.execute"},{id:"full.archive.execute",action:{type:"invoke_skill",ref:"comet-archive"},next:"completed"},{id:"hotfix.open",action:{type:"invoke_skill",ref:"comet-hotfix"},next:"hotfix.build.execute"},{id:"hotfix.build.execute",action:{type:"invoke_skill",ref:"comet-build"},next:"hotfix.build.complete"},{id:"hotfix.build.complete",action:{type:"invoke_skill",ref:"comet-build"},next:"hotfix.verify.run"},{id:"hotfix.verify.run",action:{type:"invoke_skill",ref:"comet-verify"},next:"hotfix.verify.branch"},{id:"hotfix.verify.branch",action:{type:"invoke_skill",ref:"comet-verify"},next:"hotfix.archive.confirm"},{id:"hotfix.archive.confirm",action:{type:"invoke_skill",ref:"comet-archive"},next:"hotfix.archive.execute"},{id:"hotfix.archive.execute",action:{type:"invoke_skill",ref:"comet-archive"},next:"completed"},{id:"tweak.open",action:{type:"invoke_skill",ref:"comet-tweak"},next:"tweak.build.execute"},{id:"tweak.build.execute",action:{type:"invoke_skill",ref:"comet-build"},next:"tweak.build.complete"},{id:"tweak.build.complete",action:{type:"invoke_skill",ref:"comet-build"},next:"tweak.verify.run"},{id:"tweak.verify.run",action:{type:"invoke_skill",ref:"comet-verify"},next:"tweak.verify.branch"},{id:"tweak.verify.branch",action:{type:"invoke_skill",ref:"comet-verify"},next:"tweak.archive.confirm"},{id:"tweak.archive.confirm",action:{type:"invoke_skill",ref:"comet-archive"},next:"tweak.archive.execute"},{id:"tweak.archive.execute",action:{type:"invoke_skill",ref:"comet-archive"},next:"completed"},{id:"completed",action:{type:"checkpoint"},completionEvals:["classic-completed"]}]},skills:[{id:"comet-open"},{id:"comet-design"},{id:"comet-build"},{id:"comet-verify"},{id:"comet-archive"},{id:"comet-hotfix"},{id:"comet-tweak"}],agents:[],tools:[]},guardrails:{allowedSkills:["comet-open","comet-design","comet-build","comet-verify","comet-archive","comet-hotfix","comet-tweak"],allowedAgents:[],allowedTools:[],maxIterations:500,maxRetriesPerAction:3,confirmationRequiredFor:[]},evals:[{id:"classic-completed",scope:"completion",type:"state_equals",field:"status",equals:"completed"}]}}async function qw(){let t=Q.dirname(Su(import.meta.url)),e=[process.env.COMET_RUNTIME_CLASSIC_ROOT,Q.resolve(t,"..","runtime","classic"),Q.resolve(t,"..","..","comet","runtime","classic"),Q.resolve(t,"..","..","assets","skills","comet","runtime","classic"),Q.resolve("assets","skills","comet","runtime","classic"),process.env.COMET_CLASSIC_SKILL_ROOT,Q.resolve(t,"..","..","comet-classic"),Q.resolve(t,"..","..","assets","skills","comet-classic"),Q.resolve("assets","skills","comet-classic")].filter(n=>!!n);for(let n of e)if(await jw(n))return n;return null}async function $w(t){return await ir(Q.join(t,"skill.yaml"))?cu(t):au(t)}async function Cu(t){let e=await qw();return bu(t,{skillPackage:e?await $w(e):Iw(Q.dirname(Su(import.meta.url)))})}async function Eu(t,e,n,i){let r=await de(t);if(!r.classic||!r.run)throw new Error("Classic transition requires synchronized Classic and Run projections");let s=await gt(t,{classic:e,run:n,unknownKeys:r.unknownKeys}),o=Di(e,s),a={...n,currentStep:o,iteration:n.iteration+1,status:o==="completed"?"completed":"running"};await et(t,{classic:e,run:a,unknownKeys:r.unknownKeys});let c=await yn(t,a.trajectoryRef);return await yt(t,a.trajectoryRef,{sequence:c.length+1,timestamp:new Date().toISOString(),type:"state_transitioned",runId:a.runId,data:{kind:"classic",fromStep:n.currentStep,toStep:o,...i}}),a}Bi();import Lw from"path";var Dw=Lw.join(".comet","state-events.jsonl"),Fw=8*1024*1024;async function xu(t,e){let n={schemaVersion:1,timestamp:new Date().toISOString(),...e};return await Mi(t,Dw,`${JSON.stringify(n)} -`,Fw,"Classic state event log"),n}var Mw={"open-complete":{event:"open-complete",from:"open",guardRefs:["open-artifacts-present"]},"design-complete":{event:"design-complete",from:"design",guardRefs:["design-evidence-present"]},"build-complete":{event:"build-complete",from:"build",guardRefs:["build-decisions-selected"]},"verify-pass":{event:"verify-pass",from:"verify",guardRefs:["verification-report-present"]},"verify-fail":{event:"verify-fail",from:"verify",guardRefs:["verification-failed"]},"archive-confirm":{event:"archive-confirm",from:"archive",guardRefs:["archive-final-confirmation"]},"archive-reopen":{event:"archive-reopen",from:"archive",guardRefs:["archive-not-finalized"]},archived:{event:"archived",from:"archive",guardRefs:["verify-result-pass","archive-confirmed"]},"preset-escalate":{event:"preset-escalate",from:"build",guardRefs:["preset-workflow"]}};function Ww(t){return t.toISOString().slice(0,10)}function x(t,e,n,i){let r=t[n];t[n]=i,r!==i&&e.push({field:n,from:r,to:i})}function _u(t,e,n={}){let i=Mw[e];if(t.phase!==i.from)throw new Error(`Cannot apply ${e}: phase is '${t.phase}', expected '${i.from}'`);let r={...t},s=[],o=n.now??new Date;if(e==="open-complete")x(r,s,"phase",r.workflow==="full"?"design":"build");else if(e==="design-complete")x(r,s,"phase","build");else if(e==="build-complete"){let a=r.verifyResult==="fail";x(r,s,"phase","verify"),x(r,s,"verifyResult","pending"),x(r,s,"branchStatus","pending"),a||x(r,s,"verificationReport",null)}else if(e==="verify-pass")x(r,s,"verifyResult","pass"),x(r,s,"verifyFailures",0),x(r,s,"phase","archive"),x(r,s,"verifiedAt",Ww(o)),x(r,s,"archiveConfirmation","pending"),x(r,s,"branchStatus","pending");else if(e==="verify-fail")x(r,s,"verifyResult","fail"),x(r,s,"verifyFailures",r.verifyFailures+1),x(r,s,"phase","build"),x(r,s,"branchStatus","pending");else if(e==="preset-escalate"){if(r.workflow!=="hotfix"&&r.workflow!=="tweak")throw new Error(`Cannot apply ${e}: workflow must be hotfix or tweak, got '${r.workflow}'`);x(r,s,"workflow","full"),x(r,s,"classicProfile","full"),x(r,s,"phase","design"),x(r,s,"designDoc",null),x(r,s,"buildPause",null),x(r,s,"buildMode",null),x(r,s,"subagentDispatch",null),x(r,s,"tddMode",null),x(r,s,"reviewMode",null),x(r,s,"isolation",null),x(r,s,"boundBranch",null),x(r,s,"verifyMode",null),x(r,s,"directOverride",null)}else if(e==="archive-confirm"){if(r.verifyResult!=="pass")throw new Error(`Cannot apply ${e}: verifyResult must be pass`);if(r.archived)throw new Error(`Cannot apply ${e}: already archived`);x(r,s,"archiveConfirmation","confirmed")}else if(e==="archive-reopen"){if(r.archived)throw new Error(`Cannot apply ${e}: already archived`);x(r,s,"verifyResult","pending"),x(r,s,"verifyFailures",0),x(r,s,"phase","verify"),x(r,s,"verifiedAt",null),x(r,s,"archiveConfirmation",null),x(r,s,"branchStatus","pending")}else{if(r.verifyResult!=="pass")throw new Error(`Cannot apply ${e}: verifyResult must be pass`);if(r.archiveConfirmation!=="confirmed")throw new Error(`Cannot apply ${e}: archiveConfirmation must be confirmed`);x(r,s,"archived",!0)}return{classic:r,effects:s,definition:i}}Us();import{promises as Bw}from"fs";import Kw from"path";var yo="comet.selection.v2",Yw=16*1024;function vo(t){return Kw.join(t,".comet","current-change.json")}function Uw(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function Pu(t){return t===null||typeof t=="string"}function Jw(t){let e;try{e=JSON.parse(t)}catch(n){throw new Error(`current change selection contains invalid JSON: ${n instanceof Error?n.message:String(n)}`,{cause:n})}if(!Uw(e))throw new Error("current change selection must be a JSON object");if(e.version===1){if(typeof e.change!="string")throw new Error("legacy current change selection change must be a string");if(e.branch!==void 0&&!Pu(e.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:yo,workflow:"classic",change:e.change,branch:e.branch??null},legacy:!0}}if(e.schema!==yo)throw new Error(`current change selection schema must be ${yo}`);if(e.workflow!=="native"&&e.workflow!=="classic")throw new Error("current change selection workflow must be native or classic");if(typeof e.change!="string")throw new Error("current change selection change must be a string");if(!Pu(e.branch))throw new Error("current change selection branch must be a string or null");if(e.workflow==="native"&&e.branch!==null)throw new Error("Native current change selection branch must be null");return{selection:e,legacy:!1}}async function bo(t){let e;try{let i=vo(t),{bytes:r}=await _i(i,Yw,{label:"current change selection"});e=r.toString("utf8")}catch(i){if(i.code==="ENOENT")return{status:"missing"};throw new Error(`cannot read current change selection: ${i instanceof Error?i.message:String(i)}`,{cause:i})}return{status:"selected",...Jw(e)}}async function Ru(t){await Bw.rm(vo(t),{force:!0})}async function Ou(t,e,n){let i=await bo(t);return i.status!=="selected"||i.selection.workflow!==e||i.selection.change!==n?!1:(await Ru(t),!0)}var Au=null;function Nu(t,e){let n=t;for(let i of e)n+="\0"+(typeof i=="string"?i:JSON.stringify(i));return n}function Tu(t,e){return(...n)=>{let i=Au;if(i===null)return e(...n);let r=Nu(`async:${t}`,n),s=i.entries.get(r);if(s)return s.value;let o=e(...n).catch(a=>{throw i.entries.delete(r),a});return i.entries.set(r,{value:o}),o}}function ko(t,e){return(...n)=>{let i=Au;if(i===null)return e(...n);let r=Nu(`sync:${t}`,n),s=i.entries.get(r);if(s)return s.value;let o=e(...n);return i.entries.set(r,{value:o}),o}}import{execFileSync as ju}from"child_process";var Vw=nt(ze(),1);function Hw(t){try{let e=ju("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();return e&&e!=="HEAD"?e:null}catch{return null}}var cC=ko("liveGitBranch",t=>Hw(t));function Gw(t){try{return ju("git",["rev-parse","--is-inside-work-tree"],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()==="true"}catch{return!1}}var lC=ko("isGitWorkTree",t=>Gw(t));var bC=Tu("readCometCurrentSelection",t=>bo(t));async function Iu(t,e){return Ou(t,"classic",e)}var Xw="\x1B[32m",Zw="\x1B[31m",ey="\x1B[33m",Co="\x1B[0m";function te(t){return`${Xw}${t}${Co}`}function G(t){return`${Zw}${t}${Co}`}function vn(t){return`${ey}${t}${Co}`}var B=class extends Error{constructor(n,i=1){super(n);this.exitCode=i}exitCode},So=class{stderr=[];openSpecStdout=[];openSpecStderr=[];stepsOk=0;stepsTotal=0;captureOpenSpec(e){e.stdout&&this.openSpecStdout.push(e.stdout),e.stderr&&this.openSpecStderr.push(e.stderr)}toResult(e=0){let n=this.stderr.length>0?this.stderr.join(` +`,n)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let n=wi(e),i=pt(n);return i.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let n=wi(e),i=pt(n);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,n){return this.type!=="comment"||this.indent<=n?!1:e.every(i=>i.type==="newline"||i.type==="space")}*documentEnd(e){this.type!=="doc-mode"&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};cl.Parser=Ds});var pl=v(Qt=>{"use strict";var ll=xs(),ah=Bt(),zt=Ut(),ch=Cr(),lh=_(),uh=Ls(),ul=Fs();function fl(t){let e=t.prettyErrors!==!1;return{lineCounter:t.lineCounter||e&&new uh.LineCounter||null,prettyErrors:e}}function fh(t,e={}){let{lineCounter:n,prettyErrors:i}=fl(e),r=new ul.Parser(n?.addNewLine),s=new ll.Composer(e),o=Array.from(s.compose(r.parse(t)));if(i&&n)for(let a of o)a.errors.forEach(zt.prettifyError(t,n)),a.warnings.forEach(zt.prettifyError(t,n));return o.length>0?o:Object.assign([],{empty:!0},s.streamInfo())}function dl(t,e={}){let{lineCounter:n,prettyErrors:i}=fl(e),r=new ul.Parser(n?.addNewLine),s=new ll.Composer(e),o=null;for(let a of s.compose(r.parse(t),!0,t.length))if(!o)o=a;else if(o.options.logLevel!=="silent"){o.errors.push(new zt.YAMLParseError(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return i&&n&&(o.errors.forEach(zt.prettifyError(t,n)),o.warnings.forEach(zt.prettifyError(t,n))),o}function dh(t,e,n){let i;typeof e=="function"?i=e:n===void 0&&e&&typeof e=="object"&&(n=e);let r=dl(t,n);if(!r)return null;if(r.warnings.forEach(s=>ch.warn(r.options.logLevel,s)),r.errors.length>0){if(r.options.logLevel!=="silent")throw r.errors[0];r.errors=[]}return r.toJS(Object.assign({reviver:i},n))}function ph(t,e,n){let i=null;if(typeof e=="function"||Array.isArray(e)?i=e:n===void 0&&e&&(n=e),typeof n=="string"&&(n=n.length),typeof n=="number"){let r=Math.round(n);n=r<1?void 0:r>8?{indent:8}:{indent:r}}if(t===void 0){let{keepUndefined:r}=n??e??{};if(!r)return}return lh.isDocument(t)&&!i?t.toString(n):new ah.Document(t,i,n).toString(n)}Qt.parse=dh;Qt.parseAllDocuments=fh;Qt.parseDocument=dl;Qt.stringify=ph});var ze=v(O=>{"use strict";var mh=xs(),hh=Bt(),gh=ss(),Ms=Ut(),wh=_t(),je=_(),yh=Re(),vh=j(),bh=Ae(),kh=Ne(),Sh=hi(),Ch=$s(),Eh=Ls(),xh=Fs(),vi=pl(),ml=St();O.Composer=mh.Composer;O.Document=hh.Document;O.Schema=gh.Schema;O.YAMLError=Ms.YAMLError;O.YAMLParseError=Ms.YAMLParseError;O.YAMLWarning=Ms.YAMLWarning;O.Alias=wh.Alias;O.isAlias=je.isAlias;O.isCollection=je.isCollection;O.isDocument=je.isDocument;O.isMap=je.isMap;O.isNode=je.isNode;O.isPair=je.isPair;O.isScalar=je.isScalar;O.isSeq=je.isSeq;O.Pair=yh.Pair;O.Scalar=vh.Scalar;O.YAMLMap=bh.YAMLMap;O.YAMLSeq=kh.YAMLSeq;O.CST=Sh;O.Lexer=Ch.Lexer;O.LineCounter=Eh.LineCounter;O.Parser=xh.Parser;O.parse=vi.parse;O.parseAllDocuments=vi.parseAllDocuments;O.parseDocument=vi.parseDocument;O.stringify=vi.stringify;O.visit=ml.visit;O.visitAsync=ml.visitAsync});import bi from"path";function Rh(t,e){if(typeof t!="string")throw new Error(`${e} must be a string`);let n=t.trim();if(n.length===0||bi.posix.isAbsolute(n)||bi.win32.isAbsolute(n)||/^(?:~|[\\/])/u.test(n))throw new Error(`${e} must be a project-relative path`);if(n===".")return[];let i=n.replaceAll("\\","/").split("/");if(i.some(r=>r===".."))throw new Error(`${e} must stay inside the project root`);if(i.some(r=>r===""||r==="."))throw new Error(`${e} must not contain empty or dot path segments`);return i}function ki(t){let e=Rh(t,"native.artifact_root");return e.length===0?".":e.join("/")}function gl(t,e="docs"){let n=t??e;if(n!=="legacy"&&n!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return n}function Ie(t,e,n=!1){if(typeof t!="string")throw new Error(`${e} must be a string`);let i=t.trim().replaceAll("\\","/");if(i.length===0||bi.posix.isAbsolute(i)||bi.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${e} must be relative to its declared path base`);let r=i.split("/");if(r.some(s=>s===".."))throw new Error(`${e} must stay inside its declared path base`);if(r.some(s=>s===""||s==="."))throw new Error(`${e} must not contain empty or dot path segments`);if(!n&&/[*?]/u.test(i))throw new Error(`${e} cannot contain wildcards`);return r.join("/")}function Xt(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function wl(t,e,n){let i=t??e;if(i!=="en"&&i!=="zh-CN")throw new Error(`${n} must be en or zh-CN`);return i}function yl(t,e){if(typeof t!="string"||t.length===0||t.includes("\\")||t.includes("\0")||t.startsWith("/")||t.split("/").includes(".."))throw new Error(`${e} contains an unsafe pattern`);if(t.length>Bs)throw new Error(`${e} exceeds ${Bs} characters`);let n=0;for(let i=0;iKs)throw new Error(`${e} contains more than ${Ks} wildcard tokens`);return t}function hl(t,e,n){if(t===void 0)return[...n];if(!Array.isArray(t))throw new Error(`${e} contains an unsafe pattern`);return[...new Set(t.map(i=>yl(i,e)))].sort((i,r)=>i.localeCompare(r,"en"))}function Ws(t,e,n){let i=t??e;if(!Number.isSafeInteger(i)||i<1)throw new Error(`${n} must be a positive integer`);return i}function Oh(t){if(t===void 0)return{...we,include:[...we.include],exclude:[...we.exclude]};let e=Xt(t,"native.snapshot");return{include:hl(e.include,"native.snapshot.include",we.include),exclude:hl(e.exclude,"native.snapshot.exclude",we.exclude),max_files:Ws(e.max_files,we.max_files,"native.snapshot.max_files"),max_total_bytes:Ws(e.max_total_bytes,we.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:Ws(e.max_duration_ms,we.max_duration_ms,"native.snapshot.max_duration_ms")}}function Ah(t){if(t===void 0)return;let e=Xt(t,"native.pending_root_move"),n=e.id,i=e.from_artifact_root,r=e.to_artifact_root,s=e.stage;if(typeof n!="string"||!/^[a-f0-9-]{8,}$/u.test(n))throw new Error("native.pending_root_move.id is invalid");if(typeof i!="string"||typeof r!="string")throw new Error("native.pending_root_move roots must be strings");if(s!=="copying"&&s!=="ready"&&s!=="switched")throw new Error("native.pending_root_move.stage is invalid");let o;if(e.cleanup!==void 0){let a=Xt(e.cleanup,"native.pending_root_move.cleanup"),c=a.kind,l=a.state,f=a.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof f!="string"||!/^[a-f0-9]{64}$/u.test(f))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:f}}return{id:n,fromArtifactRoot:ki(i),toArtifactRoot:ki(r),stage:s,...o?{cleanup:o}:{}}}function Nh(t,e={}){let n=Xt(t,"native"),i=n.artifact_root??(e.allowMissingArtifactRoot?"docs":void 0);if(typeof i!="string")throw new Error("native.artifact_root must be a string");let r=n.clarification_mode??"sequential";if(r!=="sequential"&&r!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let s=n.archive_confirmation??"automatic";if(s!=="automatic"&&s!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=n.max_verify_failures??_h;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let a=Ah(n.pending_root_move);return{artifact_root:ki(i),language:wl(n.language,"en","native.language"),clarification_mode:r,archive_confirmation:s,max_verify_failures:o,snapshot:Oh(n.snapshot),...a?{pending_root_move:a}:{}}}function Th(t){let e=Xt(t,"classic"),n=e.context_compression??"off";if(n!=="off"&&n!=="beta")throw new Error("classic.context_compression must be off or beta");let i=e.review_mode??"standard";if(i!=="off"&&i!=="standard"&&i!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let r=e.auto_transition??!0;if(typeof r!="boolean")throw new Error("classic.auto_transition must be true or false");return{artifact_layout:gl(e.artifact_layout),language:wl(e.language,"zh-CN","classic.language"),context_compression:n,review_mode:i,auto_transition:r}}function jh(t){let e=t??!0;if(typeof e!="boolean")throw new Error("ambient_resume must be true or false");return e}function Ih(t,e,n,i,r){let s=t.schema!==void 0;if(!(s||t.default_workflow!==void 0||t.workflows!==void 0||!r.allowPartialProject&&t.native!==void 0)||r.allowPartialProject&&!s)return null;if(t.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(t.default_workflow!=="native"&&t.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let a=t.workflows??[t.default_workflow];if(!Array.isArray(a)||a.length===0||a.some(l=>l!=="native"&&l!=="classic"))throw new Error("workflows must contain native and/or classic");let c=[...new Set(a)];if(!c.includes(t.default_workflow))throw new Error("workflows must include default_workflow");if(c.includes("native")&&!e)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:t.default_workflow,workflows:c,ambient_resume:i,...e?{native:e}:{},...n?{classic:n}:{}}}function mt(t,e={}){let n=(0,Ys.parseDocument)(t,{uniqueKeys:!0});if(n.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${n.errors[0].message}`);let i=n.toJS();if(i==null)return{value:{},config:null,ambient_resume:!0};if(typeof i!="object"||Array.isArray(i))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let r=i,s=jh(r.ambient_resume),o=r.native===void 0?void 0:Nh(r.native,{allowMissingArtifactRoot:e.allowMissingNativeFields}),a=r.classic===void 0?void 0:Th(r.classic),c=Ih(r,o,a,s,{allowPartialProject:e.allowPartialProject??!1});return{value:r,config:c,ambient_resume:s,...o?{native:o}:{},...a?{classic:a}:{}}}var Ys,Zt,Bs,Ks,_h,Ph,we,ye=K(()=>{"use strict";Ys=nt(ze(),1),Zt=64*1024,Bs=1024,Ks=64,_h=5,Ph=[".agents/skills/**",".amazonq/skills/**",".augment/skills/**",".bob/skills/**",".claude/skills/**",".cline/skills/**",".codebuddy/skills/**",".continue/skills/**",".cospec/skills/**",".crush/skills/**",".cursor/skills/**",".factory/skills/**",".forge/skills/**",".gemini/skills/**",".github/skills/**",".iflow/skills/**",".junie/skills/**",".kilocode/skills/**",".kimi-code/skills/**",".kiro/skills/**",".lingma/skills/**",".mimocode/skills/**",".opencode/skills/**",".pi/skills/**",".qoder/skills/**",".qwen/skills/**",".roo/skills/**",".trae-cn/skills/**",".trae/skills/**",".windsurf/skills/**",".zcode/skills/**"],we={include:["**/*"],exclude:[...Ph],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4}});function $e(t){return t!==0&&t!==0n&&t!=="0"}function Si(t,e){return $e(t.dev)&&$e(e.dev)&&$e(t.ino)&&$e(e.ino)}function ve(t,e){let n=$e(t.dev)&&$e(e.dev);if(n&&t.dev!==e.dev)return!1;let i=$e(t.ino)&&$e(e.ino);return i&&t.ino!==e.ino?!1:n&&i?!0:t.birthtime===e.birthtime}var Ci=K(()=>{"use strict"});import{constants as Ei,promises as Qe}from"fs";function Us(t){return"birthtimeNs"in t&&typeof t.birthtimeNs=="bigint"?t.birthtimeNs:t.birthtimeMs}function vl(t){return"ctimeNs"in t&&typeof t.ctimeNs=="bigint"?t.ctimeNs:t.ctimeMs}function en(t){return{dev:t.dev,ino:t.ino,birthtime:Us(t)}}function xi(t,e){let n=en(t),i=en(e);return Si(n,i)?ve(n,i):ve(n,i)&&Us(t)===Us(e)&&vl(t)===vl(e)&&t.size===e.size}async function _i(t,e,n={}){if(!Number.isSafeInteger(e)||e<1)throw new Error("race-safe read byte limit must be a positive integer");let i=n.label??"file",r=n.bigint===!0,s=await Qe.lstat(t,{bigint:r});if(!s.isFile()||s.isSymbolicLink())throw new qe("not-regular-file",`${i} must be a regular file`);if(BigInt(s.size)>BigInt(e))throw new qe("too-large",`${i} exceeds ${e} bytes`);let o=await Qe.realpath(t);await n.verify?.("pre-open",{realPath:o,identity:en(s)});let a=process.platform==="win32"?Ei.O_RDONLY:Ei.O_RDONLY|Ei.O_NOFOLLOW|Ei.O_NONBLOCK,c;try{c=await Qe.open(t,a)}catch(l){throw l.code==="ELOOP"?new qe("not-regular-file",`${i} must be a regular file`,{cause:l}):l}try{let[l,f,u]=await Promise.all([c.stat({bigint:r}),Qe.lstat(t,{bigint:r}),Qe.realpath(t)]);if(!l.isFile()||!f.isFile()||f.isSymbolicLink()||u!==o||!xi(s,l)||!xi(s,f))throw new qe("changed",`${i} changed while opening`);await n.verify?.("post-open",{realPath:u,identity:en(l)}),await n.hooks?.afterOpen?.();let d=[],h=0,g=Buffer.allocUnsafe(Math.min(64*1024,e+1));for(;;){let y=e+1-h,{bytesRead:S}=await c.read(g,0,Math.min(g.length,y),null);if(S===0)break;if(h+=S,h>e)throw new qe("too-large",`${i} exceeds ${e} bytes`);d.push(Buffer.from(g.subarray(0,S)))}await n.hooks?.beforeFinalCheck?.();let[p,m,w]=await Promise.all([c.stat({bigint:r}),Qe.lstat(t,{bigint:r}),Qe.realpath(t)]);if(!m.isFile()||m.isSymbolicLink()||w!==o||!xi(s,p)||!xi(s,m))throw new qe("changed",`${i} changed while reading`);return await n.verify?.("post-read",{realPath:w,identity:en(p)}),{bytes:Buffer.concat(d,h),stat:p,realPath:w}}finally{await c.close()}}var qe,Js=K(()=>{"use strict";Ci();qe=class extends Error{reason;constructor(e,n,i){super(n,i),this.name="RaceSafeReadError",this.reason=e}}});import{promises as Le}from"fs";import oe from"path";function bl(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}function Pi(t,e){let n=oe.relative(t,e);return n===""||!oe.isAbsolute(n)&&n!==".."&&!n.startsWith(`..${oe.sep}`)}async function Vs(t,e){let n=oe.resolve(t),i=await Le.lstat(n);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${e} project root must be a real directory`);return Le.realpath(n)}async function Hs(t,e,n,i){let r=t;for(let s=0;s{if(!Pi(s,a.realPath))throw new Error(`${i.label} resolves outside the project root`);await Hs(r.projectRoot,s,r.relative.split("/"),{label:i.label,expected:"file"})}})}var Z=K(()=>{"use strict";Js();ye()});import{createHash as $h}from"crypto";function qh(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function Oi(t,e={}){return(await Ai(t,e)).document}async function Lh(t){try{return(await F(t,tn,Zt,{label:tn})).bytes}catch(e){if(qh(e))return null;throw e}}function Dh(t){return t?{exists:!0,sha256:$h("sha256").update(t).digest("hex")}:{exists:!1,sha256:null}}async function Ai(t,e={}){let n=await Lh(t);return{document:n?mt(n.toString("utf8"),e):null,identity:Dh(n)}}var tn,nn=K(()=>{"use strict";ye();Z();tn=".comet/config.yaml"});import{randomUUID as Fh}from"crypto";import{constants as Mh,promises as I}from"fs";import W from"path";async function zs(t,e){try{return await I.link(t,e),{linked:!0}}catch(n){let i=n.code;if(i!=="ENOTSUP"&&i!=="EOPNOTSUPP")throw n}return await I.copyFile(t,e,Mh.COPYFILE_EXCL),{linked:!1}}function ht(t,e){let n=W.relative(t,e);return n===""||!W.isAbsolute(n)&&n!==".."&&!n.startsWith(`..${W.sep}`)}function Ti(t){return{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs}}function Wh(t,e){return ve(t,Ti(e))}function Ni(t,e){let n=Ti(t),i=Ti(e);return Si(n,i)?ve(n,i):ve(n,i)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.size===e.size}async function ji(t){let e=await I.lstat(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Contained atomic write parent must be a real directory: ${t}`);return{path:t,realPath:await I.realpath(t),...Ti(e)}}async function De(t){for(let e of t){let n=await I.lstat(e.path);if(!n.isDirectory()||n.isSymbolicLink()||!Wh(e,n)||await I.realpath(e.path)!==e.realPath)throw new Error(`Contained atomic write parent changed before commit: ${e.path}`)}}async function Bh(t,e){let n=W.resolve(t),i=W.resolve(e);if(!ht(n,i))throw new Error(`Contained atomic write parent is outside its managed root: ${e}`);let r=[await ji(n)],s=W.relative(n,i).split(W.sep).filter(Boolean),o=n;for(let a of s){await De(r),o=W.join(o,a);try{await I.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await ji(o);if(!ht(r[0].realPath,c.realPath))throw new Error(`Contained atomic write parent resolves outside its managed root: ${o}`);r.push(c)}return await De(r),r}async function Kh(t,e){let n=W.resolve(t),i=W.resolve(e);if(!ht(n,i))throw new Error(`Contained file parent is outside its managed root: ${e}`);let r=[await ji(n)],s=W.relative(n,i).split(W.sep).filter(Boolean),o=n;for(let a of s){o=W.join(o,a);try{let c=await ji(o);if(!ht(r[0].realPath,c.realPath))throw new Error(`Contained file parent resolves outside its managed root: ${o}`);r.push(c)}catch(c){if(c.code==="ENOENT")return null;throw c}}return await De(r),r}async function kl(t){let e;try{e=await I.open(t,"r"),await e.sync()}catch(n){let i=n.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(i??""))throw n}finally{await e?.close()}}async function Yh(t,e,n){let i=W.dirname(t),r=await Bh(n.containedRoot,i),s=W.join(i,`.${W.basename(t)}.${Fh()}.tmp`),o,a;try{await n.beforeTemporaryOpen?.(),o=await I.open(s,"wx"),a=await o.stat();let[c,l]=await Promise.all([I.lstat(s),I.realpath(s)]);if(await De(r),!c.isFile()||c.isSymbolicLink()||!Ni(a,c)||!ht(r[0].realPath,l))throw new Error("Contained atomic write temporary file opened outside its managed parent");if(typeof e=="string"?await o.writeFile(e,"utf8"):await o.writeFile(e),await o.sync(),!Ni(a,await o.stat()))throw new Error("Contained atomic write temporary file changed while writing");await o.close(),o=void 0,await n.beforeCommit?.(),await De(r);let f=await I.lstat(s);if(!f.isFile()||f.isSymbolicLink()||!Ni(f,a))throw new Error("Contained atomic write temporary file changed before commit");n.exclusive?(await zs(s,t),await I.unlink(s)):await I.rename(s,t),await kl(i)}catch(c){await o?.close();try{await De(r),await I.rm(s,{force:!0})}catch{}throw c}}async function ae(t,e,n){await Yh(t,e,n)}async function Qs(t,e){let n=W.dirname(t),i=await Kh(e.containedRoot,n);if(!i)return!1;let r,s;try{r=await I.lstat(t),s=await I.realpath(t)}catch(c){if(c.code==="ENOENT")return!1;throw c}if(!r.isFile()||r.isSymbolicLink()||!ht(i[0].realPath,s))throw new Error("Contained file removal target must be a regular file inside its managed root");await e.beforeRemove?.(),await De(i);let[o,a]=await Promise.all([I.lstat(t),I.realpath(t)]);if(!o.isFile()||o.isSymbolicLink()||!Ni(r,o)||a!==s)throw new Error("Contained file removal target changed before removal");return await I.unlink(t),await De(i),await kl(n),!0}var Xe=K(()=>{"use strict";Ci()});var tb,Xs=K(()=>{"use strict";Xe();nn();Z();tb=16*1024});var eo=K(()=>{"use strict";Xe();ye();nn();Z();Xs()});var Mi=K(()=>{"use strict"});var $l=K(()=>{"use strict"});var ro=K(()=>{"use strict";Mi()});var ql=K(()=>{"use strict";Mi();ro()});var _g,Ll=K(()=>{"use strict";_g=nt(ze(),1);Xe();ye();Z()});var Dl=K(()=>{"use strict";Mi();Xe();$l();ql();ye();Ll();Z();nn();eo();Xs();ro()});import{TextDecoder as Pg}from"util";function Fl(t){return{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs}}function Rg(t,e){try{return new Pg("utf-8",{fatal:!0}).decode(t.bytes)}catch(n){throw new Error(`${e} is not valid UTF-8`,{cause:n})}}async function so(t,e,n,i,r={}){try{let s=await F(t,e,n,{label:i,hooks:r.hooks});return{result:s,text:Rg(s,i)}}catch(s){let o=s.code;if(o==="ENOENT"||o==="ENOTDIR")return null;throw s}}async function Me(t,e,n,i,r={}){return(await so(t,e,n,i,r))?.text??null}async function We(t,e,n,i,r,s={}){if(Buffer.byteLength(n,"utf8")>i)throw new Error(`${r} exceeds ${i} bytes`);let o=await so(t,e,i,r),a=await T(t,e,{label:r,expected:"file"});await ae(a.target,n,{containedRoot:a.projectRoot,beforeCommit:async()=>{await s.beforeCommit?.();let c=await so(t,e,i,r);if(!(!o&&!c)){if(!o||!c)throw new Error(`${r} changed before commit`);if(o.result.realPath!==c.result.realPath||!ve(Fl(o.result.stat),Fl(c.result.stat))||o.text!==c.text)throw new Error(`${r} changed before commit`)}}})}async function Wi(t,e,n,i,r,s={}){let o=await Me(t,e,i,r);await We(t,e,`${o??""}${n}`,i,r,s)}async function Bi(t,e,n,i={}){let r=await T(t,e,{label:n,expected:"file"});return r.exists?Qs(r.target,{containedRoot:r.projectRoot,beforeRemove:i.beforeRemove}):!1}var Ki=K(()=>{"use strict";Dl();Ci()});var Bl={};Vu(Bl,{RUN_STATE_FILE:()=>Ui,applyRunStateToDocument:()=>oo,readRunState:()=>ao,removeRunState:()=>co,runStateFromDocument:()=>Yi,writeRunState:()=>Ji});import Og from"path";function gn(t,e){let n=t[e];if(typeof n!="string"||n.length===0)throw new Error(`Invalid Run state: ${e} must be a non-empty string`);return n}function hn(t,e){let n=gn(t,e);if(Og.isAbsolute(n)||/^(?:[A-Za-z]:|[\\/]|~)/u.test(n)||n.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Run state: ${e} must stay inside the change directory`);return n}function Ag(t){let e=t.run_retries??"{}",n;try{n=typeof e=="string"?JSON.parse(e):e}catch(i){throw new Error("Invalid Run state: run_retries must be a JSON object",{cause:i})}if(!n||typeof n!="object"||Array.isArray(n))throw new Error("Invalid Run state: run_retries must be a JSON object");for(let i of Object.values(n))if(!Number.isInteger(i)||Number(i)<0)throw new Error("Invalid Run state: retry counts must be non-negative integers");return n}function Yi(t){if(!t.run_id)return null;let e=gn(t,"run_id"),n=gn(t,"skill"),i=gn(t,"skill_version"),r=gn(t,"skill_hash"),s=hn(t,"pending_ref"),o=hn(t,"trajectory_ref"),a=hn(t,"context_ref"),c=hn(t,"artifacts_ref"),l=hn(t,"checkpoint_ref"),f=Number(t.iteration);if(!Number.isInteger(f)||f<0)throw new Error("Invalid Run state: iteration must be a non-negative integer");if(t.orchestration!=="deterministic"&&t.orchestration!=="adaptive")throw new Error("Invalid Run state: orchestration must be deterministic or adaptive");if(t.run_status!=="running"&&t.run_status!=="waiting"&&t.run_status!=="completed"&&t.run_status!=="failed")throw new Error("Invalid Run state: run_status is invalid");return{runId:e,skill:n,skillVersion:i,skillHash:r,orchestration:t.orchestration,currentStep:Ml(t,"current_step"),iteration:f,pending:Ml(t,"pending"),pendingRef:s,trajectoryRef:o,contextRef:a,artifactsRef:c,checkpointRef:l,status:t.run_status,retries:Ag(t)}}function oo(t,e){e?t.run_id=e.runId:delete t.run_id}function Ng(t){return{runId:t.runId,skill:t.skill,skillVersion:t.skillVersion,skillHash:t.skillHash,orchestration:t.orchestration,currentStep:t.currentStep,iteration:t.iteration,pending:t.pending,pendingRef:t.pendingRef,trajectoryRef:t.trajectoryRef,contextRef:t.contextRef,artifactsRef:t.artifactsRef,checkpointRef:t.checkpointRef,status:t.status,retries:t.retries}}function Tg(t){let e={run_id:t.runId,skill:t.skill,skill_version:t.skillVersion,skill_hash:t.skillHash,orchestration:t.orchestration,current_step:t.currentStep,iteration:t.iteration,pending:t.pending,pending_ref:t.pendingRef,trajectory_ref:t.trajectoryRef,context_ref:t.contextRef,artifacts_ref:t.artifactsRef,checkpoint_ref:t.checkpointRef,run_status:t.status,run_retries:JSON.stringify(t.retries)};return Yi(e)}async function ao(t,e={}){let n=await Me(t,Ui,Wl,"Run state",e);if(n===null)return null;let i=JSON.parse(n);return Tg(i)}async function Ji(t,e,n={}){await We(t,Ui,JSON.stringify(Ng(e),null,2),Wl,"Run state",n)}async function co(t,e={}){await Bi(t,Ui,"Run state",e)}var Ml,Ui,Wl,Vi=K(()=>{"use strict";Ki();Ml=(t,e)=>{let n=t[e];return n==null?null:String(n)};Ui=".comet/run-state.json",Wl=256*1024});import{createHash as zw}from"crypto";import{promises as Qw}from"fs";import me from"path";import{spawnSync as ng}from"child_process";function Gu(t){return t.length>0&&/^[A-Za-z0-9@+=:,./\\_-]+$/.test(t)?t:`"${t.replace(/"/g,'""')}"`}function _o(t){return t.map(e=>Gu(e))}import{promises as xl}from"fs";import N from"path";import{promises as zu}from"fs";async function kt(t){try{return await zu.access(t),!0}catch(e){if(Qu(e))return!1;throw e}}function Qu(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}ye();nn();eo();Z();var rn=class extends Error{code="classic-layout-unavailable";constructor(e="Classic artifact layout is unavailable from .comet/config.yaml"){super(e),this.name="ClassicLayoutUnavailableError"}},El=".comet/config.yaml";function _l(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function Pl(t){await T(t,El,{label:El,expected:"file"})}function Ii(t,e){let n=N.resolve(t),i=e==="docs"?N.join(n,"docs"):n,r=N.join(i,"openspec"),s=N.join(n,"docs","superpowers");return{projectRoot:n,artifactLayout:e,openSpecBase:i,openSpecRoot:r,changesDir:N.join(r,"changes"),archiveDir:N.join(r,"changes","archive"),specsDir:N.join(r,"specs"),superpowersRoot:s,superpowersSpecsDir:N.join(s,"specs"),superpowersPlansDir:N.join(s,"plans"),superpowersReportsDir:N.join(s,"reports")}}async function Gh(t){await Pl(t);let e=await Oi(t,{allowPartialProject:!0,allowMissingNativeFields:!0});if(!e?.config)throw new rn;if(!(e.config.workflows??[e.config.default_workflow]).includes("classic"))throw new rn("Classic artifact layout is unavailable because Classic is not enabled");return e.classic?.artifact_layout??"legacy"}async function zh(t,e){return Ii(t,e??await Gh(t))}async function Qh(t){try{return await xl.lstat(t),!0}catch(e){if(_l(e))return!1;throw e}}async function Xh(t,e){let n=await zh(t,e),i=n.artifactLayout==="legacy"?"docs":"legacy",r=Ii(t,i).openSpecRoot,[s,o]=await Promise.all([T(n.projectRoot,$(n.projectRoot,n.openSpecRoot),{label:"Configured Classic OpenSpec root",expected:"directory"}),Qh(r)]),a=s.exists;return{paths:n,configuredRootExists:a,alternateRoot:r,alternateRootExists:o,dualRoots:a&&o}}async function Zh(t){let e=[t.openSpecRoot,t.changesDir,t.archiveDir,t.specsDir,t.superpowersRoot,t.superpowersSpecsDir,t.superpowersPlansDir,t.superpowersReportsDir];for(let n of e){let i=$(t.projectRoot,n);await T(t.projectRoot,i,{label:`Classic managed physical path ${i}`,expected:"directory"})}}async function ce(t,e){let n=await Xh(t,e);if(await Zh(n.paths),!n.configuredRootExists){let i=$(n.paths.projectRoot,n.paths.openSpecRoot),r=$(n.paths.projectRoot,n.alternateRoot);throw new rn(`Configured Classic OpenSpec root is missing: ${i} (alternate ${r} is ${n.alternateRootExists?"present":"missing"})`)}return n.paths}async function sn(t,e){let n=N.join(N.resolve(t),".comet","classic-root-move.json");if(await kt(n))throw new Error("Classic root move transaction is incomplete; inspect it with comet doctor and recover it explicitly before writing");let i=await ce(t,e);if(!await kt(i.openSpecRoot))throw new Error(`Configured Classic OpenSpec root is missing: ${$(i.projectRoot,i.openSpecRoot)}`);return i}async function be(t){let e=N.resolve(t),n=null;try{(await xl.lstat(e)).isDirectory()||(e=N.dirname(e))}catch(i){if(!_l(i))throw i}for(;;){N.basename(e)==="openspec"&&(n=N.dirname(e));let i=N.join(e,".comet","config.yaml"),r=!1;if(await kt(i))try{await Pl(e);let o=(await Oi(e))?.value;r=!!o&&typeof o=="object"&&!Array.isArray(o)&&(o.schema==="comet.project.v1"||o.default_workflow!==void 0||o.native!==void 0)}catch{}if(r||await kt(N.join(e,".git")))return e;let s=N.dirname(e);if(s===e)return n??N.resolve(t);e=s}}function $(t,e){return N.relative(N.resolve(t),e).replaceAll("\\","/")}var Rl=nt(ze(),1);Z();import eg from"path";var tg=1024*1024;async function Ol(t,e){let n=e??await ce(t),i=eg.join(n.openSpecRoot,"config.yaml"),r=$(n.projectRoot,i),s;try{s=(await F(n.projectRoot,r,tg,{label:"Classic OpenSpec project config",bigint:!0})).bytes.toString("utf8")}catch(l){throw l.code==="ENOENT"?new Error(`Classic OpenSpec root is unhealthy: ${r} is missing; rerun OpenSpec initialization for the configured Classic layout`,{cause:l}):new Error(`Classic OpenSpec root is unhealthy: ${l instanceof Error?l.message:String(l)}`,{cause:l})}let o=(0,Rl.parseDocument)(s,{uniqueKeys:!0});if(o.errors.length>0)throw new Error(`Classic OpenSpec root is unhealthy: ${r} is invalid YAML (${o.errors[0].message})`);let a=o.toJS();if(!a||typeof a!="object"||Array.isArray(a))throw new Error(`Classic OpenSpec root is unhealthy: ${r} must contain a mapping`);let c=a.schema;if(typeof c!="string"||c.trim()==="")throw new Error(`Classic OpenSpec root is unhealthy: ${r} must declare a non-empty schema`);return{layout:n,configPath:r,schema:c}}function ig(t){return t[0]==="--"?t.slice(1):[...t]}async function Al(t,e=process.cwd()){let n=ig(t);if(n.length===0)return{exitCode:64,stderr:"Usage: comet classic openspec -- "};let i=await be(e),r=await sn(i);await Ol(i,r);let s=process.env.COMET_OPENSPEC||"openspec",o=process.platform==="win32",a=ng(s,o?_o(n):n,{cwd:r.openSpecBase,encoding:"utf8",shell:o,windowsHide:!0});if(a.error){let c=a.error.code;return{exitCode:c==="ENOENT"?127:70,stdout:a.stdout||void 0,stderr:a.stderr||(c==="ENOENT"?`OpenSpec CLI not found: ${s}`:a.error.message)}}return{exitCode:a.status??1,stdout:a.stdout||void 0,stderr:a.stderr||void 0}}import{promises as og}from"fs";import ln from"path";Xe();ye();Z();import on from"path";var rg=2*1024*1024;function $i(t,e,n){let i=on.resolve(t),r=on.isAbsolute(e)?on.resolve(e):on.resolve(i,e),s=on.relative(i,r).replaceAll("\\","/");return{root:i,relative:Ie(s,n),target:r}}async function Fe(t,e,n){let i=$i(t,e,n.label);return T(i.root,i.relative,n)}async function an(t,e,n){return(await Fe(t,e,{label:n.label,expected:n.expected??"any"})).exists}async function cn(t,e,n){return(await sg(t,e,n)).toString("utf8")}async function sg(t,e,n){let i=$i(t,e,n.label);return(await F(i.root,i.relative,n.maxBytes??rg,{label:n.label,hooks:n.hooks})).bytes}async function to(t,e,n){let i=$i(t,e,n);return Gs(i.root,i.relative,{label:n})}async function Nl(t,e,n,i){let r=$i(t,e,i.label);await T(r.root,r.relative,{label:i.label,expected:"file"}),await ae(r.target,n,{containedRoot:r.root,beforeTemporaryOpen:i.beforeTemporaryOpen,beforeCommit:i.beforeCommit,exclusive:i.exclusive})}function no(t){return t?/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t)?t.includes("..")?"Change name cannot contain '..' (path traversal not allowed)":null:`Invalid change name: '${t}' +Valid format: lowercase kebab-case (a-z, 0-9, single hyphens)`:"Change name cannot be empty"}function un(t){let e=no(t);if(e)throw new Error(e)}function ag(t,e){return{label:$(t,e),directory:e}}async function qi(t,e,n){let i=ag(t,e);if(!(await Fe(t,e,{label:n,expected:"directory"})).exists)return{change:i,exists:!1,stateExists:!1};let s=await Fe(t,ln.join(e,".comet.yaml"),{label:`${n} state`,expected:"file"});return{change:i,exists:!0,stateExists:s.exists}}function Tl(t,e){let n=e.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&");return new RegExp(`^\\d{4}-\\d{2}-\\d{2}-${n}$`,"u").test(t)}async function cg(t,e,n,i={}){if(!i.skipExactCompatibility){let o=await qi(t,ln.join(e,n),`Classic archived change ${n}`);if(o.exists)return o.change}if(!(await Fe(t,e,{label:"Classic archive directory",expected:"directory"})).exists)return null;let s=[];for(let o of await og.readdir(e,{withFileTypes:!0})){if(!Tl(o.name,n))continue;let a=await qi(t,ln.join(e,o.name),`Classic archived change ${o.name}`);a.exists&&a.stateExists&&s.push(a.change)}return s.sort((o,a)=>a.directory.localeCompare(o.directory))[0]??null}async function io(t,e=process.cwd()){un(t);let n=await ce(e),i=await qi(n.projectRoot,ln.join(n.changesDir,t),`Classic active change ${t}`);return{...i.change,exists:i.exists,stateExists:i.stateExists}}async function Li(t,e=process.cwd(),n={}){un(t);let i=await ce(e);if(n.preferredArchiveName!==void 0){let r=n.preferredArchiveName;if(r!==t&&!Tl(r,t))throw new Error(`Classic preferred archive name '${r}' does not belong to change '${t}'`);let s=await qi(i.projectRoot,ln.join(i.archiveDir,r),`Classic preferred archived change ${r}`);return s.exists&&s.stateExists?s.change:null}return cg(i.projectRoot,i.archiveDir,t,n)}import{promises as Su}from"fs";import Q from"path";import{fileURLToPath as Cu}from"url";import{promises as ug}from"fs";import ke from"path";Z();ye();import fn from"path";function lg(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function jl(t,e,n,i){let r=Ie(n,"Classic handoff artifact pointer");if((await T(t,r,{label:"Classic handoff artifact",expected:"file"})).exists)return null;let o=await ce(t),a=`${$(t,o.changesDir)}/`,l=(o.artifactLayout==="docs"?[a,"openspec/changes/"]:[a]).find(y=>r.startsWith(y));if(!l)return null;let f=r.slice(l.length).split("/");if(f.length<4||f[1]!==".comet"||f.slice(2).some(y=>y.length===0))return null;let u=f[0];un(u);let d=f.slice(2),h=fn.resolve(e);if(fn.dirname(h)!==fn.resolve(o.archiveDir))return null;let g=fn.basename(h),p=/^\d{4}-\d{2}-\d{2}-(.+)$/u.exec(g);if(g!==u&&p?.[1]!==u)return null;await T(t,$(t,h),{label:"Classic archived change directory",expected:"directory"});let m=fn.join(h,".comet",...d),w=$(t,m);try{return await F(t,w,i,{label:"Historical Classic archived handoff artifact"}),w}catch(y){if(lg(y))return null;throw y}}Z();var Il=2*1024*1024;function dn(t,e){return ke.relative(t,e).split(ke.sep).join("/")}async function pn(t,e,n,i,r){if(!n)return{code:e,satisfied:!1};let s=n.replaceAll("\\","/");if(r)return{code:e,satisfied:!1,source:s,detail:`Classic layout is unsafe or unavailable: ${r instanceof Error?r.message:String(r)}`};try{if(i){let a=i.artifactLayout==="legacy"?"docs":"legacy",c=$(t,Ii(t,a).openSpecRoot);if((s===c||s.startsWith(`${c}/`))&&(await T(t,s,{label:`${e} artifact`,expected:"file"})).exists)return{code:e,satisfied:!1,source:s,detail:"standalone OpenSpec root is not a Comet artifact root"}}let o=await Ri(t,s,{label:`${e} artifact`});return{code:e,satisfied:o,source:s,...o?{resolvedSource:s}:{}}}catch(o){return{code:e,satisfied:!1,source:s,detail:`unsafe artifact pointer outside the project or through a special path: ${o instanceof Error?o.message:String(o)}`}}}async function fg(t,e,n,i){try{i??=await ce(t)}catch(s){return{code:"design.handoff",satisfied:!1,...n?{source:n.replaceAll("\\","/")}:{},detail:`Classic layout is unsafe or unavailable for handoff evidence: ${s instanceof Error?s.message:String(s)}`}}let r=await pn(t,"design.handoff",n,i);if(!n||r.satisfied||r.detail)return r;try{let s=await jl(t,e,n,Il);return s?{...r,satisfied:!0,resolvedSource:s,detail:`resolved historical legacy pointer from archived change: ${s}`}:r}catch(s){return{...r,satisfied:!1,detail:`unsafe archived handoff fallback: ${s instanceof Error?s.message:String(s)}`}}}async function Di(t,e,n){return pn(t,e,dn(t,n))}async function dg(t,e){let n=ke.join(e,"specs"),i;try{let o=dn(t,n);if(!(await T(t,o,{label:"OpenSpec delta-spec directory",expected:"directory"})).exists)return{code:"openspec.delta-spec",satisfied:!1};i=await ug.readdir(n)}catch(o){return o.code==="ENOENT"?{code:"openspec.delta-spec",satisfied:!1}:{code:"openspec.delta-spec",satisfied:!1,detail:`unsafe delta-spec path: ${o instanceof Error?o.message:String(o)}`}}let r=i.map(o=>ke.join(n,o,"spec.md")),s=(await Promise.all(r.map(async o=>{try{return await Ri(t,dn(t,o),{label:"OpenSpec delta spec"})?o:null}catch{return null}}))).filter(o=>o!==null);return{code:"openspec.delta-spec",satisfied:s.length>0,source:s[0]?dn(t,s[0]):void 0,detail:`${s.length} delta spec${s.length===1?"":"s"}`}}async function pg(t,e){let n,i=dn(t,e);try{n=(await F(t,i,Il,{label:"Classic tasks artifact"})).bytes.toString("utf8")}catch(o){return o.code==="ENOENT"?{code:"build.tasks-complete",satisfied:!1}:{code:"build.tasks-complete",satisfied:!1,source:i,detail:`unsafe tasks artifact: ${o instanceof Error?o.message:String(o)}`}}let r=[...n.matchAll(/^\s*[-*]\s+\[([ xX])\]\s+/gmu)],s=r.filter(o=>o[1].toLowerCase()==="x").length;return{code:"build.tasks-complete",satisfied:r.length>0&&s===r.length,source:i,detail:`${s} of ${r.length} tasks complete`}}function mn(t,e){return t.some(n=>n.code===e&&n.satisfied)}async function gt(t,e){let n=await be(t),i=e.classic,r=ke.join(t,"proposal.md"),s=ke.join(t,"design.md"),o=ke.join(t,"tasks.md"),a=e.run?ke.resolve(t,e.run.checkpointRef):ke.join(t,".comet","checkpoint.json"),c,l;try{c=await ce(n)}catch(d){l=d}let f=await Promise.all([Di(n,"openspec.proposal",r),Di(n,"openspec.design",s),Di(n,"openspec.tasks",o),dg(n,t),pn(n,"design.document",i?.designDoc??null,c,l),pn(n,"build.plan",i?.plan??null,c,l),pg(n,o),pn(n,"verification.report",i?.verificationReport??null,c,l),fg(n,t,i?.handoffContext??null,c),Di(n,"run.checkpoint",a)]),u=f.find(d=>d.code==="design.handoff");return u&&!i?.handoffHash&&(u.satisfied=!1,u.detail="handoff hash is missing"),f.push({code:"archive.confirmed",satisfied:i?.archiveConfirmation==="confirmed"}),f}import{createHash as xw,randomUUID as _w}from"crypto";import{promises as wo}from"fs";import Ce from"path";function mg(t){return t.classicProfile??t.workflow}function hg(t){return!t.buildMode||!t.tddMode||!t.isolation||!t.verifyMode?!1:t.buildMode==="subagent-driven-development"?t.subagentDispatch==="confirmed":t.buildMode==="direct"?t.directOverride===!0:!0}function gg(t){return t.buildMode==="direct"&&t.tddMode==="direct"&&t.isolation!==null&&t.verifyMode==="light"}function wg(t,e,n){if(e.verifyResult==="fail")return t==="full"?"full.build.fix":`${t}.build.execute`;if(t==="full"){if(!mn(n,"build.plan"))return"full.build.plan";if(e.buildPause==="plan-ready")return"full.build.plan-ready";if(!hg(e))return"full.build.configure"}else if(!gg(e))throw new Error(`${t} build configuration is incomplete`);return mn(n,"build.tasks-complete")?`${t}.build.complete`:`${t}.build.execute`}function yg(t,e,n){return e.verifyResult!=="pass"||!mn(n,"verification.report")?`${t}.verify.run`:`${t}.verify.branch`}function vg(t,e){if(e.verifyResult!=="pass")throw new Error("archive requires verify_result=pass");return e.archiveConfirmation==="confirmed"?`${t}.archive.execute`:`${t}.archive.confirm`}function Fi(t,e){let n=mg(t);if(t.archived&&t.phase!=="archive")throw new Error("archived=true requires phase=archive");if(t.archived)return"completed";if(n!=="full"&&t.phase==="design")throw new Error(`${n} workflow cannot enter design`);switch(t.phase){case"open":return`${n}.open`;case"design":return mn(e,"design.handoff")?"full.design.document":"full.design.handoff";case"build":return wg(n,t,e);case"verify":return yg(n,t,e);case"archive":return vg(n,t)}}var Qi=nt(ze(),1);Xe();Z();import zi from"path";Vi();var Kl=["full","hotfix","tweak"],Ze=1,jg=["open","design","build","verify","archive"],Ig=["en","zh-CN"],$g=["off","beta"],qg=["subagent-driven-development","executing-plans","direct"],Lg=["plan-ready"],Dg=["confirmed"],Fg=["tdd","direct"],Mg=["off","standard","thorough"],Wg=["current","branch","worktree"],Bg=["light","full"],Kg=["pending","pass","fail"],Yg=["pending","handled"],Ug=["pending","confirmed"],Gi=["workflow","language","phase","context_compression","build_mode","build_pause","subagent_dispatch","tdd_mode","review_mode","isolation","bound_branch","verify_mode","auto_transition","base_ref","design_doc","plan","verify_result","verify_failures","verification_report","branch_status","created_at","verified_at","archive_confirmation","archived","direct_override","handoff_context","handoff_hash","classic_profile","classic_migration"],Jg=["run_id"],Vg=new Set([...Gi,...Jg]),Hg=["workflow","phase","design_doc","plan","build_mode","isolation","verify_mode","verify_result","verified_at","archived"];function Yl(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function wt(t,e){let n=t[e];if(n==null||n==="")return null;if(typeof n!="string")throw new Error(`Invalid Classic state: ${e} must be a string or null`);return n}function Y(t,e,n,i=!0){let r=t[e];if(r==null||r===""){if(i)return null;throw new Error(`Invalid Classic state: ${e} is required`)}if(typeof r!="string"||!n.includes(r))throw new Error(`Invalid Classic state: ${e} must be one of ${n.join(", ")}${i?" or null":""}`);return r}function lo(t,e,n=!0){let i=t[e];if(i==null||i===""){if(n)return null;throw new Error(`Invalid Classic state: ${e} is required`)}if(typeof i!="boolean")throw new Error(`Invalid Classic state: ${e} must be true or false`);return i}function Gg(t,e,n=0){let i=t[e];if(i==null||i==="")return n;if(typeof i!="number"||!Number.isInteger(i)||i<0)throw new Error(`Invalid Classic state: ${e} must be a non-negative integer`);return i}function Hi(t,e){let n=wt(t,e);if(n===null)return null;if(/^(?:[A-Za-z]:|[\\/]|~)/u.test(n)||n.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Classic state: ${e} must be a relative repository path`);return n}function zg(t,e){let n=wt(t,e);if(n!==null&&!/^[a-f0-9]{64}$/u.test(n))throw new Error(`Invalid Classic state: ${e} must be a sha256 hex digest`);return n}function Qg(t){let e=t.classic_migration;if(e==null||e==="")return null;if(e!==Ze)throw new Error(`Invalid Classic state: classic_migration must be ${Ze}`);return e}function Xg(t){if(!Gi.some(n=>Yl(t,n)))return null;for(let n of Hg)if(!Yl(t,n))return null;return{workflow:Y(t,"workflow",Kl,!1),language:Y(t,"language",Ig),phase:Y(t,"phase",jg,!1),contextCompression:Y(t,"context_compression",$g),buildMode:Y(t,"build_mode",qg),buildPause:Y(t,"build_pause",Lg),subagentDispatch:Y(t,"subagent_dispatch",Dg),tddMode:Y(t,"tdd_mode",Fg),reviewMode:Y(t,"review_mode",Mg),isolation:Y(t,"isolation",Wg),boundBranch:wt(t,"bound_branch"),verifyMode:Y(t,"verify_mode",Bg),autoTransition:lo(t,"auto_transition"),baseRef:wt(t,"base_ref"),designDoc:Hi(t,"design_doc"),plan:Hi(t,"plan"),verifyResult:Y(t,"verify_result",Kg,!1),verifyFailures:Gg(t,"verify_failures"),verificationReport:Hi(t,"verification_report"),branchStatus:Y(t,"branch_status",Yg),createdAt:wt(t,"created_at"),verifiedAt:wt(t,"verified_at"),archiveConfirmation:Y(t,"archive_confirmation",Ug),archived:lo(t,"archived",!1),directOverride:lo(t,"direct_override"),handoffContext:Hi(t,"handoff_context"),handoffHash:zg(t,"handoff_hash"),classicProfile:Y(t,"classic_profile",Kl),classicMigration:Qg(t)}}function uo(t,e){let n=e??null;if(n===null&&e===void 0&&t.run_id&&t.skill)try{n=Yi(t)}catch(i){let r=i instanceof Error?i.message:String(i);throw new Error(r.replace(/^Invalid Run state:/u,"Invalid Classic state:"),{cause:i})}return{classic:Xg(t),run:n,unknownKeys:Object.keys(t).filter(i=>!Vg.has(i))}}function Ul(t){return{workflow:t.workflow,language:t.language,phase:t.phase,context_compression:t.contextCompression,build_mode:t.buildMode,build_pause:t.buildPause,subagent_dispatch:t.subagentDispatch,tdd_mode:t.tddMode,review_mode:t.reviewMode,isolation:t.isolation,bound_branch:t.boundBranch,verify_mode:t.verifyMode,auto_transition:t.autoTransition,base_ref:t.baseRef,design_doc:t.designDoc,plan:t.plan,verify_result:t.verifyResult,verify_failures:t.verifyFailures,verification_report:t.verificationReport,branch_status:t.branchStatus,created_at:t.createdAt,verified_at:t.verifiedAt,archive_confirmation:t.archiveConfirmation,archived:t.archived,direct_override:t.directOverride,handoff_context:t.handoffContext,handoff_hash:t.handoffHash,classic_profile:t.classicProfile,classic_migration:t.classicMigration}}Vi();var Zg=2*1024*1024;function wn(t){let e=t.toJS();if(e===null)return{};if(typeof e!="object"||Array.isArray(e))throw new Error("Invalid Classic state document: root must be a mapping");return e}function Jl(t,e,n){t.get(e)!==n&&t.set(e,n)}function ew(t,e){if(e.classic)for(let[n,i]of Object.entries(Ul(e.classic)))Jl(t,n,i);else for(let n of Gi)t.delete(n);oo(t.toJS(),e.run),e.run?Jl(t,"run_id",e.run.runId):t.delete("run_id")}function tw(t){let e=["skill","skill_version","skill_hash","orchestration","current_step","iteration","pending","pending_ref","trajectory_ref","context_ref","artifacts_ref","checkpoint_ref","run_status","run_retries"];for(let n of e)t.delete(n)}function nw(t){let e=!1;for(let n of["build_command","verify_command"])t.has(n)&&(t.delete(n),e=!0);return e}async function Vl(t){let e;try{e=(await F(zi.dirname(t),zi.basename(t),Zg,{label:"Classic state document"})).bytes.toString("utf8")}catch(i){if(i.code!=="ENOENT")throw i;return new Qi.Document({})}let n=(0,Qi.parseDocument)(e);if(n.errors.length>0)throw new Error(`Invalid Classic state document: ${n.errors[0].message}`);return wn(n),n}async function de(t,e={}){let n=e.migrate!==!1,i=zi.join(t,".comet.yaml"),r=await Vl(i),s=wn(r),o=nw(r);o&&(s=wn(r));let a=await ao(t);if(!a&&s.run_id&&s.skill){let{runStateFromDocument:c}=await Promise.resolve().then(()=>(Vi(),Bl));a=c(s),a&&n&&(await Ji(t,a),tw(r),o=!0)}return o&&n&&await ae(i,r.toString(),{containedRoot:t}),uo(wn(r),a)}async function et(t,e,n={}){let i=zi.join(t,".comet.yaml"),r=await Vl(i);ew(r,{...e,unknownKeys:e.unknownKeys??[]}),uo(wn(r),e.run??null),await ae(i,r.toString(),{containedRoot:t,beforeCommit:n.beforeCommit}),e.run?await Ji(t,e.run):await co(t)}function Hl(t,e,n){return{runId:e,skill:t.definition.metadata.name,skillVersion:t.definition.metadata.version,skillHash:n,orchestration:t.definition.orchestration.mode,currentStep:t.definition.orchestration.entry??null,iteration:0,pending:null,pendingRef:".comet/pending-action.json",trajectoryRef:".comet/trajectory.jsonl",contextRef:".comet/context.md",artifactsRef:".comet/artifacts.json",checkpointRef:".comet/checkpoint.json",status:"running",retries:{}}}Ki();import Xi from"path";var Se={trajectory:8*1024*1024,artifacts:1024*1024,context:1024*1024,pendingAction:256*1024,checkpoint:256*1024};function pe(t,e){if(Xi.isAbsolute(e))throw new Error("Run path must stay inside the change directory");let n=Xi.resolve(t),i=Xi.resolve(n,e);if(i!==n&&!i.startsWith(n+Xi.sep))throw new Error("Run path must stay inside the change directory")}async function yt(t,e,n,i={}){pe(t,e),await Wi(t,e,`${JSON.stringify(n)} +`,Se.trajectory,"Run trajectory",i)}async function yn(t,e,n={}){pe(t,e);let i=await Me(t,e,Se.trajectory,"Run trajectory",n);return i===null?[]:i.split(/\r?\n/).map((r,s)=>({line:r,number:s+1})).filter(({line:r})=>r.length>0).map(({line:r,number:s})=>{try{return JSON.parse(r)}catch(o){throw new Error(`Invalid Trajectory event at line ${s}`,{cause:o})}})}async function fo(t,e,n={}){pe(t,e);let i=await Me(t,e,Se.artifacts,"Run artifacts",n);return i===null?{}:JSON.parse(i)}async function Zi(t,e,n,i={}){pe(t,e),await We(t,e,JSON.stringify(n,null,2)+` +`,Se.artifacts,"Run artifacts",i)}async function Gl(t,e,n,i={}){pe(t,e),await We(t,e,n,Se.context,"Run context",i)}async function zl(t,e,n={}){return pe(t,e),Me(t,e,Se.context,"Run context",n)}async function Ql(t,e,n,i={}){pe(t,e),await We(t,e,JSON.stringify(n,null,2)+` +`,Se.pendingAction,"Run pending action",i)}async function Xl(t,e,n={}){pe(t,e);let i=await Me(t,e,Se.pendingAction,"Run pending action",n);return i===null?null:JSON.parse(i)}async function Zl(t,e,n={}){pe(t,e),await Bi(t,e,"Run pending action",n)}async function er(t,e,n,i={}){pe(t,e),await We(t,e,JSON.stringify(n,null,2)+` +`,Se.checkpoint,"Run checkpoint",i)}import{createHash as pu,randomUUID as bw}from"crypto";import{promises as D}from"fs";import q from"path";var nu=nt(ze(),1);import{promises as po}from"fs";import ee from"path";var iw=["invoke_skill","call_tool","handoff","ask_user","checkpoint"],rw=["deterministic","adaptive"],sw=["function","mcp","script","agent"],ow=["none","read","write","external"],aw=["progress","step","completion"],cw=["artifact_exists","state_equals"];function tt(t,e,n){return new Error(`${t}: ${e} ${n}`)}function H(t,e,n="document"){if(t===null||typeof t!="object"||Array.isArray(t))throw tt(e,n,"must be an object")}function Be(t,e,n){if(!Array.isArray(t))throw tt(e,n,"must be an array")}function U(t,e,n){if(typeof t!="string")throw tt(e,n,"must be a string")}function le(t,e,n,i){e in t&&U(t[e],n,`${i}.${e}`)}function iu(t,e,n,i){if(e in t&&typeof t[e]!="boolean")throw tt(n,`${i}.${e}`,"must be a boolean")}function Ke(t,e,n,i){if(typeof t!="string"||!e.includes(t))throw tt(n,i,`must be one of ${e.join(", ")}`)}function tr(t,e,n){Be(t,e,n),t.forEach((i,r)=>{U(i,e,`${n}[${r}]`)})}function eu(t,e,n){H(t,e,n),U(t.name,e,`${n}.name`),U(t.description,e,`${n}.description`),iu(t,"required",e,n)}function lw(t,e,n){H(t,e,n),U(t.id,e,`${n}.id`),le(t,"source",e,n),le(t,"version",e,n)}function uw(t,e,n){H(t,e,n),U(t.id,e,`${n}.id`),U(t.role,e,`${n}.role`),le(t,"instructions",e,n)}function fw(t,e,n){H(t,e,n),U(t.id,e,`${n}.id`),Ke(t.kind,sw,e,`${n}.kind`),U(t.source,e,`${n}.source`),Ke(t.sideEffect,ow,e,`${n}.sideEffect`),iu(t,"requiresConfirmation",e,n)}function dw(t,e,n){H(t,e,n),Ke(t.type,iw,e,`${n}.type`),le(t,"ref",e,n),le(t,"prompt",e,n),le(t,"question",e,n),"options"in t&&tr(t.options,e,`${n}.options`)}function pw(t,e,n){H(t,e,n),U(t.id,e,`${n}.id`),dw(t.action,e,`${n}.action`),le(t,"next",e,n),"completionEvals"in t&&tr(t.completionEvals,e,`${n}.completionEvals`)}function mw(t,e){let n="goal";H(t,e,n),U(t.statement,e,`${n}.statement`),Be(t.inputs,e,`${n}.inputs`),t.inputs.forEach((i,r)=>{eu(i,e,`${n}.inputs[${r}]`)}),Be(t.outputs,e,`${n}.outputs`),t.outputs.forEach((i,r)=>{eu(i,e,`${n}.outputs[${r}]`)}),tr(t.success,e,`${n}.success`)}function hw(t,e){let n="orchestration";H(t,e,n),Ke(t.mode,rw,e,`${n}.mode`),le(t,"entry",e,n),"steps"in t&&(Be(t.steps,e,`${n}.steps`),t.steps.forEach((i,r)=>{pw(i,e,`${n}.steps[${r}]`)}))}function ru(t,e){return H(t,e),Ke(t.apiVersion,["comet/v1alpha1"],e,"apiVersion"),Ke(t.kind,["Skill"],e,"kind"),H(t.metadata,e,"metadata"),U(t.metadata.name,e,"metadata.name"),U(t.metadata.version,e,"metadata.version"),U(t.metadata.description,e,"metadata.description"),mw(t.goal,e),hw(t.orchestration,e),Be(t.skills,e,"skills"),t.skills.forEach((n,i)=>{lw(n,e,`skills[${i}]`)}),Be(t.agents,e,"agents"),t.agents.forEach((n,i)=>{uw(n,e,`agents[${i}]`)}),Be(t.tools,e,"tools"),t.tools.forEach((n,i)=>{fw(n,e,`tools[${i}]`)}),t}function su(t,e){H(t,e);for(let n of["allowedSkills","allowedAgents","allowedTools","confirmationRequiredFor"])n in t&&tr(t[n],e,n);for(let n of["maxIterations","maxRetriesPerAction"])if(n in t&&(typeof t[n]!="number"||!Number.isFinite(t[n])))throw tt(e,n,"must be a finite number");return t}function gw(t,e){return H(t,e),"runtime"in t&&ou(t.runtime,e,"runtime"),t}function ou(t,e,n){return Be(t,e,n),t.forEach((i,r)=>{let s=`${n}[${r}]`;H(i,e,s),U(i.id,e,`${s}.id`),Ke(i.scope,aw,e,`${s}.scope`),Ke(i.type,cw,e,`${s}.type`),le(i,"artifact",e,s),le(i,"field",e,s),le(i,"equals",e,s)}),t}async function mo(t){let e=await po.readFile(t,"utf8");try{return(0,nu.parse)(e)}catch(n){let i=n instanceof Error?n.message:String(n);throw tt(t,"document",i)}}async function ww(t){try{return await mo(t)}catch(e){if(e.code==="ENOENT")return null;throw e}}async function tu(t){try{return await po.access(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function yw(t){let e=ee.join(t,"checks.yaml"),n=ee.join(t,"evals.yaml"),[i,r]=await Promise.all([tu(e),tu(n)]);if(r)throw new Error(`${n}: evals.yaml is no longer supported; use checks.yaml`);return i?{document:gw(await mo(e),e)}:{document:null}}async function au(t){let e=ee.resolve(t.root),n=ee.resolve(t.controlRoot);t.requireSkillMarkdown&&await po.access(ee.join(e,"SKILL.md"));let i=ee.join(n,"skill.yaml"),r=ee.join(n,"guardrails.yaml"),s=ru(await mo(i),i),o=await ww(r),a=o===null?null:su(o,r),c=await yw(n),l={allowedSkills:s.skills.map(f=>f.id),allowedAgents:s.agents.map(f=>f.id),allowedTools:s.tools.map(f=>f.id),maxIterations:50,maxRetriesPerAction:3,confirmationRequiredFor:s.tools.filter(f=>f.requiresConfirmation).map(f=>f.id)};return{root:e,packageKind:t.packageKind==="runtime"?"runtime":void 0,definition:s,guardrails:{...l,...a},evals:c.document?.runtime??[]}}async function cu(t){let e=ee.resolve(t);return au({root:e,controlRoot:ee.join(e,"comet"),packageKind:"skill",requireSkillMarkdown:!0})}async function lu(t){let e=ee.resolve(t);return au({root:e,controlRoot:e,packageKind:"runtime",requireSkillMarkdown:!1})}function uu(t,e,n=ee.join(e,"package.json")){H(t,n);let i=t.packageKind==="runtime"?"runtime":void 0,r=ru(t.definition,n),s=su(t.guardrails,n),o=ou(t.evals,n,"evals"),a={allowedSkills:r.skills.map(c=>c.id),allowedAgents:r.agents.map(c=>c.id),allowedTools:r.tools.map(c=>c.id),maxIterations:50,maxRetriesPerAction:3,confirmationRequiredFor:r.tools.filter(c=>c.requiresConfirmation).map(c=>c.id)};return{root:ee.resolve(e),packageKind:i,definition:r,guardrails:{...a,...s},evals:o}}import fu from"path";function vw(t,e,n,i){t.type==="invoke_skill"&&!e.definition.skills.some(r=>r.id===t.ref)&&n.push(`step ${i} references undeclared skill: ${t.ref??"(missing)"}`),t.type==="call_tool"&&!e.definition.tools.some(r=>r.id===t.ref)&&n.push(`step ${i} references undeclared tool: ${t.ref??"(missing)"}`),t.type==="handoff"&&!e.definition.agents.some(r=>r.id===t.ref)&&n.push(`step ${i} references undeclared agent: ${t.ref??"(missing)"}`),t.type==="ask_user"&&!t.question&&n.push(`step ${i} ask_user action requires question`)}function du(t){let e=[],{definition:n,guardrails:i,evals:r}=t;n.apiVersion!=="comet/v1alpha1"&&e.push("unsupported apiVersion"),n.kind!=="Skill"&&e.push("kind must be Skill"),n.metadata.name||e.push("metadata.name is required"),n.goal.statement||e.push("goal.statement is required"),i.maxIterations<1&&e.push("maxIterations must be at least 1"),i.maxRetriesPerAction<0&&e.push("maxRetriesPerAction must not be negative");let s=n.orchestration.steps??[];if(n.orchestration.mode==="adaptive")(n.orchestration.entry||s.length>0)&&e.push("adaptive orchestration must not define entry or steps");else{let o=new Set;for(let a of s)o.has(a.id)&&e.push(`duplicate step id: ${a.id}`),o.add(a.id),vw(a.action,t,e,a.id);(!n.orchestration.entry||!o.has(n.orchestration.entry))&&e.push(`orchestration.entry references unknown step: ${n.orchestration.entry??"(missing)"}`);for(let a of s){a.next&&!o.has(a.next)&&e.push(`step ${a.id} has unknown next step: ${a.next}`);for(let c of a.completionEvals??[])r.some(l=>l.id===c)||e.push(`step ${a.id} references unknown eval: ${c}`)}}for(let o of n.tools){if(o.kind!=="script")continue;let a=fu.posix.normalize(o.source.replaceAll("\\","/"));(fu.isAbsolute(o.source)||a===".."||a.startsWith("../"))&&e.push(`script tool ${o.id} must reference a relative path inside the Skill package`)}for(let o of i.allowedSkills)n.skills.some(a=>a.id===o)||e.push(`guardrails allow undeclared skill: ${o}`);for(let o of i.allowedAgents)n.agents.some(a=>a.id===o)||e.push(`guardrails allow undeclared agent: ${o}`);for(let o of i.allowedTools)n.tools.some(a=>a.id===o)||e.push(`guardrails allow undeclared tool: ${o}`);return e}function nr(t){return Array.isArray(t)?t.map(nr):t&&typeof t=="object"?Object.fromEntries(Object.entries(t).sort(([e],[n])=>e.localeCompare(n)).map(([e,n])=>[e,nr(n)])):t}function kw(t){return nr({...t.packageKind==="runtime"?{packageKind:"runtime"}:{},definition:t.definition,guardrails:t.guardrails,evals:t.evals})}function Sw(t){return q.posix.normalize(t.replaceAll("\\","/"))}function vt(t,e,n){let i=q.relative(t,e);if(!(i===""||!q.isAbsolute(i)&&!i.startsWith(`..${q.sep}`)))throw new Error(`${n} resolves outside the Skill package`)}async function mu(t,e,n){let i=Sw(e);if(q.posix.isAbsolute(i)||i===".."||i.startsWith("../"))throw new Error(`${n} resolves outside the Skill package`);let r=q.resolve(t,...i.split("/"));vt(t,r,n);let s;try{s=await D.realpath(r)}catch(o){throw o.code==="ENOENT"?new Error(`${n} does not exist: ${e}`,{cause:o}):o}if(vt(t,s,n),!(await D.stat(s)).isFile())throw new Error(`${n} is not a file: ${e}`);return{path:i,content:await D.readFile(s)}}async function Cw(t){let e=await D.realpath(t.root),n=t.packageKind==="runtime"?[]:[await mu(e,"SKILL.md","SKILL.md")];for(let i of t.definition.tools)i.kind==="script"&&n.push(await mu(e,i.source,`Script tool ${i.id}`));return n.sort((i,r)=>i.path.localeCompare(r.path))}function Ew(t,e){let n=e.map(i=>({path:i.path,sha256:pu("sha256").update(i.content).digest("hex")}));return pu("sha256").update(JSON.stringify(nr({package:t,files:n}))).digest("hex")}function wu(t){return JSON.stringify(t,null,2)+` +`}async function yu(t){let e=kw(t),n=await Cw(t);return{document:e,files:n,hash:Ew(e,n)}}async function ir(t){return(await yu(t)).hash}async function hu(t){try{return await D.access(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function gu(t,e){try{if((await D.readFile(q.join(t,"sha256"),"utf8")).trim()!==e.hash)throw new Error("hash mismatch");if(await D.readFile(q.join(t,"package.json"),"utf8")!==wu(e.document))throw new Error("package mismatch");for(let r of e.files)if(!(await D.readFile(q.join(t,...r.path.split("/")))).equals(r.content))throw new Error(`file mismatch: ${r.path}`)}catch(n){throw new Error(`Existing Skill snapshot is invalid: ${e.hash}`,{cause:n})}}async function ho(t,e){let n=await yu(t),i=q.resolve(e,".comet","skill-snapshots"),r=q.join(i,n.hash);if(await D.mkdir(i,{recursive:!0}),await hu(r))return await gu(r,n),{hash:n.hash,snapshotDir:r};let s=q.join(i,`.tmp-${bw()}`);vt(i,s,"Temporary snapshot"),vt(i,r,"Published snapshot");try{await D.mkdir(s);for(let o of n.files){let a=q.join(s,...o.path.split("/"));vt(s,a,`Snapshot file ${o.path}`),await D.mkdir(q.dirname(a),{recursive:!0}),await D.writeFile(a,o.content)}await D.writeFile(q.join(s,"package.json"),wu(n.document)),await D.writeFile(q.join(s,"sha256"),n.hash+` +`),await D.rename(s,r)}catch(o){if(await hu(r)){try{await gu(r,n)}finally{await D.rm(s,{recursive:!0,force:!0})}return{hash:n.hash,snapshotDir:r}}throw await D.rm(s,{recursive:!0,force:!0}),o}return{hash:n.hash,snapshotDir:r}}async function go(t,e){if(!/^[a-f0-9]{64}$/u.test(e))throw new Error(`Invalid Skill snapshot hash: ${e}`);let n=q.resolve(t,".comet","skill-snapshots"),i=q.join(n,e);vt(n,i,"Skill snapshot");try{let r=(await D.readFile(q.join(i,"sha256"),"utf8")).trim();if(r!==e)throw new Error(`stored hash is ${r||"(empty)"}`);let s=q.join(i,"package.json"),o=JSON.parse(await D.readFile(s,"utf8")),a=uu(o,i,s),c=du(a);if(c.length>0)throw new Error(c.map(f=>` - ${f}`).join(` +`));let l=await ir(a);if(l!==e)throw new Error(`calculated hash is ${l}`);return a}catch(r){throw new Error(`Skill snapshot is invalid or missing: ${e}`,{cause:r})}}async function vu(t){try{return await wo.access(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}function bu(t){return xw("sha256").update(t).digest("hex")}function Pw(t){return bu(JSON.stringify(Object.fromEntries(Object.entries(t).sort(([e],[n])=>e.localeCompare(n)))))}function Rw(t){return t.replaceAll(".","_").replaceAll("-","_")}async function Ow(t,e){let n=await be(t),i=Object.fromEntries(e.filter(o=>o.satisfied&&o.source).map(o=>[Rw(o.code),o.source])),r=Ce.join(t,"subagent-progress.md");await vu(r)&&(i.subagent_progress=Ce.relative(n,r).split(Ce.sep).join("/"));let s=e.find(o=>o.code==="design.handoff"&&o.satisfied);return s?.source&&(i.handoff_context=s.source),i}function Aw(t,e,n){return[{sequence:1,timestamp:n,type:"run_started",runId:t.runId,data:{skill:t.skill,skillVersion:t.skillVersion,skillHash:t.skillHash}},{sequence:2,timestamp:n,type:"state_migrated",runId:t.runId,data:{kind:"classic",migrationVersion:Ze,profile:e,source:"pre-migration"}}]}async function Nw(t){await Promise.all(t.map(e=>wo.rm(e,{recursive:!0,force:!0})))}async function ku(t,e){let n=await de(t);if(!n.classic)throw new Error("Classic migration requires a legacy state projection");let i=n.classic,r=i.classicProfile??i.workflow;if(n.run){if(i.classicMigration!==Ze)throw new Error("Classic Run exists without a supported classic_migration marker");if(n.run.skill!==e.skillPackage.definition.metadata.name)throw new Error(`Classic Run skill mismatch: expected ${e.skillPackage.definition.metadata.name}, got ${n.run.skill}`);if(await ir(e.skillPackage)!==n.run.skillHash)return await go(t,n.run.skillHash),{classic:i,run:n.run,evidence:await gt(t,n),migrated:!1,snapshotDir:Ce.join(t,".comet","skill-snapshots",n.run.skillHash)};let d=await ho(e.skillPackage,t);return{classic:i,run:n.run,evidence:await gt(t,n),migrated:!1,snapshotDir:d.snapshotDir}}let s=await gt(t,n),o=Fi(i,s);if(!e.skillPackage.definition.orchestration.steps?.some(u=>u.id===o))throw new Error(`Classic Skill package does not define resolved step: ${o}`);let a=await ir(e.skillPackage),c=Ce.join(t,".comet","skill-snapshots",a),l=await vu(c),f=[];try{let u=await ho(e.skillPackage,t),d=Hl(e.skillPackage,e.runId?.()??_w(),u.hash);d.currentStep=o,o==="completed"&&(d.status="completed");let h={...i,classicProfile:r,classicMigration:Ze},g=await Ow(t,s),p=await be(t),m=s.find(k=>k.code==="design.handoff"&&k.satisfied),w=null;m?.source&&(w=await cn(p,m.resolvedSource??m.source,{label:"Classic migration handoff context",hooks:e.handoffReadHooks}),await Gl(t,d.contextRef,w),f.push(Ce.resolve(t,d.contextRef))),await Zi(t,d.artifactsRef,g),f.push(Ce.resolve(t,d.artifactsRef));let y=(e.now?.()??new Date).toISOString(),S={runId:d.runId,stateVersion:1,trajectoryOffset:2,contextHash:w===null?null:bu(w),artifactsHash:Pw(g),createdAt:y};await er(t,d.checkpointRef,S),f.push(Ce.resolve(t,d.checkpointRef)),f.push(Ce.resolve(t,d.trajectoryRef));for(let k of Aw(d,r,y))await yt(t,d.trajectoryRef,k);return await et(t,{classic:h,run:d,unknownKeys:n.unknownKeys}),{classic:h,run:d,evidence:s,migrated:!0,snapshotDir:u.snapshotDir}}catch(u){throw await Nw(f),l||await wo.rm(c,{recursive:!0,force:!0}),u}}async function Tw(t){try{return(await Su.stat(t)).isDirectory()}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function rr(t){try{return(await Su.stat(t)).isFile()}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function jw(t){return await Tw(t)?await rr(Q.join(t,"skill.yaml"))?!0:await rr(Q.join(t,"SKILL.md"))&&await rr(Q.join(t,"comet","skill.yaml")):!1}function Iw(t){return{root:t,packageKind:"runtime",definition:{apiVersion:"comet/v1alpha1",kind:"Skill",metadata:{name:"comet-classic",version:"1",description:"Internal compatibility orchestration for classic Comet full, hotfix, and tweak workflows"},goal:{statement:"Advance or restore a classic Comet Run without changing the user command surface",inputs:[{name:"classic-state",description:"Validated ClassicState consistent with the Run projection",required:!0},{name:"evidence",description:"Structured evidence produced by the Classic Evidence collector",required:!0}],outputs:[{name:"run-state",description:"Atomically synchronized Classic and Run state",required:!0}],success:["Legacy fields and Run fields remain consistent","Every step invokes only a declared public Comet Skill","The completed state passes its completion eval"]},orchestration:{mode:"deterministic",entry:"full.open",steps:[{id:"full.open",action:{type:"invoke_skill",ref:"comet-open"},next:"full.design.handoff"},{id:"full.design.handoff",action:{type:"invoke_skill",ref:"comet-design"},next:"full.design.document"},{id:"full.design.document",action:{type:"invoke_skill",ref:"comet-design"},next:"full.build.plan"},{id:"full.build.plan",action:{type:"invoke_skill",ref:"comet-build"},next:"full.build.plan-ready"},{id:"full.build.plan-ready",action:{type:"invoke_skill",ref:"comet-build"},next:"full.build.configure"},{id:"full.build.configure",action:{type:"invoke_skill",ref:"comet-build"},next:"full.build.execute"},{id:"full.build.execute",action:{type:"invoke_skill",ref:"comet-build"},next:"full.build.complete"},{id:"full.build.complete",action:{type:"invoke_skill",ref:"comet-build"},next:"full.verify.run"},{id:"full.build.fix",action:{type:"invoke_skill",ref:"comet-build"},next:"full.build.execute"},{id:"full.verify.run",action:{type:"invoke_skill",ref:"comet-verify"},next:"full.verify.branch"},{id:"full.verify.branch",action:{type:"invoke_skill",ref:"comet-verify"},next:"full.archive.confirm"},{id:"full.archive.confirm",action:{type:"invoke_skill",ref:"comet-archive"},next:"full.archive.execute"},{id:"full.archive.execute",action:{type:"invoke_skill",ref:"comet-archive"},next:"completed"},{id:"hotfix.open",action:{type:"invoke_skill",ref:"comet-hotfix"},next:"hotfix.build.execute"},{id:"hotfix.build.execute",action:{type:"invoke_skill",ref:"comet-build"},next:"hotfix.build.complete"},{id:"hotfix.build.complete",action:{type:"invoke_skill",ref:"comet-build"},next:"hotfix.verify.run"},{id:"hotfix.verify.run",action:{type:"invoke_skill",ref:"comet-verify"},next:"hotfix.verify.branch"},{id:"hotfix.verify.branch",action:{type:"invoke_skill",ref:"comet-verify"},next:"hotfix.archive.confirm"},{id:"hotfix.archive.confirm",action:{type:"invoke_skill",ref:"comet-archive"},next:"hotfix.archive.execute"},{id:"hotfix.archive.execute",action:{type:"invoke_skill",ref:"comet-archive"},next:"completed"},{id:"tweak.open",action:{type:"invoke_skill",ref:"comet-tweak"},next:"tweak.build.execute"},{id:"tweak.build.execute",action:{type:"invoke_skill",ref:"comet-build"},next:"tweak.build.complete"},{id:"tweak.build.complete",action:{type:"invoke_skill",ref:"comet-build"},next:"tweak.verify.run"},{id:"tweak.verify.run",action:{type:"invoke_skill",ref:"comet-verify"},next:"tweak.verify.branch"},{id:"tweak.verify.branch",action:{type:"invoke_skill",ref:"comet-verify"},next:"tweak.archive.confirm"},{id:"tweak.archive.confirm",action:{type:"invoke_skill",ref:"comet-archive"},next:"tweak.archive.execute"},{id:"tweak.archive.execute",action:{type:"invoke_skill",ref:"comet-archive"},next:"completed"},{id:"completed",action:{type:"checkpoint"},completionEvals:["classic-completed"]}]},skills:[{id:"comet-open"},{id:"comet-design"},{id:"comet-build"},{id:"comet-verify"},{id:"comet-archive"},{id:"comet-hotfix"},{id:"comet-tweak"}],agents:[],tools:[]},guardrails:{allowedSkills:["comet-open","comet-design","comet-build","comet-verify","comet-archive","comet-hotfix","comet-tweak"],allowedAgents:[],allowedTools:[],maxIterations:500,maxRetriesPerAction:3,confirmationRequiredFor:[]},evals:[{id:"classic-completed",scope:"completion",type:"state_equals",field:"status",equals:"completed"}]}}async function $w(){let t=Q.dirname(Cu(import.meta.url)),e=[process.env.COMET_RUNTIME_CLASSIC_ROOT,Q.resolve(t,"..","runtime","classic"),Q.resolve(t,"..","..","comet","runtime","classic"),Q.resolve(t,"..","..","assets","skills","comet","runtime","classic"),Q.resolve("assets","skills","comet","runtime","classic"),process.env.COMET_CLASSIC_SKILL_ROOT,Q.resolve(t,"..","..","comet-classic"),Q.resolve(t,"..","..","assets","skills","comet-classic"),Q.resolve("assets","skills","comet-classic")].filter(n=>!!n);for(let n of e)if(await jw(n))return n;return null}async function qw(t){return await rr(Q.join(t,"skill.yaml"))?lu(t):cu(t)}async function Eu(t){let e=await $w();return ku(t,{skillPackage:e?await qw(e):Iw(Q.dirname(Cu(import.meta.url)))})}async function xu(t,e,n,i){let r=await de(t);if(!r.classic||!r.run)throw new Error("Classic transition requires synchronized Classic and Run projections");let s=await gt(t,{classic:e,run:n,unknownKeys:r.unknownKeys}),o=Fi(e,s),a={...n,currentStep:o,iteration:n.iteration+1,status:o==="completed"?"completed":"running"};await et(t,{classic:e,run:a,unknownKeys:r.unknownKeys});let c=await yn(t,a.trajectoryRef);return await yt(t,a.trajectoryRef,{sequence:c.length+1,timestamp:new Date().toISOString(),type:"state_transitioned",runId:a.runId,data:{kind:"classic",fromStep:n.currentStep,toStep:o,...i}}),a}Ki();import Lw from"path";var Dw=Lw.join(".comet","state-events.jsonl"),Fw=8*1024*1024;async function _u(t,e){let n={schemaVersion:1,timestamp:new Date().toISOString(),...e};return await Wi(t,Dw,`${JSON.stringify(n)} +`,Fw,"Classic state event log"),n}var Mw={"open-complete":{event:"open-complete",from:"open",guardRefs:["open-artifacts-present"]},"design-complete":{event:"design-complete",from:"design",guardRefs:["design-evidence-present"]},"build-complete":{event:"build-complete",from:"build",guardRefs:["build-decisions-selected"]},"verify-pass":{event:"verify-pass",from:"verify",guardRefs:["verification-report-present"]},"verify-fail":{event:"verify-fail",from:"verify",guardRefs:["verification-failed"]},"archive-confirm":{event:"archive-confirm",from:"archive",guardRefs:["archive-final-confirmation"]},"archive-reopen":{event:"archive-reopen",from:"archive",guardRefs:["archive-not-finalized"]},archived:{event:"archived",from:"archive",guardRefs:["verify-result-pass","archive-confirmed"]},"preset-escalate":{event:"preset-escalate",from:"build",guardRefs:["preset-workflow"]}};function Ww(t){return t.toISOString().slice(0,10)}function x(t,e,n,i){let r=t[n];t[n]=i,r!==i&&e.push({field:n,from:r,to:i})}function Pu(t,e,n={}){let i=Mw[e];if(t.phase!==i.from)throw new Error(`Cannot apply ${e}: phase is '${t.phase}', expected '${i.from}'`);let r={...t},s=[],o=n.now??new Date;if(e==="open-complete")x(r,s,"phase",r.workflow==="full"?"design":"build");else if(e==="design-complete")x(r,s,"phase","build");else if(e==="build-complete"){let a=r.verifyResult==="fail";x(r,s,"phase","verify"),x(r,s,"verifyResult","pending"),x(r,s,"branchStatus","pending"),a||x(r,s,"verificationReport",null)}else if(e==="verify-pass")x(r,s,"verifyResult","pass"),x(r,s,"verifyFailures",0),x(r,s,"phase","archive"),x(r,s,"verifiedAt",Ww(o)),x(r,s,"archiveConfirmation","pending"),x(r,s,"branchStatus","pending");else if(e==="verify-fail")x(r,s,"verifyResult","fail"),x(r,s,"verifyFailures",r.verifyFailures+1),x(r,s,"phase","build"),x(r,s,"branchStatus","pending");else if(e==="preset-escalate"){if(r.workflow!=="hotfix"&&r.workflow!=="tweak")throw new Error(`Cannot apply ${e}: workflow must be hotfix or tweak, got '${r.workflow}'`);x(r,s,"workflow","full"),x(r,s,"classicProfile","full"),x(r,s,"phase","design"),x(r,s,"designDoc",null),x(r,s,"buildPause",null),x(r,s,"buildMode",null),x(r,s,"subagentDispatch",null),x(r,s,"tddMode",null),x(r,s,"reviewMode",null),x(r,s,"isolation",null),x(r,s,"boundBranch",null),x(r,s,"verifyMode",null),x(r,s,"directOverride",null)}else if(e==="archive-confirm"){if(r.verifyResult!=="pass")throw new Error(`Cannot apply ${e}: verifyResult must be pass`);if(r.archived)throw new Error(`Cannot apply ${e}: already archived`);x(r,s,"archiveConfirmation","confirmed")}else if(e==="archive-reopen"){if(r.archived)throw new Error(`Cannot apply ${e}: already archived`);x(r,s,"verifyResult","pending"),x(r,s,"verifyFailures",0),x(r,s,"phase","verify"),x(r,s,"verifiedAt",null),x(r,s,"archiveConfirmation",null),x(r,s,"branchStatus","pending")}else{if(r.verifyResult!=="pass")throw new Error(`Cannot apply ${e}: verifyResult must be pass`);if(r.archiveConfirmation!=="confirmed")throw new Error(`Cannot apply ${e}: archiveConfirmation must be confirmed`);x(r,s,"archived",!0)}return{classic:r,effects:s,definition:i}}Js();import{promises as Bw}from"fs";import Kw from"path";var yo="comet.selection.v2",Yw=16*1024;function vo(t){return Kw.join(t,".comet","current-change.json")}function Uw(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function Ru(t){return t===null||typeof t=="string"}function Jw(t){let e;try{e=JSON.parse(t)}catch(n){throw new Error(`current change selection contains invalid JSON: ${n instanceof Error?n.message:String(n)}`,{cause:n})}if(!Uw(e))throw new Error("current change selection must be a JSON object");if(e.version===1){if(typeof e.change!="string")throw new Error("legacy current change selection change must be a string");if(e.branch!==void 0&&!Ru(e.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:yo,workflow:"classic",change:e.change,branch:e.branch??null},legacy:!0}}if(e.schema!==yo)throw new Error(`current change selection schema must be ${yo}`);if(e.workflow!=="native"&&e.workflow!=="classic")throw new Error("current change selection workflow must be native or classic");if(typeof e.change!="string")throw new Error("current change selection change must be a string");if(!Ru(e.branch))throw new Error("current change selection branch must be a string or null");if(e.workflow==="native"&&e.branch!==null)throw new Error("Native current change selection branch must be null");return{selection:e,legacy:!1}}async function bo(t){let e;try{let i=vo(t),{bytes:r}=await _i(i,Yw,{label:"current change selection"});e=r.toString("utf8")}catch(i){if(i.code==="ENOENT")return{status:"missing"};throw new Error(`cannot read current change selection: ${i instanceof Error?i.message:String(i)}`,{cause:i})}return{status:"selected",...Jw(e)}}async function Ou(t){await Bw.rm(vo(t),{force:!0})}async function Au(t,e,n){let i=await bo(t);return i.status!=="selected"||i.selection.workflow!==e||i.selection.change!==n?!1:(await Ou(t),!0)}var Nu=null;function Tu(t,e){let n=t;for(let i of e)n+="\0"+(typeof i=="string"?i:JSON.stringify(i));return n}function ju(t,e){return(...n)=>{let i=Nu;if(i===null)return e(...n);let r=Tu(`async:${t}`,n),s=i.entries.get(r);if(s)return s.value;let o=e(...n).catch(a=>{throw i.entries.delete(r),a});return i.entries.set(r,{value:o}),o}}function ko(t,e){return(...n)=>{let i=Nu;if(i===null)return e(...n);let r=Tu(`sync:${t}`,n),s=i.entries.get(r);if(s)return s.value;let o=e(...n);return i.entries.set(r,{value:o}),o}}import{execFileSync as Iu}from"child_process";var Vw=nt(ze(),1);function Hw(t){try{let e=Iu("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();return e&&e!=="HEAD"?e:null}catch{return null}}var cC=ko("liveGitBranch",t=>Hw(t));function Gw(t){try{return Iu("git",["rev-parse","--is-inside-work-tree"],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()==="true"}catch{return!1}}var lC=ko("isGitWorkTree",t=>Gw(t));var bC=ju("readCometCurrentSelection",t=>bo(t));async function $u(t,e){return Au(t,"classic",e)}var Xw="\x1B[32m",Zw="\x1B[31m",ey="\x1B[33m",Co="\x1B[0m";function te(t){return`${Xw}${t}${Co}`}function G(t){return`${Zw}${t}${Co}`}function vn(t){return`${ey}${t}${Co}`}var B=class extends Error{constructor(n,i=1){super(n);this.exitCode=i}exitCode},So=class{stderr=[];openSpecStdout=[];openSpecStderr=[];stepsOk=0;stepsTotal=0;captureOpenSpec(e){e.stdout&&this.openSpecStdout.push(e.stdout),e.stderr&&this.openSpecStderr.push(e.stderr)}toResult(e=0){let n=this.stderr.length>0?this.stderr.join(` `)+` `:"",i=this.openSpecStderr.join(""),r=i&&n&&!i.endsWith(` `)?` -`:"";return{exitCode:e,...this.openSpecStdout.length>0?{stdout:this.openSpecStdout.join("")}:{},...i||n?{stderr:`${i}${r}${n}`}:{}}}};function ty(t){let e=no(t);if(e)throw new B(G(`FATAL: ${e}`))}function $u(t){return zw("sha256").update(t).digest("hex")}function ny(t){return $u(JSON.stringify(Object.fromEntries(Object.entries(t).sort(([e],[n])=>e.localeCompare(n)))))}function iy(t,e){let n=me.relative(t,e);return n!==""&&!me.isAbsolute(n)&&n!==".."&&!n.startsWith(`..${me.sep}`)}function bn(t,e,n,i){if(!i)return i;let r=me.resolve(t,i);return iy(e,r)?j(t,me.join(n,me.relative(e,r))):i}function ry(t,e,n,i){let r={...i};for(let s of["handoff_context","handoff_markdown"]){let o=r[s];o&&(r[s]=bn(t,e,n,o)??o)}return r}async function sy(t,e){let n=await de(e);if(!n.classic||!n.run||!n.classic.archived)throw new B(G(" [FAIL] Final archived state is incomplete"));let i=[["design_doc",n.classic.designDoc],["plan",n.classic.plan],["verification_report",n.classic.verificationReport],["handoff_context",n.classic.handoffContext]],r=await fo(e,n.run.artifactsRef),s=[["artifacts.handoff_context",r.handoff_context],["artifacts.handoff_markdown",r.handoff_markdown]];for(let[o,a]of[...i,...s])if(a&&!await an(t,me.resolve(t,a),{label:`Classic archived ${o}`,expected:"file"}))throw new B(G(` [FAIL] Final archived ${o} does not exist: ${a}`))}function qu(t){return`${t.replace(/\n+$/u,"")} +`:"";return{exitCode:e,...this.openSpecStdout.length>0?{stdout:this.openSpecStdout.join("")}:{},...i||n?{stderr:`${i}${r}${n}`}:{}}}};function ty(t){let e=no(t);if(e)throw new B(G(`FATAL: ${e}`))}function Lu(t){return zw("sha256").update(t).digest("hex")}function ny(t){return Lu(JSON.stringify(Object.fromEntries(Object.entries(t).sort(([e],[n])=>e.localeCompare(n)))))}function iy(t,e){let n=me.relative(t,e);return n!==""&&!me.isAbsolute(n)&&n!==".."&&!n.startsWith(`..${me.sep}`)}function bn(t,e,n,i){if(!i)return i;let r=me.resolve(t,i);return iy(e,r)?$(t,me.join(n,me.relative(e,r))):i}function ry(t,e,n,i){let r={...i};for(let s of["handoff_context","handoff_markdown"]){let o=r[s];o&&(r[s]=bn(t,e,n,o)??o)}return r}async function sy(t,e){let n=await de(e);if(!n.classic||!n.run||!n.classic.archived)throw new B(G(" [FAIL] Final archived state is incomplete"));let i=[["design_doc",n.classic.designDoc],["plan",n.classic.plan],["verification_report",n.classic.verificationReport],["handoff_context",n.classic.handoffContext]],r=await fo(e,n.run.artifactsRef),s=[["artifacts.handoff_context",r.handoff_context],["artifacts.handoff_markdown",r.handoff_markdown]];for(let[o,a]of[...i,...s])if(a&&!await an(t,me.resolve(t,a),{label:`Classic archived ${o}`,expected:"file"}))throw new B(G(` [FAIL] Final archived ${o} does not exist: ${a}`))}function qu(t){return`${t.replace(/\n+$/u,"")} `}function oy(t,e,n){let i=t.replace(/\r\n/gu,` `),r=i.split(` `),s=r[0]==="---"?r.indexOf("---",1):-1,o=n.match(/^([^:\n]+):/u)?.[1]?.trim();if(s!==-1){let c=r.slice(1,s).filter(l=>{let f=l.match(/^([^:\n]+):/u)?.[1]?.trim();return f===void 0?!0:f!=="archived-with"&&f!==o});return c.push(`archived-with: ${e}`),n&&c.push(n),qu(["---",...c,"---",...r.slice(s+1)].join(` `))}let a=["---",`archived-with: ${e}`];return n&&a.push(n),o!=="status"&&a.push("status: final"),a.push("---"),qu([...a,i].join(` -`))}async function ay(t,e,n){let i=await yn(t,e.trajectoryRef);i.some(r=>r.type==="recovery_reconciled"&&r.data.kind==="classic-archive"&&r.data.actionId===n)||await yt(t,e.trajectoryRef,{sequence:i.length+1,timestamp:new Date().toISOString(),type:"recovery_reconciled",runId:e.runId,data:{kind:"classic-archive",actionId:n}})}async function rr(t,e,n,i,r,s){if(!await an(e,n,{label:"Classic archive annotation target",expected:"file"}))return;if(s){t.stderr.push(vn(` [DRY-RUN] Would annotate: ${n}`)),t.stepsOk+=1,t.stepsTotal+=1;return}let o=await cn(e,n,{label:"Classic archive annotation target"}),a=oy(o,i,r);await Al(e,n,a,{label:"Classic archive annotation target"}),t.stderr.push(te(` [OK] Annotated: ${n}`)),t.stepsOk+=1,t.stepsTotal+=1}async function cy(t,e){if(!(await Fe(t,e,{label:"Classic main specs directory",expected:"directory"})).exists)return;let i=!1,r=await Qw.readdir(e,{withFileTypes:!0});for(let s of r){if(!s.isDirectory()&&!s.isSymbolicLink())continue;let o=`${e}/${s.name}/spec.md`,a=await(async()=>await an(t,o,{label:`Classic main spec ${s.name}`,expected:"file"})?cn(t,o,{label:`Classic main spec ${s.name}`}):null)();if(a===null)continue;let c=a.split(/\r?\n/u).map((l,f)=>({line:l,number:f+1})).filter(l=>/^## (ADDED|MODIFIED|REMOVED|RENAMED) Requirements$/u.test(l.line));if(c.length>0){i=!0,process.stderr.write(G(`FATAL: delta-only section heading leaked into main spec: ${o}`)+` +`))}async function ay(t,e,n){let i=await yn(t,e.trajectoryRef);i.some(r=>r.type==="recovery_reconciled"&&r.data.kind==="classic-archive"&&r.data.actionId===n)||await yt(t,e.trajectoryRef,{sequence:i.length+1,timestamp:new Date().toISOString(),type:"recovery_reconciled",runId:e.runId,data:{kind:"classic-archive",actionId:n}})}async function sr(t,e,n,i,r,s){if(!await an(e,n,{label:"Classic archive annotation target",expected:"file"}))return;if(s){t.stderr.push(vn(` [DRY-RUN] Would annotate: ${n}`)),t.stepsOk+=1,t.stepsTotal+=1;return}let o=await cn(e,n,{label:"Classic archive annotation target"}),a=oy(o,i,r);await Nl(e,n,a,{label:"Classic archive annotation target"}),t.stderr.push(te(` [OK] Annotated: ${n}`)),t.stepsOk+=1,t.stepsTotal+=1}async function cy(t,e){if(!(await Fe(t,e,{label:"Classic main specs directory",expected:"directory"})).exists)return;let i=!1,r=await Qw.readdir(e,{withFileTypes:!0});for(let s of r){if(!s.isDirectory()&&!s.isSymbolicLink())continue;let o=`${e}/${s.name}/spec.md`,a=await(async()=>await an(t,o,{label:`Classic main spec ${s.name}`,expected:"file"})?cn(t,o,{label:`Classic main spec ${s.name}`}):null)();if(a===null)continue;let c=a.split(/\r?\n/u).map((l,f)=>({line:l,number:f+1})).filter(l=>/^## (ADDED|MODIFIED|REMOVED|RENAMED) Requirements$/u.test(l.line));if(c.length>0){i=!0,process.stderr.write(G(`FATAL: delta-only section heading leaked into main spec: ${o}`)+` `);for(let l of c)process.stderr.write(`${l.number}:${l.line} -`)}}if(i)throw new B("")}var Lu=async t=>{let e=new So,n=t[0],i=t[1]==="--dry-run";try{ty(n);let r=await be(process.cwd()),s=await sn(r),o=await io(n,s.projectRoot),a=o.directory,c=j(s.projectRoot,a),f=`${new Date().toISOString().slice(0,10)}-${n}`,u=me.join(s.archiveDir,f);e.stderr.push(`=== Comet Archive: ${n} ===`);let d=o.stateExists,h=d?null:await $i(n,s.projectRoot),g=d?a:h?.directory;if(!g||!await an(s.projectRoot,`${g}/.comet.yaml`,{label:`Classic change ${n} state`,expected:"file"}))throw new B(G(`FATAL: .comet.yaml not found in ${c}/`));h&&(u=h.directory,f=me.basename(h.directory));let p=await de(g);if(!p.classic)throw new B(G("FATAL: archive requires Classic state"));let m=p.classic,w=m.designDoc,y=m.plan;if(m.phase!=="archive")throw new B(G(`FATAL: phase is '${m.phase}', expected 'archive'`));if(m.verifyResult!=="pass")throw new B(G(`FATAL: verify_result is '${m.verifyResult}', expected 'pass'. Run comet-verify first.`));e.stderr.push(te(" [OK] Entry state verified")),e.stepsOk+=1,e.stepsTotal+=1;let S=await Fe(s.projectRoot,u,{label:`Classic archive target ${f}`,expected:"directory"});if(d&&S.exists)throw new B(G(`FATAL: archive target already exists: ${u}`));if(e.stderr.push(te(" [OK] Archive target available")),e.stepsOk+=1,e.stepsTotal+=1,i)e.stderr.push(vn(` [DRY-RUN] Would run OpenSpec archive: ${n}`)),e.stepsOk+=1,e.stepsTotal+=1;else if(!m.archived||p.run?.pending){await to(s.projectRoot,`${g}/.comet`,"Classic change runtime directory");let k=await Cu(g),C=`classic-archive:${n}`,E=await Ql(g,k.run.pendingRef),R=!!h||E?.id===C&&E.type==="checkpoint"&&E.ref===n;if(k.run.pending&&k.run.pending!==C)throw new B(G(`FATAL: another action is pending: ${k.run.pending}`));if(!R&&!m.archived&&m.archiveConfirmation!=="confirmed")throw new B(G(`FATAL: archive_confirmation is '${m.archiveConfirmation??"null"}', expected 'confirmed'. Run final archive confirmation first.`));if(!R){let bt={id:C,stepId:k.run.currentStep,type:"checkpoint",ref:n};await zl(g,k.run.pendingRef,bt),await et(g,{classic:k.classic,run:{...k.run,pending:C,status:"waiting"},unknownKeys:(await de(g)).unknownKeys})}if(!h){let bt=await Ol(["archive",n,"--yes"],s.projectRoot);if(e.captureOpenSpec(bt),bt.exitCode!==0)throw new B("",bt.exitCode)}let b=await $i(n,s.projectRoot,{preferredArchiveName:f});if(!b&&!h&&(b=await $i(n,s.projectRoot,{skipExactCompatibility:!0})),!b)return e.stderr.push(G(" [FAIL] OpenSpec archive output not found")),e.stepsTotal+=1,e.stderr.push(""),e.stderr.push(te(`Archive complete. ${e.stepsOk}/${e.stepsTotal} steps succeeded.`)),e.toResult(1);u=b.directory,f=me.basename(b.directory),e.stderr.push(te(` [OK] OpenSpec archive completed: ${u}`)),e.stepsOk+=1,e.stepsTotal+=1,await cy(s.projectRoot,s.specsDir),e.stderr.push(te(" [OK] Main specs verified clean")),e.stepsOk+=1,e.stepsTotal+=1,w&&await rr(e,s.projectRoot,w,f,"status: final",!1),y&&await rr(e,s.projectRoot,y,f,"",!1);let P=await de(u);if(!P.classic||!P.run)throw new B(G(" [FAIL] archived state projection is incomplete"));let ne={...ry(s.projectRoot,a,u,await fo(u,P.run.artifactsRef)),archive_directory:j(s.projectRoot,u)};await Xi(u,P.run.artifactsRef,ne);let z=_u(R&&P.classic.archiveConfirmation!=="confirmed"?{...P.classic,archiveConfirmation:"confirmed"}:P.classic,"archived"),A={...z.classic,designDoc:bn(s.projectRoot,a,u,z.classic.designDoc),plan:bn(s.projectRoot,a,u,z.classic.plan),verificationReport:bn(s.projectRoot,a,u,z.classic.verificationReport),handoffContext:bn(s.projectRoot,a,u,z.classic.handoffContext)},ie=P.run;(P.run.currentStep!=="completed"||P.run.status!=="completed")&&(ie=await Eu(u,A,P.run,{actionId:C,archiveDirectory:j(s.projectRoot,u),event:"archived",source:"comet-archive"})),R&&await ay(u,ie,C);let Fu=await yn(u,ie.trajectoryRef),Eo=await Gl(u,ie.contextRef),Mu={runId:ie.runId,stateVersion:ie.iteration,trajectoryOffset:Fu.length,contextHash:Eo===null?null:$u(Eo),artifactsHash:ny(ne),createdAt:new Date().toISOString()};await Zi(u,ie.checkpointRef,Mu);let xo={...ie,pending:null,status:"completed"};await et(u,{classic:A,run:xo,unknownKeys:P.unknownKeys}),await xu(u,{change:f,event:"archived",source:"comet-archive",from:P.classic,to:A,effects:z.effects}),await Xl(u,xo.pendingRef),e.stderr.push(te(" [OK] archived: true")),e.stepsOk+=1,e.stepsTotal+=1}else{if(!p.run)throw new B(G("FATAL: archived Classic state is missing its Run projection"));e.stderr.push(te(` [OK] OpenSpec archive completed: ${u}`)),e.stepsOk+=1,e.stepsTotal+=1,e.stderr.push(te(" [OK] Main specs verified clean")),e.stepsOk+=1,e.stepsTotal+=1,e.stderr.push(te(" [OK] archived: true")),e.stepsOk+=1,e.stepsTotal+=1}return i?(w&&await rr(e,s.projectRoot,w,f,"status: final",!0),y&&await rr(e,s.projectRoot,y,f,"",!0),e.stderr.push(vn(` [DRY-RUN] Would set archived: true in ${u}/.comet.yaml`)),e.stepsOk+=1,e.stepsTotal+=1,e.stderr.push(vn(" [DRY-RUN] Would verify final archive integrity")),e.stepsOk+=1,e.stepsTotal+=1):(await sy(s.projectRoot,u),e.stderr.push(te(" [OK] Final archive integrity verified")),e.stepsOk+=1,e.stepsTotal+=1),i||await Iu(s.projectRoot,n),e.stderr.push(""),e.stderr.push(i?vn(`Dry run complete. ${e.stepsOk}/${e.stepsTotal} steps would succeed.`):te(`Archive complete. ${e.stepsOk}/${e.stepsTotal} steps succeeded.`)),e.toResult(e.stepsOk{let e=new So,n=t[0],i=t[1]==="--dry-run";try{ty(n);let r=await be(process.cwd()),s=await sn(r),o=await io(n,s.projectRoot),a=o.directory,c=$(s.projectRoot,a),f=`${new Date().toISOString().slice(0,10)}-${n}`,u=me.join(s.archiveDir,f);e.stderr.push(`=== Comet Archive: ${n} ===`);let d=o.stateExists,h=d?null:await Li(n,s.projectRoot),g=d?a:h?.directory;if(!g||!await an(s.projectRoot,`${g}/.comet.yaml`,{label:`Classic change ${n} state`,expected:"file"}))throw new B(G(`FATAL: .comet.yaml not found in ${c}/`));h&&(u=h.directory,f=me.basename(h.directory));let p=await de(g);if(!p.classic)throw new B(G("FATAL: archive requires Classic state"));let m=p.classic,w=m.designDoc,y=m.plan;if(m.phase!=="archive")throw new B(G(`FATAL: phase is '${m.phase}', expected 'archive'`));if(m.verifyResult!=="pass")throw new B(G(`FATAL: verify_result is '${m.verifyResult}', expected 'pass'. Run comet-verify first.`));e.stderr.push(te(" [OK] Entry state verified")),e.stepsOk+=1,e.stepsTotal+=1;let S=await Fe(s.projectRoot,u,{label:`Classic archive target ${f}`,expected:"directory"});if(d&&S.exists)throw new B(G(`FATAL: archive target already exists: ${u}`));if(e.stderr.push(te(" [OK] Archive target available")),e.stepsOk+=1,e.stepsTotal+=1,i)e.stderr.push(vn(` [DRY-RUN] Would run OpenSpec archive: ${n}`)),e.stepsOk+=1,e.stepsTotal+=1;else if(!m.archived||p.run?.pending){await to(s.projectRoot,`${g}/.comet`,"Classic change runtime directory");let k=await Eu(g),C=`classic-archive:${n}`,E=await Xl(g,k.run.pendingRef),R=!!h||E?.id===C&&E.type==="checkpoint"&&E.ref===n;if(k.run.pending&&k.run.pending!==C)throw new B(G(`FATAL: another action is pending: ${k.run.pending}`));if(!R&&!m.archived&&m.archiveConfirmation!=="confirmed")throw new B(G(`FATAL: archive_confirmation is '${m.archiveConfirmation??"null"}', expected 'confirmed'. Run final archive confirmation first.`));if(!R){let bt={id:C,stepId:k.run.currentStep,type:"checkpoint",ref:n};await Ql(g,k.run.pendingRef,bt),await et(g,{classic:k.classic,run:{...k.run,pending:C,status:"waiting"},unknownKeys:(await de(g)).unknownKeys})}if(!h){let bt=await Al(["archive",n,"--yes"],s.projectRoot);if(e.captureOpenSpec(bt),bt.exitCode!==0)throw new B("",bt.exitCode)}let b=await Li(n,s.projectRoot,{preferredArchiveName:f});if(!b&&!h&&(b=await Li(n,s.projectRoot,{skipExactCompatibility:!0})),!b)return e.stderr.push(G(" [FAIL] OpenSpec archive output not found")),e.stepsTotal+=1,e.stderr.push(""),e.stderr.push(te(`Archive complete. ${e.stepsOk}/${e.stepsTotal} steps succeeded.`)),e.toResult(1);u=b.directory,f=me.basename(b.directory),e.stderr.push(te(` [OK] OpenSpec archive completed: ${u}`)),e.stepsOk+=1,e.stepsTotal+=1,await cy(s.projectRoot,s.specsDir),e.stderr.push(te(" [OK] Main specs verified clean")),e.stepsOk+=1,e.stepsTotal+=1,w&&await sr(e,s.projectRoot,w,f,"status: final",!1),y&&await sr(e,s.projectRoot,y,f,"",!1);let P=await de(u);if(!P.classic||!P.run)throw new B(G(" [FAIL] archived state projection is incomplete"));let ne={...ry(s.projectRoot,a,u,await fo(u,P.run.artifactsRef)),archive_directory:$(s.projectRoot,u)};await Zi(u,P.run.artifactsRef,ne);let z=Pu(R&&P.classic.archiveConfirmation!=="confirmed"?{...P.classic,archiveConfirmation:"confirmed"}:P.classic,"archived"),A={...z.classic,designDoc:bn(s.projectRoot,a,u,z.classic.designDoc),plan:bn(s.projectRoot,a,u,z.classic.plan),verificationReport:bn(s.projectRoot,a,u,z.classic.verificationReport),handoffContext:bn(s.projectRoot,a,u,z.classic.handoffContext)},ie=P.run;(P.run.currentStep!=="completed"||P.run.status!=="completed")&&(ie=await xu(u,A,P.run,{actionId:C,archiveDirectory:$(s.projectRoot,u),event:"archived",source:"comet-archive"})),R&&await ay(u,ie,C);let Mu=await yn(u,ie.trajectoryRef),Eo=await zl(u,ie.contextRef),Wu={runId:ie.runId,stateVersion:ie.iteration,trajectoryOffset:Mu.length,contextHash:Eo===null?null:Lu(Eo),artifactsHash:ny(ne),createdAt:new Date().toISOString()};await er(u,ie.checkpointRef,Wu);let xo={...ie,pending:null,status:"completed"};await et(u,{classic:A,run:xo,unknownKeys:P.unknownKeys}),await _u(u,{change:f,event:"archived",source:"comet-archive",from:P.classic,to:A,effects:z.effects}),await Zl(u,xo.pendingRef),e.stderr.push(te(" [OK] archived: true")),e.stepsOk+=1,e.stepsTotal+=1}else{if(!p.run)throw new B(G("FATAL: archived Classic state is missing its Run projection"));e.stderr.push(te(` [OK] OpenSpec archive completed: ${u}`)),e.stepsOk+=1,e.stepsTotal+=1,e.stderr.push(te(" [OK] Main specs verified clean")),e.stepsOk+=1,e.stepsTotal+=1,e.stderr.push(te(" [OK] archived: true")),e.stepsOk+=1,e.stepsTotal+=1}return i?(w&&await sr(e,s.projectRoot,w,f,"status: final",!0),y&&await sr(e,s.projectRoot,y,f,"",!0),e.stderr.push(vn(` [DRY-RUN] Would set archived: true in ${u}/.comet.yaml`)),e.stepsOk+=1,e.stepsTotal+=1,e.stderr.push(vn(" [DRY-RUN] Would verify final archive integrity")),e.stepsOk+=1,e.stepsTotal+=1):(await sy(s.projectRoot,u),e.stderr.push(te(" [OK] Final archive integrity verified")),e.stepsOk+=1,e.stepsTotal+=1),i||await $u(s.projectRoot,n),e.stderr.push(""),e.stderr.push(i?vn(`Dry run complete. ${e.stepsOk}/${e.stepsTotal} steps would succeed.`):te(`Archive complete. ${e.stepsOk}/${e.stepsTotal} steps succeeded.`)),e.toResult(e.stepsOka!=="--json"),s;try{s=await e(r,{json:i})}catch(a){s={exitCode:70,stderr:a instanceof Error?a.message:String(a)}}let o=i?ly(t,s):s;return o.stdout&&process.stdout.write(o.stdout),o.stderr&&process.stderr.write(o.stderr+(o.stderr.endsWith(` +`}}async function Fu(t,e,n=process.argv.slice(2)){let i=n.includes("--json"),r=n.filter(a=>a!=="--json"),s;try{s=await e(r,{json:i})}catch(a){s={exitCode:70,stderr:a instanceof Error?a.message:String(a)}}let o=i?ly(t,s):s;return o.stdout&&process.stdout.write(o.stdout),o.stderr&&process.stderr.write(o.stderr+(o.stderr.endsWith(` `)?"":` -`)),o.exitCode}process.exitCode=await Du("archive",Lu); +`)),o.exitCode}process.exitCode=await Fu("archive",Du); diff --git a/assets/skills/comet/scripts/comet-guard.mjs b/assets/skills/comet/scripts/comet-guard.mjs index 67d19b4d8..cf1943625 100644 --- a/assets/skills/comet/scripts/comet-guard.mjs +++ b/assets/skills/comet/scripts/comet-guard.mjs @@ -1,41 +1,41 @@ #!/usr/bin/env node import { createRequire as __cometCreateRequire } from 'module'; const require = __cometCreateRequire(import.meta.url); -var ff=Object.create;var hr=Object.defineProperty;var df=Object.getOwnPropertyDescriptor;var pf=Object.getOwnPropertyNames;var mf=Object.getPrototypeOf,hf=Object.prototype.hasOwnProperty;var jn=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var G=(t,e,n)=>()=>{if(n)throw n[0];try{return t&&(e=t(t=0)),e}catch(i){throw n=[i],i}};var v=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(n){throw e=0,n}},gf=(t,e)=>{for(var n in e)hr(t,n,{get:e[n],enumerable:!0})},wf=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of pf(e))!hf.call(t,r)&&r!==n&&hr(t,r,{get:()=>e[r],enumerable:!(i=df(e,r))||i.enumerable});return t};var Ve=(t,e,n)=>(n=t!=null?ff(mf(t)):{},wf(e||!t||!t.__esModule?hr(n,"default",{value:t,enumerable:!0}):n,t));var N=v(U=>{"use strict";var gr=Symbol.for("yaml.alias"),Fo=Symbol.for("yaml.document"),Tn=Symbol.for("yaml.map"),Mo=Symbol.for("yaml.pair"),wr=Symbol.for("yaml.scalar"),In=Symbol.for("yaml.seq"),ge=Symbol.for("yaml.node.type"),yf=t=>!!t&&typeof t=="object"&&t[ge]===gr,vf=t=>!!t&&typeof t=="object"&&t[ge]===Fo,bf=t=>!!t&&typeof t=="object"&&t[ge]===Tn,kf=t=>!!t&&typeof t=="object"&&t[ge]===Mo,Wo=t=>!!t&&typeof t=="object"&&t[ge]===wr,Sf=t=>!!t&&typeof t=="object"&&t[ge]===In;function Bo(t){if(t&&typeof t=="object")switch(t[ge]){case Tn:case In:return!0}return!1}function Cf(t){if(t&&typeof t=="object")switch(t[ge]){case gr:case Tn:case wr:case In:return!0}return!1}var Ef=t=>(Wo(t)||Bo(t))&&!!t.anchor;U.ALIAS=gr;U.DOC=Fo;U.MAP=Tn;U.NODE_TYPE=ge;U.PAIR=Mo;U.SCALAR=wr;U.SEQ=In;U.hasAnchor=Ef;U.isAlias=yf;U.isCollection=Bo;U.isDocument=vf;U.isMap=bf;U.isNode=Cf;U.isPair=kf;U.isScalar=Wo;U.isSeq=Sf});var Ot=v(yr=>{"use strict";var B=N(),Z=Symbol("break visit"),Ko=Symbol("skip children"),de=Symbol("remove node");function $n(t,e){let n=Yo(e);B.isDocument(t)?ft(null,t.contents,n,Object.freeze([t]))===de&&(t.contents=null):ft(null,t,n,Object.freeze([]))}$n.BREAK=Z;$n.SKIP=Ko;$n.REMOVE=de;function ft(t,e,n,i){let r=Uo(t,e,n,i);if(B.isNode(r)||B.isPair(r))return Vo(t,i,r),ft(t,r,n,i);if(typeof r!="symbol"){if(B.isCollection(e)){i=Object.freeze(i.concat(e));for(let s=0;s{"use strict";var Jo=N(),xf=Ot(),_f={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Pf=t=>t.replace(/[!,[\]{}]/g,e=>_f[e]),At=class t{constructor(e,n){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},t.defaultYaml,e),this.tags=Object.assign({},t.defaultTags,n)}clone(){let e=new t(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){let e=new t(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:t.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},t.defaultTags);break}return e}add(e,n){this.atNextDocument&&(this.yaml={explicit:t.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},t.defaultTags),this.atNextDocument=!1);let i=e.trim().split(/[ \t]+/),r=i.shift();switch(r){case"%TAG":{if(i.length!==2&&(n(0,"%TAG directive should contain exactly two parts"),i.length<2))return!1;let[s,o]=i;return this.tags[s]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,i.length!==1)return n(0,"%YAML directive should contain exactly one part"),!1;let[s]=i;if(s==="1.1"||s==="1.2")return this.yaml.version=s,!0;{let o=/^\d+\.\d+$/.test(s);return n(6,`Unsupported YAML version ${s}`,o),!1}}default:return n(0,`Unknown directive ${r}`,!0),!1}}tagName(e,n){if(e==="!")return"!";if(e[0]!=="!")return n(`Not a valid tag: ${e}`),null;if(e[1]==="<"){let o=e.slice(2,-1);return o==="!"||o==="!!"?(n(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&n("Verbatim tags must end with a >"),o)}let[,i,r]=e.match(/^(.*!)([^!]*)$/s);r||n(`The ${e} tag has no suffix`);let s=this.tags[i];if(s)try{return s+decodeURIComponent(r)}catch(o){return n(String(o)),null}return i==="!"?e:(n(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[n,i]of Object.entries(this.tags))if(e.startsWith(i))return n+Pf(e.substring(i.length));return e[0]==="!"?e:`!<${e}>`}toString(e){let n=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],i=Object.entries(this.tags),r;if(e&&i.length>0&&Jo.isNode(e.contents)){let s={};xf.visit(e.contents,(o,a)=>{Jo.isNode(a)&&a.tag&&(s[a.tag]=!0)}),r=Object.keys(s)}else r=[];for(let[s,o]of i)s==="!!"&&o==="tag:yaml.org,2002:"||(!e||r.some(a=>a.startsWith(o)))&&n.push(`%TAG ${s} ${o}`);return n.join(` -`)}};At.defaultYaml={explicit:!1,version:"1.2"};At.defaultTags={"!!":"tag:yaml.org,2002:"};Ho.Directives=At});var Ln=v(jt=>{"use strict";var Go=N(),Rf=Ot();function Nf(t){if(/[\x00-\x19\s,[\]{}]/.test(t)){let n=`Anchor must not contain whitespace or control characters: ${JSON.stringify(t)}`;throw new Error(n)}return!0}function zo(t){let e=new Set;return Rf.visit(t,{Value(n,i){i.anchor&&e.add(i.anchor)}}),e}function Qo(t,e){for(let n=1;;++n){let i=`${t}${n}`;if(!e.has(i))return i}}function Of(t,e){let n=[],i=new Map,r=null;return{onAnchor:s=>{n.push(s),r??(r=zo(t));let o=Qo(e,r);return r.add(o),o},setAnchors:()=>{for(let s of n){let o=i.get(s);if(typeof o=="object"&&o.anchor&&(Go.isScalar(o.node)||Go.isCollection(o.node)))o.node.anchor=o.anchor;else{let a=new Error("Failed to resolve repeated object (this should not happen)");throw a.source=s,a}}},sourceObjects:i}}jt.anchorIsValid=Nf;jt.anchorNames=zo;jt.createNodeAnchors=Of;jt.findNewAnchor=Qo});var br=v(Xo=>{"use strict";function Tt(t,e,n,i){if(i&&typeof i=="object")if(Array.isArray(i))for(let r=0,s=i.length;r{"use strict";var Af=N();function Zo(t,e,n){if(Array.isArray(t))return t.map((i,r)=>Zo(i,String(r),n));if(t&&typeof t.toJSON=="function"){if(!n||!Af.hasAnchor(t))return t.toJSON(e,n);let i={aliasCount:0,count:1,res:void 0};n.anchors.set(t,i),n.onCreate=s=>{i.res=s,delete n.onCreate};let r=t.toJSON(e,n);return n.onCreate&&n.onCreate(r),r}return typeof t=="bigint"&&!n?.keep?Number(t):t}ea.toJS=Zo});var Dn=v(na=>{"use strict";var jf=br(),ta=N(),Tf=Ee(),kr=class{constructor(e){Object.defineProperty(this,ta.NODE_TYPE,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:n,maxAliasCount:i,onAnchor:r,reviver:s}={}){if(!ta.isDocument(e))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:e,keep:!0,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},a=Tf.toJS(this,"",o);if(typeof r=="function")for(let{count:c,res:l}of o.anchors.values())r(l,c);return typeof s=="function"?jf.applyReviver(s,{"":a},"",a):a}};na.NodeBase=kr});var It=v(ia=>{"use strict";var If=Ln(),$f=Ot(),pt=N(),qf=Dn(),Lf=Ee(),Sr=class extends qf.NodeBase{constructor(e){super(pt.ALIAS),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,n){if(n?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let i;n?.aliasResolveCache?i=n.aliasResolveCache:(i=[],$f.visit(e,{Node:(s,o)=>{(pt.isAlias(o)||pt.hasAnchor(o))&&i.push(o)}}),n&&(n.aliasResolveCache=i));let r;for(let s of i){if(s===this)break;s.anchor===this.source&&(r=s)}return r}toJSON(e,n){if(!n)return{source:this.source};let{anchors:i,doc:r,maxAliasCount:s}=n,o=this.resolve(r,n);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let a=i.get(o);if(a||(Lf.toJS(o,null,n),a=i.get(o)),a?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(s>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=Fn(r,o,i)),a.count*a.aliasCount>s)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return a.res}toString(e,n,i){let r=`*${this.source}`;if(e){if(If.anchorIsValid(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let s=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(s)}if(e.implicitKey)return`${r} `}return r}};function Fn(t,e,n){if(pt.isAlias(e)){let i=e.resolve(t),r=n&&i&&n.get(i);return r?r.count*r.aliasCount:0}else if(pt.isCollection(e)){let i=0;for(let r of e.items){let s=Fn(t,r,n);s>i&&(i=s)}return i}else if(pt.isPair(e)){let i=Fn(t,e.key,n),r=Fn(t,e.value,n);return Math.max(i,r)}return 1}ia.Alias=Sr});var q=v(Cr=>{"use strict";var Df=N(),Ff=Dn(),Mf=Ee(),Wf=t=>!t||typeof t!="function"&&typeof t!="object",xe=class extends Ff.NodeBase{constructor(e){super(Df.SCALAR),this.value=e}toJSON(e,n){return n?.keep?this.value:Mf.toJS(this.value,e,n)}toString(){return String(this.value)}};xe.BLOCK_FOLDED="BLOCK_FOLDED";xe.BLOCK_LITERAL="BLOCK_LITERAL";xe.PLAIN="PLAIN";xe.QUOTE_DOUBLE="QUOTE_DOUBLE";xe.QUOTE_SINGLE="QUOTE_SINGLE";Cr.Scalar=xe;Cr.isScalarValue=Wf});var $t=v(sa=>{"use strict";var Bf=It(),Je=N(),ra=q(),Kf="tag:yaml.org,2002:";function Yf(t,e,n){if(e){let i=n.filter(s=>s.tag===e),r=i.find(s=>!s.format)??i[0];if(!r)throw new Error(`Tag ${e} not found`);return r}return n.find(i=>i.identify?.(t)&&!i.format)}function Uf(t,e,n){if(Je.isDocument(t)&&(t=t.contents),Je.isNode(t))return t;if(Je.isPair(t)){let u=n.schema[Je.MAP].createNode?.(n.schema,null,n);return u.items.push(t),u}(t instanceof String||t instanceof Number||t instanceof Boolean||typeof BigInt<"u"&&t instanceof BigInt)&&(t=t.valueOf());let{aliasDuplicateObjects:i,onAnchor:r,onTagObj:s,schema:o,sourceObjects:a}=n,c;if(i&&t&&typeof t=="object"){if(c=a.get(t),c)return c.anchor??(c.anchor=r(t)),new Bf.Alias(c.anchor);c={anchor:null,node:null},a.set(t,c)}e?.startsWith("!!")&&(e=Kf+e.slice(2));let l=Yf(t,e,o.tags);if(!l){if(t&&typeof t.toJSON=="function"&&(t=t.toJSON()),!t||typeof t!="object"){let u=new ra.Scalar(t);return c&&(c.node=u),u}l=t instanceof Map?o[Je.MAP]:Symbol.iterator in Object(t)?o[Je.SEQ]:o[Je.MAP]}s&&(s(l),delete n.onTagObj);let f=l?.createNode?l.createNode(n.schema,t,n):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(n.schema,t,n):new ra.Scalar(t);return e?f.tag=e:l.default||(f.tag=l.tag),c&&(c.node=f),f}sa.createNode=Uf});var Wn=v(Mn=>{"use strict";var Vf=$t(),pe=N(),Jf=Dn();function Er(t,e,n){let i=n;for(let r=e.length-1;r>=0;--r){let s=e[r];if(typeof s=="number"&&Number.isInteger(s)&&s>=0){let o=[];o[s]=i,i=o}else i=new Map([[s,i]])}return Vf.createNode(i,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:t,sourceObjects:new Map})}var oa=t=>t==null||typeof t=="object"&&!!t[Symbol.iterator]().next().done,xr=class extends Jf.NodeBase{constructor(e,n){super(e),Object.defineProperty(this,"schema",{value:n,configurable:!0,enumerable:!1,writable:!0})}clone(e){let n=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(n.schema=e),n.items=n.items.map(i=>pe.isNode(i)||pe.isPair(i)?i.clone(e):i),this.range&&(n.range=this.range.slice()),n}addIn(e,n){if(oa(e))this.add(n);else{let[i,...r]=e,s=this.get(i,!0);if(pe.isCollection(s))s.addIn(r,n);else if(s===void 0&&this.schema)this.set(i,Er(this.schema,r,n));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${r}`)}}deleteIn(e){let[n,...i]=e;if(i.length===0)return this.delete(n);let r=this.get(n,!0);if(pe.isCollection(r))return r.deleteIn(i);throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}getIn(e,n){let[i,...r]=e,s=this.get(i,!0);return r.length===0?!n&&pe.isScalar(s)?s.value:s:pe.isCollection(s)?s.getIn(r,n):void 0}hasAllNullValues(e){return this.items.every(n=>{if(!pe.isPair(n))return!1;let i=n.value;return i==null||e&&pe.isScalar(i)&&i.value==null&&!i.commentBefore&&!i.comment&&!i.tag})}hasIn(e){let[n,...i]=e;if(i.length===0)return this.has(n);let r=this.get(n,!0);return pe.isCollection(r)?r.hasIn(i):!1}setIn(e,n){let[i,...r]=e;if(r.length===0)this.set(i,n);else{let s=this.get(i,!0);if(pe.isCollection(s))s.setIn(r,n);else if(s===void 0&&this.schema)this.set(i,Er(this.schema,r,n));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${r}`)}}};Mn.Collection=xr;Mn.collectionFromPath=Er;Mn.isEmptyPath=oa});var qt=v(Bn=>{"use strict";var Hf=t=>t.replace(/^(?!$)(?: $)?/gm,"#");function _r(t,e){return/^\n+$/.test(t)?t.substring(1):e?t.replace(/^(?! *$)/gm,e):t}var Gf=(t,e,n)=>t.endsWith(` -`)?_r(n,e):n.includes(` +var df=Object.create;var gr=Object.defineProperty;var pf=Object.getOwnPropertyDescriptor;var mf=Object.getOwnPropertyNames;var hf=Object.getPrototypeOf,gf=Object.prototype.hasOwnProperty;var jn=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var G=(t,e,n)=>()=>{if(n)throw n[0];try{return t&&(e=t(t=0)),e}catch(i){throw n=[i],i}};var v=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(n){throw e=0,n}},wf=(t,e)=>{for(var n in e)gr(t,n,{get:e[n],enumerable:!0})},yf=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of mf(e))!gf.call(t,r)&&r!==n&&gr(t,r,{get:()=>e[r],enumerable:!(i=pf(e,r))||i.enumerable});return t};var Je=(t,e,n)=>(n=t!=null?df(hf(t)):{},yf(e||!t||!t.__esModule?gr(n,"default",{value:t,enumerable:!0}):n,t));var N=v(U=>{"use strict";var wr=Symbol.for("yaml.alias"),Fo=Symbol.for("yaml.document"),Tn=Symbol.for("yaml.map"),Mo=Symbol.for("yaml.pair"),yr=Symbol.for("yaml.scalar"),In=Symbol.for("yaml.seq"),ge=Symbol.for("yaml.node.type"),vf=t=>!!t&&typeof t=="object"&&t[ge]===wr,bf=t=>!!t&&typeof t=="object"&&t[ge]===Fo,kf=t=>!!t&&typeof t=="object"&&t[ge]===Tn,Sf=t=>!!t&&typeof t=="object"&&t[ge]===Mo,Wo=t=>!!t&&typeof t=="object"&&t[ge]===yr,Cf=t=>!!t&&typeof t=="object"&&t[ge]===In;function Bo(t){if(t&&typeof t=="object")switch(t[ge]){case Tn:case In:return!0}return!1}function Ef(t){if(t&&typeof t=="object")switch(t[ge]){case wr:case Tn:case yr:case In:return!0}return!1}var xf=t=>(Wo(t)||Bo(t))&&!!t.anchor;U.ALIAS=wr;U.DOC=Fo;U.MAP=Tn;U.NODE_TYPE=ge;U.PAIR=Mo;U.SCALAR=yr;U.SEQ=In;U.hasAnchor=xf;U.isAlias=vf;U.isCollection=Bo;U.isDocument=bf;U.isMap=kf;U.isNode=Ef;U.isPair=Sf;U.isScalar=Wo;U.isSeq=Cf});var Ot=v(vr=>{"use strict";var B=N(),Z=Symbol("break visit"),Ko=Symbol("skip children"),de=Symbol("remove node");function $n(t,e){let n=Yo(e);B.isDocument(t)?ft(null,t.contents,n,Object.freeze([t]))===de&&(t.contents=null):ft(null,t,n,Object.freeze([]))}$n.BREAK=Z;$n.SKIP=Ko;$n.REMOVE=de;function ft(t,e,n,i){let r=Uo(t,e,n,i);if(B.isNode(r)||B.isPair(r))return Vo(t,i,r),ft(t,r,n,i);if(typeof r!="symbol"){if(B.isCollection(e)){i=Object.freeze(i.concat(e));for(let s=0;s{"use strict";var Jo=N(),_f=Ot(),Pf={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Rf=t=>t.replace(/[!,[\]{}]/g,e=>Pf[e]),At=class t{constructor(e,n){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},t.defaultYaml,e),this.tags=Object.assign({},t.defaultTags,n)}clone(){let e=new t(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){let e=new t(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:t.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},t.defaultTags);break}return e}add(e,n){this.atNextDocument&&(this.yaml={explicit:t.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},t.defaultTags),this.atNextDocument=!1);let i=e.trim().split(/[ \t]+/),r=i.shift();switch(r){case"%TAG":{if(i.length!==2&&(n(0,"%TAG directive should contain exactly two parts"),i.length<2))return!1;let[s,o]=i;return this.tags[s]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,i.length!==1)return n(0,"%YAML directive should contain exactly one part"),!1;let[s]=i;if(s==="1.1"||s==="1.2")return this.yaml.version=s,!0;{let o=/^\d+\.\d+$/.test(s);return n(6,`Unsupported YAML version ${s}`,o),!1}}default:return n(0,`Unknown directive ${r}`,!0),!1}}tagName(e,n){if(e==="!")return"!";if(e[0]!=="!")return n(`Not a valid tag: ${e}`),null;if(e[1]==="<"){let o=e.slice(2,-1);return o==="!"||o==="!!"?(n(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&n("Verbatim tags must end with a >"),o)}let[,i,r]=e.match(/^(.*!)([^!]*)$/s);r||n(`The ${e} tag has no suffix`);let s=this.tags[i];if(s)try{return s+decodeURIComponent(r)}catch(o){return n(String(o)),null}return i==="!"?e:(n(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[n,i]of Object.entries(this.tags))if(e.startsWith(i))return n+Rf(e.substring(i.length));return e[0]==="!"?e:`!<${e}>`}toString(e){let n=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],i=Object.entries(this.tags),r;if(e&&i.length>0&&Jo.isNode(e.contents)){let s={};_f.visit(e.contents,(o,a)=>{Jo.isNode(a)&&a.tag&&(s[a.tag]=!0)}),r=Object.keys(s)}else r=[];for(let[s,o]of i)s==="!!"&&o==="tag:yaml.org,2002:"||(!e||r.some(a=>a.startsWith(o)))&&n.push(`%TAG ${s} ${o}`);return n.join(` +`)}};At.defaultYaml={explicit:!1,version:"1.2"};At.defaultTags={"!!":"tag:yaml.org,2002:"};Ho.Directives=At});var Ln=v(jt=>{"use strict";var Go=N(),Nf=Ot();function Of(t){if(/[\x00-\x19\s,[\]{}]/.test(t)){let n=`Anchor must not contain whitespace or control characters: ${JSON.stringify(t)}`;throw new Error(n)}return!0}function zo(t){let e=new Set;return Nf.visit(t,{Value(n,i){i.anchor&&e.add(i.anchor)}}),e}function Qo(t,e){for(let n=1;;++n){let i=`${t}${n}`;if(!e.has(i))return i}}function Af(t,e){let n=[],i=new Map,r=null;return{onAnchor:s=>{n.push(s),r??(r=zo(t));let o=Qo(e,r);return r.add(o),o},setAnchors:()=>{for(let s of n){let o=i.get(s);if(typeof o=="object"&&o.anchor&&(Go.isScalar(o.node)||Go.isCollection(o.node)))o.node.anchor=o.anchor;else{let a=new Error("Failed to resolve repeated object (this should not happen)");throw a.source=s,a}}},sourceObjects:i}}jt.anchorIsValid=Of;jt.anchorNames=zo;jt.createNodeAnchors=Af;jt.findNewAnchor=Qo});var kr=v(Xo=>{"use strict";function Tt(t,e,n,i){if(i&&typeof i=="object")if(Array.isArray(i))for(let r=0,s=i.length;r{"use strict";var jf=N();function Zo(t,e,n){if(Array.isArray(t))return t.map((i,r)=>Zo(i,String(r),n));if(t&&typeof t.toJSON=="function"){if(!n||!jf.hasAnchor(t))return t.toJSON(e,n);let i={aliasCount:0,count:1,res:void 0};n.anchors.set(t,i),n.onCreate=s=>{i.res=s,delete n.onCreate};let r=t.toJSON(e,n);return n.onCreate&&n.onCreate(r),r}return typeof t=="bigint"&&!n?.keep?Number(t):t}ea.toJS=Zo});var Dn=v(na=>{"use strict";var Tf=kr(),ta=N(),If=Ee(),Sr=class{constructor(e){Object.defineProperty(this,ta.NODE_TYPE,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:n,maxAliasCount:i,onAnchor:r,reviver:s}={}){if(!ta.isDocument(e))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:e,keep:!0,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},a=If.toJS(this,"",o);if(typeof r=="function")for(let{count:c,res:l}of o.anchors.values())r(l,c);return typeof s=="function"?Tf.applyReviver(s,{"":a},"",a):a}};na.NodeBase=Sr});var It=v(ia=>{"use strict";var $f=Ln(),qf=Ot(),pt=N(),Lf=Dn(),Df=Ee(),Cr=class extends Lf.NodeBase{constructor(e){super(pt.ALIAS),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,n){if(n?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let i;n?.aliasResolveCache?i=n.aliasResolveCache:(i=[],qf.visit(e,{Node:(s,o)=>{(pt.isAlias(o)||pt.hasAnchor(o))&&i.push(o)}}),n&&(n.aliasResolveCache=i));let r;for(let s of i){if(s===this)break;s.anchor===this.source&&(r=s)}return r}toJSON(e,n){if(!n)return{source:this.source};let{anchors:i,doc:r,maxAliasCount:s}=n,o=this.resolve(r,n);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let a=i.get(o);if(a||(Df.toJS(o,null,n),a=i.get(o)),a?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(s>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=Fn(r,o,i)),a.count*a.aliasCount>s)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return a.res}toString(e,n,i){let r=`*${this.source}`;if(e){if($f.anchorIsValid(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let s=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(s)}if(e.implicitKey)return`${r} `}return r}};function Fn(t,e,n){if(pt.isAlias(e)){let i=e.resolve(t),r=n&&i&&n.get(i);return r?r.count*r.aliasCount:0}else if(pt.isCollection(e)){let i=0;for(let r of e.items){let s=Fn(t,r,n);s>i&&(i=s)}return i}else if(pt.isPair(e)){let i=Fn(t,e.key,n),r=Fn(t,e.value,n);return Math.max(i,r)}return 1}ia.Alias=Cr});var q=v(Er=>{"use strict";var Ff=N(),Mf=Dn(),Wf=Ee(),Bf=t=>!t||typeof t!="function"&&typeof t!="object",xe=class extends Mf.NodeBase{constructor(e){super(Ff.SCALAR),this.value=e}toJSON(e,n){return n?.keep?this.value:Wf.toJS(this.value,e,n)}toString(){return String(this.value)}};xe.BLOCK_FOLDED="BLOCK_FOLDED";xe.BLOCK_LITERAL="BLOCK_LITERAL";xe.PLAIN="PLAIN";xe.QUOTE_DOUBLE="QUOTE_DOUBLE";xe.QUOTE_SINGLE="QUOTE_SINGLE";Er.Scalar=xe;Er.isScalarValue=Bf});var $t=v(sa=>{"use strict";var Kf=It(),He=N(),ra=q(),Yf="tag:yaml.org,2002:";function Uf(t,e,n){if(e){let i=n.filter(s=>s.tag===e),r=i.find(s=>!s.format)??i[0];if(!r)throw new Error(`Tag ${e} not found`);return r}return n.find(i=>i.identify?.(t)&&!i.format)}function Vf(t,e,n){if(He.isDocument(t)&&(t=t.contents),He.isNode(t))return t;if(He.isPair(t)){let u=n.schema[He.MAP].createNode?.(n.schema,null,n);return u.items.push(t),u}(t instanceof String||t instanceof Number||t instanceof Boolean||typeof BigInt<"u"&&t instanceof BigInt)&&(t=t.valueOf());let{aliasDuplicateObjects:i,onAnchor:r,onTagObj:s,schema:o,sourceObjects:a}=n,c;if(i&&t&&typeof t=="object"){if(c=a.get(t),c)return c.anchor??(c.anchor=r(t)),new Kf.Alias(c.anchor);c={anchor:null,node:null},a.set(t,c)}e?.startsWith("!!")&&(e=Yf+e.slice(2));let l=Uf(t,e,o.tags);if(!l){if(t&&typeof t.toJSON=="function"&&(t=t.toJSON()),!t||typeof t!="object"){let u=new ra.Scalar(t);return c&&(c.node=u),u}l=t instanceof Map?o[He.MAP]:Symbol.iterator in Object(t)?o[He.SEQ]:o[He.MAP]}s&&(s(l),delete n.onTagObj);let d=l?.createNode?l.createNode(n.schema,t,n):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(n.schema,t,n):new ra.Scalar(t);return e?d.tag=e:l.default||(d.tag=l.tag),c&&(c.node=d),d}sa.createNode=Vf});var Wn=v(Mn=>{"use strict";var Jf=$t(),pe=N(),Hf=Dn();function xr(t,e,n){let i=n;for(let r=e.length-1;r>=0;--r){let s=e[r];if(typeof s=="number"&&Number.isInteger(s)&&s>=0){let o=[];o[s]=i,i=o}else i=new Map([[s,i]])}return Jf.createNode(i,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:t,sourceObjects:new Map})}var oa=t=>t==null||typeof t=="object"&&!!t[Symbol.iterator]().next().done,_r=class extends Hf.NodeBase{constructor(e,n){super(e),Object.defineProperty(this,"schema",{value:n,configurable:!0,enumerable:!1,writable:!0})}clone(e){let n=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(n.schema=e),n.items=n.items.map(i=>pe.isNode(i)||pe.isPair(i)?i.clone(e):i),this.range&&(n.range=this.range.slice()),n}addIn(e,n){if(oa(e))this.add(n);else{let[i,...r]=e,s=this.get(i,!0);if(pe.isCollection(s))s.addIn(r,n);else if(s===void 0&&this.schema)this.set(i,xr(this.schema,r,n));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${r}`)}}deleteIn(e){let[n,...i]=e;if(i.length===0)return this.delete(n);let r=this.get(n,!0);if(pe.isCollection(r))return r.deleteIn(i);throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}getIn(e,n){let[i,...r]=e,s=this.get(i,!0);return r.length===0?!n&&pe.isScalar(s)?s.value:s:pe.isCollection(s)?s.getIn(r,n):void 0}hasAllNullValues(e){return this.items.every(n=>{if(!pe.isPair(n))return!1;let i=n.value;return i==null||e&&pe.isScalar(i)&&i.value==null&&!i.commentBefore&&!i.comment&&!i.tag})}hasIn(e){let[n,...i]=e;if(i.length===0)return this.has(n);let r=this.get(n,!0);return pe.isCollection(r)?r.hasIn(i):!1}setIn(e,n){let[i,...r]=e;if(r.length===0)this.set(i,n);else{let s=this.get(i,!0);if(pe.isCollection(s))s.setIn(r,n);else if(s===void 0&&this.schema)this.set(i,xr(this.schema,r,n));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${r}`)}}};Mn.Collection=_r;Mn.collectionFromPath=xr;Mn.isEmptyPath=oa});var qt=v(Bn=>{"use strict";var Gf=t=>t.replace(/^(?!$)(?: $)?/gm,"#");function Pr(t,e){return/^\n+$/.test(t)?t.substring(1):e?t.replace(/^(?! *$)/gm,e):t}var zf=(t,e,n)=>t.endsWith(` +`)?Pr(n,e):n.includes(` `)?` -`+_r(n,e):(t.endsWith(" ")?"":" ")+n;Bn.indentComment=_r;Bn.lineComment=Gf;Bn.stringifyComment=Hf});var ca=v(Lt=>{"use strict";var zf="flow",Pr="block",Kn="quoted";function Qf(t,e,n="flow",{indentAtStart:i,lineWidth:r=80,minContentWidth:s=20,onFold:o,onOverflow:a}={}){if(!r||r<0)return t;rr-Math.max(2,s)?l.push(0):u=r-i);let d,h,w=!1,p=-1,m=-1,g=-1;n===Pr&&(p=aa(t,p,e.length),p!==-1&&(u=p+c));for(let k;k=t[p+=1];){if(n===Kn&&k==="\\"){switch(m=p,t[p+1]){case"x":p+=3;break;case"u":p+=5;break;case"U":p+=9;break;default:p+=1}g=p}if(k===` -`)n===Pr&&(p=aa(t,p,e.length)),u=p+e.length+c,d=void 0;else{if(k===" "&&h&&h!==" "&&h!==` +`+Pr(n,e):(t.endsWith(" ")?"":" ")+n;Bn.indentComment=Pr;Bn.lineComment=zf;Bn.stringifyComment=Gf});var ca=v(Lt=>{"use strict";var Qf="flow",Rr="block",Kn="quoted";function Xf(t,e,n="flow",{indentAtStart:i,lineWidth:r=80,minContentWidth:s=20,onFold:o,onOverflow:a}={}){if(!r||r<0)return t;rr-Math.max(2,s)?l.push(0):u=r-i);let f,h,w=!1,p=-1,m=-1,g=-1;n===Rr&&(p=aa(t,p,e.length),p!==-1&&(u=p+c));for(let k;k=t[p+=1];){if(n===Kn&&k==="\\"){switch(m=p,t[p+1]){case"x":p+=3;break;case"u":p+=5;break;case"U":p+=9;break;default:p+=1}g=p}if(k===` +`)n===Rr&&(p=aa(t,p,e.length)),u=p+e.length+c,f=void 0;else{if(k===" "&&h&&h!==" "&&h!==` `&&h!==" "){let C=t[p+1];C&&C!==" "&&C!==` -`&&C!==" "&&(d=p)}if(p>=u)if(d)l.push(d),u=d+c,d=void 0;else if(n===Kn){for(;h===" "||h===" ";)h=k,k=t[p+=1],w=!0;let C=p>g+1?p-2:m-1;if(f[C])return t;l.push(C),f[C]=!0,u=C+c,d=void 0}else w=!0}h=k}if(w&&a&&a(),l.length===0)return t;o&&o();let y=t.slice(0,l[0]);for(let k=0;k=u)if(f)l.push(f),u=f+c,f=void 0;else if(n===Kn){for(;h===" "||h===" ";)h=k,k=t[p+=1],w=!0;let C=p>g+1?p-2:m-1;if(d[C])return t;l.push(C),d[C]=!0,u=C+c,f=void 0}else w=!0}h=k}if(w&&a&&a(),l.length===0)return t;o&&o();let y=t.slice(0,l[0]);for(let k=0;k{"use strict";var ae=q(),_e=ca(),Un=(t,e)=>({indentAtStart:e?t.indent.length:t.indentAtStart,lineWidth:t.options.lineWidth,minContentWidth:t.options.minContentWidth}),Vn=t=>/^(%|---|\.\.\.)/m.test(t);function Xf(t,e,n){if(!e||e<0)return!1;let i=e-n,r=t.length;if(r<=i)return!1;for(let s=0,o=0;si)return!0;if(o=s+1,r-o<=i)return!1}return!0}function Dt(t,e){let n=JSON.stringify(t);if(e.options.doubleQuotedAsJSON)return n;let{implicitKey:i}=e,r=e.options.doubleQuotedMinMultiLineLength,s=e.indent||(Vn(t)?" ":""),o="",a=0;for(let c=0,l=n[c];l;l=n[++c])if(l===" "&&n[c+1]==="\\"&&n[c+2]==="n"&&(o+=n.slice(a,c)+"\\ ",c+=1,a=c,l="\\"),l==="\\")switch(n[c+1]){case"u":{o+=n.slice(a,c);let f=n.substr(c+2,4);switch(f){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:f.substr(0,2)==="00"?o+="\\x"+f.substr(2):o+=n.substr(c,6)}c+=5,a=c+1}break;case"n":if(i||n[c+2]==='"'||n.length{"use strict";var ae=q(),_e=ca(),Un=(t,e)=>({indentAtStart:e?t.indent.length:t.indentAtStart,lineWidth:t.options.lineWidth,minContentWidth:t.options.minContentWidth}),Vn=t=>/^(%|---|\.\.\.)/m.test(t);function Zf(t,e,n){if(!e||e<0)return!1;let i=e-n,r=t.length;if(r<=i)return!1;for(let s=0,o=0;si)return!0;if(o=s+1,r-o<=i)return!1}return!0}function Dt(t,e){let n=JSON.stringify(t);if(e.options.doubleQuotedAsJSON)return n;let{implicitKey:i}=e,r=e.options.doubleQuotedMinMultiLineLength,s=e.indent||(Vn(t)?" ":""),o="",a=0;for(let c=0,l=n[c];l;l=n[++c])if(l===" "&&n[c+1]==="\\"&&n[c+2]==="n"&&(o+=n.slice(a,c)+"\\ ",c+=1,a=c,l="\\"),l==="\\")switch(n[c+1]){case"u":{o+=n.slice(a,c);let d=n.substr(c+2,4);switch(d){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:d.substr(0,2)==="00"?o+="\\x"+d.substr(2):o+=n.substr(c,6)}c+=5,a=c+1}break;case"n":if(i||n[c+2]==='"'||n.length -`;let u,d;for(d=n.length;d>0;--d){let x=n[d-1];if(x!==` -`&&x!==" "&&x!==" ")break}let h=n.substring(d),w=h.indexOf(` +`;let u,f;for(f=n.length;f>0;--f){let x=n[f-1];if(x!==` +`&&x!==" "&&x!==" ")break}let h=n.substring(f),w=h.indexOf(` `);w===-1?u="-":n===h||w!==h.length-1?(u="+",s&&s()):u="",h&&(n=n.slice(0,-h.length),h[h.length-1]===` -`&&(h=h.slice(0,-1)),h=h.replace(Nr,`$&${l}`));let p=!1,m,g=-1;for(m=0;m{P=!0});let b=_e.foldFlowLines(`${y}${x}${h}`,l,_e.FOLD_BLOCK,j);if(!P)return`>${C} ${l}${b}`}return n=n.replace(/\n+/g,`$&${l}`),`|${C} -${l}${y}${n}${h}`}function Zf(t,e,n,i){let{type:r,value:s}=t,{actualString:o,implicitKey:a,indent:c,indentStep:l,inFlow:f}=e;if(a&&s.includes(` -`)||f&&/[[\]{},]/.test(s))return mt(s,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(s))return a||f||!s.includes(` -`)?mt(s,e):Yn(t,e,n,i);if(!a&&!f&&r!==ae.Scalar.PLAIN&&s.includes(` +${l}${y}${n}${h}`}function ed(t,e,n,i){let{type:r,value:s}=t,{actualString:o,implicitKey:a,indent:c,indentStep:l,inFlow:d}=e;if(a&&s.includes(` +`)||d&&/[[\]{},]/.test(s))return mt(s,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(s))return a||d||!s.includes(` +`)?mt(s,e):Yn(t,e,n,i);if(!a&&!d&&r!==ae.Scalar.PLAIN&&s.includes(` `))return Yn(t,e,n,i);if(Vn(s)){if(c==="")return e.forceBlockIndent=!0,Yn(t,e,n,i);if(a&&c===l)return mt(s,e)}let u=s.replace(/\n+/g,`$& -${c}`);if(o){let d=p=>p.default&&p.tag!=="tag:yaml.org,2002:str"&&p.test?.test(u),{compat:h,tags:w}=e.doc.schema;if(w.some(d)||h?.some(d))return mt(s,e)}return a?u:_e.foldFlowLines(u,c,_e.FOLD_FLOW,Un(e,!1))}function ed(t,e,n,i){let{implicitKey:r,inFlow:s}=e,o=typeof t.value=="string"?t:Object.assign({},t,{value:String(t.value)}),{type:a}=t;a!==ae.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=ae.Scalar.QUOTE_DOUBLE);let c=f=>{switch(f){case ae.Scalar.BLOCK_FOLDED:case ae.Scalar.BLOCK_LITERAL:return r||s?mt(o.value,e):Yn(o,e,n,i);case ae.Scalar.QUOTE_DOUBLE:return Dt(o.value,e);case ae.Scalar.QUOTE_SINGLE:return Rr(o.value,e);case ae.Scalar.PLAIN:return Zf(o,e,n,i);default:return null}},l=c(a);if(l===null){let{defaultKeyType:f,defaultStringType:u}=e.options,d=r&&f||u;if(l=c(d),l===null)throw new Error(`Unsupported default string type ${d}`)}return l}la.stringifyString=ed});var Mt=v(Or=>{"use strict";var td=Ln(),Pe=N(),nd=qt(),id=Ft();function rd(t,e){let n=Object.assign({blockQuote:!0,commentString:nd.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},t.schema.toStringOptions,e),i;switch(n.collectionStyle){case"block":i=!1;break;case"flow":i=!0;break;default:i=null}return{anchors:new Set,doc:t,flowCollectionPadding:n.flowCollectionPadding?" ":"",indent:"",indentStep:typeof n.indent=="number"?" ".repeat(n.indent):" ",inFlow:i,options:n}}function sd(t,e){if(e.tag){let r=t.filter(s=>s.tag===e.tag);if(r.length>0)return r.find(s=>s.format===e.format)??r[0]}let n,i;if(Pe.isScalar(e)){i=e.value;let r=t.filter(s=>s.identify?.(i));if(r.length>1){let s=r.filter(o=>o.test);s.length>0&&(r=s)}n=r.find(s=>s.format===e.format)??r.find(s=>!s.format)}else i=e,n=t.find(r=>r.nodeClass&&i instanceof r.nodeClass);if(!n){let r=i?.constructor?.name??(i===null?"null":typeof i);throw new Error(`Tag not resolved for ${r} value`)}return n}function od(t,e,{anchors:n,doc:i}){if(!i.directives)return"";let r=[],s=(Pe.isScalar(t)||Pe.isCollection(t))&&t.anchor;s&&td.anchorIsValid(s)&&(n.add(s),r.push(`&${s}`));let o=t.tag??(e.default?null:e.tag);return o&&r.push(i.directives.tagString(o)),r.join(" ")}function ad(t,e,n,i){if(Pe.isPair(t))return t.toString(e,n,i);if(Pe.isAlias(t)){if(e.doc.directives)return t.toString(e);if(e.resolvedAliases?.has(t))throw new TypeError("Cannot stringify circular structure without alias nodes");e.resolvedAliases?e.resolvedAliases.add(t):e.resolvedAliases=new Set([t]),t=t.resolve(e.doc)}let r,s=Pe.isNode(t)?t:e.doc.createNode(t,{onTagObj:c=>r=c});r??(r=sd(e.doc.schema.tags,s));let o=od(s,r,e);o.length>0&&(e.indentAtStart=(e.indentAtStart??0)+o.length+1);let a=typeof r.stringify=="function"?r.stringify(s,e,n,i):Pe.isScalar(s)?id.stringifyString(s,e,n,i):s.toString(e,n,i);return o?Pe.isScalar(s)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o} -${e.indent}${a}`:a}Or.createStringifyContext=rd;Or.stringify=ad});var pa=v(da=>{"use strict";var we=N(),ua=q(),fa=Mt(),Wt=qt();function cd({key:t,value:e},n,i,r){let{allNullValues:s,doc:o,indent:a,indentStep:c,options:{commentString:l,indentSeq:f,simpleKeys:u}}=n,d=we.isNode(t)&&t.comment||null;if(u){if(d)throw new Error("With simple keys, key nodes cannot have comments");if(we.isCollection(t)||!we.isNode(t)&&typeof t=="object"){let j="With simple keys, collection cannot be used as a key value";throw new Error(j)}}let h=!u&&(!t||d&&e==null&&!n.inFlow||we.isCollection(t)||(we.isScalar(t)?t.type===ua.Scalar.BLOCK_FOLDED||t.type===ua.Scalar.BLOCK_LITERAL:typeof t=="object"));n=Object.assign({},n,{allNullValues:!1,implicitKey:!h&&(u||!s),indent:a+c});let w=!1,p=!1,m=fa.stringify(t,n,()=>w=!0,()=>p=!0);if(!h&&!n.inFlow&&m.length>1024){if(u)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");h=!0}if(n.inFlow){if(s||e==null)return w&&i&&i(),m===""?"?":h?`? ${m}`:m}else if(s&&!u||e==null&&h)return m=`? ${m}`,d&&!w?m+=Wt.lineComment(m,n.indent,l(d)):p&&r&&r(),m;w&&(d=null),h?(d&&(m+=Wt.lineComment(m,n.indent,l(d))),m=`? ${m} -${a}:`):(m=`${m}:`,d&&(m+=Wt.lineComment(m,n.indent,l(d))));let g,y,k;we.isNode(e)?(g=!!e.spaceBefore,y=e.commentBefore,k=e.comment):(g=!1,y=null,k=null,e&&typeof e=="object"&&(e=o.createNode(e))),n.implicitKey=!1,!h&&!d&&we.isScalar(e)&&(n.indentAtStart=m.length+1),p=!1,!f&&c.length>=2&&!n.inFlow&&!h&&we.isSeq(e)&&!e.flow&&!e.tag&&!e.anchor&&(n.indent=n.indent.substring(2));let C=!1,x=fa.stringify(e,n,()=>C=!0,()=>p=!0),P=" ";if(d||g||y){if(P=g?` +${c}`);if(o){let f=p=>p.default&&p.tag!=="tag:yaml.org,2002:str"&&p.test?.test(u),{compat:h,tags:w}=e.doc.schema;if(w.some(f)||h?.some(f))return mt(s,e)}return a?u:_e.foldFlowLines(u,c,_e.FOLD_FLOW,Un(e,!1))}function td(t,e,n,i){let{implicitKey:r,inFlow:s}=e,o=typeof t.value=="string"?t:Object.assign({},t,{value:String(t.value)}),{type:a}=t;a!==ae.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=ae.Scalar.QUOTE_DOUBLE);let c=d=>{switch(d){case ae.Scalar.BLOCK_FOLDED:case ae.Scalar.BLOCK_LITERAL:return r||s?mt(o.value,e):Yn(o,e,n,i);case ae.Scalar.QUOTE_DOUBLE:return Dt(o.value,e);case ae.Scalar.QUOTE_SINGLE:return Nr(o.value,e);case ae.Scalar.PLAIN:return ed(o,e,n,i);default:return null}},l=c(a);if(l===null){let{defaultKeyType:d,defaultStringType:u}=e.options,f=r&&d||u;if(l=c(f),l===null)throw new Error(`Unsupported default string type ${f}`)}return l}la.stringifyString=td});var Mt=v(Ar=>{"use strict";var nd=Ln(),Pe=N(),id=qt(),rd=Ft();function sd(t,e){let n=Object.assign({blockQuote:!0,commentString:id.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},t.schema.toStringOptions,e),i;switch(n.collectionStyle){case"block":i=!1;break;case"flow":i=!0;break;default:i=null}return{anchors:new Set,doc:t,flowCollectionPadding:n.flowCollectionPadding?" ":"",indent:"",indentStep:typeof n.indent=="number"?" ".repeat(n.indent):" ",inFlow:i,options:n}}function od(t,e){if(e.tag){let r=t.filter(s=>s.tag===e.tag);if(r.length>0)return r.find(s=>s.format===e.format)??r[0]}let n,i;if(Pe.isScalar(e)){i=e.value;let r=t.filter(s=>s.identify?.(i));if(r.length>1){let s=r.filter(o=>o.test);s.length>0&&(r=s)}n=r.find(s=>s.format===e.format)??r.find(s=>!s.format)}else i=e,n=t.find(r=>r.nodeClass&&i instanceof r.nodeClass);if(!n){let r=i?.constructor?.name??(i===null?"null":typeof i);throw new Error(`Tag not resolved for ${r} value`)}return n}function ad(t,e,{anchors:n,doc:i}){if(!i.directives)return"";let r=[],s=(Pe.isScalar(t)||Pe.isCollection(t))&&t.anchor;s&&nd.anchorIsValid(s)&&(n.add(s),r.push(`&${s}`));let o=t.tag??(e.default?null:e.tag);return o&&r.push(i.directives.tagString(o)),r.join(" ")}function cd(t,e,n,i){if(Pe.isPair(t))return t.toString(e,n,i);if(Pe.isAlias(t)){if(e.doc.directives)return t.toString(e);if(e.resolvedAliases?.has(t))throw new TypeError("Cannot stringify circular structure without alias nodes");e.resolvedAliases?e.resolvedAliases.add(t):e.resolvedAliases=new Set([t]),t=t.resolve(e.doc)}let r,s=Pe.isNode(t)?t:e.doc.createNode(t,{onTagObj:c=>r=c});r??(r=od(e.doc.schema.tags,s));let o=ad(s,r,e);o.length>0&&(e.indentAtStart=(e.indentAtStart??0)+o.length+1);let a=typeof r.stringify=="function"?r.stringify(s,e,n,i):Pe.isScalar(s)?rd.stringifyString(s,e,n,i):s.toString(e,n,i);return o?Pe.isScalar(s)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o} +${e.indent}${a}`:a}Ar.createStringifyContext=sd;Ar.stringify=cd});var pa=v(da=>{"use strict";var we=N(),ua=q(),fa=Mt(),Wt=qt();function ld({key:t,value:e},n,i,r){let{allNullValues:s,doc:o,indent:a,indentStep:c,options:{commentString:l,indentSeq:d,simpleKeys:u}}=n,f=we.isNode(t)&&t.comment||null;if(u){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(we.isCollection(t)||!we.isNode(t)&&typeof t=="object"){let j="With simple keys, collection cannot be used as a key value";throw new Error(j)}}let h=!u&&(!t||f&&e==null&&!n.inFlow||we.isCollection(t)||(we.isScalar(t)?t.type===ua.Scalar.BLOCK_FOLDED||t.type===ua.Scalar.BLOCK_LITERAL:typeof t=="object"));n=Object.assign({},n,{allNullValues:!1,implicitKey:!h&&(u||!s),indent:a+c});let w=!1,p=!1,m=fa.stringify(t,n,()=>w=!0,()=>p=!0);if(!h&&!n.inFlow&&m.length>1024){if(u)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");h=!0}if(n.inFlow){if(s||e==null)return w&&i&&i(),m===""?"?":h?`? ${m}`:m}else if(s&&!u||e==null&&h)return m=`? ${m}`,f&&!w?m+=Wt.lineComment(m,n.indent,l(f)):p&&r&&r(),m;w&&(f=null),h?(f&&(m+=Wt.lineComment(m,n.indent,l(f))),m=`? ${m} +${a}:`):(m=`${m}:`,f&&(m+=Wt.lineComment(m,n.indent,l(f))));let g,y,k;we.isNode(e)?(g=!!e.spaceBefore,y=e.commentBefore,k=e.comment):(g=!1,y=null,k=null,e&&typeof e=="object"&&(e=o.createNode(e))),n.implicitKey=!1,!h&&!f&&we.isScalar(e)&&(n.indentAtStart=m.length+1),p=!1,!d&&c.length>=2&&!n.inFlow&&!h&&we.isSeq(e)&&!e.flow&&!e.tag&&!e.anchor&&(n.indent=n.indent.substring(2));let C=!1,x=fa.stringify(e,n,()=>C=!0,()=>p=!0),P=" ";if(f||g||y){if(P=g?` `:"",y){let j=l(y);P+=` ${Wt.indentComment(j,n.indent)}`}x===""&&!n.inFlow?P===` `&&k&&(P=` @@ -44,86 +44,86 @@ ${Wt.indentComment(j,n.indent)}`}x===""&&!n.inFlow?P===` ${n.indent}`}else if(!h&&we.isCollection(e)){let j=x[0],b=x.indexOf(` `),M=b!==-1,Ce=n.inFlow??e.flow??e.items.length===0;if(M||!Ce){let ut=!1;if(M&&(j==="&"||j==="!")){let W=x.indexOf(" ");j==="&"&&W!==-1&&W{"use strict";var ma=jn("process");function ld(t,...e){t==="debug"&&console.log(...e)}function ud(t,e){(t==="debug"||t==="warn")&&(typeof ma.emitWarning=="function"?ma.emitWarning(e):console.warn(e))}Ar.debug=ld;Ar.warn=ud});var Qn=v(zn=>{"use strict";var Gn=N(),ha=q(),Jn="<<",Hn={identify:t=>t===Jn||typeof t=="symbol"&&t.description===Jn,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new ha.Scalar(Symbol(Jn)),{addToJSMap:ga}),stringify:()=>Jn},fd=(t,e)=>(Hn.identify(e)||Gn.isScalar(e)&&(!e.type||e.type===ha.Scalar.PLAIN)&&Hn.identify(e.value))&&t?.doc.schema.tags.some(n=>n.tag===Hn.tag&&n.default);function ga(t,e,n){let i=wa(t,n);if(Gn.isSeq(i))for(let r of i.items)Tr(t,e,r);else if(Array.isArray(i))for(let r of i)Tr(t,e,r);else Tr(t,e,i)}function Tr(t,e,n){let i=wa(t,n);if(!Gn.isMap(i))throw new Error("Merge sources must be maps or map aliases");let r=i.toJSON(null,t,Map);for(let[s,o]of r)e instanceof Map?e.has(s)||e.set(s,o):e instanceof Set?e.add(s):Object.prototype.hasOwnProperty.call(e,s)||Object.defineProperty(e,s,{value:o,writable:!0,enumerable:!0,configurable:!0});return e}function wa(t,e){return t&&Gn.isAlias(e)?e.resolve(t.doc,t):e}zn.addMergeToJSMap=ga;zn.isMergeKey=fd;zn.merge=Hn});var $r=v(ba=>{"use strict";var dd=jr(),ya=Qn(),pd=Mt(),va=N(),Ir=Ee();function md(t,e,{key:n,value:i}){if(va.isNode(n)&&n.addToJSMap)n.addToJSMap(t,e,i);else if(ya.isMergeKey(t,n))ya.addMergeToJSMap(t,e,i);else{let r=Ir.toJS(n,"",t);if(e instanceof Map)e.set(r,Ir.toJS(i,r,t));else if(e instanceof Set)e.add(r);else{let s=hd(n,r,t),o=Ir.toJS(i,s,t);s in e?Object.defineProperty(e,s,{value:o,writable:!0,enumerable:!0,configurable:!0}):e[s]=o}}return e}function hd(t,e,n){if(e===null)return"";if(typeof e!="object")return String(e);if(va.isNode(t)&&n?.doc){let i=pd.createStringifyContext(n.doc,{});i.anchors=new Set;for(let s of n.anchors.keys())i.anchors.add(s.anchor);i.inFlow=!0,i.inStringifyKey=!0;let r=t.toString(i);if(!n.mapKeyWarned){let s=JSON.stringify(r);s.length>40&&(s=s.substring(0,36)+'..."'),dd.warn(n.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${s}. Set mapAsMap: true to use object keys.`),n.mapKeyWarned=!0}return r}return JSON.stringify(e)}ba.addPairToJSMap=md});var Re=v(qr=>{"use strict";var ka=$t(),gd=pa(),wd=$r(),Xn=N();function yd(t,e,n){let i=ka.createNode(t,void 0,n),r=ka.createNode(e,void 0,n);return new Zn(i,r)}var Zn=class t{constructor(e,n=null){Object.defineProperty(this,Xn.NODE_TYPE,{value:Xn.PAIR}),this.key=e,this.value=n}clone(e){let{key:n,value:i}=this;return Xn.isNode(n)&&(n=n.clone(e)),Xn.isNode(i)&&(i=i.clone(e)),new t(n,i)}toJSON(e,n){let i=n?.mapAsMap?new Map:{};return wd.addPairToJSMap(n,i,this)}toString(e,n,i){return e?.doc?gd.stringifyPair(this,e,n,i):JSON.stringify(this)}};qr.Pair=Zn;qr.createPair=yd});var Lr=v(Ca=>{"use strict";var He=N(),Sa=Mt(),ei=qt();function vd(t,e,n){return(e.inFlow??t.flow?kd:bd)(t,e,n)}function bd({comment:t,items:e},n,{blockItemPrefix:i,flowChars:r,itemIndent:s,onChompKeep:o,onComment:a}){let{indent:c,options:{commentString:l}}=n,f=Object.assign({},n,{indent:s,type:null}),u=!1,d=[];for(let w=0;wm=null,()=>u=!0);m&&(g+=ei.lineComment(g,s,l(m))),u&&m&&(u=!1),d.push(i+g)}let h;if(d.length===0)h=r.start+r.end;else{h=d[0];for(let w=1;w{"use strict";var ma=jn("process");function ud(t,...e){t==="debug"&&console.log(...e)}function fd(t,e){(t==="debug"||t==="warn")&&(typeof ma.emitWarning=="function"?ma.emitWarning(e):console.warn(e))}jr.debug=ud;jr.warn=fd});var Qn=v(zn=>{"use strict";var Gn=N(),ha=q(),Jn="<<",Hn={identify:t=>t===Jn||typeof t=="symbol"&&t.description===Jn,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new ha.Scalar(Symbol(Jn)),{addToJSMap:ga}),stringify:()=>Jn},dd=(t,e)=>(Hn.identify(e)||Gn.isScalar(e)&&(!e.type||e.type===ha.Scalar.PLAIN)&&Hn.identify(e.value))&&t?.doc.schema.tags.some(n=>n.tag===Hn.tag&&n.default);function ga(t,e,n){let i=wa(t,n);if(Gn.isSeq(i))for(let r of i.items)Ir(t,e,r);else if(Array.isArray(i))for(let r of i)Ir(t,e,r);else Ir(t,e,i)}function Ir(t,e,n){let i=wa(t,n);if(!Gn.isMap(i))throw new Error("Merge sources must be maps or map aliases");let r=i.toJSON(null,t,Map);for(let[s,o]of r)e instanceof Map?e.has(s)||e.set(s,o):e instanceof Set?e.add(s):Object.prototype.hasOwnProperty.call(e,s)||Object.defineProperty(e,s,{value:o,writable:!0,enumerable:!0,configurable:!0});return e}function wa(t,e){return t&&Gn.isAlias(e)?e.resolve(t.doc,t):e}zn.addMergeToJSMap=ga;zn.isMergeKey=dd;zn.merge=Hn});var qr=v(ba=>{"use strict";var pd=Tr(),ya=Qn(),md=Mt(),va=N(),$r=Ee();function hd(t,e,{key:n,value:i}){if(va.isNode(n)&&n.addToJSMap)n.addToJSMap(t,e,i);else if(ya.isMergeKey(t,n))ya.addMergeToJSMap(t,e,i);else{let r=$r.toJS(n,"",t);if(e instanceof Map)e.set(r,$r.toJS(i,r,t));else if(e instanceof Set)e.add(r);else{let s=gd(n,r,t),o=$r.toJS(i,s,t);s in e?Object.defineProperty(e,s,{value:o,writable:!0,enumerable:!0,configurable:!0}):e[s]=o}}return e}function gd(t,e,n){if(e===null)return"";if(typeof e!="object")return String(e);if(va.isNode(t)&&n?.doc){let i=md.createStringifyContext(n.doc,{});i.anchors=new Set;for(let s of n.anchors.keys())i.anchors.add(s.anchor);i.inFlow=!0,i.inStringifyKey=!0;let r=t.toString(i);if(!n.mapKeyWarned){let s=JSON.stringify(r);s.length>40&&(s=s.substring(0,36)+'..."'),pd.warn(n.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${s}. Set mapAsMap: true to use object keys.`),n.mapKeyWarned=!0}return r}return JSON.stringify(e)}ba.addPairToJSMap=hd});var Re=v(Lr=>{"use strict";var ka=$t(),wd=pa(),yd=qr(),Xn=N();function vd(t,e,n){let i=ka.createNode(t,void 0,n),r=ka.createNode(e,void 0,n);return new Zn(i,r)}var Zn=class t{constructor(e,n=null){Object.defineProperty(this,Xn.NODE_TYPE,{value:Xn.PAIR}),this.key=e,this.value=n}clone(e){let{key:n,value:i}=this;return Xn.isNode(n)&&(n=n.clone(e)),Xn.isNode(i)&&(i=i.clone(e)),new t(n,i)}toJSON(e,n){let i=n?.mapAsMap?new Map:{};return yd.addPairToJSMap(n,i,this)}toString(e,n,i){return e?.doc?wd.stringifyPair(this,e,n,i):JSON.stringify(this)}};Lr.Pair=Zn;Lr.createPair=vd});var Dr=v(Ca=>{"use strict";var Ge=N(),Sa=Mt(),ei=qt();function bd(t,e,n){return(e.inFlow??t.flow?Sd:kd)(t,e,n)}function kd({comment:t,items:e},n,{blockItemPrefix:i,flowChars:r,itemIndent:s,onChompKeep:o,onComment:a}){let{indent:c,options:{commentString:l}}=n,d=Object.assign({},n,{indent:s,type:null}),u=!1,f=[];for(let w=0;wm=null,()=>u=!0);m&&(g+=ei.lineComment(g,s,l(m))),u&&m&&(u=!1),f.push(i+g)}let h;if(f.length===0)h=r.start+r.end;else{h=f[0];for(let w=1;wm=null);l||(l=u.length>f||g.includes(` -`)),w0&&(l||(l=u.reduce((y,k)=>y+k.length+2,2)+(g.length+2)>e.options.lineWidth)),l&&(g+=",")),m&&(g+=ei.lineComment(g,i,a(m))),u.push(g),f=u.length}let{start:d,end:h}=n;if(u.length===0)return d+h;if(!l){let w=u.reduce((p,m)=>p+m.length+2,2);l=e.options.lineWidth>0&&w>e.options.lineWidth}if(l){let w=d;for(let p of u)w+=p?` +`+ei.indentComment(l(t),c),a&&a()):u&&o&&o(),h}function Sd({items:t},e,{flowChars:n,itemIndent:i}){let{indent:r,indentStep:s,flowCollectionPadding:o,options:{commentString:a}}=e;i+=s;let c=Object.assign({},e,{indent:i,inFlow:!0,type:null}),l=!1,d=0,u=[];for(let w=0;wm=null);l||(l=u.length>d||g.includes(` +`)),w0&&(l||(l=u.reduce((y,k)=>y+k.length+2,2)+(g.length+2)>e.options.lineWidth)),l&&(g+=",")),m&&(g+=ei.lineComment(g,i,a(m))),u.push(g),d=u.length}let{start:f,end:h}=n;if(u.length===0)return f+h;if(!l){let w=u.reduce((p,m)=>p+m.length+2,2);l=e.options.lineWidth>0&&w>e.options.lineWidth}if(l){let w=f;for(let p of u)w+=p?` ${s}${r}${p}`:` `;return`${w} -${r}${h}`}else return`${d}${o}${u.join(" ")}${o}${h}`}function ti({indent:t,options:{commentString:e}},n,i,r){if(i&&r&&(i=i.replace(/^\n+/,"")),i){let s=ei.indentComment(e(i),t);n.push(s.trimStart())}}Ca.stringifyCollection=vd});var Oe=v(Fr=>{"use strict";var Sd=Lr(),Cd=$r(),Ed=Wn(),Ne=N(),ni=Re(),xd=q();function Bt(t,e){let n=Ne.isScalar(e)?e.value:e;for(let i of t)if(Ne.isPair(i)&&(i.key===e||i.key===n||Ne.isScalar(i.key)&&i.key.value===n))return i}var Dr=class extends Ed.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(Ne.MAP,e),this.items=[]}static from(e,n,i){let{keepUndefined:r,replacer:s}=i,o=new this(e),a=(c,l)=>{if(typeof s=="function")l=s.call(n,c,l);else if(Array.isArray(s)&&!s.includes(c))return;(l!==void 0||r)&&o.items.push(ni.createPair(c,l,i))};if(n instanceof Map)for(let[c,l]of n)a(c,l);else if(n&&typeof n=="object")for(let c of Object.keys(n))a(c,n[c]);return typeof e.sortMapEntries=="function"&&o.items.sort(e.sortMapEntries),o}add(e,n){let i;Ne.isPair(e)?i=e:!e||typeof e!="object"||!("key"in e)?i=new ni.Pair(e,e?.value):i=new ni.Pair(e.key,e.value);let r=Bt(this.items,i.key),s=this.schema?.sortMapEntries;if(r){if(!n)throw new Error(`Key ${i.key} already set`);Ne.isScalar(r.value)&&xd.isScalarValue(i.value)?r.value.value=i.value:r.value=i.value}else if(s){let o=this.items.findIndex(a=>s(i,a)<0);o===-1?this.items.push(i):this.items.splice(o,0,i)}else this.items.push(i)}delete(e){let n=Bt(this.items,e);return n?this.items.splice(this.items.indexOf(n),1).length>0:!1}get(e,n){let r=Bt(this.items,e)?.value;return(!n&&Ne.isScalar(r)?r.value:r)??void 0}has(e){return!!Bt(this.items,e)}set(e,n){this.add(new ni.Pair(e,n),!0)}toJSON(e,n,i){let r=i?new i:n?.mapAsMap?new Map:{};n?.onCreate&&n.onCreate(r);for(let s of this.items)Cd.addPairToJSMap(n,r,s);return r}toString(e,n,i){if(!e)return JSON.stringify(this);for(let r of this.items)if(!Ne.isPair(r))throw new Error(`Map items must all be pairs; found ${JSON.stringify(r)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),Sd.stringifyCollection(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:i,onComment:n})}};Fr.YAMLMap=Dr;Fr.findPair=Bt});var ht=v(xa=>{"use strict";var _d=N(),Ea=Oe(),Pd={collection:"map",default:!0,nodeClass:Ea.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(t,e){return _d.isMap(t)||e("Expected a mapping for this tag"),t},createNode:(t,e,n)=>Ea.YAMLMap.from(t,e,n)};xa.map=Pd});var Ae=v(_a=>{"use strict";var Rd=$t(),Nd=Lr(),Od=Wn(),ri=N(),Ad=q(),jd=Ee(),Mr=class extends Od.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(ri.SEQ,e),this.items=[]}add(e){this.items.push(e)}delete(e){let n=ii(e);return typeof n!="number"?!1:this.items.splice(n,1).length>0}get(e,n){let i=ii(e);if(typeof i!="number")return;let r=this.items[i];return!n&&ri.isScalar(r)?r.value:r}has(e){let n=ii(e);return typeof n=="number"&&n=0?e:null}_a.YAMLSeq=Mr});var gt=v(Ra=>{"use strict";var Td=N(),Pa=Ae(),Id={collection:"seq",default:!0,nodeClass:Pa.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(t,e){return Td.isSeq(t)||e("Expected a sequence for this tag"),t},createNode:(t,e,n)=>Pa.YAMLSeq.from(t,e,n)};Ra.seq=Id});var Kt=v(Na=>{"use strict";var $d=Ft(),qd={identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify(t,e,n,i){return e=Object.assign({actualString:!0},e),$d.stringifyString(t,e,n,i)}};Na.string=qd});var si=v(ja=>{"use strict";var Oa=q(),Aa={identify:t=>t==null,createNode:()=>new Oa.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Oa.Scalar(null),stringify:({source:t},e)=>typeof t=="string"&&Aa.test.test(t)?t:e.options.nullStr};ja.nullTag=Aa});var Wr=v(Ia=>{"use strict";var Ld=q(),Ta={identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:t=>new Ld.Scalar(t[0]==="t"||t[0]==="T"),stringify({source:t,value:e},n){if(t&&Ta.test.test(t)){let i=t[0]==="t"||t[0]==="T";if(e===i)return t}return e?n.options.trueStr:n.options.falseStr}};Ia.boolTag=Ta});var wt=v($a=>{"use strict";function Dd({format:t,minFractionDigits:e,tag:n,value:i}){if(typeof i=="bigint")return String(i);let r=typeof i=="number"?i:Number(i);if(!isFinite(r))return isNaN(r)?".nan":r<0?"-.inf":".inf";let s=Object.is(i,-0)?"-0":JSON.stringify(i);if(!t&&e&&(!n||n==="tag:yaml.org,2002:float")&&/^-?\d/.test(s)&&!s.includes("e")){let o=s.indexOf(".");o<0&&(o=s.length,s+=".");let a=e-(s.length-o-1);for(;a-- >0;)s+="0"}return s}$a.stringifyNumber=Dd});var Kr=v(oi=>{"use strict";var Fd=q(),Br=wt(),Md={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:t=>t.slice(-3).toLowerCase()==="nan"?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Br.stringifyNumber},Wd={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t),stringify(t){let e=Number(t.value);return isFinite(e)?e.toExponential():Br.stringifyNumber(t)}},Bd={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(t){let e=new Fd.Scalar(parseFloat(t)),n=t.indexOf(".");return n!==-1&&t[t.length-1]==="0"&&(e.minFractionDigits=t.length-n-1),e},stringify:Br.stringifyNumber};oi.float=Bd;oi.floatExp=Wd;oi.floatNaN=Md});var Ur=v(ci=>{"use strict";var qa=wt(),ai=t=>typeof t=="bigint"||Number.isInteger(t),Yr=(t,e,n,{intAsBigInt:i})=>i?BigInt(t):parseInt(t.substring(e),n);function La(t,e,n){let{value:i}=t;return ai(i)&&i>=0?n+i.toString(e):qa.stringifyNumber(t)}var Kd={identify:t=>ai(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(t,e,n)=>Yr(t,2,8,n),stringify:t=>La(t,8,"0o")},Yd={identify:ai,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(t,e,n)=>Yr(t,0,10,n),stringify:qa.stringifyNumber},Ud={identify:t=>ai(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(t,e,n)=>Yr(t,2,16,n),stringify:t=>La(t,16,"0x")};ci.int=Yd;ci.intHex=Ud;ci.intOct=Kd});var Fa=v(Da=>{"use strict";var Vd=ht(),Jd=si(),Hd=gt(),Gd=Kt(),zd=Wr(),Vr=Kr(),Jr=Ur(),Qd=[Vd.map,Hd.seq,Gd.string,Jd.nullTag,zd.boolTag,Jr.intOct,Jr.int,Jr.intHex,Vr.floatNaN,Vr.floatExp,Vr.float];Da.schema=Qd});var Ba=v(Wa=>{"use strict";var Xd=q(),Zd=ht(),ep=gt();function Ma(t){return typeof t=="bigint"||Number.isInteger(t)}var li=({value:t})=>JSON.stringify(t),tp=[{identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify:li},{identify:t=>t==null,createNode:()=>new Xd.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:li},{identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:t=>t==="true",stringify:li},{identify:Ma,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(t,e,{intAsBigInt:n})=>n?BigInt(t):parseInt(t,10),stringify:({value:t})=>Ma(t)?t.toString():JSON.stringify(t)},{identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:t=>parseFloat(t),stringify:li}],np={default:!0,tag:"",test:/^/,resolve(t,e){return e(`Unresolved plain scalar ${JSON.stringify(t)}`),t}},ip=[Zd.map,ep.seq].concat(tp,np);Wa.schema=ip});var Gr=v(Ka=>{"use strict";var Yt=jn("buffer"),Hr=q(),rp=Ft(),sp={identify:t=>t instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(t,e){if(typeof Yt.Buffer=="function")return Yt.Buffer.from(t,"base64");if(typeof atob=="function"){let n=atob(t.replace(/[\n\r]/g,"")),i=new Uint8Array(n.length);for(let r=0;r{"use strict";var ui=N(),zr=Re(),op=q(),ap=Ae();function Ya(t,e){if(ui.isSeq(t))for(let n=0;n1&&e("Each pair must have its own sequence indicator");let r=i.items[0]||new zr.Pair(new op.Scalar(null));if(i.commentBefore&&(r.key.commentBefore=r.key.commentBefore?`${i.commentBefore} +${r}${h}`}else return`${f}${o}${u.join(" ")}${o}${h}`}function ti({indent:t,options:{commentString:e}},n,i,r){if(i&&r&&(i=i.replace(/^\n+/,"")),i){let s=ei.indentComment(e(i),t);n.push(s.trimStart())}}Ca.stringifyCollection=bd});var Oe=v(Mr=>{"use strict";var Cd=Dr(),Ed=qr(),xd=Wn(),Ne=N(),ni=Re(),_d=q();function Bt(t,e){let n=Ne.isScalar(e)?e.value:e;for(let i of t)if(Ne.isPair(i)&&(i.key===e||i.key===n||Ne.isScalar(i.key)&&i.key.value===n))return i}var Fr=class extends xd.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(Ne.MAP,e),this.items=[]}static from(e,n,i){let{keepUndefined:r,replacer:s}=i,o=new this(e),a=(c,l)=>{if(typeof s=="function")l=s.call(n,c,l);else if(Array.isArray(s)&&!s.includes(c))return;(l!==void 0||r)&&o.items.push(ni.createPair(c,l,i))};if(n instanceof Map)for(let[c,l]of n)a(c,l);else if(n&&typeof n=="object")for(let c of Object.keys(n))a(c,n[c]);return typeof e.sortMapEntries=="function"&&o.items.sort(e.sortMapEntries),o}add(e,n){let i;Ne.isPair(e)?i=e:!e||typeof e!="object"||!("key"in e)?i=new ni.Pair(e,e?.value):i=new ni.Pair(e.key,e.value);let r=Bt(this.items,i.key),s=this.schema?.sortMapEntries;if(r){if(!n)throw new Error(`Key ${i.key} already set`);Ne.isScalar(r.value)&&_d.isScalarValue(i.value)?r.value.value=i.value:r.value=i.value}else if(s){let o=this.items.findIndex(a=>s(i,a)<0);o===-1?this.items.push(i):this.items.splice(o,0,i)}else this.items.push(i)}delete(e){let n=Bt(this.items,e);return n?this.items.splice(this.items.indexOf(n),1).length>0:!1}get(e,n){let r=Bt(this.items,e)?.value;return(!n&&Ne.isScalar(r)?r.value:r)??void 0}has(e){return!!Bt(this.items,e)}set(e,n){this.add(new ni.Pair(e,n),!0)}toJSON(e,n,i){let r=i?new i:n?.mapAsMap?new Map:{};n?.onCreate&&n.onCreate(r);for(let s of this.items)Ed.addPairToJSMap(n,r,s);return r}toString(e,n,i){if(!e)return JSON.stringify(this);for(let r of this.items)if(!Ne.isPair(r))throw new Error(`Map items must all be pairs; found ${JSON.stringify(r)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),Cd.stringifyCollection(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:i,onComment:n})}};Mr.YAMLMap=Fr;Mr.findPair=Bt});var ht=v(xa=>{"use strict";var Pd=N(),Ea=Oe(),Rd={collection:"map",default:!0,nodeClass:Ea.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(t,e){return Pd.isMap(t)||e("Expected a mapping for this tag"),t},createNode:(t,e,n)=>Ea.YAMLMap.from(t,e,n)};xa.map=Rd});var Ae=v(_a=>{"use strict";var Nd=$t(),Od=Dr(),Ad=Wn(),ri=N(),jd=q(),Td=Ee(),Wr=class extends Ad.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(ri.SEQ,e),this.items=[]}add(e){this.items.push(e)}delete(e){let n=ii(e);return typeof n!="number"?!1:this.items.splice(n,1).length>0}get(e,n){let i=ii(e);if(typeof i!="number")return;let r=this.items[i];return!n&&ri.isScalar(r)?r.value:r}has(e){let n=ii(e);return typeof n=="number"&&n=0?e:null}_a.YAMLSeq=Wr});var gt=v(Ra=>{"use strict";var Id=N(),Pa=Ae(),$d={collection:"seq",default:!0,nodeClass:Pa.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(t,e){return Id.isSeq(t)||e("Expected a sequence for this tag"),t},createNode:(t,e,n)=>Pa.YAMLSeq.from(t,e,n)};Ra.seq=$d});var Kt=v(Na=>{"use strict";var qd=Ft(),Ld={identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify(t,e,n,i){return e=Object.assign({actualString:!0},e),qd.stringifyString(t,e,n,i)}};Na.string=Ld});var si=v(ja=>{"use strict";var Oa=q(),Aa={identify:t=>t==null,createNode:()=>new Oa.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Oa.Scalar(null),stringify:({source:t},e)=>typeof t=="string"&&Aa.test.test(t)?t:e.options.nullStr};ja.nullTag=Aa});var Br=v(Ia=>{"use strict";var Dd=q(),Ta={identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:t=>new Dd.Scalar(t[0]==="t"||t[0]==="T"),stringify({source:t,value:e},n){if(t&&Ta.test.test(t)){let i=t[0]==="t"||t[0]==="T";if(e===i)return t}return e?n.options.trueStr:n.options.falseStr}};Ia.boolTag=Ta});var wt=v($a=>{"use strict";function Fd({format:t,minFractionDigits:e,tag:n,value:i}){if(typeof i=="bigint")return String(i);let r=typeof i=="number"?i:Number(i);if(!isFinite(r))return isNaN(r)?".nan":r<0?"-.inf":".inf";let s=Object.is(i,-0)?"-0":JSON.stringify(i);if(!t&&e&&(!n||n==="tag:yaml.org,2002:float")&&/^-?\d/.test(s)&&!s.includes("e")){let o=s.indexOf(".");o<0&&(o=s.length,s+=".");let a=e-(s.length-o-1);for(;a-- >0;)s+="0"}return s}$a.stringifyNumber=Fd});var Yr=v(oi=>{"use strict";var Md=q(),Kr=wt(),Wd={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:t=>t.slice(-3).toLowerCase()==="nan"?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Kr.stringifyNumber},Bd={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t),stringify(t){let e=Number(t.value);return isFinite(e)?e.toExponential():Kr.stringifyNumber(t)}},Kd={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(t){let e=new Md.Scalar(parseFloat(t)),n=t.indexOf(".");return n!==-1&&t[t.length-1]==="0"&&(e.minFractionDigits=t.length-n-1),e},stringify:Kr.stringifyNumber};oi.float=Kd;oi.floatExp=Bd;oi.floatNaN=Wd});var Vr=v(ci=>{"use strict";var qa=wt(),ai=t=>typeof t=="bigint"||Number.isInteger(t),Ur=(t,e,n,{intAsBigInt:i})=>i?BigInt(t):parseInt(t.substring(e),n);function La(t,e,n){let{value:i}=t;return ai(i)&&i>=0?n+i.toString(e):qa.stringifyNumber(t)}var Yd={identify:t=>ai(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(t,e,n)=>Ur(t,2,8,n),stringify:t=>La(t,8,"0o")},Ud={identify:ai,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(t,e,n)=>Ur(t,0,10,n),stringify:qa.stringifyNumber},Vd={identify:t=>ai(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(t,e,n)=>Ur(t,2,16,n),stringify:t=>La(t,16,"0x")};ci.int=Ud;ci.intHex=Vd;ci.intOct=Yd});var Fa=v(Da=>{"use strict";var Jd=ht(),Hd=si(),Gd=gt(),zd=Kt(),Qd=Br(),Jr=Yr(),Hr=Vr(),Xd=[Jd.map,Gd.seq,zd.string,Hd.nullTag,Qd.boolTag,Hr.intOct,Hr.int,Hr.intHex,Jr.floatNaN,Jr.floatExp,Jr.float];Da.schema=Xd});var Ba=v(Wa=>{"use strict";var Zd=q(),ep=ht(),tp=gt();function Ma(t){return typeof t=="bigint"||Number.isInteger(t)}var li=({value:t})=>JSON.stringify(t),np=[{identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify:li},{identify:t=>t==null,createNode:()=>new Zd.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:li},{identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:t=>t==="true",stringify:li},{identify:Ma,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(t,e,{intAsBigInt:n})=>n?BigInt(t):parseInt(t,10),stringify:({value:t})=>Ma(t)?t.toString():JSON.stringify(t)},{identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:t=>parseFloat(t),stringify:li}],ip={default:!0,tag:"",test:/^/,resolve(t,e){return e(`Unresolved plain scalar ${JSON.stringify(t)}`),t}},rp=[ep.map,tp.seq].concat(np,ip);Wa.schema=rp});var zr=v(Ka=>{"use strict";var Yt=jn("buffer"),Gr=q(),sp=Ft(),op={identify:t=>t instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(t,e){if(typeof Yt.Buffer=="function")return Yt.Buffer.from(t,"base64");if(typeof atob=="function"){let n=atob(t.replace(/[\n\r]/g,"")),i=new Uint8Array(n.length);for(let r=0;r{"use strict";var ui=N(),Qr=Re(),ap=q(),cp=Ae();function Ya(t,e){if(ui.isSeq(t))for(let n=0;n1&&e("Each pair must have its own sequence indicator");let r=i.items[0]||new Qr.Pair(new ap.Scalar(null));if(i.commentBefore&&(r.key.commentBefore=r.key.commentBefore?`${i.commentBefore} ${r.key.commentBefore}`:i.commentBefore),i.comment){let s=r.value??r.key;s.comment=s.comment?`${i.comment} -${s.comment}`:i.comment}i=r}t.items[n]=ui.isPair(i)?i:new zr.Pair(i)}}else e("Expected a sequence for this tag");return t}function Ua(t,e,n){let{replacer:i}=n,r=new ap.YAMLSeq(t);r.tag="tag:yaml.org,2002:pairs";let s=0;if(e&&Symbol.iterator in Object(e))for(let o of e){typeof i=="function"&&(o=i.call(e,String(s++),o));let a,c;if(Array.isArray(o))if(o.length===2)a=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)a=l[0],c=o[a];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else a=o;r.items.push(zr.createPair(a,c,n))}return r}var cp={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Ya,createNode:Ua};fi.createPairs=Ua;fi.pairs=cp;fi.resolvePairs=Ya});var Zr=v(Xr=>{"use strict";var Va=N(),Qr=Ee(),Ut=Oe(),lp=Ae(),Ja=di(),Ge=class t extends lp.YAMLSeq{constructor(){super(),this.add=Ut.YAMLMap.prototype.add.bind(this),this.delete=Ut.YAMLMap.prototype.delete.bind(this),this.get=Ut.YAMLMap.prototype.get.bind(this),this.has=Ut.YAMLMap.prototype.has.bind(this),this.set=Ut.YAMLMap.prototype.set.bind(this),this.tag=t.tag}toJSON(e,n){if(!n)return super.toJSON(e);let i=new Map;n?.onCreate&&n.onCreate(i);for(let r of this.items){let s,o;if(Va.isPair(r)?(s=Qr.toJS(r.key,"",n),o=Qr.toJS(r.value,s,n)):s=Qr.toJS(r,"",n),i.has(s))throw new Error("Ordered maps must not include duplicate keys");i.set(s,o)}return i}static from(e,n,i){let r=Ja.createPairs(e,n,i),s=new this;return s.items=r.items,s}};Ge.tag="tag:yaml.org,2002:omap";var up={collection:"seq",identify:t=>t instanceof Map,nodeClass:Ge,default:!1,tag:"tag:yaml.org,2002:omap",resolve(t,e){let n=Ja.resolvePairs(t,e),i=[];for(let{key:r}of n.items)Va.isScalar(r)&&(i.includes(r.value)?e(`Ordered maps must not include duplicate keys: ${r.value}`):i.push(r.value));return Object.assign(new Ge,n)},createNode:(t,e,n)=>Ge.from(t,e,n)};Xr.YAMLOMap=Ge;Xr.omap=up});var Xa=v(es=>{"use strict";var Ha=q();function Ga({value:t,source:e},n){return e&&(t?za:Qa).test.test(e)?e:t?n.options.trueStr:n.options.falseStr}var za={identify:t=>t===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new Ha.Scalar(!0),stringify:Ga},Qa={identify:t=>t===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new Ha.Scalar(!1),stringify:Ga};es.falseTag=Qa;es.trueTag=za});var Za=v(pi=>{"use strict";var fp=q(),ts=wt(),dp={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:t=>t.slice(-3).toLowerCase()==="nan"?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:ts.stringifyNumber},pp={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t.replace(/_/g,"")),stringify(t){let e=Number(t.value);return isFinite(e)?e.toExponential():ts.stringifyNumber(t)}},mp={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(t){let e=new fp.Scalar(parseFloat(t.replace(/_/g,""))),n=t.indexOf(".");if(n!==-1){let i=t.substring(n+1).replace(/_/g,"");i[i.length-1]==="0"&&(e.minFractionDigits=i.length)}return e},stringify:ts.stringifyNumber};pi.float=mp;pi.floatExp=pp;pi.floatNaN=dp});var tc=v(Jt=>{"use strict";var ec=wt(),Vt=t=>typeof t=="bigint"||Number.isInteger(t);function mi(t,e,n,{intAsBigInt:i}){let r=t[0];if((r==="-"||r==="+")&&(e+=1),t=t.substring(e).replace(/_/g,""),i){switch(n){case 2:t=`0b${t}`;break;case 8:t=`0o${t}`;break;case 16:t=`0x${t}`;break}let o=BigInt(t);return r==="-"?BigInt(-1)*o:o}let s=parseInt(t,n);return r==="-"?-1*s:s}function ns(t,e,n){let{value:i}=t;if(Vt(i)){let r=i.toString(e);return i<0?"-"+n+r.substr(1):n+r}return ec.stringifyNumber(t)}var hp={identify:Vt,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(t,e,n)=>mi(t,2,2,n),stringify:t=>ns(t,2,"0b")},gp={identify:Vt,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(t,e,n)=>mi(t,1,8,n),stringify:t=>ns(t,8,"0")},wp={identify:Vt,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(t,e,n)=>mi(t,0,10,n),stringify:ec.stringifyNumber},yp={identify:Vt,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(t,e,n)=>mi(t,2,16,n),stringify:t=>ns(t,16,"0x")};Jt.int=wp;Jt.intBin=hp;Jt.intHex=yp;Jt.intOct=gp});var rs=v(is=>{"use strict";var wi=N(),hi=Re(),gi=Oe(),ze=class t extends gi.YAMLMap{constructor(e){super(e),this.tag=t.tag}add(e){let n;wi.isPair(e)?n=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?n=new hi.Pair(e.key,null):n=new hi.Pair(e,null),gi.findPair(this.items,n.key)||this.items.push(n)}get(e,n){let i=gi.findPair(this.items,e);return!n&&wi.isPair(i)?wi.isScalar(i.key)?i.key.value:i.key:i}set(e,n){if(typeof n!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof n}`);let i=gi.findPair(this.items,e);i&&!n?this.items.splice(this.items.indexOf(i),1):!i&&n&&this.items.push(new hi.Pair(e))}toJSON(e,n){return super.toJSON(e,n,Set)}toString(e,n,i){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),n,i);throw new Error("Set items must all have null values")}static from(e,n,i){let{replacer:r}=i,s=new this(e);if(n&&Symbol.iterator in Object(n))for(let o of n)typeof r=="function"&&(o=r.call(n,o,o)),s.items.push(hi.createPair(o,null,i));return s}};ze.tag="tag:yaml.org,2002:set";var vp={collection:"map",identify:t=>t instanceof Set,nodeClass:ze,default:!1,tag:"tag:yaml.org,2002:set",createNode:(t,e,n)=>ze.from(t,e,n),resolve(t,e){if(wi.isMap(t)){if(t.hasAllNullValues(!0))return Object.assign(new ze,t);e("Set items must all have null values")}else e("Expected a mapping for this tag");return t}};is.YAMLSet=ze;is.set=vp});var os=v(yi=>{"use strict";var bp=wt();function ss(t,e){let n=t[0],i=n==="-"||n==="+"?t.substring(1):t,r=o=>e?BigInt(o):Number(o),s=i.replace(/_/g,"").split(":").reduce((o,a)=>o*r(60)+r(a),r(0));return n==="-"?r(-1)*s:s}function nc(t){let{value:e}=t,n=o=>o;if(typeof e=="bigint")n=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return bp.stringifyNumber(t);let i="";e<0&&(i="-",e*=n(-1));let r=n(60),s=[e%r];return e<60?s.unshift(0):(e=(e-s[0])/r,s.unshift(e%r),e>=60&&(e=(e-s[0])/r,s.unshift(e))),i+s.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var kp={identify:t=>typeof t=="bigint"||Number.isInteger(t),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(t,e,{intAsBigInt:n})=>ss(t,n),stringify:nc},Sp={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:t=>ss(t,!1),stringify:nc},ic={identify:t=>t instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(t){let e=t.match(ic.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,n,i,r,s,o,a]=e.map(Number),c=e[7]?Number((e[7]+"00").substr(1,3)):0,l=Date.UTC(n,i-1,r,s||0,o||0,a||0,c),f=e[8];if(f&&f!=="Z"){let u=ss(f,!1);Math.abs(u)<30&&(u*=60),l-=6e4*u}return new Date(l)},stringify:({value:t})=>t?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};yi.floatTime=Sp;yi.intTime=kp;yi.timestamp=ic});var oc=v(sc=>{"use strict";var Cp=ht(),Ep=si(),xp=gt(),_p=Kt(),Pp=Gr(),rc=Xa(),as=Za(),vi=tc(),Rp=Qn(),Np=Zr(),Op=di(),Ap=rs(),cs=os(),jp=[Cp.map,xp.seq,_p.string,Ep.nullTag,rc.trueTag,rc.falseTag,vi.intBin,vi.intOct,vi.int,vi.intHex,as.floatNaN,as.floatExp,as.float,Pp.binary,Rp.merge,Np.omap,Op.pairs,Ap.set,cs.intTime,cs.floatTime,cs.timestamp];sc.schema=jp});var gc=v(fs=>{"use strict";var uc=ht(),Tp=si(),fc=gt(),Ip=Kt(),$p=Wr(),ls=Kr(),us=Ur(),qp=Fa(),Lp=Ba(),dc=Gr(),Ht=Qn(),pc=Zr(),mc=di(),ac=oc(),hc=rs(),bi=os(),cc=new Map([["core",qp.schema],["failsafe",[uc.map,fc.seq,Ip.string]],["json",Lp.schema],["yaml11",ac.schema],["yaml-1.1",ac.schema]]),lc={binary:dc.binary,bool:$p.boolTag,float:ls.float,floatExp:ls.floatExp,floatNaN:ls.floatNaN,floatTime:bi.floatTime,int:us.int,intHex:us.intHex,intOct:us.intOct,intTime:bi.intTime,map:uc.map,merge:Ht.merge,null:Tp.nullTag,omap:pc.omap,pairs:mc.pairs,seq:fc.seq,set:hc.set,timestamp:bi.timestamp},Dp={"tag:yaml.org,2002:binary":dc.binary,"tag:yaml.org,2002:merge":Ht.merge,"tag:yaml.org,2002:omap":pc.omap,"tag:yaml.org,2002:pairs":mc.pairs,"tag:yaml.org,2002:set":hc.set,"tag:yaml.org,2002:timestamp":bi.timestamp};function Fp(t,e,n){let i=cc.get(e);if(i&&!t)return n&&!i.includes(Ht.merge)?i.concat(Ht.merge):i.slice();let r=i;if(!r)if(Array.isArray(t))r=[];else{let s=Array.from(cc.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${e}"; use one of ${s} or define customTags array`)}if(Array.isArray(t))for(let s of t)r=r.concat(s);else typeof t=="function"&&(r=t(r.slice()));return n&&(r=r.concat(Ht.merge)),r.reduce((s,o)=>{let a=typeof o=="string"?lc[o]:o;if(!a){let c=JSON.stringify(o),l=Object.keys(lc).map(f=>JSON.stringify(f)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return s.includes(a)||s.push(a),s},[])}fs.coreKnownTags=Dp;fs.getTags=Fp});var ms=v(wc=>{"use strict";var ds=N(),Mp=ht(),Wp=gt(),Bp=Kt(),ki=gc(),Kp=(t,e)=>t.keye.key?1:0,ps=class t{constructor({compat:e,customTags:n,merge:i,resolveKnownTags:r,schema:s,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?ki.getTags(e,"compat"):e?ki.getTags(null,e):null,this.name=typeof s=="string"&&s||"core",this.knownTags=r?ki.coreKnownTags:{},this.tags=ki.getTags(n,this.name,i),this.toStringOptions=a??null,Object.defineProperty(this,ds.MAP,{value:Mp.map}),Object.defineProperty(this,ds.SCALAR,{value:Bp.string}),Object.defineProperty(this,ds.SEQ,{value:Wp.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?Kp:null}clone(){let e=Object.create(t.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};wc.Schema=ps});var vc=v(yc=>{"use strict";var Yp=N(),hs=Mt(),Gt=qt();function Up(t,e){let n=[],i=e.directives===!0;if(e.directives!==!1&&t.directives){let c=t.directives.toString(t);c?(n.push(c),i=!0):t.directives.docStart&&(i=!0)}i&&n.push("---");let r=hs.createStringifyContext(t,e),{commentString:s}=r.options;if(t.commentBefore){n.length!==1&&n.unshift("");let c=s(t.commentBefore);n.unshift(Gt.indentComment(c,""))}let o=!1,a=null;if(t.contents){if(Yp.isNode(t.contents)){if(t.contents.spaceBefore&&i&&n.push(""),t.contents.commentBefore){let f=s(t.contents.commentBefore);n.push(Gt.indentComment(f,""))}r.forceBlockIndent=!!t.comment,a=t.contents.comment}let c=a?void 0:()=>o=!0,l=hs.stringify(t.contents,r,()=>a=null,c);a&&(l+=Gt.lineComment(l,"",s(a))),(l[0]==="|"||l[0]===">")&&n[n.length-1]==="---"?n[n.length-1]=`--- ${l}`:n.push(l)}else n.push(hs.stringify(t.contents,r));if(t.directives?.docEnd)if(t.comment){let c=s(t.comment);c.includes(` +${s.comment}`:i.comment}i=r}t.items[n]=ui.isPair(i)?i:new Qr.Pair(i)}}else e("Expected a sequence for this tag");return t}function Ua(t,e,n){let{replacer:i}=n,r=new cp.YAMLSeq(t);r.tag="tag:yaml.org,2002:pairs";let s=0;if(e&&Symbol.iterator in Object(e))for(let o of e){typeof i=="function"&&(o=i.call(e,String(s++),o));let a,c;if(Array.isArray(o))if(o.length===2)a=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)a=l[0],c=o[a];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else a=o;r.items.push(Qr.createPair(a,c,n))}return r}var lp={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Ya,createNode:Ua};fi.createPairs=Ua;fi.pairs=lp;fi.resolvePairs=Ya});var es=v(Zr=>{"use strict";var Va=N(),Xr=Ee(),Ut=Oe(),up=Ae(),Ja=di(),ze=class t extends up.YAMLSeq{constructor(){super(),this.add=Ut.YAMLMap.prototype.add.bind(this),this.delete=Ut.YAMLMap.prototype.delete.bind(this),this.get=Ut.YAMLMap.prototype.get.bind(this),this.has=Ut.YAMLMap.prototype.has.bind(this),this.set=Ut.YAMLMap.prototype.set.bind(this),this.tag=t.tag}toJSON(e,n){if(!n)return super.toJSON(e);let i=new Map;n?.onCreate&&n.onCreate(i);for(let r of this.items){let s,o;if(Va.isPair(r)?(s=Xr.toJS(r.key,"",n),o=Xr.toJS(r.value,s,n)):s=Xr.toJS(r,"",n),i.has(s))throw new Error("Ordered maps must not include duplicate keys");i.set(s,o)}return i}static from(e,n,i){let r=Ja.createPairs(e,n,i),s=new this;return s.items=r.items,s}};ze.tag="tag:yaml.org,2002:omap";var fp={collection:"seq",identify:t=>t instanceof Map,nodeClass:ze,default:!1,tag:"tag:yaml.org,2002:omap",resolve(t,e){let n=Ja.resolvePairs(t,e),i=[];for(let{key:r}of n.items)Va.isScalar(r)&&(i.includes(r.value)?e(`Ordered maps must not include duplicate keys: ${r.value}`):i.push(r.value));return Object.assign(new ze,n)},createNode:(t,e,n)=>ze.from(t,e,n)};Zr.YAMLOMap=ze;Zr.omap=fp});var Xa=v(ts=>{"use strict";var Ha=q();function Ga({value:t,source:e},n){return e&&(t?za:Qa).test.test(e)?e:t?n.options.trueStr:n.options.falseStr}var za={identify:t=>t===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new Ha.Scalar(!0),stringify:Ga},Qa={identify:t=>t===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new Ha.Scalar(!1),stringify:Ga};ts.falseTag=Qa;ts.trueTag=za});var Za=v(pi=>{"use strict";var dp=q(),ns=wt(),pp={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:t=>t.slice(-3).toLowerCase()==="nan"?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:ns.stringifyNumber},mp={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t.replace(/_/g,"")),stringify(t){let e=Number(t.value);return isFinite(e)?e.toExponential():ns.stringifyNumber(t)}},hp={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(t){let e=new dp.Scalar(parseFloat(t.replace(/_/g,""))),n=t.indexOf(".");if(n!==-1){let i=t.substring(n+1).replace(/_/g,"");i[i.length-1]==="0"&&(e.minFractionDigits=i.length)}return e},stringify:ns.stringifyNumber};pi.float=hp;pi.floatExp=mp;pi.floatNaN=pp});var tc=v(Jt=>{"use strict";var ec=wt(),Vt=t=>typeof t=="bigint"||Number.isInteger(t);function mi(t,e,n,{intAsBigInt:i}){let r=t[0];if((r==="-"||r==="+")&&(e+=1),t=t.substring(e).replace(/_/g,""),i){switch(n){case 2:t=`0b${t}`;break;case 8:t=`0o${t}`;break;case 16:t=`0x${t}`;break}let o=BigInt(t);return r==="-"?BigInt(-1)*o:o}let s=parseInt(t,n);return r==="-"?-1*s:s}function is(t,e,n){let{value:i}=t;if(Vt(i)){let r=i.toString(e);return i<0?"-"+n+r.substr(1):n+r}return ec.stringifyNumber(t)}var gp={identify:Vt,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(t,e,n)=>mi(t,2,2,n),stringify:t=>is(t,2,"0b")},wp={identify:Vt,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(t,e,n)=>mi(t,1,8,n),stringify:t=>is(t,8,"0")},yp={identify:Vt,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(t,e,n)=>mi(t,0,10,n),stringify:ec.stringifyNumber},vp={identify:Vt,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(t,e,n)=>mi(t,2,16,n),stringify:t=>is(t,16,"0x")};Jt.int=yp;Jt.intBin=gp;Jt.intHex=vp;Jt.intOct=wp});var ss=v(rs=>{"use strict";var wi=N(),hi=Re(),gi=Oe(),Qe=class t extends gi.YAMLMap{constructor(e){super(e),this.tag=t.tag}add(e){let n;wi.isPair(e)?n=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?n=new hi.Pair(e.key,null):n=new hi.Pair(e,null),gi.findPair(this.items,n.key)||this.items.push(n)}get(e,n){let i=gi.findPair(this.items,e);return!n&&wi.isPair(i)?wi.isScalar(i.key)?i.key.value:i.key:i}set(e,n){if(typeof n!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof n}`);let i=gi.findPair(this.items,e);i&&!n?this.items.splice(this.items.indexOf(i),1):!i&&n&&this.items.push(new hi.Pair(e))}toJSON(e,n){return super.toJSON(e,n,Set)}toString(e,n,i){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),n,i);throw new Error("Set items must all have null values")}static from(e,n,i){let{replacer:r}=i,s=new this(e);if(n&&Symbol.iterator in Object(n))for(let o of n)typeof r=="function"&&(o=r.call(n,o,o)),s.items.push(hi.createPair(o,null,i));return s}};Qe.tag="tag:yaml.org,2002:set";var bp={collection:"map",identify:t=>t instanceof Set,nodeClass:Qe,default:!1,tag:"tag:yaml.org,2002:set",createNode:(t,e,n)=>Qe.from(t,e,n),resolve(t,e){if(wi.isMap(t)){if(t.hasAllNullValues(!0))return Object.assign(new Qe,t);e("Set items must all have null values")}else e("Expected a mapping for this tag");return t}};rs.YAMLSet=Qe;rs.set=bp});var as=v(yi=>{"use strict";var kp=wt();function os(t,e){let n=t[0],i=n==="-"||n==="+"?t.substring(1):t,r=o=>e?BigInt(o):Number(o),s=i.replace(/_/g,"").split(":").reduce((o,a)=>o*r(60)+r(a),r(0));return n==="-"?r(-1)*s:s}function nc(t){let{value:e}=t,n=o=>o;if(typeof e=="bigint")n=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return kp.stringifyNumber(t);let i="";e<0&&(i="-",e*=n(-1));let r=n(60),s=[e%r];return e<60?s.unshift(0):(e=(e-s[0])/r,s.unshift(e%r),e>=60&&(e=(e-s[0])/r,s.unshift(e))),i+s.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var Sp={identify:t=>typeof t=="bigint"||Number.isInteger(t),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(t,e,{intAsBigInt:n})=>os(t,n),stringify:nc},Cp={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:t=>os(t,!1),stringify:nc},ic={identify:t=>t instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(t){let e=t.match(ic.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,n,i,r,s,o,a]=e.map(Number),c=e[7]?Number((e[7]+"00").substr(1,3)):0,l=Date.UTC(n,i-1,r,s||0,o||0,a||0,c),d=e[8];if(d&&d!=="Z"){let u=os(d,!1);Math.abs(u)<30&&(u*=60),l-=6e4*u}return new Date(l)},stringify:({value:t})=>t?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};yi.floatTime=Cp;yi.intTime=Sp;yi.timestamp=ic});var oc=v(sc=>{"use strict";var Ep=ht(),xp=si(),_p=gt(),Pp=Kt(),Rp=zr(),rc=Xa(),cs=Za(),vi=tc(),Np=Qn(),Op=es(),Ap=di(),jp=ss(),ls=as(),Tp=[Ep.map,_p.seq,Pp.string,xp.nullTag,rc.trueTag,rc.falseTag,vi.intBin,vi.intOct,vi.int,vi.intHex,cs.floatNaN,cs.floatExp,cs.float,Rp.binary,Np.merge,Op.omap,Ap.pairs,jp.set,ls.intTime,ls.floatTime,ls.timestamp];sc.schema=Tp});var gc=v(ds=>{"use strict";var uc=ht(),Ip=si(),fc=gt(),$p=Kt(),qp=Br(),us=Yr(),fs=Vr(),Lp=Fa(),Dp=Ba(),dc=zr(),Ht=Qn(),pc=es(),mc=di(),ac=oc(),hc=ss(),bi=as(),cc=new Map([["core",Lp.schema],["failsafe",[uc.map,fc.seq,$p.string]],["json",Dp.schema],["yaml11",ac.schema],["yaml-1.1",ac.schema]]),lc={binary:dc.binary,bool:qp.boolTag,float:us.float,floatExp:us.floatExp,floatNaN:us.floatNaN,floatTime:bi.floatTime,int:fs.int,intHex:fs.intHex,intOct:fs.intOct,intTime:bi.intTime,map:uc.map,merge:Ht.merge,null:Ip.nullTag,omap:pc.omap,pairs:mc.pairs,seq:fc.seq,set:hc.set,timestamp:bi.timestamp},Fp={"tag:yaml.org,2002:binary":dc.binary,"tag:yaml.org,2002:merge":Ht.merge,"tag:yaml.org,2002:omap":pc.omap,"tag:yaml.org,2002:pairs":mc.pairs,"tag:yaml.org,2002:set":hc.set,"tag:yaml.org,2002:timestamp":bi.timestamp};function Mp(t,e,n){let i=cc.get(e);if(i&&!t)return n&&!i.includes(Ht.merge)?i.concat(Ht.merge):i.slice();let r=i;if(!r)if(Array.isArray(t))r=[];else{let s=Array.from(cc.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${e}"; use one of ${s} or define customTags array`)}if(Array.isArray(t))for(let s of t)r=r.concat(s);else typeof t=="function"&&(r=t(r.slice()));return n&&(r=r.concat(Ht.merge)),r.reduce((s,o)=>{let a=typeof o=="string"?lc[o]:o;if(!a){let c=JSON.stringify(o),l=Object.keys(lc).map(d=>JSON.stringify(d)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return s.includes(a)||s.push(a),s},[])}ds.coreKnownTags=Fp;ds.getTags=Mp});var hs=v(wc=>{"use strict";var ps=N(),Wp=ht(),Bp=gt(),Kp=Kt(),ki=gc(),Yp=(t,e)=>t.keye.key?1:0,ms=class t{constructor({compat:e,customTags:n,merge:i,resolveKnownTags:r,schema:s,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?ki.getTags(e,"compat"):e?ki.getTags(null,e):null,this.name=typeof s=="string"&&s||"core",this.knownTags=r?ki.coreKnownTags:{},this.tags=ki.getTags(n,this.name,i),this.toStringOptions=a??null,Object.defineProperty(this,ps.MAP,{value:Wp.map}),Object.defineProperty(this,ps.SCALAR,{value:Kp.string}),Object.defineProperty(this,ps.SEQ,{value:Bp.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?Yp:null}clone(){let e=Object.create(t.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};wc.Schema=ms});var vc=v(yc=>{"use strict";var Up=N(),gs=Mt(),Gt=qt();function Vp(t,e){let n=[],i=e.directives===!0;if(e.directives!==!1&&t.directives){let c=t.directives.toString(t);c?(n.push(c),i=!0):t.directives.docStart&&(i=!0)}i&&n.push("---");let r=gs.createStringifyContext(t,e),{commentString:s}=r.options;if(t.commentBefore){n.length!==1&&n.unshift("");let c=s(t.commentBefore);n.unshift(Gt.indentComment(c,""))}let o=!1,a=null;if(t.contents){if(Up.isNode(t.contents)){if(t.contents.spaceBefore&&i&&n.push(""),t.contents.commentBefore){let d=s(t.contents.commentBefore);n.push(Gt.indentComment(d,""))}r.forceBlockIndent=!!t.comment,a=t.contents.comment}let c=a?void 0:()=>o=!0,l=gs.stringify(t.contents,r,()=>a=null,c);a&&(l+=Gt.lineComment(l,"",s(a))),(l[0]==="|"||l[0]===">")&&n[n.length-1]==="---"?n[n.length-1]=`--- ${l}`:n.push(l)}else n.push(gs.stringify(t.contents,r));if(t.directives?.docEnd)if(t.comment){let c=s(t.comment);c.includes(` `)?(n.push("..."),n.push(Gt.indentComment(c,""))):n.push(`... ${c}`)}else n.push("...");else{let c=t.comment;c&&o&&(c=c.replace(/^\n+/,"")),c&&((!o||a)&&n[n.length-1]!==""&&n.push(""),n.push(Gt.indentComment(s(c),"")))}return n.join(` `)+` -`}yc.stringifyDocument=Up});var zt=v(bc=>{"use strict";var Vp=It(),yt=Wn(),re=N(),Jp=Re(),Hp=Ee(),Gp=ms(),zp=vc(),gs=Ln(),Qp=br(),Xp=$t(),ws=vr(),ys=class t{constructor(e,n,i){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,re.NODE_TYPE,{value:re.DOC});let r=null;typeof n=="function"||Array.isArray(n)?r=n:i===void 0&&n&&(i=n,n=void 0);let s=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},i);this.options=s;let{version:o}=s;i?._directives?(this.directives=i._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new ws.Directives({version:o}),this.setSchema(o,i),this.contents=e===void 0?null:this.createNode(e,r,i)}clone(){let e=Object.create(t.prototype,{[re.NODE_TYPE]:{value:re.DOC}});return e.commentBefore=this.commentBefore,e.comment=this.comment,e.errors=this.errors.slice(),e.warnings=this.warnings.slice(),e.options=Object.assign({},this.options),this.directives&&(e.directives=this.directives.clone()),e.schema=this.schema.clone(),e.contents=re.isNode(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){vt(this.contents)&&this.contents.add(e)}addIn(e,n){vt(this.contents)&&this.contents.addIn(e,n)}createAlias(e,n){if(!e.anchor){let i=gs.anchorNames(this);e.anchor=!n||i.has(n)?gs.findNewAnchor(n||"a",i):n}return new Vp.Alias(e.anchor)}createNode(e,n,i){let r;if(typeof n=="function")e=n.call({"":e},"",e),r=n;else if(Array.isArray(n)){let m=y=>typeof y=="number"||y instanceof String||y instanceof Number,g=n.filter(m).map(String);g.length>0&&(n=n.concat(g)),r=n}else i===void 0&&n&&(i=n,n=void 0);let{aliasDuplicateObjects:s,anchorPrefix:o,flow:a,keepUndefined:c,onTagObj:l,tag:f}=i??{},{onAnchor:u,setAnchors:d,sourceObjects:h}=gs.createNodeAnchors(this,o||"a"),w={aliasDuplicateObjects:s??!0,keepUndefined:c??!1,onAnchor:u,onTagObj:l,replacer:r,schema:this.schema,sourceObjects:h},p=Xp.createNode(e,f,w);return a&&re.isCollection(p)&&(p.flow=!0),d(),p}createPair(e,n,i={}){let r=this.createNode(e,null,i),s=this.createNode(n,null,i);return new Jp.Pair(r,s)}delete(e){return vt(this.contents)?this.contents.delete(e):!1}deleteIn(e){return yt.isEmptyPath(e)?this.contents==null?!1:(this.contents=null,!0):vt(this.contents)?this.contents.deleteIn(e):!1}get(e,n){return re.isCollection(this.contents)?this.contents.get(e,n):void 0}getIn(e,n){return yt.isEmptyPath(e)?!n&&re.isScalar(this.contents)?this.contents.value:this.contents:re.isCollection(this.contents)?this.contents.getIn(e,n):void 0}has(e){return re.isCollection(this.contents)?this.contents.has(e):!1}hasIn(e){return yt.isEmptyPath(e)?this.contents!==void 0:re.isCollection(this.contents)?this.contents.hasIn(e):!1}set(e,n){this.contents==null?this.contents=yt.collectionFromPath(this.schema,[e],n):vt(this.contents)&&this.contents.set(e,n)}setIn(e,n){yt.isEmptyPath(e)?this.contents=n:this.contents==null?this.contents=yt.collectionFromPath(this.schema,Array.from(e),n):vt(this.contents)&&this.contents.setIn(e,n)}setSchema(e,n={}){typeof e=="number"&&(e=String(e));let i;switch(e){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new ws.Directives({version:"1.1"}),i={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=e:this.directives=new ws.Directives({version:e}),i={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,i=null;break;default:{let r=JSON.stringify(e);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${r}`)}}if(n.schema instanceof Object)this.schema=n.schema;else if(i)this.schema=new Gp.Schema(Object.assign(i,n));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:e,jsonArg:n,mapAsMap:i,maxAliasCount:r,onAnchor:s,reviver:o}={}){let a={anchors:new Map,doc:this,keep:!e,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},c=Hp.toJS(this.contents,n??"",a);if(typeof s=="function")for(let{count:l,res:f}of a.anchors.values())s(f,l);return typeof o=="function"?Qp.applyReviver(o,{"":c},"",c):c}toJSON(e,n){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:n})}toString(e={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let n=JSON.stringify(e.indent);throw new Error(`"indent" option must be a positive integer, not ${n}`)}return zp.stringifyDocument(this,e)}};function vt(t){if(re.isCollection(t))return!0;throw new Error("Expected a YAML collection as document contents")}bc.Document=ys});var Zt=v(Xt=>{"use strict";var Qt=class extends Error{constructor(e,n,i,r){super(),this.name=e,this.code=i,this.message=r,this.pos=n}},vs=class extends Qt{constructor(e,n,i){super("YAMLParseError",e,n,i)}},bs=class extends Qt{constructor(e,n,i){super("YAMLWarning",e,n,i)}},Zp=(t,e)=>n=>{if(n.pos[0]===-1)return;n.linePos=n.pos.map(a=>e.linePos(a));let{line:i,col:r}=n.linePos[0];n.message+=` at line ${i}, column ${r}`;let s=r-1,o=t.substring(e.lineStarts[i-1],e.lineStarts[i]).replace(/[\n\r]+$/,"");if(s>=60&&o.length>80){let a=Math.min(s-39,o.length-79);o="…"+o.substring(a),s-=a-1}if(o.length>80&&(o=o.substring(0,79)+"…"),i>1&&/^ *$/.test(o.substring(0,s))){let a=t.substring(e.lineStarts[i-2],e.lineStarts[i-1]);a.length>80&&(a=a.substring(0,79)+`… +`}yc.stringifyDocument=Vp});var zt=v(bc=>{"use strict";var Jp=It(),yt=Wn(),re=N(),Hp=Re(),Gp=Ee(),zp=hs(),Qp=vc(),ws=Ln(),Xp=kr(),Zp=$t(),ys=br(),vs=class t{constructor(e,n,i){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,re.NODE_TYPE,{value:re.DOC});let r=null;typeof n=="function"||Array.isArray(n)?r=n:i===void 0&&n&&(i=n,n=void 0);let s=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},i);this.options=s;let{version:o}=s;i?._directives?(this.directives=i._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new ys.Directives({version:o}),this.setSchema(o,i),this.contents=e===void 0?null:this.createNode(e,r,i)}clone(){let e=Object.create(t.prototype,{[re.NODE_TYPE]:{value:re.DOC}});return e.commentBefore=this.commentBefore,e.comment=this.comment,e.errors=this.errors.slice(),e.warnings=this.warnings.slice(),e.options=Object.assign({},this.options),this.directives&&(e.directives=this.directives.clone()),e.schema=this.schema.clone(),e.contents=re.isNode(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){vt(this.contents)&&this.contents.add(e)}addIn(e,n){vt(this.contents)&&this.contents.addIn(e,n)}createAlias(e,n){if(!e.anchor){let i=ws.anchorNames(this);e.anchor=!n||i.has(n)?ws.findNewAnchor(n||"a",i):n}return new Jp.Alias(e.anchor)}createNode(e,n,i){let r;if(typeof n=="function")e=n.call({"":e},"",e),r=n;else if(Array.isArray(n)){let m=y=>typeof y=="number"||y instanceof String||y instanceof Number,g=n.filter(m).map(String);g.length>0&&(n=n.concat(g)),r=n}else i===void 0&&n&&(i=n,n=void 0);let{aliasDuplicateObjects:s,anchorPrefix:o,flow:a,keepUndefined:c,onTagObj:l,tag:d}=i??{},{onAnchor:u,setAnchors:f,sourceObjects:h}=ws.createNodeAnchors(this,o||"a"),w={aliasDuplicateObjects:s??!0,keepUndefined:c??!1,onAnchor:u,onTagObj:l,replacer:r,schema:this.schema,sourceObjects:h},p=Zp.createNode(e,d,w);return a&&re.isCollection(p)&&(p.flow=!0),f(),p}createPair(e,n,i={}){let r=this.createNode(e,null,i),s=this.createNode(n,null,i);return new Hp.Pair(r,s)}delete(e){return vt(this.contents)?this.contents.delete(e):!1}deleteIn(e){return yt.isEmptyPath(e)?this.contents==null?!1:(this.contents=null,!0):vt(this.contents)?this.contents.deleteIn(e):!1}get(e,n){return re.isCollection(this.contents)?this.contents.get(e,n):void 0}getIn(e,n){return yt.isEmptyPath(e)?!n&&re.isScalar(this.contents)?this.contents.value:this.contents:re.isCollection(this.contents)?this.contents.getIn(e,n):void 0}has(e){return re.isCollection(this.contents)?this.contents.has(e):!1}hasIn(e){return yt.isEmptyPath(e)?this.contents!==void 0:re.isCollection(this.contents)?this.contents.hasIn(e):!1}set(e,n){this.contents==null?this.contents=yt.collectionFromPath(this.schema,[e],n):vt(this.contents)&&this.contents.set(e,n)}setIn(e,n){yt.isEmptyPath(e)?this.contents=n:this.contents==null?this.contents=yt.collectionFromPath(this.schema,Array.from(e),n):vt(this.contents)&&this.contents.setIn(e,n)}setSchema(e,n={}){typeof e=="number"&&(e=String(e));let i;switch(e){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new ys.Directives({version:"1.1"}),i={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=e:this.directives=new ys.Directives({version:e}),i={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,i=null;break;default:{let r=JSON.stringify(e);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${r}`)}}if(n.schema instanceof Object)this.schema=n.schema;else if(i)this.schema=new zp.Schema(Object.assign(i,n));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:e,jsonArg:n,mapAsMap:i,maxAliasCount:r,onAnchor:s,reviver:o}={}){let a={anchors:new Map,doc:this,keep:!e,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},c=Gp.toJS(this.contents,n??"",a);if(typeof s=="function")for(let{count:l,res:d}of a.anchors.values())s(d,l);return typeof o=="function"?Xp.applyReviver(o,{"":c},"",c):c}toJSON(e,n){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:n})}toString(e={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let n=JSON.stringify(e.indent);throw new Error(`"indent" option must be a positive integer, not ${n}`)}return Qp.stringifyDocument(this,e)}};function vt(t){if(re.isCollection(t))return!0;throw new Error("Expected a YAML collection as document contents")}bc.Document=vs});var Zt=v(Xt=>{"use strict";var Qt=class extends Error{constructor(e,n,i,r){super(),this.name=e,this.code=i,this.message=r,this.pos=n}},bs=class extends Qt{constructor(e,n,i){super("YAMLParseError",e,n,i)}},ks=class extends Qt{constructor(e,n,i){super("YAMLWarning",e,n,i)}},em=(t,e)=>n=>{if(n.pos[0]===-1)return;n.linePos=n.pos.map(a=>e.linePos(a));let{line:i,col:r}=n.linePos[0];n.message+=` at line ${i}, column ${r}`;let s=r-1,o=t.substring(e.lineStarts[i-1],e.lineStarts[i]).replace(/[\n\r]+$/,"");if(s>=60&&o.length>80){let a=Math.min(s-39,o.length-79);o="…"+o.substring(a),s-=a-1}if(o.length>80&&(o=o.substring(0,79)+"…"),i>1&&/^ *$/.test(o.substring(0,s))){let a=t.substring(e.lineStarts[i-2],e.lineStarts[i-1]);a.length>80&&(a=a.substring(0,79)+`… `),o=a+o}if(/[^ ]/.test(o)){let a=1,c=n.linePos[1];c?.line===i&&c.col>r&&(a=Math.max(1,Math.min(c.col-r,80-s)));let l=" ".repeat(s)+"^".repeat(a);n.message+=`: ${o} ${l} -`}};Xt.YAMLError=Qt;Xt.YAMLParseError=vs;Xt.YAMLWarning=bs;Xt.prettifyError=Zp});var en=v(kc=>{"use strict";function em(t,{flow:e,indicator:n,next:i,offset:r,onError:s,parentIndent:o,startOnNewline:a}){let c=!1,l=a,f=a,u="",d="",h=!1,w=!1,p=null,m=null,g=null,y=null,k=null,C=null,x=null;for(let b of t)switch(w&&(b.type!=="space"&&b.type!=="newline"&&b.type!=="comma"&&s(b.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),w=!1),p&&(l&&b.type!=="comment"&&b.type!=="newline"&&s(p,"TAB_AS_INDENT","Tabs are not allowed as indentation"),p=null),b.type){case"space":!e&&(n!=="doc-start"||i?.type!=="flow-collection")&&b.source.includes(" ")&&(p=b),f=!0;break;case"comment":{f||s(b,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let M=b.source.substring(1)||" ";u?u+=d+M:u=M,d="",l=!1;break}case"newline":l?u?u+=b.source:(!C||n!=="seq-item-ind")&&(c=!0):d+=b.source,l=!0,h=!0,(m||g)&&(y=b),f=!0;break;case"anchor":m&&s(b,"MULTIPLE_ANCHORS","A node can have at most one anchor"),b.source.endsWith(":")&&s(b.offset+b.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),m=b,x??(x=b.offset),l=!1,f=!1,w=!0;break;case"tag":{g&&s(b,"MULTIPLE_TAGS","A node can have at most one tag"),g=b,x??(x=b.offset),l=!1,f=!1,w=!0;break}case n:(m||g)&&s(b,"BAD_PROP_ORDER",`Anchors and tags must be after the ${b.source} indicator`),C&&s(b,"UNEXPECTED_TOKEN",`Unexpected ${b.source} in ${e??"collection"}`),C=b,l=n==="seq-item-ind"||n==="explicit-key-ind",f=!1;break;case"comma":if(e){k&&s(b,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),k=b,l=!1,f=!1;break}default:s(b,"UNEXPECTED_TOKEN",`Unexpected ${b.type} token`),l=!1,f=!1}let P=t[t.length-1],j=P?P.offset+P.source.length:r;return w&&i&&i.type!=="space"&&i.type!=="newline"&&i.type!=="comma"&&(i.type!=="scalar"||i.source!=="")&&s(i.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),p&&(l&&p.indent<=o||i?.type==="block-map"||i?.type==="block-seq")&&s(p,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:k,found:C,spaceBefore:c,comment:u,hasNewline:h,anchor:m,tag:g,newlineAfterProp:y,end:j,start:x??j}}kc.resolveProps=em});var Si=v(Sc=>{"use strict";function ks(t){if(!t)return null;switch(t.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(t.source.includes(` -`))return!0;if(t.end){for(let e of t.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(let e of t.items){for(let n of e.start)if(n.type==="newline")return!0;if(e.sep){for(let n of e.sep)if(n.type==="newline")return!0}if(ks(e.key)||ks(e.value))return!0}return!1;default:return!0}}Sc.containsNewline=ks});var Ss=v(Cc=>{"use strict";var tm=Si();function nm(t,e,n){if(e?.type==="flow-collection"){let i=e.end[0];i.indent===t&&(i.source==="]"||i.source==="}")&&tm.containsNewline(e)&&n(i,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Cc.flowIndentCheck=nm});var Cs=v(xc=>{"use strict";var Ec=N();function im(t,e,n){let{uniqueKeys:i}=t.options;if(i===!1)return!1;let r=typeof i=="function"?i:(s,o)=>s===o||Ec.isScalar(s)&&Ec.isScalar(o)&&s.value===o.value;return e.some(s=>r(s.key,n))}xc.mapIncludes=im});var Ac=v(Oc=>{"use strict";var _c=Re(),rm=Oe(),Pc=en(),sm=Si(),Rc=Ss(),om=Cs(),Nc="All mapping items must start at the same column";function am({composeNode:t,composeEmptyNode:e},n,i,r,s){let o=s?.nodeClass??rm.YAMLMap,a=new o(n.schema);n.atRoot&&(n.atRoot=!1);let c=i.offset,l=null;for(let f of i.items){let{start:u,key:d,sep:h,value:w}=f,p=Pc.resolveProps(u,{indicator:"explicit-key-ind",next:d??h?.[0],offset:c,onError:r,parentIndent:i.indent,startOnNewline:!0}),m=!p.found;if(m){if(d&&(d.type==="block-seq"?r(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in d&&d.indent!==i.indent&&r(c,"BAD_INDENT",Nc)),!p.anchor&&!p.tag&&!h){l=p.end,p.comment&&(a.comment?a.comment+=` -`+p.comment:a.comment=p.comment);continue}(p.newlineAfterProp||sm.containsNewline(d))&&r(d??u[u.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else p.found?.indent!==i.indent&&r(c,"BAD_INDENT",Nc);n.atKey=!0;let g=p.end,y=d?t(n,d,p,r):e(n,g,u,null,p,r);n.schema.compat&&Rc.flowIndentCheck(i.indent,d,r),n.atKey=!1,om.mapIncludes(n,a.items,y)&&r(g,"DUPLICATE_KEY","Map keys must be unique");let k=Pc.resolveProps(h??[],{indicator:"map-value-ind",next:w,offset:y.range[2],onError:r,parentIndent:i.indent,startOnNewline:!d||d.type==="block-scalar"});if(c=k.end,k.found){m&&(w?.type==="block-map"&&!k.hasNewline&&r(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),n.options.strict&&p.start{"use strict";var cm=Ae(),lm=en(),um=Ss();function fm({composeNode:t,composeEmptyNode:e},n,i,r,s){let o=s?.nodeClass??cm.YAMLSeq,a=new o(n.schema);n.atRoot&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let c=i.offset,l=null;for(let{start:f,value:u}of i.items){let d=lm.resolveProps(f,{indicator:"seq-item-ind",next:u,offset:c,onError:r,parentIndent:i.indent,startOnNewline:!0});if(!d.found)if(d.anchor||d.tag||u)u?.type==="block-seq"?r(d.end,"BAD_INDENT","All sequence items must start at the same column"):r(c,"MISSING_CHAR","Sequence item without - indicator");else{l=d.end,d.comment&&(a.comment=d.comment);continue}let h=u?t(n,u,d,r):e(n,d.end,f,null,d,r);n.schema.compat&&um.flowIndentCheck(i.indent,u,r),c=h.range[2],a.items.push(h)}return a.range=[i.offset,c,l??c],a}jc.resolveBlockSeq=fm});var bt=v(Ic=>{"use strict";function dm(t,e,n,i){let r="";if(t){let s=!1,o="";for(let a of t){let{source:c,type:l}=a;switch(l){case"space":s=!0;break;case"comment":{n&&!s&&i(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let f=c.substring(1)||" ";r?r+=o+f:r=f,o="";break}case"newline":r&&(o+=c),s=!0;break;default:i(a,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}e+=c.length}}return{comment:r,offset:e}}Ic.resolveEnd=dm});var Dc=v(Lc=>{"use strict";var pm=N(),mm=Re(),$c=Oe(),hm=Ae(),gm=bt(),qc=en(),wm=Si(),ym=Cs(),Es="Block collections are not allowed within flow collections",xs=t=>t&&(t.type==="block-map"||t.type==="block-seq");function vm({composeNode:t,composeEmptyNode:e},n,i,r,s){let o=i.start.source==="{",a=o?"flow map":"flow sequence",c=s?.nodeClass??(o?$c.YAMLMap:hm.YAMLSeq),l=new c(n.schema);l.flow=!0;let f=n.atRoot;f&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let u=i.offset+i.start.source.length;for(let m=0;m0){let m=gm.resolveEnd(w,p,n.options.strict,r);m.comment&&(l.comment?l.comment+=` -`+m.comment:l.comment=m.comment),l.range=[i.offset,p,m.offset]}else l.range=[i.offset,p,p];return l}Lc.resolveFlowCollection=vm});var Mc=v(Fc=>{"use strict";var bm=N(),km=q(),Sm=Oe(),Cm=Ae(),Em=Ac(),xm=Tc(),_m=Dc();function _s(t,e,n,i,r,s){let o=n.type==="block-map"?Em.resolveBlockMap(t,e,n,i,s):n.type==="block-seq"?xm.resolveBlockSeq(t,e,n,i,s):_m.resolveFlowCollection(t,e,n,i,s),a=o.constructor;return r==="!"||r===a.tagName?(o.tag=a.tagName,o):(r&&(o.tag=r),o)}function Pm(t,e,n,i,r){let s=i.tag,o=s?e.directives.tagName(s.source,d=>r(s,"TAG_RESOLVE_FAILED",d)):null;if(n.type==="block-seq"){let{anchor:d,newlineAfterProp:h}=i,w=d&&s?d.offset>s.offset?d:s:d??s;w&&(!h||h.offsetd.tag===o&&d.collection===a);if(!c){let d=e.schema.knownTags[o];if(d?.collection===a)e.schema.tags.push(Object.assign({},d,{default:!1})),c=d;else return d?r(s,"BAD_COLLECTION_TYPE",`${d.tag} used for ${a} collection, but expects ${d.collection??"scalar"}`,!0):r(s,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),_s(t,e,n,r,o)}let l=_s(t,e,n,r,o,c),f=c.resolve?.(l,d=>r(s,"TAG_RESOLVE_FAILED",d),e.options)??l,u=bm.isNode(f)?f:new km.Scalar(f);return u.range=l.range,u.tag=o,c?.format&&(u.format=c.format),u}Fc.composeCollection=Pm});var Rs=v(Wc=>{"use strict";var Ps=q();function Rm(t,e,n){let i=e.offset,r=Nm(e,t.options.strict,n);if(!r)return{value:"",type:null,comment:"",range:[i,i,i]};let s=r.mode===">"?Ps.Scalar.BLOCK_FOLDED:Ps.Scalar.BLOCK_LITERAL,o=e.source?Om(e.source):[],a=o.length;for(let p=o.length-1;p>=0;--p){let m=o[p][1];if(m===""||m==="\r")a=p;else break}if(a===0){let p=r.chomp==="+"&&o.length>0?` -`.repeat(Math.max(1,o.length-1)):"",m=i+r.length;return e.source&&(m+=e.source.length),{value:p,type:s,comment:r.comment,range:[i,m,m]}}let c=e.indent+r.indent,l=e.offset+r.length,f=0;for(let p=0;pc&&(c=m.length);else{m.length=a;--p)o[p][0].length>c&&(a=p+1);let u="",d="",h=!1;for(let p=0;pc||g[0]===" "?(d===" "?d=` -`:!h&&d===` -`&&(d=` +`}};Xt.YAMLError=Qt;Xt.YAMLParseError=bs;Xt.YAMLWarning=ks;Xt.prettifyError=em});var en=v(kc=>{"use strict";function tm(t,{flow:e,indicator:n,next:i,offset:r,onError:s,parentIndent:o,startOnNewline:a}){let c=!1,l=a,d=a,u="",f="",h=!1,w=!1,p=null,m=null,g=null,y=null,k=null,C=null,x=null;for(let b of t)switch(w&&(b.type!=="space"&&b.type!=="newline"&&b.type!=="comma"&&s(b.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),w=!1),p&&(l&&b.type!=="comment"&&b.type!=="newline"&&s(p,"TAB_AS_INDENT","Tabs are not allowed as indentation"),p=null),b.type){case"space":!e&&(n!=="doc-start"||i?.type!=="flow-collection")&&b.source.includes(" ")&&(p=b),d=!0;break;case"comment":{d||s(b,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let M=b.source.substring(1)||" ";u?u+=f+M:u=M,f="",l=!1;break}case"newline":l?u?u+=b.source:(!C||n!=="seq-item-ind")&&(c=!0):f+=b.source,l=!0,h=!0,(m||g)&&(y=b),d=!0;break;case"anchor":m&&s(b,"MULTIPLE_ANCHORS","A node can have at most one anchor"),b.source.endsWith(":")&&s(b.offset+b.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),m=b,x??(x=b.offset),l=!1,d=!1,w=!0;break;case"tag":{g&&s(b,"MULTIPLE_TAGS","A node can have at most one tag"),g=b,x??(x=b.offset),l=!1,d=!1,w=!0;break}case n:(m||g)&&s(b,"BAD_PROP_ORDER",`Anchors and tags must be after the ${b.source} indicator`),C&&s(b,"UNEXPECTED_TOKEN",`Unexpected ${b.source} in ${e??"collection"}`),C=b,l=n==="seq-item-ind"||n==="explicit-key-ind",d=!1;break;case"comma":if(e){k&&s(b,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),k=b,l=!1,d=!1;break}default:s(b,"UNEXPECTED_TOKEN",`Unexpected ${b.type} token`),l=!1,d=!1}let P=t[t.length-1],j=P?P.offset+P.source.length:r;return w&&i&&i.type!=="space"&&i.type!=="newline"&&i.type!=="comma"&&(i.type!=="scalar"||i.source!=="")&&s(i.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),p&&(l&&p.indent<=o||i?.type==="block-map"||i?.type==="block-seq")&&s(p,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:k,found:C,spaceBefore:c,comment:u,hasNewline:h,anchor:m,tag:g,newlineAfterProp:y,end:j,start:x??j}}kc.resolveProps=tm});var Si=v(Sc=>{"use strict";function Ss(t){if(!t)return null;switch(t.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(t.source.includes(` +`))return!0;if(t.end){for(let e of t.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(let e of t.items){for(let n of e.start)if(n.type==="newline")return!0;if(e.sep){for(let n of e.sep)if(n.type==="newline")return!0}if(Ss(e.key)||Ss(e.value))return!0}return!1;default:return!0}}Sc.containsNewline=Ss});var Cs=v(Cc=>{"use strict";var nm=Si();function im(t,e,n){if(e?.type==="flow-collection"){let i=e.end[0];i.indent===t&&(i.source==="]"||i.source==="}")&&nm.containsNewline(e)&&n(i,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Cc.flowIndentCheck=im});var Es=v(xc=>{"use strict";var Ec=N();function rm(t,e,n){let{uniqueKeys:i}=t.options;if(i===!1)return!1;let r=typeof i=="function"?i:(s,o)=>s===o||Ec.isScalar(s)&&Ec.isScalar(o)&&s.value===o.value;return e.some(s=>r(s.key,n))}xc.mapIncludes=rm});var Ac=v(Oc=>{"use strict";var _c=Re(),sm=Oe(),Pc=en(),om=Si(),Rc=Cs(),am=Es(),Nc="All mapping items must start at the same column";function cm({composeNode:t,composeEmptyNode:e},n,i,r,s){let o=s?.nodeClass??sm.YAMLMap,a=new o(n.schema);n.atRoot&&(n.atRoot=!1);let c=i.offset,l=null;for(let d of i.items){let{start:u,key:f,sep:h,value:w}=d,p=Pc.resolveProps(u,{indicator:"explicit-key-ind",next:f??h?.[0],offset:c,onError:r,parentIndent:i.indent,startOnNewline:!0}),m=!p.found;if(m){if(f&&(f.type==="block-seq"?r(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in f&&f.indent!==i.indent&&r(c,"BAD_INDENT",Nc)),!p.anchor&&!p.tag&&!h){l=p.end,p.comment&&(a.comment?a.comment+=` +`+p.comment:a.comment=p.comment);continue}(p.newlineAfterProp||om.containsNewline(f))&&r(f??u[u.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else p.found?.indent!==i.indent&&r(c,"BAD_INDENT",Nc);n.atKey=!0;let g=p.end,y=f?t(n,f,p,r):e(n,g,u,null,p,r);n.schema.compat&&Rc.flowIndentCheck(i.indent,f,r),n.atKey=!1,am.mapIncludes(n,a.items,y)&&r(g,"DUPLICATE_KEY","Map keys must be unique");let k=Pc.resolveProps(h??[],{indicator:"map-value-ind",next:w,offset:y.range[2],onError:r,parentIndent:i.indent,startOnNewline:!f||f.type==="block-scalar"});if(c=k.end,k.found){m&&(w?.type==="block-map"&&!k.hasNewline&&r(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),n.options.strict&&p.start{"use strict";var lm=Ae(),um=en(),fm=Cs();function dm({composeNode:t,composeEmptyNode:e},n,i,r,s){let o=s?.nodeClass??lm.YAMLSeq,a=new o(n.schema);n.atRoot&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let c=i.offset,l=null;for(let{start:d,value:u}of i.items){let f=um.resolveProps(d,{indicator:"seq-item-ind",next:u,offset:c,onError:r,parentIndent:i.indent,startOnNewline:!0});if(!f.found)if(f.anchor||f.tag||u)u?.type==="block-seq"?r(f.end,"BAD_INDENT","All sequence items must start at the same column"):r(c,"MISSING_CHAR","Sequence item without - indicator");else{l=f.end,f.comment&&(a.comment=f.comment);continue}let h=u?t(n,u,f,r):e(n,f.end,d,null,f,r);n.schema.compat&&fm.flowIndentCheck(i.indent,u,r),c=h.range[2],a.items.push(h)}return a.range=[i.offset,c,l??c],a}jc.resolveBlockSeq=dm});var bt=v(Ic=>{"use strict";function pm(t,e,n,i){let r="";if(t){let s=!1,o="";for(let a of t){let{source:c,type:l}=a;switch(l){case"space":s=!0;break;case"comment":{n&&!s&&i(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let d=c.substring(1)||" ";r?r+=o+d:r=d,o="";break}case"newline":r&&(o+=c),s=!0;break;default:i(a,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}e+=c.length}}return{comment:r,offset:e}}Ic.resolveEnd=pm});var Dc=v(Lc=>{"use strict";var mm=N(),hm=Re(),$c=Oe(),gm=Ae(),wm=bt(),qc=en(),ym=Si(),vm=Es(),xs="Block collections are not allowed within flow collections",_s=t=>t&&(t.type==="block-map"||t.type==="block-seq");function bm({composeNode:t,composeEmptyNode:e},n,i,r,s){let o=i.start.source==="{",a=o?"flow map":"flow sequence",c=s?.nodeClass??(o?$c.YAMLMap:gm.YAMLSeq),l=new c(n.schema);l.flow=!0;let d=n.atRoot;d&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let u=i.offset+i.start.source.length;for(let m=0;m0){let m=wm.resolveEnd(w,p,n.options.strict,r);m.comment&&(l.comment?l.comment+=` +`+m.comment:l.comment=m.comment),l.range=[i.offset,p,m.offset]}else l.range=[i.offset,p,p];return l}Lc.resolveFlowCollection=bm});var Mc=v(Fc=>{"use strict";var km=N(),Sm=q(),Cm=Oe(),Em=Ae(),xm=Ac(),_m=Tc(),Pm=Dc();function Ps(t,e,n,i,r,s){let o=n.type==="block-map"?xm.resolveBlockMap(t,e,n,i,s):n.type==="block-seq"?_m.resolveBlockSeq(t,e,n,i,s):Pm.resolveFlowCollection(t,e,n,i,s),a=o.constructor;return r==="!"||r===a.tagName?(o.tag=a.tagName,o):(r&&(o.tag=r),o)}function Rm(t,e,n,i,r){let s=i.tag,o=s?e.directives.tagName(s.source,f=>r(s,"TAG_RESOLVE_FAILED",f)):null;if(n.type==="block-seq"){let{anchor:f,newlineAfterProp:h}=i,w=f&&s?f.offset>s.offset?f:s:f??s;w&&(!h||h.offsetf.tag===o&&f.collection===a);if(!c){let f=e.schema.knownTags[o];if(f?.collection===a)e.schema.tags.push(Object.assign({},f,{default:!1})),c=f;else return f?r(s,"BAD_COLLECTION_TYPE",`${f.tag} used for ${a} collection, but expects ${f.collection??"scalar"}`,!0):r(s,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),Ps(t,e,n,r,o)}let l=Ps(t,e,n,r,o,c),d=c.resolve?.(l,f=>r(s,"TAG_RESOLVE_FAILED",f),e.options)??l,u=km.isNode(d)?d:new Sm.Scalar(d);return u.range=l.range,u.tag=o,c?.format&&(u.format=c.format),u}Fc.composeCollection=Rm});var Ns=v(Wc=>{"use strict";var Rs=q();function Nm(t,e,n){let i=e.offset,r=Om(e,t.options.strict,n);if(!r)return{value:"",type:null,comment:"",range:[i,i,i]};let s=r.mode===">"?Rs.Scalar.BLOCK_FOLDED:Rs.Scalar.BLOCK_LITERAL,o=e.source?Am(e.source):[],a=o.length;for(let p=o.length-1;p>=0;--p){let m=o[p][1];if(m===""||m==="\r")a=p;else break}if(a===0){let p=r.chomp==="+"&&o.length>0?` +`.repeat(Math.max(1,o.length-1)):"",m=i+r.length;return e.source&&(m+=e.source.length),{value:p,type:s,comment:r.comment,range:[i,m,m]}}let c=e.indent+r.indent,l=e.offset+r.length,d=0;for(let p=0;pc&&(c=m.length);else{m.length=a;--p)o[p][0].length>c&&(a=p+1);let u="",f="",h=!1;for(let p=0;pc||g[0]===" "?(f===" "?f=` +`:!h&&f===` +`&&(f=` -`),u+=d+m.slice(c)+g,d=` -`,h=!0):g===""?d===` +`),u+=f+m.slice(c)+g,f=` +`,h=!0):g===""?f===` `?u+=` -`:d=` -`:(u+=d+g,d=" ",h=!1)}switch(r.chomp){case"-":break;case"+":for(let p=a;p{"use strict";var Ns=q(),Am=bt();function jm(t,e,n){let{offset:i,type:r,source:s,end:o}=t,a,c,l=(d,h,w)=>n(i+d,h,w);switch(r){case"scalar":a=Ns.Scalar.PLAIN,c=Tm(s,l);break;case"single-quoted-scalar":a=Ns.Scalar.QUOTE_SINGLE,c=Im(s,l);break;case"double-quoted-scalar":a=Ns.Scalar.QUOTE_DOUBLE,c=$m(s,l);break;default:return n(t,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${r}`),{value:"",type:null,comment:"",range:[i,i+s.length,i+s.length]}}let f=i+s.length,u=Am.resolveEnd(o,f,e,n);return{value:c,type:a,comment:u.comment,range:[i,f,u.offset]}}function Tm(t,e){let n="";switch(t[0]){case" ":n="a tab character";break;case",":n="flow indicator character ,";break;case"%":n="directive indicator character %";break;case"|":case">":{n=`block scalar indicator ${t[0]}`;break}case"@":case"`":{n=`reserved character ${t[0]}`;break}}return n&&e(0,"BAD_SCALAR_START",`Plain value cannot start with ${n}`),Bc(t)}function Im(t,e){return(t[t.length-1]!=="'"||t.length===1)&&e(t.length,"MISSING_CHAR","Missing closing 'quote"),Bc(t.slice(1,-1)).replace(/''/g,"'")}function Bc(t){let e,n;try{e=new RegExp(`(.*?)(?{"use strict";var Os=q(),jm=bt();function Tm(t,e,n){let{offset:i,type:r,source:s,end:o}=t,a,c,l=(f,h,w)=>n(i+f,h,w);switch(r){case"scalar":a=Os.Scalar.PLAIN,c=Im(s,l);break;case"single-quoted-scalar":a=Os.Scalar.QUOTE_SINGLE,c=$m(s,l);break;case"double-quoted-scalar":a=Os.Scalar.QUOTE_DOUBLE,c=qm(s,l);break;default:return n(t,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${r}`),{value:"",type:null,comment:"",range:[i,i+s.length,i+s.length]}}let d=i+s.length,u=jm.resolveEnd(o,d,e,n);return{value:c,type:a,comment:u.comment,range:[i,d,u.offset]}}function Im(t,e){let n="";switch(t[0]){case" ":n="a tab character";break;case",":n="flow indicator character ,";break;case"%":n="directive indicator character %";break;case"|":case">":{n=`block scalar indicator ${t[0]}`;break}case"@":case"`":{n=`reserved character ${t[0]}`;break}}return n&&e(0,"BAD_SCALAR_START",`Plain value cannot start with ${n}`),Bc(t)}function $m(t,e){return(t[t.length-1]!=="'"||t.length===1)&&e(t.length,"MISSING_CHAR","Missing closing 'quote"),Bc(t.slice(1,-1)).replace(/''/g,"'")}function Bc(t){let e,n;try{e=new RegExp(`(.*?)(?s?t.slice(s,i+1):r)}else n+=r}return(t[t.length-1]!=='"'||t.length===1)&&e(t.length,"MISSING_CHAR",'Missing closing "quote'),n}function qm(t,e){let n="",i=t[e+1];for(;(i===" "||i===" "||i===` +`)&&(n+=i>s?t.slice(s,i+1):r)}else n+=r}return(t[t.length-1]!=='"'||t.length===1)&&e(t.length,"MISSING_CHAR",'Missing closing "quote'),n}function Lm(t,e){let n="",i=t[e+1];for(;(i===" "||i===" "||i===` `||i==="\r")&&!(i==="\r"&&t[e+2]!==` `);)i===` `&&(n+=` -`),e+=1,i=t[e+1];return n||(n=" "),{fold:n,offset:e}}var Lm={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:` -`,r:"\r",t:" ",v:"\v",N:"…",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function Dm(t,e,n,i){let r=t.substr(e,n),o=r.length===n&&/^[0-9a-fA-F]+$/.test(r)?parseInt(r,16):NaN;try{return String.fromCodePoint(o)}catch{let a=t.substr(e-2,n+2);return i(e-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),a}}Kc.resolveFlowScalar=jm});var Vc=v(Uc=>{"use strict";var Qe=N(),Yc=q(),Fm=Rs(),Mm=Os();function Wm(t,e,n,i){let{value:r,type:s,comment:o,range:a}=e.type==="block-scalar"?Fm.resolveBlockScalar(t,e,i):Mm.resolveFlowScalar(e,t.options.strict,i),c=n?t.directives.tagName(n.source,u=>i(n,"TAG_RESOLVE_FAILED",u)):null,l;t.options.stringKeys&&t.atKey?l=t.schema[Qe.SCALAR]:c?l=Bm(t.schema,r,c,n,i):e.type==="scalar"?l=Km(t,r,e,i):l=t.schema[Qe.SCALAR];let f;try{let u=l.resolve(r,d=>i(n??e,"TAG_RESOLVE_FAILED",d),t.options);f=Qe.isScalar(u)?u:new Yc.Scalar(u)}catch(u){let d=u instanceof Error?u.message:String(u);i(n??e,"TAG_RESOLVE_FAILED",d),f=new Yc.Scalar(r)}return f.range=a,f.source=r,s&&(f.type=s),c&&(f.tag=c),l.format&&(f.format=l.format),o&&(f.comment=o),f}function Bm(t,e,n,i,r){if(n==="!")return t[Qe.SCALAR];let s=[];for(let a of t.tags)if(!a.collection&&a.tag===n)if(a.default&&a.test)s.push(a);else return a;for(let a of s)if(a.test?.test(e))return a;let o=t.knownTags[n];return o&&!o.collection?(t.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(r(i,"TAG_RESOLVE_FAILED",`Unresolved tag: ${n}`,n!=="tag:yaml.org,2002:str"),t[Qe.SCALAR])}function Km({atKey:t,directives:e,schema:n},i,r,s){let o=n.tags.find(a=>(a.default===!0||t&&a.default==="key")&&a.test?.test(i))||n[Qe.SCALAR];if(n.compat){let a=n.compat.find(c=>c.default&&c.test?.test(i))??n[Qe.SCALAR];if(o.tag!==a.tag){let c=e.tagString(o.tag),l=e.tagString(a.tag),f=`Value may be parsed as either ${c} or ${l}`;s(r,"TAG_RESOLVE_FAILED",f,!0)}}return o}Uc.composeScalar=Wm});var Hc=v(Jc=>{"use strict";function Ym(t,e,n){if(e){n??(n=e.length);for(let i=n-1;i>=0;--i){let r=e[i];switch(r.type){case"space":case"comment":case"newline":t-=r.source.length;continue}for(r=e[++i];r?.type==="space";)t+=r.source.length,r=e[++i];break}}return t}Jc.emptyScalarPosition=Ym});var Qc=v(js=>{"use strict";var Um=It(),Vm=N(),Jm=Mc(),Gc=Vc(),Hm=bt(),Gm=Hc(),zm={composeNode:zc,composeEmptyNode:As};function zc(t,e,n,i){let r=t.atKey,{spaceBefore:s,comment:o,anchor:a,tag:c}=n,l,f=!0;switch(e.type){case"alias":l=Qm(t,e,i),(a||c)&&i(e,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=Gc.composeScalar(t,e,c,i),a&&(l.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=Jm.composeCollection(zm,t,e,n,i),a&&(l.anchor=a.source.substring(1))}catch(u){let d=u instanceof Error?u.message:String(u);i(e,"RESOURCE_EXHAUSTION",d)}break;default:{let u=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;i(e,"UNEXPECTED_TOKEN",u),f=!1}}return l??(l=As(t,e.offset,void 0,null,n,i)),a&&l.anchor===""&&i(a,"BAD_ALIAS","Anchor cannot be an empty string"),r&&t.options.stringKeys&&(!Vm.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&i(c??e,"NON_STRING_KEY","With stringKeys, all keys must be strings"),s&&(l.spaceBefore=!0),o&&(e.type==="scalar"&&e.source===""?l.comment=o:l.commentBefore=o),t.options.keepSourceTokens&&f&&(l.srcToken=e),l}function As(t,e,n,i,{spaceBefore:r,comment:s,anchor:o,tag:a,end:c},l){let f={type:"scalar",offset:Gm.emptyScalarPosition(e,n,i),indent:-1,source:""},u=Gc.composeScalar(t,f,a,l);return o&&(u.anchor=o.source.substring(1),u.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),r&&(u.spaceBefore=!0),s&&(u.comment=s,u.range[2]=c),u}function Qm({options:t},{offset:e,source:n,end:i},r){let s=new Um.Alias(n.substring(1));s.source===""&&r(e,"BAD_ALIAS","Alias cannot be an empty string"),s.source.endsWith(":")&&r(e+n.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=e+n.length,a=Hm.resolveEnd(i,o,t.strict,r);return s.range=[e,o,a.offset],a.comment&&(s.comment=a.comment),s}js.composeEmptyNode=As;js.composeNode=zc});var el=v(Zc=>{"use strict";var Xm=zt(),Xc=Qc(),Zm=bt(),eh=en();function th(t,e,{offset:n,start:i,value:r,end:s},o){let a=Object.assign({_directives:e},t),c=new Xm.Document(void 0,a),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},f=eh.resolveProps(i,{indicator:"doc-start",next:r??s?.[0],offset:n,onError:o,parentIndent:0,startOnNewline:!0});f.found&&(c.directives.docStart=!0,r&&(r.type==="block-map"||r.type==="block-seq")&&!f.hasNewline&&o(f.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=r?Xc.composeNode(l,r,f,o):Xc.composeEmptyNode(l,f.end,i,null,f,o);let u=c.contents.range[2],d=Zm.resolveEnd(s,u,!1,o);return d.comment&&(c.comment=d.comment),c.range=[n,u,d.offset],c}Zc.composeDoc=th});var Is=v(il=>{"use strict";var nh=jn("process"),ih=vr(),rh=zt(),tn=Zt(),tl=N(),sh=el(),oh=bt();function nn(t){if(typeof t=="number")return[t,t+1];if(Array.isArray(t))return t.length===2?t:[t[0],t[1]];let{offset:e,source:n}=t;return[e,e+(typeof n=="string"?n.length:1)]}function nl(t){let e="",n=!1,i=!1;for(let r=0;r{"use strict";var Xe=N(),Yc=q(),Mm=Ns(),Wm=As();function Bm(t,e,n,i){let{value:r,type:s,comment:o,range:a}=e.type==="block-scalar"?Mm.resolveBlockScalar(t,e,i):Wm.resolveFlowScalar(e,t.options.strict,i),c=n?t.directives.tagName(n.source,u=>i(n,"TAG_RESOLVE_FAILED",u)):null,l;t.options.stringKeys&&t.atKey?l=t.schema[Xe.SCALAR]:c?l=Km(t.schema,r,c,n,i):e.type==="scalar"?l=Ym(t,r,e,i):l=t.schema[Xe.SCALAR];let d;try{let u=l.resolve(r,f=>i(n??e,"TAG_RESOLVE_FAILED",f),t.options);d=Xe.isScalar(u)?u:new Yc.Scalar(u)}catch(u){let f=u instanceof Error?u.message:String(u);i(n??e,"TAG_RESOLVE_FAILED",f),d=new Yc.Scalar(r)}return d.range=a,d.source=r,s&&(d.type=s),c&&(d.tag=c),l.format&&(d.format=l.format),o&&(d.comment=o),d}function Km(t,e,n,i,r){if(n==="!")return t[Xe.SCALAR];let s=[];for(let a of t.tags)if(!a.collection&&a.tag===n)if(a.default&&a.test)s.push(a);else return a;for(let a of s)if(a.test?.test(e))return a;let o=t.knownTags[n];return o&&!o.collection?(t.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(r(i,"TAG_RESOLVE_FAILED",`Unresolved tag: ${n}`,n!=="tag:yaml.org,2002:str"),t[Xe.SCALAR])}function Ym({atKey:t,directives:e,schema:n},i,r,s){let o=n.tags.find(a=>(a.default===!0||t&&a.default==="key")&&a.test?.test(i))||n[Xe.SCALAR];if(n.compat){let a=n.compat.find(c=>c.default&&c.test?.test(i))??n[Xe.SCALAR];if(o.tag!==a.tag){let c=e.tagString(o.tag),l=e.tagString(a.tag),d=`Value may be parsed as either ${c} or ${l}`;s(r,"TAG_RESOLVE_FAILED",d,!0)}}return o}Uc.composeScalar=Bm});var Hc=v(Jc=>{"use strict";function Um(t,e,n){if(e){n??(n=e.length);for(let i=n-1;i>=0;--i){let r=e[i];switch(r.type){case"space":case"comment":case"newline":t-=r.source.length;continue}for(r=e[++i];r?.type==="space";)t+=r.source.length,r=e[++i];break}}return t}Jc.emptyScalarPosition=Um});var Qc=v(Ts=>{"use strict";var Vm=It(),Jm=N(),Hm=Mc(),Gc=Vc(),Gm=bt(),zm=Hc(),Qm={composeNode:zc,composeEmptyNode:js};function zc(t,e,n,i){let r=t.atKey,{spaceBefore:s,comment:o,anchor:a,tag:c}=n,l,d=!0;switch(e.type){case"alias":l=Xm(t,e,i),(a||c)&&i(e,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=Gc.composeScalar(t,e,c,i),a&&(l.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=Hm.composeCollection(Qm,t,e,n,i),a&&(l.anchor=a.source.substring(1))}catch(u){let f=u instanceof Error?u.message:String(u);i(e,"RESOURCE_EXHAUSTION",f)}break;default:{let u=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;i(e,"UNEXPECTED_TOKEN",u),d=!1}}return l??(l=js(t,e.offset,void 0,null,n,i)),a&&l.anchor===""&&i(a,"BAD_ALIAS","Anchor cannot be an empty string"),r&&t.options.stringKeys&&(!Jm.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&i(c??e,"NON_STRING_KEY","With stringKeys, all keys must be strings"),s&&(l.spaceBefore=!0),o&&(e.type==="scalar"&&e.source===""?l.comment=o:l.commentBefore=o),t.options.keepSourceTokens&&d&&(l.srcToken=e),l}function js(t,e,n,i,{spaceBefore:r,comment:s,anchor:o,tag:a,end:c},l){let d={type:"scalar",offset:zm.emptyScalarPosition(e,n,i),indent:-1,source:""},u=Gc.composeScalar(t,d,a,l);return o&&(u.anchor=o.source.substring(1),u.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),r&&(u.spaceBefore=!0),s&&(u.comment=s,u.range[2]=c),u}function Xm({options:t},{offset:e,source:n,end:i},r){let s=new Vm.Alias(n.substring(1));s.source===""&&r(e,"BAD_ALIAS","Alias cannot be an empty string"),s.source.endsWith(":")&&r(e+n.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=e+n.length,a=Gm.resolveEnd(i,o,t.strict,r);return s.range=[e,o,a.offset],a.comment&&(s.comment=a.comment),s}Ts.composeEmptyNode=js;Ts.composeNode=zc});var el=v(Zc=>{"use strict";var Zm=zt(),Xc=Qc(),eh=bt(),th=en();function nh(t,e,{offset:n,start:i,value:r,end:s},o){let a=Object.assign({_directives:e},t),c=new Zm.Document(void 0,a),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},d=th.resolveProps(i,{indicator:"doc-start",next:r??s?.[0],offset:n,onError:o,parentIndent:0,startOnNewline:!0});d.found&&(c.directives.docStart=!0,r&&(r.type==="block-map"||r.type==="block-seq")&&!d.hasNewline&&o(d.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=r?Xc.composeNode(l,r,d,o):Xc.composeEmptyNode(l,d.end,i,null,d,o);let u=c.contents.range[2],f=eh.resolveEnd(s,u,!1,o);return f.comment&&(c.comment=f.comment),c.range=[n,u,f.offset],c}Zc.composeDoc=nh});var $s=v(il=>{"use strict";var ih=jn("process"),rh=br(),sh=zt(),tn=Zt(),tl=N(),oh=el(),ah=bt();function nn(t){if(typeof t=="number")return[t,t+1];if(Array.isArray(t))return t.length===2?t:[t[0],t[1]];let{offset:e,source:n}=t;return[e,e+(typeof n=="string"?n.length:1)]}function nl(t){let e="",n=!1,i=!1;for(let r=0;r{let o=nn(n);s?this.warnings.push(new tn.YAMLWarning(o,i,r)):this.errors.push(new tn.YAMLParseError(o,i,r))},this.directives=new ih.Directives({version:e.version||"1.2"}),this.options=e}decorate(e,n){let{comment:i,afterEmptyLine:r}=nl(this.prelude);if(i){let s=e.contents;if(n)e.comment=e.comment?`${e.comment} +`)+(s.substring(1)||" "),n=!0,i=!1;break;case"%":t[r+1]?.[0]!=="#"&&(r+=1),n=!1;break;default:n||(i=!0),n=!1}}return{comment:e,afterEmptyLine:i}}var Is=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(n,i,r,s)=>{let o=nn(n);s?this.warnings.push(new tn.YAMLWarning(o,i,r)):this.errors.push(new tn.YAMLParseError(o,i,r))},this.directives=new rh.Directives({version:e.version||"1.2"}),this.options=e}decorate(e,n){let{comment:i,afterEmptyLine:r}=nl(this.prelude);if(i){let s=e.contents;if(n)e.comment=e.comment?`${e.comment} ${i}`:i;else if(r||e.directives.docStart||!s)e.commentBefore=i;else if(tl.isCollection(s)&&!s.flow&&s.items.length>0){let o=s.items[0];tl.isPair(o)&&(o=o.key);let a=o.commentBefore;o.commentBefore=a?`${i} ${a}`:i}else{let o=s.commentBefore;s.commentBefore=o?`${i} -${o}`:i}}if(n){for(let s=0;s{let s=nn(e);s[0]+=n,this.onError(s,"BAD_DIRECTIVE",i,r)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let n=sh.composeDoc(this.options,this.directives,e,this.onError);this.atDirectives&&!n.directives.docStart&&this.onError(e,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(n,!1),this.doc&&(yield this.doc),this.doc=n,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(e.source);break;case"error":{let n=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,i=new tn.YAMLParseError(nn(e),"UNEXPECTED_TOKEN",n);this.atDirectives||!this.doc?this.errors.push(i):this.doc.errors.push(i);break}case"doc-end":{if(!this.doc){let i="Unexpected doc-end without preceding document";this.errors.push(new tn.YAMLParseError(nn(e),"UNEXPECTED_TOKEN",i));break}this.doc.directives.docEnd=!0;let n=oh.resolveEnd(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),n.comment){let i=this.doc.comment;this.doc.comment=i?`${i} -${n.comment}`:n.comment}this.doc.range[2]=n.offset;break}default:this.errors.push(new tn.YAMLParseError(nn(e),"UNEXPECTED_TOKEN",`Unsupported token ${e.type}`))}}*end(e=!1,n=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let i=Object.assign({_directives:this.directives},this.options),r=new rh.Document(void 0,i);this.atDirectives&&this.onError(n,"MISSING_CHAR","Missing directives-end indicator line"),r.range=[0,n,n],this.decorate(r,!1),yield r}}};il.Composer=Ts});var ol=v(Ci=>{"use strict";var ah=Rs(),ch=Os(),lh=Zt(),rl=Ft();function uh(t,e=!0,n){if(t){let i=(r,s,o)=>{let a=typeof r=="number"?r:Array.isArray(r)?r[0]:r.offset;if(n)n(a,s,o);else throw new lh.YAMLParseError([a,a+1],s,o)};switch(t.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return ch.resolveFlowScalar(t,e,i);case"block-scalar":return ah.resolveBlockScalar({options:{strict:e}},t,i)}}return null}function fh(t,e){let{implicitKey:n=!1,indent:i,inFlow:r=!1,offset:s=-1,type:o="PLAIN"}=e,a=rl.stringifyString({type:o,value:t},{implicitKey:n,indent:i>0?" ".repeat(i):"",inFlow:r,options:{blockQuote:!0,lineWidth:-1}}),c=e.end??[{type:"newline",offset:-1,indent:i,source:` +${o}`:i}}if(n){for(let s=0;s{let s=nn(e);s[0]+=n,this.onError(s,"BAD_DIRECTIVE",i,r)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let n=oh.composeDoc(this.options,this.directives,e,this.onError);this.atDirectives&&!n.directives.docStart&&this.onError(e,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(n,!1),this.doc&&(yield this.doc),this.doc=n,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(e.source);break;case"error":{let n=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,i=new tn.YAMLParseError(nn(e),"UNEXPECTED_TOKEN",n);this.atDirectives||!this.doc?this.errors.push(i):this.doc.errors.push(i);break}case"doc-end":{if(!this.doc){let i="Unexpected doc-end without preceding document";this.errors.push(new tn.YAMLParseError(nn(e),"UNEXPECTED_TOKEN",i));break}this.doc.directives.docEnd=!0;let n=ah.resolveEnd(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),n.comment){let i=this.doc.comment;this.doc.comment=i?`${i} +${n.comment}`:n.comment}this.doc.range[2]=n.offset;break}default:this.errors.push(new tn.YAMLParseError(nn(e),"UNEXPECTED_TOKEN",`Unsupported token ${e.type}`))}}*end(e=!1,n=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let i=Object.assign({_directives:this.directives},this.options),r=new sh.Document(void 0,i);this.atDirectives&&this.onError(n,"MISSING_CHAR","Missing directives-end indicator line"),r.range=[0,n,n],this.decorate(r,!1),yield r}}};il.Composer=Is});var ol=v(Ci=>{"use strict";var ch=Ns(),lh=As(),uh=Zt(),rl=Ft();function fh(t,e=!0,n){if(t){let i=(r,s,o)=>{let a=typeof r=="number"?r:Array.isArray(r)?r[0]:r.offset;if(n)n(a,s,o);else throw new uh.YAMLParseError([a,a+1],s,o)};switch(t.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return lh.resolveFlowScalar(t,e,i);case"block-scalar":return ch.resolveBlockScalar({options:{strict:e}},t,i)}}return null}function dh(t,e){let{implicitKey:n=!1,indent:i,inFlow:r=!1,offset:s=-1,type:o="PLAIN"}=e,a=rl.stringifyString({type:o,value:t},{implicitKey:n,indent:i>0?" ".repeat(i):"",inFlow:r,options:{blockQuote:!0,lineWidth:-1}}),c=e.end??[{type:"newline",offset:-1,indent:i,source:` `}];switch(a[0]){case"|":case">":{let l=a.indexOf(` -`),f=a.substring(0,l),u=a.substring(l+1)+` -`,d=[{type:"block-scalar-header",offset:s,indent:i,source:f}];return sl(d,c)||d.push({type:"newline",offset:-1,indent:i,source:` -`}),{type:"block-scalar",offset:s,indent:i,props:d,source:u}}case'"':return{type:"double-quoted-scalar",offset:s,indent:i,source:a,end:c};case"'":return{type:"single-quoted-scalar",offset:s,indent:i,source:a,end:c};default:return{type:"scalar",offset:s,indent:i,source:a,end:c}}}function dh(t,e,n={}){let{afterKey:i=!1,implicitKey:r=!1,inFlow:s=!1,type:o}=n,a="indent"in t?t.indent:null;if(i&&typeof a=="number"&&(a+=2),!o)switch(t.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let l=t.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let c=rl.stringifyString({type:o,value:e},{implicitKey:r||a===null,indent:a!==null&&a>0?" ".repeat(a):"",inFlow:s,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":ph(t,c);break;case'"':$s(t,c,"double-quoted-scalar");break;case"'":$s(t,c,"single-quoted-scalar");break;default:$s(t,c,"scalar")}}function ph(t,e){let n=e.indexOf(` +`),d=a.substring(0,l),u=a.substring(l+1)+` +`,f=[{type:"block-scalar-header",offset:s,indent:i,source:d}];return sl(f,c)||f.push({type:"newline",offset:-1,indent:i,source:` +`}),{type:"block-scalar",offset:s,indent:i,props:f,source:u}}case'"':return{type:"double-quoted-scalar",offset:s,indent:i,source:a,end:c};case"'":return{type:"single-quoted-scalar",offset:s,indent:i,source:a,end:c};default:return{type:"scalar",offset:s,indent:i,source:a,end:c}}}function ph(t,e,n={}){let{afterKey:i=!1,implicitKey:r=!1,inFlow:s=!1,type:o}=n,a="indent"in t?t.indent:null;if(i&&typeof a=="number"&&(a+=2),!o)switch(t.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let l=t.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let c=rl.stringifyString({type:o,value:e},{implicitKey:r||a===null,indent:a!==null&&a>0?" ".repeat(a):"",inFlow:s,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":mh(t,c);break;case'"':qs(t,c,"double-quoted-scalar");break;case"'":qs(t,c,"single-quoted-scalar");break;default:qs(t,c,"scalar")}}function mh(t,e){let n=e.indexOf(` `),i=e.substring(0,n),r=e.substring(n+1)+` `;if(t.type==="block-scalar"){let s=t.props[0];if(s.type!=="block-scalar-header")throw new Error("Invalid block scalar header");s.source=i,t.source=r}else{let{offset:s}=t,o="indent"in t?t.indent:-1,a=[{type:"block-scalar-header",offset:s,indent:o,source:i}];sl(a,"end"in t?t.end:void 0)||a.push({type:"newline",offset:-1,indent:o,source:` -`});for(let c of Object.keys(t))c!=="type"&&c!=="offset"&&delete t[c];Object.assign(t,{type:"block-scalar",indent:o,props:a,source:r})}}function sl(t,e){if(e)for(let n of e)switch(n.type){case"space":case"comment":t.push(n);break;case"newline":return t.push(n),!0}return!1}function $s(t,e,n){switch(t.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":t.type=n,t.source=e;break;case"block-scalar":{let i=t.props.slice(1),r=e.length;t.props[0].type==="block-scalar-header"&&(r-=t.props[0].source.length);for(let s of i)s.offset+=r;delete t.props,Object.assign(t,{type:n,source:e,end:i});break}case"block-map":case"block-seq":{let r={type:"newline",offset:t.offset+e.length,indent:t.indent,source:` -`};delete t.items,Object.assign(t,{type:n,source:e,end:[r]});break}default:{let i="indent"in t?t.indent:-1,r="end"in t&&Array.isArray(t.end)?t.end.filter(s=>s.type==="space"||s.type==="comment"||s.type==="newline"):[];for(let s of Object.keys(t))s!=="type"&&s!=="offset"&&delete t[s];Object.assign(t,{type:n,indent:i,source:e,end:r})}}}Ci.createScalarToken=fh;Ci.resolveAsScalar=uh;Ci.setScalarValue=dh});var cl=v(al=>{"use strict";var mh=t=>"type"in t?xi(t):Ei(t);function xi(t){switch(t.type){case"block-scalar":{let e="";for(let n of t.props)e+=xi(n);return e+t.source}case"block-map":case"block-seq":{let e="";for(let n of t.items)e+=Ei(n);return e}case"flow-collection":{let e=t.start.source;for(let n of t.items)e+=Ei(n);for(let n of t.end)e+=n.source;return e}case"document":{let e=Ei(t);if(t.end)for(let n of t.end)e+=n.source;return e}default:{let e=t.source;if("end"in t&&t.end)for(let n of t.end)e+=n.source;return e}}}function Ei({start:t,key:e,sep:n,value:i}){let r="";for(let s of t)r+=s.source;if(e&&(r+=xi(e)),n)for(let s of n)r+=s.source;return i&&(r+=xi(i)),r}al.stringify=mh});var dl=v(fl=>{"use strict";var qs=Symbol("break visit"),hh=Symbol("skip children"),ll=Symbol("remove item");function Xe(t,e){"type"in t&&t.type==="document"&&(t={start:t.start,value:t.value}),ul(Object.freeze([]),t,e)}Xe.BREAK=qs;Xe.SKIP=hh;Xe.REMOVE=ll;Xe.itemAtPath=(t,e)=>{let n=t;for(let[i,r]of e){let s=n?.[i];if(s&&"items"in s)n=s.items[r];else return}return n};Xe.parentCollection=(t,e)=>{let n=Xe.itemAtPath(t,e.slice(0,-1)),i=e[e.length-1][0],r=n?.[i];if(r&&"items"in r)return r;throw new Error("Parent collection not found")};function ul(t,e,n){let i=n(e,t);if(typeof i=="symbol")return i;for(let r of["key","value"]){let s=e[r];if(s&&"items"in s){for(let o=0;o{"use strict";var Ls=ol(),gh=cl(),wh=dl(),Ds="\uFEFF",Fs="",Ms="",Ws="",yh=t=>!!t&&"items"in t,vh=t=>!!t&&(t.type==="scalar"||t.type==="single-quoted-scalar"||t.type==="double-quoted-scalar"||t.type==="block-scalar");function bh(t){switch(t){case Ds:return"";case Fs:return"";case Ms:return"";case Ws:return"";default:return JSON.stringify(t)}}function kh(t){switch(t){case Ds:return"byte-order-mark";case Fs:return"doc-mode";case Ms:return"flow-error-end";case Ws:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case` +`});for(let c of Object.keys(t))c!=="type"&&c!=="offset"&&delete t[c];Object.assign(t,{type:"block-scalar",indent:o,props:a,source:r})}}function sl(t,e){if(e)for(let n of e)switch(n.type){case"space":case"comment":t.push(n);break;case"newline":return t.push(n),!0}return!1}function qs(t,e,n){switch(t.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":t.type=n,t.source=e;break;case"block-scalar":{let i=t.props.slice(1),r=e.length;t.props[0].type==="block-scalar-header"&&(r-=t.props[0].source.length);for(let s of i)s.offset+=r;delete t.props,Object.assign(t,{type:n,source:e,end:i});break}case"block-map":case"block-seq":{let r={type:"newline",offset:t.offset+e.length,indent:t.indent,source:` +`};delete t.items,Object.assign(t,{type:n,source:e,end:[r]});break}default:{let i="indent"in t?t.indent:-1,r="end"in t&&Array.isArray(t.end)?t.end.filter(s=>s.type==="space"||s.type==="comment"||s.type==="newline"):[];for(let s of Object.keys(t))s!=="type"&&s!=="offset"&&delete t[s];Object.assign(t,{type:n,indent:i,source:e,end:r})}}}Ci.createScalarToken=dh;Ci.resolveAsScalar=fh;Ci.setScalarValue=ph});var cl=v(al=>{"use strict";var hh=t=>"type"in t?xi(t):Ei(t);function xi(t){switch(t.type){case"block-scalar":{let e="";for(let n of t.props)e+=xi(n);return e+t.source}case"block-map":case"block-seq":{let e="";for(let n of t.items)e+=Ei(n);return e}case"flow-collection":{let e=t.start.source;for(let n of t.items)e+=Ei(n);for(let n of t.end)e+=n.source;return e}case"document":{let e=Ei(t);if(t.end)for(let n of t.end)e+=n.source;return e}default:{let e=t.source;if("end"in t&&t.end)for(let n of t.end)e+=n.source;return e}}}function Ei({start:t,key:e,sep:n,value:i}){let r="";for(let s of t)r+=s.source;if(e&&(r+=xi(e)),n)for(let s of n)r+=s.source;return i&&(r+=xi(i)),r}al.stringify=hh});var dl=v(fl=>{"use strict";var Ls=Symbol("break visit"),gh=Symbol("skip children"),ll=Symbol("remove item");function Ze(t,e){"type"in t&&t.type==="document"&&(t={start:t.start,value:t.value}),ul(Object.freeze([]),t,e)}Ze.BREAK=Ls;Ze.SKIP=gh;Ze.REMOVE=ll;Ze.itemAtPath=(t,e)=>{let n=t;for(let[i,r]of e){let s=n?.[i];if(s&&"items"in s)n=s.items[r];else return}return n};Ze.parentCollection=(t,e)=>{let n=Ze.itemAtPath(t,e.slice(0,-1)),i=e[e.length-1][0],r=n?.[i];if(r&&"items"in r)return r;throw new Error("Parent collection not found")};function ul(t,e,n){let i=n(e,t);if(typeof i=="symbol")return i;for(let r of["key","value"]){let s=e[r];if(s&&"items"in s){for(let o=0;o{"use strict";var Ds=ol(),wh=cl(),yh=dl(),Fs="\uFEFF",Ms="",Ws="",Bs="",vh=t=>!!t&&"items"in t,bh=t=>!!t&&(t.type==="scalar"||t.type==="single-quoted-scalar"||t.type==="double-quoted-scalar"||t.type==="block-scalar");function kh(t){switch(t){case Fs:return"";case Ms:return"";case Ws:return"";case Bs:return"";default:return JSON.stringify(t)}}function Sh(t){switch(t){case Fs:return"byte-order-mark";case Ms:return"doc-mode";case Ws:return"flow-error-end";case Bs:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case` `:case`\r -`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(t[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}ee.createScalarToken=Ls.createScalarToken;ee.resolveAsScalar=Ls.resolveAsScalar;ee.setScalarValue=Ls.setScalarValue;ee.stringify=gh.stringify;ee.visit=wh.visit;ee.BOM=Ds;ee.DOCUMENT=Fs;ee.FLOW_END=Ms;ee.SCALAR=Ws;ee.isCollection=yh;ee.isScalar=vh;ee.prettyToken=bh;ee.tokenType=kh});var Ys=v(ml=>{"use strict";var rn=_i();function ce(t){switch(t){case void 0:case" ":case` -`:case"\r":case" ":return!0;default:return!1}}var pl=new Set("0123456789ABCDEFabcdef"),Sh=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Pi=new Set(",[]{}"),Ch=new Set(` ,[]{} -\r `),Bs=t=>!t||Ch.has(t),Ks=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,n=!1){if(e){if(typeof e!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!n;let i=this.next??"stream";for(;i&&(n||this.hasChars(1));)i=yield*this.parseNext(i)}atLineEnd(){let e=this.pos,n=this.buffer[e];for(;n===" "||n===" ";)n=this.buffer[++e];return!n||n==="#"||n===` +`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(t[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}ee.createScalarToken=Ds.createScalarToken;ee.resolveAsScalar=Ds.resolveAsScalar;ee.setScalarValue=Ds.setScalarValue;ee.stringify=wh.stringify;ee.visit=yh.visit;ee.BOM=Fs;ee.DOCUMENT=Ms;ee.FLOW_END=Ws;ee.SCALAR=Bs;ee.isCollection=vh;ee.isScalar=bh;ee.prettyToken=kh;ee.tokenType=Sh});var Us=v(ml=>{"use strict";var rn=_i();function ce(t){switch(t){case void 0:case" ":case` +`:case"\r":case" ":return!0;default:return!1}}var pl=new Set("0123456789ABCDEFabcdef"),Ch=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Pi=new Set(",[]{}"),Eh=new Set(` ,[]{} +\r `),Ks=t=>!t||Eh.has(t),Ys=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,n=!1){if(e){if(typeof e!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!n;let i=this.next??"stream";for(;i&&(n||this.hasChars(1));)i=yield*this.parseNext(i)}atLineEnd(){let e=this.pos,n=this.buffer[e];for(;n===" "||n===" ";)n=this.buffer[++e];return!n||n==="#"||n===` `?!0:n==="\r"?this.buffer[e+1]===` `:!1}charAt(e){return this.buffer[this.pos+e]}continueScalar(e){let n=this.buffer[e];if(this.indentNext>0){let i=0;for(;n===" ";)n=this.buffer[++i+e];if(n==="\r"){let r=this.buffer[i+e+1];if(r===` `||!r&&!this.atEnd)return e+i+1}return n===` `||i>=this.indentNext||!n&&!this.atEnd?e+i:-1}if(n==="-"||n==="."){let i=this.buffer.substr(e,3);if((i==="---"||i==="...")&&ce(this.buffer[e+3]))return-1}return e}getLine(){let e=this.lineEndPos;return(typeof e!="number"||e!==-1&&ethis.indentValue&&!ce(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[e,n]=this.peek(2);if(!n&&!this.atEnd)return this.setNext("block-start");if((e==="-"||e==="?"||e===":")&&ce(n)){let i=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=i,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let e=this.getLine();if(e===null)return this.setNext("doc");let n=yield*this.pushIndicators();switch(e[n]){case"#":yield*this.pushCount(e.length-n);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(Bs),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return n+=yield*this.parseBlockScalarHeader(),n+=yield*this.pushSpaces(!0),yield*this.pushCount(e.length-n),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,n,i=-1;do e=yield*this.pushNewline(),e>0?(n=yield*this.pushSpaces(!1),this.indentValue=i=n):n=0,n+=yield*this.pushSpaces(!0);while(e+n>0);let r=this.getLine();if(r===null)return this.setNext("flow");if((i!==-1&&ithis.indentValue&&!ce(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[e,n]=this.peek(2);if(!n&&!this.atEnd)return this.setNext("block-start");if((e==="-"||e==="?"||e===":")&&ce(n)){let i=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=i,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let e=this.getLine();if(e===null)return this.setNext("doc");let n=yield*this.pushIndicators();switch(e[n]){case"#":yield*this.pushCount(e.length-n);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(Ks),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return n+=yield*this.parseBlockScalarHeader(),n+=yield*this.pushSpaces(!0),yield*this.pushCount(e.length-n),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,n,i=-1;do e=yield*this.pushNewline(),e>0?(n=yield*this.pushSpaces(!1),this.indentValue=i=n):n=0,n+=yield*this.pushSpaces(!0);while(e+n>0);let r=this.getLine();if(r===null)return this.setNext("flow");if((i!==-1&&i"0"&&n<="9")this.blockScalarIndent=Number(n)-1;else if(n!=="-")break}return yield*this.pushUntil(n=>ce(n)||n==="#")}*parseBlockScalar(){let e=this.pos-1,n=0,i;e:for(let s=this.pos;i=this.buffer[s];++s)switch(i){case" ":n+=1;break;case` `:e=s,n=0;break;case"\r":{let o=this.buffer[s+1];if(!o&&!this.atEnd)return this.setNext("block-scalar");if(o===` @@ -133,40 +133,40 @@ ${n.comment}`:n.comment}this.doc.range[2]=n.offset;break}default:this.errors.pus `&&s>=this.pos&&s+1+n>a)e=s;else break}while(!0);return yield rn.SCALAR,yield*this.pushToIndex(e+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let e=this.flowLevel>0,n=this.pos-1,i=this.pos-1,r;for(;r=this.buffer[++i];)if(r===":"){let s=this.buffer[i+1];if(ce(s)||e&&Pi.has(s))break;n=i}else if(ce(r)){let s=this.buffer[i+1];if(r==="\r"&&(s===` `?(i+=1,r=` `,s=this.buffer[i+1]):n=i),s==="#"||e&&Pi.has(s))break;if(r===` -`){let o=this.continueScalar(i+1);if(o===-1)break;i=Math.max(i,o-2)}}else{if(e&&Pi.has(r))break;n=i}return!r&&!this.atEnd?this.setNext("plain-scalar"):(yield rn.SCALAR,yield*this.pushToIndex(n+1,!0),e?"flow":"doc")}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,n){let i=this.buffer.slice(this.pos,e);return i?(yield i,this.pos+=i.length,i.length):(n&&(yield""),0)}*pushIndicators(){let e=0;e:for(;;){switch(this.charAt(0)){case"!":e+=yield*this.pushTag(),e+=yield*this.pushSpaces(!0);continue e;case"&":e+=yield*this.pushUntil(Bs),e+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let n=this.flowLevel>0,i=this.charAt(1);if(ce(i)||n&&Pi.has(i)){n?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,e+=yield*this.pushCount(1),e+=yield*this.pushSpaces(!0);continue e}}}break e}return e}*pushTag(){if(this.charAt(1)==="<"){let e=this.pos+2,n=this.buffer[e];for(;!ce(n)&&n!==">";)n=this.buffer[++e];return yield*this.pushToIndex(n===">"?e+1:e,!1)}else{let e=this.pos+1,n=this.buffer[e];for(;n;)if(Sh.has(n))n=this.buffer[++e];else if(n==="%"&&pl.has(this.buffer[e+1])&&pl.has(this.buffer[e+2]))n=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];return e===` +`){let o=this.continueScalar(i+1);if(o===-1)break;i=Math.max(i,o-2)}}else{if(e&&Pi.has(r))break;n=i}return!r&&!this.atEnd?this.setNext("plain-scalar"):(yield rn.SCALAR,yield*this.pushToIndex(n+1,!0),e?"flow":"doc")}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,n){let i=this.buffer.slice(this.pos,e);return i?(yield i,this.pos+=i.length,i.length):(n&&(yield""),0)}*pushIndicators(){let e=0;e:for(;;){switch(this.charAt(0)){case"!":e+=yield*this.pushTag(),e+=yield*this.pushSpaces(!0);continue e;case"&":e+=yield*this.pushUntil(Ks),e+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let n=this.flowLevel>0,i=this.charAt(1);if(ce(i)||n&&Pi.has(i)){n?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,e+=yield*this.pushCount(1),e+=yield*this.pushSpaces(!0);continue e}}}break e}return e}*pushTag(){if(this.charAt(1)==="<"){let e=this.pos+2,n=this.buffer[e];for(;!ce(n)&&n!==">";)n=this.buffer[++e];return yield*this.pushToIndex(n===">"?e+1:e,!1)}else{let e=this.pos+1,n=this.buffer[e];for(;n;)if(Ch.has(n))n=this.buffer[++e];else if(n==="%"&&pl.has(this.buffer[e+1])&&pl.has(this.buffer[e+2]))n=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];return e===` `?yield*this.pushCount(1):e==="\r"&&this.charAt(1)===` -`?yield*this.pushCount(2):0}*pushSpaces(e){let n=this.pos-1,i;do i=this.buffer[++n];while(i===" "||e&&i===" ");let r=n-this.pos;return r>0&&(yield this.buffer.substr(this.pos,r),this.pos=n),r}*pushUntil(e){let n=this.pos,i=this.buffer[n];for(;!e(i);)i=this.buffer[++n];return yield*this.pushToIndex(n,!1)}};ml.Lexer=Ks});var Vs=v(hl=>{"use strict";var Us=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let n=0,i=this.lineStarts.length;for(;n>1;this.lineStarts[s]{"use strict";var Eh=jn("process"),gl=_i(),xh=Ys();function je(t,e){for(let n=0;n=0;)switch(t[e].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;t[++e]?.type==="space";);return t.splice(e,t.length)}function Ni(t,e){if(e.length<1e5)Array.prototype.push.apply(t,e);else for(let n=0;n0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let e=this.peek(1);if(this.type==="doc-end"&&e?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!e)return yield*this.stream();switch(e.type){case"document":return yield*this.document(e);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(e);case"block-scalar":return yield*this.blockScalar(e);case"block-map":return yield*this.blockMap(e);case"block-seq":return yield*this.blockSequence(e);case"flow-collection":return yield*this.flowCollection(e);case"doc-end":return yield*this.documentEnd(e)}yield*this.pop()}peek(e){return this.stack[this.stack.length-e]}*pop(e){let n=e??this.stack.pop();if(!n)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield n;else{let i=this.peek(1);switch(n.type==="block-scalar"?n.indent="indent"in i?i.indent:0:n.type==="flow-collection"&&i.type==="document"&&(n.indent=0),n.type==="flow-collection"&&yl(n),i.type){case"document":i.value=n;break;case"block-scalar":i.props.push(n);break;case"block-map":{let r=i.items[i.items.length-1];if(r.value){i.items.push({start:[],key:n,sep:[]}),this.onKeyLine=!0;return}else if(r.sep)r.value=n;else{Object.assign(r,{key:n,sep:[]}),this.onKeyLine=!r.explicitKey;return}break}case"block-seq":{let r=i.items[i.items.length-1];r.value?i.items.push({start:[],value:n}):r.value=n;break}case"flow-collection":{let r=i.items[i.items.length-1];!r||r.value?i.items.push({start:[],key:n,sep:[]}):r.sep?r.value=n:Object.assign(r,{key:n,sep:[]});return}default:yield*this.pop(),yield*this.pop(n)}if((i.type==="document"||i.type==="block-map"||i.type==="block-seq")&&(n.type==="block-map"||n.type==="block-seq")){let r=n.items[n.items.length-1];r&&!r.sep&&!r.value&&r.start.length>0&&wl(r.start)===-1&&(n.indent===0||r.start.every(s=>s.type!=="comment"||s.indent0&&(yield this.buffer.substr(this.pos,r),this.pos=n),r}*pushUntil(e){let n=this.pos,i=this.buffer[n];for(;!e(i);)i=this.buffer[++n];return yield*this.pushToIndex(n,!1)}};ml.Lexer=Ys});var Js=v(hl=>{"use strict";var Vs=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let n=0,i=this.lineStarts.length;for(;n>1;this.lineStarts[s]{"use strict";var xh=jn("process"),gl=_i(),_h=Us();function je(t,e){for(let n=0;n=0;)switch(t[e].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;t[++e]?.type==="space";);return t.splice(e,t.length)}function Ni(t,e){if(e.length<1e5)Array.prototype.push.apply(t,e);else for(let n=0;n0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let e=this.peek(1);if(this.type==="doc-end"&&e?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!e)return yield*this.stream();switch(e.type){case"document":return yield*this.document(e);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(e);case"block-scalar":return yield*this.blockScalar(e);case"block-map":return yield*this.blockMap(e);case"block-seq":return yield*this.blockSequence(e);case"flow-collection":return yield*this.flowCollection(e);case"doc-end":return yield*this.documentEnd(e)}yield*this.pop()}peek(e){return this.stack[this.stack.length-e]}*pop(e){let n=e??this.stack.pop();if(!n)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield n;else{let i=this.peek(1);switch(n.type==="block-scalar"?n.indent="indent"in i?i.indent:0:n.type==="flow-collection"&&i.type==="document"&&(n.indent=0),n.type==="flow-collection"&&yl(n),i.type){case"document":i.value=n;break;case"block-scalar":i.props.push(n);break;case"block-map":{let r=i.items[i.items.length-1];if(r.value){i.items.push({start:[],key:n,sep:[]}),this.onKeyLine=!0;return}else if(r.sep)r.value=n;else{Object.assign(r,{key:n,sep:[]}),this.onKeyLine=!r.explicitKey;return}break}case"block-seq":{let r=i.items[i.items.length-1];r.value?i.items.push({start:[],value:n}):r.value=n;break}case"flow-collection":{let r=i.items[i.items.length-1];!r||r.value?i.items.push({start:[],key:n,sep:[]}):r.sep?r.value=n:Object.assign(r,{key:n,sep:[]});return}default:yield*this.pop(),yield*this.pop(n)}if((i.type==="document"||i.type==="block-map"||i.type==="block-seq")&&(n.type==="block-map"||n.type==="block-seq")){let r=n.items[n.items.length-1];r&&!r.sep&&!r.value&&r.start.length>0&&wl(r.start)===-1&&(n.indent===0||r.start.every(s=>s.type!=="comment"||s.indent=e.indent){let i=!this.onKeyLine&&this.indent===e.indent,r=i&&(n.sep||n.explicitKey)&&this.type!=="seq-item-ind",s=[];if(r&&n.sep&&!n.value){let o=[];for(let a=0;ae.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(s=n.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":r||n.value?(s.push(this.sourceToken),e.items.push({start:s}),this.onKeyLine=!0):n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"explicit-key-ind":!n.sep&&!n.explicitKey?(n.start.push(this.sourceToken),n.explicitKey=!0):r||n.value?(s.push(this.sourceToken),e.items.push({start:s,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(n.explicitKey)if(n.sep)if(n.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(je(n.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:s,key:null,sep:[this.sourceToken]}]});else if(vl(n.key)&&!je(n.sep,"newline")){let o=kt(n.start),a=n.key,c=n.sep;c.push(this.sourceToken),delete n.key,delete n.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:a,sep:c}]})}else s.length>0?n.sep=n.sep.concat(s,this.sourceToken):n.sep.push(this.sourceToken);else if(je(n.start,"newline"))Object.assign(n,{key:null,sep:[this.sourceToken]});else{let o=kt(n.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else n.sep?n.value||r?e.items.push({start:s,key:null,sep:[this.sourceToken]}):je(n.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):n.sep.push(this.sourceToken):Object.assign(n,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);r||n.value?(e.items.push({start:s,key:o,sep:[]}),this.onKeyLine=!0):n.sep?this.stack.push(o):(Object.assign(n,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(e);if(o){if(o.type==="block-seq"){if(!n.explicitKey&&n.sep&&!je(n.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else i&&e.items.push({start:s});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let n=e.items[e.items.length-1];switch(this.type){case"newline":if(n.value){let i="end"in n.value?n.value.end:void 0;(Array.isArray(i)?i[i.length-1]:void 0)?.type==="comment"?i?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else n.start.push(this.sourceToken);return;case"space":case"comment":if(n.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(n.start,e.indent)){let r=e.items[e.items.length-2]?.value?.end;if(Array.isArray(r)){Ni(r,n.start),r.push(this.sourceToken),e.items.pop();return}}n.start.push(this.sourceToken)}return;case"anchor":case"tag":if(n.value||this.indent<=e.indent)break;n.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;n.value||je(n.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):n.start.push(this.sourceToken);return}if(this.indent>e.indent){let i=this.startBlockValue(e);if(i){this.stack.push(i);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let n=e.items[e.items.length-1];if(this.type==="flow-error-end"){let i;do yield*this.pop(),i=this.peek(1);while(i?.type==="flow-collection")}else if(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!n||n.sep?e.items.push({start:[this.sourceToken]}):n.start.push(this.sourceToken);return;case"map-value-ind":!n||n.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):n.sep?n.sep.push(this.sourceToken):Object.assign(n,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!n||n.value?e.items.push({start:[this.sourceToken]}):n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let r=this.flowScalar(this.type);!n||n.value?e.items.push({start:[],key:r,sep:[]}):n.sep?this.stack.push(r):Object.assign(n,{key:r,sep:[]});return}case"flow-map-end":case"flow-seq-end":e.end.push(this.sourceToken);return}let i=this.startBlockValue(e);i?this.stack.push(i):(yield*this.pop(),yield*this.step())}else{let i=this.peek(2);if(i.type==="block-map"&&(this.type==="map-value-ind"&&i.indent===e.indent||this.type==="newline"&&!i.items[i.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&i.type!=="flow-collection"){let r=Ri(i),s=kt(r);yl(e);let o=e.end.splice(1,e.end.length);o.push(this.sourceToken);let a={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:s,key:e,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let n=this.source.indexOf(` `)+1;for(;n!==0;)this.onNewLine(this.offset+n),n=this.source.indexOf(` -`,n)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let n=Ri(e),i=kt(n);return i.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let n=Ri(e),i=kt(n);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,n){return this.type!=="comment"||this.indent<=n?!1:e.every(i=>i.type==="newline"||i.type==="space")}*documentEnd(e){this.type!=="doc-mode"&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};bl.Parser=Js});var xl=v(on=>{"use strict";var kl=Is(),_h=zt(),sn=Zt(),Ph=jr(),Rh=N(),Nh=Vs(),Sl=Hs();function Cl(t){let e=t.prettyErrors!==!1;return{lineCounter:t.lineCounter||e&&new Nh.LineCounter||null,prettyErrors:e}}function Oh(t,e={}){let{lineCounter:n,prettyErrors:i}=Cl(e),r=new Sl.Parser(n?.addNewLine),s=new kl.Composer(e),o=Array.from(s.compose(r.parse(t)));if(i&&n)for(let a of o)a.errors.forEach(sn.prettifyError(t,n)),a.warnings.forEach(sn.prettifyError(t,n));return o.length>0?o:Object.assign([],{empty:!0},s.streamInfo())}function El(t,e={}){let{lineCounter:n,prettyErrors:i}=Cl(e),r=new Sl.Parser(n?.addNewLine),s=new kl.Composer(e),o=null;for(let a of s.compose(r.parse(t),!0,t.length))if(!o)o=a;else if(o.options.logLevel!=="silent"){o.errors.push(new sn.YAMLParseError(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return i&&n&&(o.errors.forEach(sn.prettifyError(t,n)),o.warnings.forEach(sn.prettifyError(t,n))),o}function Ah(t,e,n){let i;typeof e=="function"?i=e:n===void 0&&e&&typeof e=="object"&&(n=e);let r=El(t,n);if(!r)return null;if(r.warnings.forEach(s=>Ph.warn(r.options.logLevel,s)),r.errors.length>0){if(r.options.logLevel!=="silent")throw r.errors[0];r.errors=[]}return r.toJS(Object.assign({reviver:i},n))}function jh(t,e,n){let i=null;if(typeof e=="function"||Array.isArray(e)?i=e:n===void 0&&e&&(n=e),typeof n=="string"&&(n=n.length),typeof n=="number"){let r=Math.round(n);n=r<1?void 0:r>8?{indent:8}:{indent:r}}if(t===void 0){let{keepUndefined:r}=n??e??{};if(!r)return}return Rh.isDocument(t)&&!i?t.toString(n):new _h.Document(t,i,n).toString(n)}on.parse=Ah;on.parseAllDocuments=Oh;on.parseDocument=El;on.stringify=jh});var Ie=v(O=>{"use strict";var Th=Is(),Ih=zt(),$h=ms(),Gs=Zt(),qh=It(),Te=N(),Lh=Re(),Dh=q(),Fh=Oe(),Mh=Ae(),Wh=_i(),Bh=Ys(),Kh=Vs(),Yh=Hs(),Oi=xl(),_l=Ot();O.Composer=Th.Composer;O.Document=Ih.Document;O.Schema=$h.Schema;O.YAMLError=Gs.YAMLError;O.YAMLParseError=Gs.YAMLParseError;O.YAMLWarning=Gs.YAMLWarning;O.Alias=qh.Alias;O.isAlias=Te.isAlias;O.isCollection=Te.isCollection;O.isDocument=Te.isDocument;O.isMap=Te.isMap;O.isNode=Te.isNode;O.isPair=Te.isPair;O.isScalar=Te.isScalar;O.isSeq=Te.isSeq;O.Pair=Lh.Pair;O.Scalar=Dh.Scalar;O.YAMLMap=Fh.YAMLMap;O.YAMLSeq=Mh.YAMLSeq;O.CST=Wh;O.Lexer=Bh.Lexer;O.LineCounter=Kh.LineCounter;O.Parser=Yh.Parser;O.parse=Oi.parse;O.parseAllDocuments=Oi.parseAllDocuments;O.parseDocument=Oi.parseDocument;O.stringify=Oi.stringify;O.visit=_l.visit;O.visitAsync=_l.visitAsync});var Ai=G(()=>{"use strict"});function $e(t){return t!==0&&t!==0n&&t!=="0"}function ji(t,e){return $e(t.dev)&&$e(e.dev)&&$e(t.ino)&&$e(e.ino)}function ye(t,e){let n=$e(t.dev)&&$e(e.dev);if(n&&t.dev!==e.dev)return!1;let i=$e(t.ino)&&$e(e.ino);return i&&t.ino!==e.ino?!1:n&&i?!0:t.birthtime===e.birthtime}var Ti=G(()=>{"use strict"});import{randomUUID as Uh}from"crypto";import{constants as Vh,promises as L}from"fs";import V from"path";async function zs(t,e){try{return await L.link(t,e),{linked:!0}}catch(n){let i=n.code;if(i!=="ENOTSUP"&&i!=="EOPNOTSUPP")throw n}return await L.copyFile(t,e,Vh.COPYFILE_EXCL),{linked:!1}}function St(t,e){let n=V.relative(t,e);return n===""||!V.isAbsolute(n)&&n!==".."&&!n.startsWith(`..${V.sep}`)}function $i(t){return{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs}}function Jh(t,e){return ye(t,$i(e))}function Ii(t,e){let n=$i(t),i=$i(e);return ji(n,i)?ye(n,i):ye(n,i)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.size===e.size}async function qi(t){let e=await L.lstat(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Contained atomic write parent must be a real directory: ${t}`);return{path:t,realPath:await L.realpath(t),...$i(e)}}async function qe(t){for(let e of t){let n=await L.lstat(e.path);if(!n.isDirectory()||n.isSymbolicLink()||!Jh(e,n)||await L.realpath(e.path)!==e.realPath)throw new Error(`Contained atomic write parent changed before commit: ${e.path}`)}}async function Hh(t,e){let n=V.resolve(t),i=V.resolve(e);if(!St(n,i))throw new Error(`Contained atomic write parent is outside its managed root: ${e}`);let r=[await qi(n)],s=V.relative(n,i).split(V.sep).filter(Boolean),o=n;for(let a of s){await qe(r),o=V.join(o,a);try{await L.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await qi(o);if(!St(r[0].realPath,c.realPath))throw new Error(`Contained atomic write parent resolves outside its managed root: ${o}`);r.push(c)}return await qe(r),r}async function Gh(t,e){let n=V.resolve(t),i=V.resolve(e);if(!St(n,i))throw new Error(`Contained file parent is outside its managed root: ${e}`);let r=[await qi(n)],s=V.relative(n,i).split(V.sep).filter(Boolean),o=n;for(let a of s){o=V.join(o,a);try{let c=await qi(o);if(!St(r[0].realPath,c.realPath))throw new Error(`Contained file parent resolves outside its managed root: ${o}`);r.push(c)}catch(c){if(c.code==="ENOENT")return null;throw c}}return await qe(r),r}async function Pl(t){let e;try{e=await L.open(t,"r"),await e.sync()}catch(n){let i=n.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(i??""))throw n}finally{await e?.close()}}async function zh(t,e,n){let i=V.dirname(t),r=await Hh(n.containedRoot,i),s=V.join(i,`.${V.basename(t)}.${Uh()}.tmp`),o,a;try{await n.beforeTemporaryOpen?.(),o=await L.open(s,"wx"),a=await o.stat();let[c,l]=await Promise.all([L.lstat(s),L.realpath(s)]);if(await qe(r),!c.isFile()||c.isSymbolicLink()||!Ii(a,c)||!St(r[0].realPath,l))throw new Error("Contained atomic write temporary file opened outside its managed parent");if(typeof e=="string"?await o.writeFile(e,"utf8"):await o.writeFile(e),await o.sync(),!Ii(a,await o.stat()))throw new Error("Contained atomic write temporary file changed while writing");await o.close(),o=void 0,await n.beforeCommit?.(),await qe(r);let f=await L.lstat(s);if(!f.isFile()||f.isSymbolicLink()||!Ii(f,a))throw new Error("Contained atomic write temporary file changed before commit");n.exclusive?(await zs(s,t),await L.unlink(s)):await L.rename(s,t),await Pl(i)}catch(c){await o?.close();try{await qe(r),await L.rm(s,{force:!0})}catch{}throw c}}async function me(t,e,n){await zh(t,e,n)}async function Qs(t,e){let n=V.dirname(t),i=await Gh(e.containedRoot,n);if(!i)return!1;let r,s;try{r=await L.lstat(t),s=await L.realpath(t)}catch(c){if(c.code==="ENOENT")return!1;throw c}if(!r.isFile()||r.isSymbolicLink()||!St(i[0].realPath,s))throw new Error("Contained file removal target must be a regular file inside its managed root");await e.beforeRemove?.(),await qe(i);let[o,a]=await Promise.all([L.lstat(t),L.realpath(t)]);if(!o.isFile()||o.isSymbolicLink()||!Ii(r,o)||a!==s)throw new Error("Contained file removal target changed before removal");return await L.unlink(t),await qe(i),await Pl(n),!0}var Ze=G(()=>{"use strict";Ti()});var Rl=G(()=>{"use strict"});var Xs=G(()=>{"use strict";Ai()});var Nl=G(()=>{"use strict";Ai();Xs()});import Li from"path";function ig(t,e){if(typeof t!="string")throw new Error(`${e} must be a string`);let n=t.trim();if(n.length===0||Li.posix.isAbsolute(n)||Li.win32.isAbsolute(n)||/^(?:~|[\\/])/u.test(n))throw new Error(`${e} must be a project-relative path`);if(n===".")return[];let i=n.replaceAll("\\","/").split("/");if(i.some(r=>r===".."))throw new Error(`${e} must stay inside the project root`);if(i.some(r=>r===""||r==="."))throw new Error(`${e} must not contain empty or dot path segments`);return i}function an(t){let e=ig(t,"native.artifact_root");return e.length===0?".":e.join("/")}function jl(t,e="docs"){let n=t??e;if(n!=="legacy"&&n!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return n}function et(t,e,n=!1){if(typeof t!="string")throw new Error(`${e} must be a string`);let i=t.trim().replaceAll("\\","/");if(i.length===0||Li.posix.isAbsolute(i)||Li.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${e} must be relative to its declared path base`);let r=i.split("/");if(r.some(s=>s===".."))throw new Error(`${e} must stay inside its declared path base`);if(r.some(s=>s===""||s==="."))throw new Error(`${e} must not contain empty or dot path segments`);if(!n&&/[*?]/u.test(i))throw new Error(`${e} cannot contain wildcards`);return r.join("/")}function cn(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function Tl(t,e,n){let i=t??e;if(i!=="en"&&i!=="zh-CN")throw new Error(`${n} must be en or zh-CN`);return i}function Il(t,e){if(typeof t!="string"||t.length===0||t.includes("\\")||t.includes("\0")||t.startsWith("/")||t.split("/").includes(".."))throw new Error(`${e} contains an unsafe pattern`);if(t.length>eo)throw new Error(`${e} exceeds ${eo} characters`);let n=0;for(let i=0;ito)throw new Error(`${e} contains more than ${to} wildcard tokens`);return t}function Ol(t,e,n){if(t===void 0)return[...n];if(!Array.isArray(t))throw new Error(`${e} contains an unsafe pattern`);return[...new Set(t.map(i=>Il(i,e)))].sort((i,r)=>i.localeCompare(r,"en"))}function Zs(t,e,n){let i=t??e;if(!Number.isSafeInteger(i)||i<1)throw new Error(`${n} must be a positive integer`);return i}function rg(t){if(t===void 0)return{...se,include:[...se.include],exclude:[...se.exclude]};let e=cn(t,"native.snapshot");return{include:Ol(e.include,"native.snapshot.include",se.include),exclude:Ol(e.exclude,"native.snapshot.exclude",se.exclude),max_files:Zs(e.max_files,se.max_files,"native.snapshot.max_files"),max_total_bytes:Zs(e.max_total_bytes,se.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:Zs(e.max_duration_ms,se.max_duration_ms,"native.snapshot.max_duration_ms")}}function sg(t){if(t===void 0)return;let e=cn(t,"native.pending_root_move"),n=e.id,i=e.from_artifact_root,r=e.to_artifact_root,s=e.stage;if(typeof n!="string"||!/^[a-f0-9-]{8,}$/u.test(n))throw new Error("native.pending_root_move.id is invalid");if(typeof i!="string"||typeof r!="string")throw new Error("native.pending_root_move roots must be strings");if(s!=="copying"&&s!=="ready"&&s!=="switched")throw new Error("native.pending_root_move.stage is invalid");let o;if(e.cleanup!==void 0){let a=cn(e.cleanup,"native.pending_root_move.cleanup"),c=a.kind,l=a.state,f=a.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof f!="string"||!/^[a-f0-9]{64}$/u.test(f))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:f}}return{id:n,fromArtifactRoot:an(i),toArtifactRoot:an(r),stage:s,...o?{cleanup:o}:{}}}function og(t,e={}){let n=cn(t,"native"),i=n.artifact_root??(e.allowMissingArtifactRoot?"docs":void 0);if(typeof i!="string")throw new Error("native.artifact_root must be a string");let r=n.clarification_mode??"sequential";if(r!=="sequential"&&r!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let s=n.archive_confirmation??"automatic";if(s!=="automatic"&&s!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=n.max_verify_failures??Al;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let a=sg(n.pending_root_move);return{artifact_root:an(i),language:Tl(n.language,"en","native.language"),clarification_mode:r,archive_confirmation:s,max_verify_failures:o,snapshot:rg(n.snapshot),...a?{pending_root_move:a}:{}}}function ag(t){let e=cn(t,"classic"),n=e.context_compression??"off";if(n!=="off"&&n!=="beta")throw new Error("classic.context_compression must be off or beta");let i=e.review_mode??"standard";if(i!=="off"&&i!=="standard"&&i!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let r=e.auto_transition??!0;if(typeof r!="boolean")throw new Error("classic.auto_transition must be true or false");return{artifact_layout:jl(e.artifact_layout),language:Tl(e.language,"zh-CN","classic.language"),context_compression:n,review_mode:i,auto_transition:r}}function cg(t){let e=t??!0;if(typeof e!="boolean")throw new Error("ambient_resume must be true or false");return e}function lg(t,e,n,i,r){let s=t.schema!==void 0;if(!(s||t.default_workflow!==void 0||t.workflows!==void 0||!r.allowPartialProject&&t.native!==void 0)||r.allowPartialProject&&!s)return null;if(t.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(t.default_workflow!=="native"&&t.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let a=t.workflows??[t.default_workflow];if(!Array.isArray(a)||a.length===0||a.some(l=>l!=="native"&&l!=="classic"))throw new Error("workflows must contain native and/or classic");let c=[...new Set(a)];if(!c.includes(t.default_workflow))throw new Error("workflows must include default_workflow");if(c.includes("native")&&!e)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:t.default_workflow,workflows:c,ambient_resume:i,...e?{native:e}:{},...n?{classic:n}:{}}}function Le(t,e={}){let n=(0,no.parseDocument)(t,{uniqueKeys:!0});if(n.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${n.errors[0].message}`);let i=n.toJS();if(i==null)return{value:{},config:null,ambient_resume:!0};if(typeof i!="object"||Array.isArray(i))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let r=i,s=cg(r.ambient_resume),o=r.native===void 0?void 0:og(r.native,{allowMissingArtifactRoot:e.allowMissingNativeFields}),a=r.classic===void 0?void 0:ag(r.classic),c=lg(r,o,a,s,{allowPartialProject:e.allowPartialProject??!1});return{value:r,config:c,ambient_resume:s,...o?{native:o}:{},...a?{classic:a}:{}}}function io(t="docs",e="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,native:{artifact_root:an(t),language:e,clarification_mode:"sequential",archive_confirmation:"automatic",max_verify_failures:Al,snapshot:{...se,include:[...se.include],exclude:[...se.exclude]}}}}var no,Ct,eo,to,Al,ng,se,ve=G(()=>{"use strict";no=Ve(Ie(),1),Ct=64*1024,eo=1024,to=64,Al=5,ng=[".agents/skills/**",".amazonq/skills/**",".augment/skills/**",".bob/skills/**",".claude/skills/**",".cline/skills/**",".codebuddy/skills/**",".continue/skills/**",".cospec/skills/**",".crush/skills/**",".cursor/skills/**",".factory/skills/**",".forge/skills/**",".gemini/skills/**",".github/skills/**",".iflow/skills/**",".junie/skills/**",".kilocode/skills/**",".kimi-code/skills/**",".kiro/skills/**",".lingma/skills/**",".mimocode/skills/**",".opencode/skills/**",".pi/skills/**",".qoder/skills/**",".qwen/skills/**",".roo/skills/**",".trae-cn/skills/**",".trae/skills/**",".windsurf/skills/**",".zcode/skills/**"],se={include:["**/*"],exclude:[...ng],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4}});import{constants as Di,promises as tt}from"fs";function ro(t){return"birthtimeNs"in t&&typeof t.birthtimeNs=="bigint"?t.birthtimeNs:t.birthtimeMs}function $l(t){return"ctimeNs"in t&&typeof t.ctimeNs=="bigint"?t.ctimeNs:t.ctimeMs}function ln(t){return{dev:t.dev,ino:t.ino,birthtime:ro(t)}}function Fi(t,e){let n=ln(t),i=ln(e);return ji(n,i)?ye(n,i):ye(n,i)&&ro(t)===ro(e)&&$l(t)===$l(e)&&t.size===e.size}async function ql(t,e,n={}){if(!Number.isSafeInteger(e)||e<1)throw new Error("race-safe read byte limit must be a positive integer");let i=n.label??"file",r=n.bigint===!0,s=await tt.lstat(t,{bigint:r});if(!s.isFile()||s.isSymbolicLink())throw new De("not-regular-file",`${i} must be a regular file`);if(BigInt(s.size)>BigInt(e))throw new De("too-large",`${i} exceeds ${e} bytes`);let o=await tt.realpath(t);await n.verify?.("pre-open",{realPath:o,identity:ln(s)});let a=process.platform==="win32"?Di.O_RDONLY:Di.O_RDONLY|Di.O_NOFOLLOW|Di.O_NONBLOCK,c;try{c=await tt.open(t,a)}catch(l){throw l.code==="ELOOP"?new De("not-regular-file",`${i} must be a regular file`,{cause:l}):l}try{let[l,f,u]=await Promise.all([c.stat({bigint:r}),tt.lstat(t,{bigint:r}),tt.realpath(t)]);if(!l.isFile()||!f.isFile()||f.isSymbolicLink()||u!==o||!Fi(s,l)||!Fi(s,f))throw new De("changed",`${i} changed while opening`);await n.verify?.("post-open",{realPath:u,identity:ln(l)}),await n.hooks?.afterOpen?.();let d=[],h=0,w=Buffer.allocUnsafe(Math.min(64*1024,e+1));for(;;){let y=e+1-h,{bytesRead:k}=await c.read(w,0,Math.min(w.length,y),null);if(k===0)break;if(h+=k,h>e)throw new De("too-large",`${i} exceeds ${e} bytes`);d.push(Buffer.from(w.subarray(0,k)))}await n.hooks?.beforeFinalCheck?.();let[p,m,g]=await Promise.all([c.stat({bigint:r}),tt.lstat(t,{bigint:r}),tt.realpath(t)]);if(!m.isFile()||m.isSymbolicLink()||g!==o||!Fi(s,p)||!Fi(s,m))throw new De("changed",`${i} changed while reading`);return await n.verify?.("post-read",{realPath:g,identity:ln(p)}),{bytes:Buffer.concat(d,h),stat:p,realPath:g}}finally{await c.close()}}var De,Ll=G(()=>{"use strict";Ti();De=class extends Error{reason;constructor(e,n,i){super(n,i),this.name="RaceSafeReadError",this.reason=e}}});import{promises as Mi}from"fs";import Fe from"path";function ug(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}function so(t,e){let n=Fe.relative(t,e);return n===""||!Fe.isAbsolute(n)&&n!==".."&&!n.startsWith(`..${Fe.sep}`)}async function Dl(t,e){let n=Fe.resolve(t),i=await Mi.lstat(n);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${e} project root must be a real directory`);return Mi.realpath(n)}async function Fl(t,e,n,i){let r=t;for(let s=0;s{if(!so(s,a.realPath))throw new Error(`${i.label} resolves outside the project root`);await Fl(r.projectRoot,s,r.relative.split("/"),{label:i.label,expected:"file"})}})}var le=G(()=>{"use strict";Ll();ve()});function fg(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}function dg(t){let e=(0,Wl.parseDocument)(t,{uniqueKeys:!0});if(e.errors.length>0)throw new Error(`Invalid global Comet config: ${e.errors[0].message}`);let n=e.toJS();if(n==null)return{};if(typeof n!="object"||Array.isArray(n))throw new Error("Invalid global Comet config: root must be a mapping");return n}function Kl(t){if(t.native?.pending_root_move)throw new Error("Global Comet config cannot contain native.pending_root_move");let e=t.native?(({pending_root_move:n,...i})=>i)(t.native):void 0;return{...t,schema:"comet.global.v1",...e?{native:e}:{}}}function pg(t){let e=Le(JSON.stringify({...t,schema:"comet.project.v1"})).config;if(!e)throw new Error("Invalid global Comet config: workflow template is incomplete");return Kl(e)}function mg(t){let e=Le(t,{allowPartialProject:!0,allowMissingNativeFields:!0});if(!e.native&&!e.classic)return null;let n=e.native?"native":"classic",i=e.native?.language??e.classic?.language??"en",r=io(e.native?.artifact_root??"docs",i);return{schema:"comet.global.v1",default_workflow:n,workflows:[n],ambient_resume:e.ambient_resume,...e.native?{native:{...r.native,...e.native}}:{},...e.classic?{classic:e.classic}:{}}}function Yl(t){let e=dg(t);if(Object.keys(e).length===0)return null;if(e.schema===void 0)return mg(t);if(e.schema!=="comet.global.v1")throw new Error("Unsupported Comet global schema");return pg(e)}async function ao(t){try{let e=await J(t,Bl,Ct,{label:"global Comet config"});return Yl(e.bytes.toString("utf8"))}catch(e){if(fg(e))return null;throw e}}var Wl,Bl,co=G(()=>{"use strict";Wl=Ve(Ie(),1);Ze();ve();le();Bl=".comet/config.yaml"});import{createHash as hg}from"crypto";function gg(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function Me(t,e={}){return(await Bi(t,e)).document}async function wg(t){try{return(await J(t,un,Ct,{label:un})).bytes}catch(e){if(gg(e))return null;throw e}}function yg(t){return t?{exists:!0,sha256:hg("sha256").update(t).digest("hex")}:{exists:!1,sha256:null}}async function Bi(t,e={}){let n=await wg(t);return{document:n?Le(n.toString("utf8"),e):null,identity:yg(n)}}var un,nt=G(()=>{"use strict";ve();le();un=".comet/config.yaml"});var Nk,lo=G(()=>{"use strict";Ze();nt();le();Nk=16*1024});var uo=G(()=>{"use strict";Ze();ve();nt();le();lo()});var Vl=G(()=>{"use strict";Ai();Ze();Rl();Nl();ve();co();le();nt();uo();lo();Xs()});import{TextDecoder as Eg}from"util";function Jl(t){return{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs}}function xg(t,e){try{return new Eg("utf-8",{fatal:!0}).decode(t.bytes)}catch(n){throw new Error(`${e} is not valid UTF-8`,{cause:n})}}async function fo(t,e,n,i,r={}){try{let s=await J(t,e,n,{label:i,hooks:r.hooks});return{result:s,text:xg(s,i)}}catch(s){let o=s.code;if(o==="ENOENT"||o==="ENOTDIR")return null;throw s}}async function fn(t,e,n,i,r={}){return(await fo(t,e,n,i,r))?.text??null}async function it(t,e,n,i,r,s={}){if(Buffer.byteLength(n,"utf8")>i)throw new Error(`${r} exceeds ${i} bytes`);let o=await fo(t,e,i,r),a=await D(t,e,{label:r,expected:"file"});await me(a.target,n,{containedRoot:a.projectRoot,beforeCommit:async()=>{await s.beforeCommit?.();let c=await fo(t,e,i,r);if(!(!o&&!c)){if(!o||!c)throw new Error(`${r} changed before commit`);if(o.result.realPath!==c.result.realPath||!ye(Jl(o.result.stat),Jl(c.result.stat))||o.text!==c.text)throw new Error(`${r} changed before commit`)}}})}async function Ki(t,e,n,i,r,s={}){let o=await fn(t,e,i,r);await it(t,e,`${o??""}${n}`,i,r,s)}async function po(t,e,n,i={}){let r=await D(t,e,{label:n,expected:"file"});return r.exists?Qs(r.target,{containedRoot:r.projectRoot,beforeRemove:i.beforeRemove}):!1}var Yi=G(()=>{"use strict";Vl();Ti()});var au={};gf(au,{RUN_STATE_FILE:()=>Zi,applyRunStateToDocument:()=>yo,readRunState:()=>vo,removeRunState:()=>bo,runStateFromDocument:()=>Xi,writeRunState:()=>er});import Zg from"path";function En(t,e){let n=t[e];if(typeof n!="string"||n.length===0)throw new Error(`Invalid Run state: ${e} must be a non-empty string`);return n}function Cn(t,e){let n=En(t,e);if(Zg.isAbsolute(n)||/^(?:[A-Za-z]:|[\\/]|~)/u.test(n)||n.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Run state: ${e} must stay inside the change directory`);return n}function ew(t){let e=t.run_retries??"{}",n;try{n=typeof e=="string"?JSON.parse(e):e}catch(i){throw new Error("Invalid Run state: run_retries must be a JSON object",{cause:i})}if(!n||typeof n!="object"||Array.isArray(n))throw new Error("Invalid Run state: run_retries must be a JSON object");for(let i of Object.values(n))if(!Number.isInteger(i)||Number(i)<0)throw new Error("Invalid Run state: retry counts must be non-negative integers");return n}function Xi(t){if(!t.run_id)return null;let e=En(t,"run_id"),n=En(t,"skill"),i=En(t,"skill_version"),r=En(t,"skill_hash"),s=Cn(t,"pending_ref"),o=Cn(t,"trajectory_ref"),a=Cn(t,"context_ref"),c=Cn(t,"artifacts_ref"),l=Cn(t,"checkpoint_ref"),f=Number(t.iteration);if(!Number.isInteger(f)||f<0)throw new Error("Invalid Run state: iteration must be a non-negative integer");if(t.orchestration!=="deterministic"&&t.orchestration!=="adaptive")throw new Error("Invalid Run state: orchestration must be deterministic or adaptive");if(t.run_status!=="running"&&t.run_status!=="waiting"&&t.run_status!=="completed"&&t.run_status!=="failed")throw new Error("Invalid Run state: run_status is invalid");return{runId:e,skill:n,skillVersion:i,skillHash:r,orchestration:t.orchestration,currentStep:su(t,"current_step"),iteration:f,pending:su(t,"pending"),pendingRef:s,trajectoryRef:o,contextRef:a,artifactsRef:c,checkpointRef:l,status:t.run_status,retries:ew(t)}}function yo(t,e){e?t.run_id=e.runId:delete t.run_id}function tw(t){return{runId:t.runId,skill:t.skill,skillVersion:t.skillVersion,skillHash:t.skillHash,orchestration:t.orchestration,currentStep:t.currentStep,iteration:t.iteration,pending:t.pending,pendingRef:t.pendingRef,trajectoryRef:t.trajectoryRef,contextRef:t.contextRef,artifactsRef:t.artifactsRef,checkpointRef:t.checkpointRef,status:t.status,retries:t.retries}}function nw(t){let e={run_id:t.runId,skill:t.skill,skill_version:t.skillVersion,skill_hash:t.skillHash,orchestration:t.orchestration,current_step:t.currentStep,iteration:t.iteration,pending:t.pending,pending_ref:t.pendingRef,trajectory_ref:t.trajectoryRef,context_ref:t.contextRef,artifacts_ref:t.artifactsRef,checkpoint_ref:t.checkpointRef,run_status:t.status,run_retries:JSON.stringify(t.retries)};return Xi(e)}async function vo(t,e={}){let n=await fn(t,Zi,ou,"Run state",e);if(n===null)return null;let i=JSON.parse(n);return nw(i)}async function er(t,e,n={}){await it(t,Zi,JSON.stringify(tw(e),null,2),ou,"Run state",n)}async function bo(t,e={}){await po(t,Zi,"Run state",e)}var su,Zi,ou,tr=G(()=>{"use strict";Yi();su=(t,e)=>{let n=t[e];return n==null?null:String(n)};Zi=".comet/run-state.json",ou=256*1024});var sf=Ve(Ie(),1);import{spawnSync as $y}from"child_process";import{createHash as rf}from"crypto";import{promises as qy}from"fs";import T from"path";import Ji from"path";Yi();import Ui from"path";var dn={trajectory:8*1024*1024,artifacts:1024*1024,context:1024*1024,pendingAction:256*1024,checkpoint:256*1024};function pn(t,e){if(Ui.isAbsolute(e))throw new Error("Run path must stay inside the change directory");let n=Ui.resolve(t),i=Ui.resolve(n,e);if(i!==n&&!i.startsWith(n+Ui.sep))throw new Error("Run path must stay inside the change directory")}async function mn(t,e,n,i={}){pn(t,e),await Ki(t,e,`${JSON.stringify(n)} -`,dn.trajectory,"Run trajectory",i)}async function Vi(t,e,n={}){pn(t,e);let i=await fn(t,e,dn.trajectory,"Run trajectory",n);return i===null?[]:i.split(/\r?\n/).map((r,s)=>({line:r,number:s+1})).filter(({line:r})=>r.length>0).map(({line:r,number:s})=>{try{return JSON.parse(r)}catch(o){throw new Error(`Invalid Trajectory event at line ${s}`,{cause:o})}})}async function Hl(t,e,n,i={}){pn(t,e),await it(t,e,JSON.stringify(n,null,2)+` -`,dn.artifacts,"Run artifacts",i)}async function Gl(t,e,n,i={}){pn(t,e),await it(t,e,n,dn.context,"Run context",i)}async function zl(t,e,n,i={}){pn(t,e),await it(t,e,JSON.stringify(n,null,2)+` -`,dn.checkpoint,"Run checkpoint",i)}function _g(t){if(t!=="build"&&t!=="verify")throw new Error(`Invalid command check scope: '${String(t)}'`)}function Pg(t,e="."){if(e.trim().length===0)throw new Error("Command check cwd cannot be blank");let n=Ji.resolve(t),i=Ji.resolve(n,e);if(i!==n&&!i.startsWith(n+Ji.sep))throw new Error(`Command check cwd must resolve within the project root: '${e}'`);return Ji.relative(n,i).replaceAll("\\","/")||"."}function Rg(t,e){if(e.type!=="command_check_recorded")return null;let n=e.data;if(typeof n!="object"||n===null||Array.isArray(n))return null;let{scope:i,command:r,exitCode:s,cwd:o}=n;if(i!=="build"&&i!=="verify"||typeof r!="string"||r.trim().length===0||!Number.isInteger(s)||typeof o!="string")return null;let a;try{a=Pg(t,o)}catch{return null}return{sequence:e.sequence,timestamp:e.timestamp,runId:e.runId,scope:i,command:r,exitCode:s,cwd:a}}async function Ql(t,e,n,i){_g(i);let r=await Vi(e,n.trajectoryRef);for(let s=r.length-1;s>=0;s-=1){let o=r[s];if(o.runId!==n.runId)continue;let a=Rg(t,o);if(a?.scope===i)return a}return null}import{promises as Kg}from"fs";import be from"path";import{promises as Ag}from"fs";import $ from"path";import{promises as Ng}from"fs";async function hn(t){try{return await Ng.access(t),!0}catch(e){if(Og(e))return!1;throw e}}function Og(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}ve();nt();uo();le();var gn=class extends Error{code="classic-layout-unavailable";constructor(e="Classic artifact layout is unavailable from .comet/config.yaml"){super(e),this.name="ClassicLayoutUnavailableError"}},mo=class extends Error{constructor(n,i,r){let s=z(r,n),o=z(r,i);super(`Classic layout conflict: both ${s}/ and ${o}/ exist; run comet doctor and resolve the conflict before writing`);this.configuredRoot=n;this.alternateRoot=i;this.name="ClassicLayoutConflictError"}configuredRoot;alternateRoot;code="classic-layout-conflict"},Xl=".comet/config.yaml";function jg(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function Zl(t){await D(t,Xl,{label:Xl,expected:"file"})}function eu(t,e){let n=$.resolve(t),i=e==="docs"?$.join(n,"docs"):n,r=$.join(i,"openspec"),s=$.join(n,"docs","superpowers");return{projectRoot:n,artifactLayout:e,openSpecBase:i,openSpecRoot:r,changesDir:$.join(r,"changes"),archiveDir:$.join(r,"changes","archive"),specsDir:$.join(r,"specs"),superpowersRoot:s,superpowersSpecsDir:$.join(s,"specs"),superpowersPlansDir:$.join(s,"plans"),superpowersReportsDir:$.join(s,"reports")}}async function Tg(t){await Zl(t);let e=await Me(t,{allowPartialProject:!0,allowMissingNativeFields:!0});if(!e?.config)throw new gn;if(!(e.config.workflows??[e.config.default_workflow]).includes("classic"))throw new gn("Classic artifact layout is unavailable because Classic is not enabled");return e.classic?.artifact_layout??"legacy"}async function Ig(t,e){return eu(t,e??await Tg(t))}async function $g(t,e){let n=await Ig(t,e),i=n.artifactLayout==="legacy"?"docs":"legacy",r=eu(t,i).openSpecRoot,[s,o]=await Promise.all([D(n.projectRoot,z(n.projectRoot,n.openSpecRoot),{label:"Configured Classic OpenSpec root",expected:"directory"}),D(n.projectRoot,z(n.projectRoot,r),{label:"Alternate Classic OpenSpec root",expected:"directory"})]),a=s.exists,c=o.exists;return{paths:n,configuredRootExists:a,alternateRoot:r,alternateRootExists:c,dualRoots:a&&c}}async function qg(t,e){let n=[t.openSpecRoot,t.changesDir,t.archiveDir,t.specsDir,e,t.superpowersRoot,t.superpowersSpecsDir,t.superpowersPlansDir,t.superpowersReportsDir];for(let i of n){let r=z(t.projectRoot,i);await D(t.projectRoot,r,{label:`Classic managed physical path ${r}`,expected:"directory"})}}async function rt(t,e,n={}){let i=await $g(t,e);if(await qg(i.paths,i.alternateRoot),i.dualRoots&&!n.allowAlternateRoot)throw new mo(i.paths.openSpecRoot,i.alternateRoot,i.paths.projectRoot);if(!i.configuredRootExists){let r=z(i.paths.projectRoot,i.paths.openSpecRoot),s=z(i.paths.projectRoot,i.alternateRoot);throw new gn(`Configured Classic OpenSpec root is missing: ${r} (alternate ${s} is ${i.alternateRootExists?"present":"missing"})`)}return i.paths}async function ho(t,e,n={}){let i=$.join($.resolve(t),".comet","classic-root-move.json");if(await hn(i))throw new Error("Classic root move transaction is incomplete; inspect it with comet doctor and recover it explicitly before writing");let r=await rt(t,e,n);if(!await hn(r.openSpecRoot))throw new Error(`Configured Classic OpenSpec root is missing: ${z(r.projectRoot,r.openSpecRoot)}`);return r}async function st(t){let e=$.resolve(t),n=null;try{(await Ag.lstat(e)).isDirectory()||(e=$.dirname(e))}catch(i){if(!jg(i))throw i}for(;;){$.basename(e)==="openspec"&&(n=$.dirname(e));let i=$.join(e,".comet","config.yaml"),r=!1;if(await hn(i))try{await Zl(e);let o=(await Me(e))?.value;r=!!o&&typeof o=="object"&&!Array.isArray(o)&&(o.schema==="comet.project.v1"||o.default_workflow!==void 0||o.native!==void 0)}catch{}if(r||await hn($.join(e,".git")))return e;let s=$.dirname(e);if(s===e)return n??$.resolve(t);e=s}}function z(t,e){return $.relative($.resolve(t),e).replaceAll("\\","/")}le();ve();import bn from"path";import{promises as Dg}from"fs";import Gi from"path";Ze();ve();le();import wn from"path";var Lg=2*1024*1024;function tu(t,e,n){let i=wn.resolve(t),r=wn.isAbsolute(e)?wn.resolve(e):wn.resolve(i,e),s=wn.relative(i,r).replaceAll("\\","/");return{root:i,relative:et(s,n),target:r}}async function We(t,e,n){let i=tu(t,e,n.label);return D(i.root,i.relative,n)}async function yn(t,e,n){return(await We(t,e,{label:n.label,expected:n.expected??"any"})).exists}async function nu(t,e,n,i){return await yn(t,e,{label:n,expected:"file"})?(await Hi(t,e,{label:n,hooks:i})).byteLength>0:!1}async function te(t,e,n){return(await Hi(t,e,n)).toString("utf8")}async function Hi(t,e,n){let i=tu(t,e,n.label);return(await J(i.root,i.relative,n.maxBytes??Lg,{label:n.label,hooks:n.hooks})).bytes}function vn(t){return t?/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t)?t.includes("..")?"Change name cannot contain '..' (path traversal not allowed)":null:`Invalid change name: '${t}' -Valid format: lowercase kebab-case (a-z, 0-9, single hyphens)`:"Change name cannot be empty"}function wo(t){let e=vn(t);if(e)throw new Error(e)}function Fg(t,e){return{label:z(t,e),directory:e}}async function go(t,e,n){let i=Fg(t,e);if(!(await We(t,e,{label:n,expected:"directory"})).exists)return{change:i,exists:!1,stateExists:!1};let s=await We(t,Gi.join(e,".comet.yaml"),{label:`${n} state`,expected:"file"});return{change:i,exists:!0,stateExists:s.exists}}function Mg(t,e){let n=e.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&");return new RegExp(`^\\d{4}-\\d{2}-\\d{2}-${n}$`,"u").test(t)}async function Wg(t,e,n,i={}){if(!i.skipExactCompatibility){let o=await go(t,Gi.join(e,n),`Classic archived change ${n}`);if(o.exists)return o.change}if(!(await We(t,e,{label:"Classic archive directory",expected:"directory"})).exists)return null;let s=[];for(let o of await Dg.readdir(e,{withFileTypes:!0})){if(!Mg(o.name,n))continue;let a=await go(t,Gi.join(e,o.name),`Classic archived change ${o.name}`);a.exists&&a.stateExists&&s.push(a.change)}return s.sort((o,a)=>a.directory.localeCompare(o.directory))[0]??null}async function zi(t,e=process.cwd()){wo(t);let n=await rt(e),i=await go(n.projectRoot,Gi.join(n.changesDir,t),`Classic active change ${t}`);if(i.exists)return i.change;let r=await Wg(n.projectRoot,n.archiveDir,t);return r||i.change}function Bg(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function iu(t,e,n,i){let r=et(n,"Classic handoff artifact pointer");if((await D(t,r,{label:"Classic handoff artifact",expected:"file"})).exists)return null;let o=await rt(t),a=`${z(t,o.changesDir)}/`,l=(o.artifactLayout==="docs"?[a,"openspec/changes/"]:[a]).find(y=>r.startsWith(y));if(!l)return null;let f=r.slice(l.length).split("/");if(f.length<4||f[1]!==".comet"||f.slice(2).some(y=>y.length===0))return null;let u=f[0];wo(u);let d=f.slice(2),h=bn.resolve(e);if(bn.dirname(h)!==bn.resolve(o.archiveDir))return null;let w=bn.basename(h),p=/^\d{4}-\d{2}-\d{2}-(.+)$/u.exec(w);if(w!==u&&p?.[1]!==u)return null;await D(t,z(t,h),{label:"Classic archived change directory",expected:"directory"});let m=bn.join(h,".comet",...d),g=z(t,m);try{return await J(t,g,i,{label:"Historical Classic archived handoff artifact"}),g}catch(y){if(Bg(y))return null;throw y}}le();var ru=2*1024*1024;function kn(t,e){return be.relative(t,e).split(be.sep).join("/")}async function Sn(t,e,n){if(!n)return{code:e,satisfied:!1};let i=n.replaceAll("\\","/");try{let r=await Wi(t,i,{label:`${e} artifact`});return{code:e,satisfied:r,source:i,...r?{resolvedSource:i}:{}}}catch(r){return{code:e,satisfied:!1,source:i,detail:`unsafe artifact pointer outside the project or through a special path: ${r instanceof Error?r.message:String(r)}`}}}async function Yg(t,e,n){try{await rt(t)}catch(r){return{code:"design.handoff",satisfied:!1,...n?{source:n.replaceAll("\\","/")}:{},detail:`Classic layout is unsafe or unavailable for handoff evidence: ${r instanceof Error?r.message:String(r)}`}}let i=await Sn(t,"design.handoff",n);if(!n||i.satisfied||i.detail)return i;try{let r=await iu(t,e,n,ru);return r?{...i,satisfied:!0,resolvedSource:r,detail:`resolved historical legacy pointer from archived change: ${r}`}:i}catch(r){return{...i,satisfied:!1,detail:`unsafe archived handoff fallback: ${r instanceof Error?r.message:String(r)}`}}}async function Qi(t,e,n){return Sn(t,e,kn(t,n))}async function Ug(t,e){let n=be.join(e,"specs"),i;try{let o=kn(t,n);if(!(await D(t,o,{label:"OpenSpec delta-spec directory",expected:"directory"})).exists)return{code:"openspec.delta-spec",satisfied:!1};i=await Kg.readdir(n)}catch(o){return o.code==="ENOENT"?{code:"openspec.delta-spec",satisfied:!1}:{code:"openspec.delta-spec",satisfied:!1,detail:`unsafe delta-spec path: ${o instanceof Error?o.message:String(o)}`}}let r=i.map(o=>be.join(n,o,"spec.md")),s=(await Promise.all(r.map(async o=>{try{return await Wi(t,kn(t,o),{label:"OpenSpec delta spec"})?o:null}catch{return null}}))).filter(o=>o!==null);return{code:"openspec.delta-spec",satisfied:s.length>0,source:s[0]?kn(t,s[0]):void 0,detail:`${s.length} delta spec${s.length===1?"":"s"}`}}async function Vg(t,e){let n,i=kn(t,e);try{n=(await J(t,i,ru,{label:"Classic tasks artifact"})).bytes.toString("utf8")}catch(o){return o.code==="ENOENT"?{code:"build.tasks-complete",satisfied:!1}:{code:"build.tasks-complete",satisfied:!1,source:i,detail:`unsafe tasks artifact: ${o instanceof Error?o.message:String(o)}`}}let r=[...n.matchAll(/^\s*[-*]\s+\[([ xX])\]\s+/gmu)],s=r.filter(o=>o[1].toLowerCase()==="x").length;return{code:"build.tasks-complete",satisfied:r.length>0&&s===r.length,source:i,detail:`${s} of ${r.length} tasks complete`}}function ot(t,e){return t.some(n=>n.code===e&&n.satisfied)}async function Be(t,e){let n=await st(t),i=e.classic,r=be.join(t,"proposal.md"),s=be.join(t,"design.md"),o=be.join(t,"tasks.md"),a=e.run?be.resolve(t,e.run.checkpointRef):be.join(t,".comet","checkpoint.json"),c=await Promise.all([Qi(n,"openspec.proposal",r),Qi(n,"openspec.design",s),Qi(n,"openspec.tasks",o),Ug(n,t),Sn(n,"design.document",i?.designDoc??null),Sn(n,"build.plan",i?.plan??null),Vg(n,o),Sn(n,"verification.report",i?.verificationReport??null),Yg(n,t,i?.handoffContext??null),Qi(n,"run.checkpoint",a)]),l=c.find(f=>f.code==="design.handoff");return l&&!i?.handoffHash&&(l.satisfied=!1,l.detail="handoff hash is missing"),c.push({code:"archive.confirmed",satisfied:i?.archiveConfirmation==="confirmed"}),c}import{promises as qu}from"fs";import ie from"path";import{fileURLToPath as Lu}from"url";import{createHash as Hw,randomUUID as Gw}from"crypto";import{promises as Ro}from"fs";import ke from"path";function Jg(t){return t.classicProfile??t.workflow}function Hg(t){return!t.buildMode||!t.tddMode||!t.isolation||!t.verifyMode?!1:t.buildMode==="subagent-driven-development"?t.subagentDispatch==="confirmed":t.buildMode==="direct"?t.directOverride===!0:!0}function Gg(t){return t.buildMode==="direct"&&t.tddMode==="direct"&&t.isolation!==null&&t.verifyMode==="light"}function zg(t,e,n){if(e.verifyResult==="fail")return t==="full"?"full.build.fix":`${t}.build.execute`;if(t==="full"){if(!ot(n,"build.plan"))return"full.build.plan";if(e.buildPause==="plan-ready")return"full.build.plan-ready";if(!Hg(e))return"full.build.configure"}else if(!Gg(e))throw new Error(`${t} build configuration is incomplete`);return ot(n,"build.tasks-complete")?`${t}.build.complete`:`${t}.build.execute`}function Qg(t,e,n){return e.verifyResult!=="pass"||!ot(n,"verification.report")?`${t}.verify.run`:`${t}.verify.branch`}function Xg(t,e){if(e.verifyResult!=="pass")throw new Error("archive requires verify_result=pass");return e.archiveConfirmation==="confirmed"?`${t}.archive.execute`:`${t}.archive.confirm`}function Et(t,e){let n=Jg(t);if(t.archived&&t.phase!=="archive")throw new Error("archived=true requires phase=archive");if(t.archived)return"completed";if(n!=="full"&&t.phase==="design")throw new Error(`${n} workflow cannot enter design`);switch(t.phase){case"open":return`${n}.open`;case"design":return ot(e,"design.handoff")?"full.design.document":"full.design.handoff";case"build":return zg(n,t,e);case"verify":return Qg(n,t,e);case"archive":return Xg(n,t)}}var rr=Ve(Ie(),1);Ze();le();import ir from"path";tr();var cu=["full","hotfix","tweak"],at=1,iw=["open","design","build","verify","archive"],rw=["en","zh-CN"],sw=["off","beta"],ow=["subagent-driven-development","executing-plans","direct"],aw=["plan-ready"],cw=["confirmed"],lw=["tdd","direct"],uw=["off","standard","thorough"],fw=["current","branch","worktree"],dw=["light","full"],pw=["pending","pass","fail"],mw=["pending","handled"],hw=["pending","confirmed"],_t=["workflow","language","phase","context_compression","build_mode","build_pause","subagent_dispatch","tdd_mode","review_mode","isolation","bound_branch","verify_mode","auto_transition","base_ref","design_doc","plan","verify_result","verify_failures","verification_report","branch_status","created_at","verified_at","archive_confirmation","archived","direct_override","handoff_context","handoff_hash","classic_profile","classic_migration"],So=["run_id"],gw=new Set([..._t,...So]),ww=["workflow","phase","design_doc","plan","build_mode","isolation","verify_mode","verify_result","verified_at","archived"];function lu(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function xt(t,e){let n=t[e];if(n==null||n==="")return null;if(typeof n!="string")throw new Error(`Invalid Classic state: ${e} must be a string or null`);return n}function Q(t,e,n,i=!0){let r=t[e];if(r==null||r===""){if(i)return null;throw new Error(`Invalid Classic state: ${e} is required`)}if(typeof r!="string"||!n.includes(r))throw new Error(`Invalid Classic state: ${e} must be one of ${n.join(", ")}${i?" or null":""}`);return r}function ko(t,e,n=!0){let i=t[e];if(i==null||i===""){if(n)return null;throw new Error(`Invalid Classic state: ${e} is required`)}if(typeof i!="boolean")throw new Error(`Invalid Classic state: ${e} must be true or false`);return i}function yw(t,e,n=0){let i=t[e];if(i==null||i==="")return n;if(typeof i!="number"||!Number.isInteger(i)||i<0)throw new Error(`Invalid Classic state: ${e} must be a non-negative integer`);return i}function nr(t,e){let n=xt(t,e);if(n===null)return null;if(/^(?:[A-Za-z]:|[\\/]|~)/u.test(n)||n.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Classic state: ${e} must be a relative repository path`);return n}function vw(t,e){let n=xt(t,e);if(n!==null&&!/^[a-f0-9]{64}$/u.test(n))throw new Error(`Invalid Classic state: ${e} must be a sha256 hex digest`);return n}function bw(t){let e=t.classic_migration;if(e==null||e==="")return null;if(e!==at)throw new Error(`Invalid Classic state: classic_migration must be ${at}`);return e}function kw(t){if(!_t.some(n=>lu(t,n)))return null;for(let n of ww)if(!lu(t,n))return null;return{workflow:Q(t,"workflow",cu,!1),language:Q(t,"language",rw),phase:Q(t,"phase",iw,!1),contextCompression:Q(t,"context_compression",sw),buildMode:Q(t,"build_mode",ow),buildPause:Q(t,"build_pause",aw),subagentDispatch:Q(t,"subagent_dispatch",cw),tddMode:Q(t,"tdd_mode",lw),reviewMode:Q(t,"review_mode",uw),isolation:Q(t,"isolation",fw),boundBranch:xt(t,"bound_branch"),verifyMode:Q(t,"verify_mode",dw),autoTransition:ko(t,"auto_transition"),baseRef:xt(t,"base_ref"),designDoc:nr(t,"design_doc"),plan:nr(t,"plan"),verifyResult:Q(t,"verify_result",pw,!1),verifyFailures:yw(t,"verify_failures"),verificationReport:nr(t,"verification_report"),branchStatus:Q(t,"branch_status",mw),createdAt:xt(t,"created_at"),verifiedAt:xt(t,"verified_at"),archiveConfirmation:Q(t,"archive_confirmation",hw),archived:ko(t,"archived",!1),directOverride:ko(t,"direct_override"),handoffContext:nr(t,"handoff_context"),handoffHash:vw(t,"handoff_hash"),classicProfile:Q(t,"classic_profile",cu),classicMigration:bw(t)}}function Co(t,e){let n=e??null;if(n===null&&e===void 0&&t.run_id&&t.skill)try{n=Xi(t)}catch(i){let r=i instanceof Error?i.message:String(i);throw new Error(r.replace(/^Invalid Run state:/u,"Invalid Classic state:"),{cause:i})}return{classic:kw(t),run:n,unknownKeys:Object.keys(t).filter(i=>!gw.has(i))}}function uu(t){return{workflow:t.workflow,language:t.language,phase:t.phase,context_compression:t.contextCompression,build_mode:t.buildMode,build_pause:t.buildPause,subagent_dispatch:t.subagentDispatch,tdd_mode:t.tddMode,review_mode:t.reviewMode,isolation:t.isolation,bound_branch:t.boundBranch,verify_mode:t.verifyMode,auto_transition:t.autoTransition,base_ref:t.baseRef,design_doc:t.designDoc,plan:t.plan,verify_result:t.verifyResult,verify_failures:t.verifyFailures,verification_report:t.verificationReport,branch_status:t.branchStatus,created_at:t.createdAt,verified_at:t.verifiedAt,archive_confirmation:t.archiveConfirmation,archived:t.archived,direct_override:t.directOverride,handoff_context:t.handoffContext,handoff_hash:t.handoffHash,classic_profile:t.classicProfile,classic_migration:t.classicMigration}}tr();var Sw=2*1024*1024;function xn(t){let e=t.toJS();if(e===null)return{};if(typeof e!="object"||Array.isArray(e))throw new Error("Invalid Classic state document: root must be a mapping");return e}function fu(t,e,n){t.get(e)!==n&&t.set(e,n)}function Cw(t,e){if(e.classic)for(let[n,i]of Object.entries(uu(e.classic)))fu(t,n,i);else for(let n of _t)t.delete(n);yo(t.toJS(),e.run),e.run?fu(t,"run_id",e.run.runId):t.delete("run_id")}function Ew(t){let e=["skill","skill_version","skill_hash","orchestration","current_step","iteration","pending","pending_ref","trajectory_ref","context_ref","artifacts_ref","checkpoint_ref","run_status","run_retries"];for(let n of e)t.delete(n)}function xw(t){let e=!1;for(let n of["build_command","verify_command"])t.has(n)&&(t.delete(n),e=!0);return e}async function du(t){let e;try{e=(await J(ir.dirname(t),ir.basename(t),Sw,{label:"Classic state document"})).bytes.toString("utf8")}catch(i){if(i.code!=="ENOENT")throw i;return new rr.Document({})}let n=(0,rr.parseDocument)(e);if(n.errors.length>0)throw new Error(`Invalid Classic state document: ${n.errors[0].message}`);return xn(n),n}async function Ke(t,e={}){let n=e.migrate!==!1,i=ir.join(t,".comet.yaml"),r=await du(i),s=xn(r),o=xw(r);o&&(s=xn(r));let a=await vo(t);if(!a&&s.run_id&&s.skill){let{runStateFromDocument:c}=await Promise.resolve().then(()=>(tr(),au));a=c(s),a&&n&&(await er(t,a),Ew(r),o=!0)}return o&&n&&await me(i,r.toString(),{containedRoot:t}),Co(xn(r),a)}async function sr(t,e,n={}){let i=ir.join(t,".comet.yaml"),r=await du(i);Cw(r,{...e,unknownKeys:e.unknownKeys??[]}),Co(xn(r),e.run??null),await me(i,r.toString(),{containedRoot:t,beforeCommit:n.beforeCommit}),e.run?await er(t,e.run):await bo(t)}function pu(t,e,n){return{runId:e,skill:t.definition.metadata.name,skillVersion:t.definition.metadata.version,skillHash:n,orchestration:t.definition.orchestration.mode,currentStep:t.definition.orchestration.entry??null,iteration:0,pending:null,pendingRef:".comet/pending-action.json",trajectoryRef:".comet/trajectory.jsonl",contextRef:".comet/context.md",artifactsRef:".comet/artifacts.json",checkpointRef:".comet/checkpoint.json",status:"running",retries:{}}}import{createHash as Pu,randomUUID as Kw}from"crypto";import{promises as K}from"fs";import F from"path";var gu=Ve(Ie(),1);import{promises as Eo}from"fs";import oe from"path";var _w=["invoke_skill","call_tool","handoff","ask_user","checkpoint"],Pw=["deterministic","adaptive"],Rw=["function","mcp","script","agent"],Nw=["none","read","write","external"],Ow=["progress","step","completion"],Aw=["artifact_exists","state_equals"];function ct(t,e,n){return new Error(`${t}: ${e} ${n}`)}function ne(t,e,n="document"){if(t===null||typeof t!="object"||Array.isArray(t))throw ct(e,n,"must be an object")}function Ye(t,e,n){if(!Array.isArray(t))throw ct(e,n,"must be an array")}function X(t,e,n){if(typeof t!="string")throw ct(e,n,"must be a string")}function ue(t,e,n,i){e in t&&X(t[e],n,`${i}.${e}`)}function wu(t,e,n,i){if(e in t&&typeof t[e]!="boolean")throw ct(n,`${i}.${e}`,"must be a boolean")}function Ue(t,e,n,i){if(typeof t!="string"||!e.includes(t))throw ct(n,i,`must be one of ${e.join(", ")}`)}function or(t,e,n){Ye(t,e,n),t.forEach((i,r)=>{X(i,e,`${n}[${r}]`)})}function mu(t,e,n){ne(t,e,n),X(t.name,e,`${n}.name`),X(t.description,e,`${n}.description`),wu(t,"required",e,n)}function jw(t,e,n){ne(t,e,n),X(t.id,e,`${n}.id`),ue(t,"source",e,n),ue(t,"version",e,n)}function Tw(t,e,n){ne(t,e,n),X(t.id,e,`${n}.id`),X(t.role,e,`${n}.role`),ue(t,"instructions",e,n)}function Iw(t,e,n){ne(t,e,n),X(t.id,e,`${n}.id`),Ue(t.kind,Rw,e,`${n}.kind`),X(t.source,e,`${n}.source`),Ue(t.sideEffect,Nw,e,`${n}.sideEffect`),wu(t,"requiresConfirmation",e,n)}function $w(t,e,n){ne(t,e,n),Ue(t.type,_w,e,`${n}.type`),ue(t,"ref",e,n),ue(t,"prompt",e,n),ue(t,"question",e,n),"options"in t&&or(t.options,e,`${n}.options`)}function qw(t,e,n){ne(t,e,n),X(t.id,e,`${n}.id`),$w(t.action,e,`${n}.action`),ue(t,"next",e,n),"completionEvals"in t&&or(t.completionEvals,e,`${n}.completionEvals`)}function Lw(t,e){let n="goal";ne(t,e,n),X(t.statement,e,`${n}.statement`),Ye(t.inputs,e,`${n}.inputs`),t.inputs.forEach((i,r)=>{mu(i,e,`${n}.inputs[${r}]`)}),Ye(t.outputs,e,`${n}.outputs`),t.outputs.forEach((i,r)=>{mu(i,e,`${n}.outputs[${r}]`)}),or(t.success,e,`${n}.success`)}function Dw(t,e){let n="orchestration";ne(t,e,n),Ue(t.mode,Pw,e,`${n}.mode`),ue(t,"entry",e,n),"steps"in t&&(Ye(t.steps,e,`${n}.steps`),t.steps.forEach((i,r)=>{qw(i,e,`${n}.steps[${r}]`)}))}function yu(t,e){return ne(t,e),Ue(t.apiVersion,["comet/v1alpha1"],e,"apiVersion"),Ue(t.kind,["Skill"],e,"kind"),ne(t.metadata,e,"metadata"),X(t.metadata.name,e,"metadata.name"),X(t.metadata.version,e,"metadata.version"),X(t.metadata.description,e,"metadata.description"),Lw(t.goal,e),Dw(t.orchestration,e),Ye(t.skills,e,"skills"),t.skills.forEach((n,i)=>{jw(n,e,`skills[${i}]`)}),Ye(t.agents,e,"agents"),t.agents.forEach((n,i)=>{Tw(n,e,`agents[${i}]`)}),Ye(t.tools,e,"tools"),t.tools.forEach((n,i)=>{Iw(n,e,`tools[${i}]`)}),t}function vu(t,e){ne(t,e);for(let n of["allowedSkills","allowedAgents","allowedTools","confirmationRequiredFor"])n in t&&or(t[n],e,n);for(let n of["maxIterations","maxRetriesPerAction"])if(n in t&&(typeof t[n]!="number"||!Number.isFinite(t[n])))throw ct(e,n,"must be a finite number");return t}function Fw(t,e){return ne(t,e),"runtime"in t&&bu(t.runtime,e,"runtime"),t}function bu(t,e,n){return Ye(t,e,n),t.forEach((i,r)=>{let s=`${n}[${r}]`;ne(i,e,s),X(i.id,e,`${s}.id`),Ue(i.scope,Ow,e,`${s}.scope`),Ue(i.type,Aw,e,`${s}.type`),ue(i,"artifact",e,s),ue(i,"field",e,s),ue(i,"equals",e,s)}),t}async function xo(t){let e=await Eo.readFile(t,"utf8");try{return(0,gu.parse)(e)}catch(n){let i=n instanceof Error?n.message:String(n);throw ct(t,"document",i)}}async function Mw(t){try{return await xo(t)}catch(e){if(e.code==="ENOENT")return null;throw e}}async function hu(t){try{return await Eo.access(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function Ww(t){let e=oe.join(t,"checks.yaml"),n=oe.join(t,"evals.yaml"),[i,r]=await Promise.all([hu(e),hu(n)]);if(r)throw new Error(`${n}: evals.yaml is no longer supported; use checks.yaml`);return i?{document:Fw(await xo(e),e)}:{document:null}}async function ku(t){let e=oe.resolve(t.root),n=oe.resolve(t.controlRoot);t.requireSkillMarkdown&&await Eo.access(oe.join(e,"SKILL.md"));let i=oe.join(n,"skill.yaml"),r=oe.join(n,"guardrails.yaml"),s=yu(await xo(i),i),o=await Mw(r),a=o===null?null:vu(o,r),c=await Ww(n),l={allowedSkills:s.skills.map(f=>f.id),allowedAgents:s.agents.map(f=>f.id),allowedTools:s.tools.map(f=>f.id),maxIterations:50,maxRetriesPerAction:3,confirmationRequiredFor:s.tools.filter(f=>f.requiresConfirmation).map(f=>f.id)};return{root:e,packageKind:t.packageKind==="runtime"?"runtime":void 0,definition:s,guardrails:{...l,...a},evals:c.document?.runtime??[]}}async function Su(t){let e=oe.resolve(t);return ku({root:e,controlRoot:oe.join(e,"comet"),packageKind:"skill",requireSkillMarkdown:!0})}async function Cu(t){let e=oe.resolve(t);return ku({root:e,controlRoot:e,packageKind:"runtime",requireSkillMarkdown:!1})}function Eu(t,e,n=oe.join(e,"package.json")){ne(t,n);let i=t.packageKind==="runtime"?"runtime":void 0,r=yu(t.definition,n),s=vu(t.guardrails,n),o=bu(t.evals,n,"evals"),a={allowedSkills:r.skills.map(c=>c.id),allowedAgents:r.agents.map(c=>c.id),allowedTools:r.tools.map(c=>c.id),maxIterations:50,maxRetriesPerAction:3,confirmationRequiredFor:r.tools.filter(c=>c.requiresConfirmation).map(c=>c.id)};return{root:oe.resolve(e),packageKind:i,definition:r,guardrails:{...a,...s},evals:o}}import xu from"path";function Bw(t,e,n,i){t.type==="invoke_skill"&&!e.definition.skills.some(r=>r.id===t.ref)&&n.push(`step ${i} references undeclared skill: ${t.ref??"(missing)"}`),t.type==="call_tool"&&!e.definition.tools.some(r=>r.id===t.ref)&&n.push(`step ${i} references undeclared tool: ${t.ref??"(missing)"}`),t.type==="handoff"&&!e.definition.agents.some(r=>r.id===t.ref)&&n.push(`step ${i} references undeclared agent: ${t.ref??"(missing)"}`),t.type==="ask_user"&&!t.question&&n.push(`step ${i} ask_user action requires question`)}function _u(t){let e=[],{definition:n,guardrails:i,evals:r}=t;n.apiVersion!=="comet/v1alpha1"&&e.push("unsupported apiVersion"),n.kind!=="Skill"&&e.push("kind must be Skill"),n.metadata.name||e.push("metadata.name is required"),n.goal.statement||e.push("goal.statement is required"),i.maxIterations<1&&e.push("maxIterations must be at least 1"),i.maxRetriesPerAction<0&&e.push("maxRetriesPerAction must not be negative");let s=n.orchestration.steps??[];if(n.orchestration.mode==="adaptive")(n.orchestration.entry||s.length>0)&&e.push("adaptive orchestration must not define entry or steps");else{let o=new Set;for(let a of s)o.has(a.id)&&e.push(`duplicate step id: ${a.id}`),o.add(a.id),Bw(a.action,t,e,a.id);(!n.orchestration.entry||!o.has(n.orchestration.entry))&&e.push(`orchestration.entry references unknown step: ${n.orchestration.entry??"(missing)"}`);for(let a of s){a.next&&!o.has(a.next)&&e.push(`step ${a.id} has unknown next step: ${a.next}`);for(let c of a.completionEvals??[])r.some(l=>l.id===c)||e.push(`step ${a.id} references unknown eval: ${c}`)}}for(let o of n.tools){if(o.kind!=="script")continue;let a=xu.posix.normalize(o.source.replaceAll("\\","/"));(xu.isAbsolute(o.source)||a===".."||a.startsWith("../"))&&e.push(`script tool ${o.id} must reference a relative path inside the Skill package`)}for(let o of i.allowedSkills)n.skills.some(a=>a.id===o)||e.push(`guardrails allow undeclared skill: ${o}`);for(let o of i.allowedAgents)n.agents.some(a=>a.id===o)||e.push(`guardrails allow undeclared agent: ${o}`);for(let o of i.allowedTools)n.tools.some(a=>a.id===o)||e.push(`guardrails allow undeclared tool: ${o}`);return e}function ar(t){return Array.isArray(t)?t.map(ar):t&&typeof t=="object"?Object.fromEntries(Object.entries(t).sort(([e],[n])=>e.localeCompare(n)).map(([e,n])=>[e,ar(n)])):t}function Yw(t){return ar({...t.packageKind==="runtime"?{packageKind:"runtime"}:{},definition:t.definition,guardrails:t.guardrails,evals:t.evals})}function Uw(t){return F.posix.normalize(t.replaceAll("\\","/"))}function Pt(t,e,n){let i=F.relative(t,e);if(!(i===""||!F.isAbsolute(i)&&!i.startsWith(`..${F.sep}`)))throw new Error(`${n} resolves outside the Skill package`)}async function Ru(t,e,n){let i=Uw(e);if(F.posix.isAbsolute(i)||i===".."||i.startsWith("../"))throw new Error(`${n} resolves outside the Skill package`);let r=F.resolve(t,...i.split("/"));Pt(t,r,n);let s;try{s=await K.realpath(r)}catch(o){throw o.code==="ENOENT"?new Error(`${n} does not exist: ${e}`,{cause:o}):o}if(Pt(t,s,n),!(await K.stat(s)).isFile())throw new Error(`${n} is not a file: ${e}`);return{path:i,content:await K.readFile(s)}}async function Vw(t){let e=await K.realpath(t.root),n=t.packageKind==="runtime"?[]:[await Ru(e,"SKILL.md","SKILL.md")];for(let i of t.definition.tools)i.kind==="script"&&n.push(await Ru(e,i.source,`Script tool ${i.id}`));return n.sort((i,r)=>i.path.localeCompare(r.path))}function Jw(t,e){let n=e.map(i=>({path:i.path,sha256:Pu("sha256").update(i.content).digest("hex")}));return Pu("sha256").update(JSON.stringify(ar({package:t,files:n}))).digest("hex")}function Au(t){return JSON.stringify(t,null,2)+` -`}async function ju(t){let e=Yw(t),n=await Vw(t);return{document:e,files:n,hash:Jw(e,n)}}async function cr(t){return(await ju(t)).hash}async function Nu(t){try{return await K.access(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function Ou(t,e){try{if((await K.readFile(F.join(t,"sha256"),"utf8")).trim()!==e.hash)throw new Error("hash mismatch");if(await K.readFile(F.join(t,"package.json"),"utf8")!==Au(e.document))throw new Error("package mismatch");for(let r of e.files)if(!(await K.readFile(F.join(t,...r.path.split("/")))).equals(r.content))throw new Error(`file mismatch: ${r.path}`)}catch(n){throw new Error(`Existing Skill snapshot is invalid: ${e.hash}`,{cause:n})}}async function _o(t,e){let n=await ju(t),i=F.resolve(e,".comet","skill-snapshots"),r=F.join(i,n.hash);if(await K.mkdir(i,{recursive:!0}),await Nu(r))return await Ou(r,n),{hash:n.hash,snapshotDir:r};let s=F.join(i,`.tmp-${Kw()}`);Pt(i,s,"Temporary snapshot"),Pt(i,r,"Published snapshot");try{await K.mkdir(s);for(let o of n.files){let a=F.join(s,...o.path.split("/"));Pt(s,a,`Snapshot file ${o.path}`),await K.mkdir(F.dirname(a),{recursive:!0}),await K.writeFile(a,o.content)}await K.writeFile(F.join(s,"package.json"),Au(n.document)),await K.writeFile(F.join(s,"sha256"),n.hash+` -`),await K.rename(s,r)}catch(o){if(await Nu(r)){try{await Ou(r,n)}finally{await K.rm(s,{recursive:!0,force:!0})}return{hash:n.hash,snapshotDir:r}}throw await K.rm(s,{recursive:!0,force:!0}),o}return{hash:n.hash,snapshotDir:r}}async function Po(t,e){if(!/^[a-f0-9]{64}$/u.test(e))throw new Error(`Invalid Skill snapshot hash: ${e}`);let n=F.resolve(t,".comet","skill-snapshots"),i=F.join(n,e);Pt(n,i,"Skill snapshot");try{let r=(await K.readFile(F.join(i,"sha256"),"utf8")).trim();if(r!==e)throw new Error(`stored hash is ${r||"(empty)"}`);let s=F.join(i,"package.json"),o=JSON.parse(await K.readFile(s,"utf8")),a=Eu(o,i,s),c=_u(a);if(c.length>0)throw new Error(c.map(f=>` - ${f}`).join(` -`));let l=await cr(a);if(l!==e)throw new Error(`calculated hash is ${l}`);return a}catch(r){throw new Error(`Skill snapshot is invalid or missing: ${e}`,{cause:r})}}async function Tu(t){try{return await Ro.access(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}function Iu(t){return Hw("sha256").update(t).digest("hex")}function zw(t){return Iu(JSON.stringify(Object.fromEntries(Object.entries(t).sort(([e],[n])=>e.localeCompare(n)))))}function Qw(t){return t.replaceAll(".","_").replaceAll("-","_")}async function Xw(t,e){let n=await st(t),i=Object.fromEntries(e.filter(o=>o.satisfied&&o.source).map(o=>[Qw(o.code),o.source])),r=ke.join(t,"subagent-progress.md");await Tu(r)&&(i.subagent_progress=ke.relative(n,r).split(ke.sep).join("/"));let s=e.find(o=>o.code==="design.handoff"&&o.satisfied);return s?.source&&(i.handoff_context=s.source),i}function Zw(t,e,n){return[{sequence:1,timestamp:n,type:"run_started",runId:t.runId,data:{skill:t.skill,skillVersion:t.skillVersion,skillHash:t.skillHash}},{sequence:2,timestamp:n,type:"state_migrated",runId:t.runId,data:{kind:"classic",migrationVersion:at,profile:e,source:"pre-migration"}}]}async function ey(t){await Promise.all(t.map(e=>Ro.rm(e,{recursive:!0,force:!0})))}async function $u(t,e){let n=await Ke(t);if(!n.classic)throw new Error("Classic migration requires a legacy state projection");let i=n.classic,r=i.classicProfile??i.workflow;if(n.run){if(i.classicMigration!==at)throw new Error("Classic Run exists without a supported classic_migration marker");if(n.run.skill!==e.skillPackage.definition.metadata.name)throw new Error(`Classic Run skill mismatch: expected ${e.skillPackage.definition.metadata.name}, got ${n.run.skill}`);if(await cr(e.skillPackage)!==n.run.skillHash)return await Po(t,n.run.skillHash),{classic:i,run:n.run,evidence:await Be(t,n),migrated:!1,snapshotDir:ke.join(t,".comet","skill-snapshots",n.run.skillHash)};let d=await _o(e.skillPackage,t);return{classic:i,run:n.run,evidence:await Be(t,n),migrated:!1,snapshotDir:d.snapshotDir}}let s=await Be(t,n),o=Et(i,s);if(!e.skillPackage.definition.orchestration.steps?.some(u=>u.id===o))throw new Error(`Classic Skill package does not define resolved step: ${o}`);let a=await cr(e.skillPackage),c=ke.join(t,".comet","skill-snapshots",a),l=await Tu(c),f=[];try{let u=await _o(e.skillPackage,t),d=pu(e.skillPackage,e.runId?.()??Gw(),u.hash);d.currentStep=o,o==="completed"&&(d.status="completed");let h={...i,classicProfile:r,classicMigration:at},w=await Xw(t,s),p=await st(t),m=s.find(C=>C.code==="design.handoff"&&C.satisfied),g=null;m?.source&&(g=await te(p,m.resolvedSource??m.source,{label:"Classic migration handoff context",hooks:e.handoffReadHooks}),await Gl(t,d.contextRef,g),f.push(ke.resolve(t,d.contextRef))),await Hl(t,d.artifactsRef,w),f.push(ke.resolve(t,d.artifactsRef));let y=(e.now?.()??new Date).toISOString(),k={runId:d.runId,stateVersion:1,trajectoryOffset:2,contextHash:g===null?null:Iu(g),artifactsHash:zw(w),createdAt:y};await zl(t,d.checkpointRef,k),f.push(ke.resolve(t,d.checkpointRef)),f.push(ke.resolve(t,d.trajectoryRef));for(let C of Zw(d,r,y))await mn(t,d.trajectoryRef,C);return await sr(t,{classic:h,run:d,unknownKeys:n.unknownKeys}),{classic:h,run:d,evidence:s,migrated:!0,snapshotDir:u.snapshotDir}}catch(u){throw await ey(f),l||await Ro.rm(c,{recursive:!0,force:!0}),u}}async function ty(t){try{return(await qu.stat(t)).isDirectory()}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function lr(t){try{return(await qu.stat(t)).isFile()}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function ny(t){return await ty(t)?await lr(ie.join(t,"skill.yaml"))?!0:await lr(ie.join(t,"SKILL.md"))&&await lr(ie.join(t,"comet","skill.yaml")):!1}function iy(t){return{root:t,packageKind:"runtime",definition:{apiVersion:"comet/v1alpha1",kind:"Skill",metadata:{name:"comet-classic",version:"1",description:"Internal compatibility orchestration for classic Comet full, hotfix, and tweak workflows"},goal:{statement:"Advance or restore a classic Comet Run without changing the user command surface",inputs:[{name:"classic-state",description:"Validated ClassicState consistent with the Run projection",required:!0},{name:"evidence",description:"Structured evidence produced by the Classic Evidence collector",required:!0}],outputs:[{name:"run-state",description:"Atomically synchronized Classic and Run state",required:!0}],success:["Legacy fields and Run fields remain consistent","Every step invokes only a declared public Comet Skill","The completed state passes its completion eval"]},orchestration:{mode:"deterministic",entry:"full.open",steps:[{id:"full.open",action:{type:"invoke_skill",ref:"comet-open"},next:"full.design.handoff"},{id:"full.design.handoff",action:{type:"invoke_skill",ref:"comet-design"},next:"full.design.document"},{id:"full.design.document",action:{type:"invoke_skill",ref:"comet-design"},next:"full.build.plan"},{id:"full.build.plan",action:{type:"invoke_skill",ref:"comet-build"},next:"full.build.plan-ready"},{id:"full.build.plan-ready",action:{type:"invoke_skill",ref:"comet-build"},next:"full.build.configure"},{id:"full.build.configure",action:{type:"invoke_skill",ref:"comet-build"},next:"full.build.execute"},{id:"full.build.execute",action:{type:"invoke_skill",ref:"comet-build"},next:"full.build.complete"},{id:"full.build.complete",action:{type:"invoke_skill",ref:"comet-build"},next:"full.verify.run"},{id:"full.build.fix",action:{type:"invoke_skill",ref:"comet-build"},next:"full.build.execute"},{id:"full.verify.run",action:{type:"invoke_skill",ref:"comet-verify"},next:"full.verify.branch"},{id:"full.verify.branch",action:{type:"invoke_skill",ref:"comet-verify"},next:"full.archive.confirm"},{id:"full.archive.confirm",action:{type:"invoke_skill",ref:"comet-archive"},next:"full.archive.execute"},{id:"full.archive.execute",action:{type:"invoke_skill",ref:"comet-archive"},next:"completed"},{id:"hotfix.open",action:{type:"invoke_skill",ref:"comet-hotfix"},next:"hotfix.build.execute"},{id:"hotfix.build.execute",action:{type:"invoke_skill",ref:"comet-build"},next:"hotfix.build.complete"},{id:"hotfix.build.complete",action:{type:"invoke_skill",ref:"comet-build"},next:"hotfix.verify.run"},{id:"hotfix.verify.run",action:{type:"invoke_skill",ref:"comet-verify"},next:"hotfix.verify.branch"},{id:"hotfix.verify.branch",action:{type:"invoke_skill",ref:"comet-verify"},next:"hotfix.archive.confirm"},{id:"hotfix.archive.confirm",action:{type:"invoke_skill",ref:"comet-archive"},next:"hotfix.archive.execute"},{id:"hotfix.archive.execute",action:{type:"invoke_skill",ref:"comet-archive"},next:"completed"},{id:"tweak.open",action:{type:"invoke_skill",ref:"comet-tweak"},next:"tweak.build.execute"},{id:"tweak.build.execute",action:{type:"invoke_skill",ref:"comet-build"},next:"tweak.build.complete"},{id:"tweak.build.complete",action:{type:"invoke_skill",ref:"comet-build"},next:"tweak.verify.run"},{id:"tweak.verify.run",action:{type:"invoke_skill",ref:"comet-verify"},next:"tweak.verify.branch"},{id:"tweak.verify.branch",action:{type:"invoke_skill",ref:"comet-verify"},next:"tweak.archive.confirm"},{id:"tweak.archive.confirm",action:{type:"invoke_skill",ref:"comet-archive"},next:"tweak.archive.execute"},{id:"tweak.archive.execute",action:{type:"invoke_skill",ref:"comet-archive"},next:"completed"},{id:"completed",action:{type:"checkpoint"},completionEvals:["classic-completed"]}]},skills:[{id:"comet-open"},{id:"comet-design"},{id:"comet-build"},{id:"comet-verify"},{id:"comet-archive"},{id:"comet-hotfix"},{id:"comet-tweak"}],agents:[],tools:[]},guardrails:{allowedSkills:["comet-open","comet-design","comet-build","comet-verify","comet-archive","comet-hotfix","comet-tweak"],allowedAgents:[],allowedTools:[],maxIterations:500,maxRetriesPerAction:3,confirmationRequiredFor:[]},evals:[{id:"classic-completed",scope:"completion",type:"state_equals",field:"status",equals:"completed"}]}}async function ry(){let t=ie.dirname(Lu(import.meta.url)),e=[process.env.COMET_RUNTIME_CLASSIC_ROOT,ie.resolve(t,"..","runtime","classic"),ie.resolve(t,"..","..","comet","runtime","classic"),ie.resolve(t,"..","..","assets","skills","comet","runtime","classic"),ie.resolve("assets","skills","comet","runtime","classic"),process.env.COMET_CLASSIC_SKILL_ROOT,ie.resolve(t,"..","..","comet-classic"),ie.resolve(t,"..","..","assets","skills","comet-classic"),ie.resolve("assets","skills","comet-classic")].filter(n=>!!n);for(let n of e)if(await ny(n))return n;return null}async function sy(t){return await lr(ie.join(t,"skill.yaml"))?Cu(t):Su(t)}async function ur(t){let e=await ry();return $u(t,{skillPackage:e?await sy(e):iy(ie.dirname(Lu(import.meta.url)))})}async function Du(t){let e=await Ke(t),n=Array.from(new Set(e.unknownKeys)).sort();if(n.length>0)throw new Error(`Invalid Classic state: unknown field(s): ${n.join(", ")}`);return ur(t)}async function Fu(t,e,n,i){let r=await Ke(t);if(!r.classic||!r.run)throw new Error("Classic transition requires synchronized Classic and Run projections");let s=await Be(t,{classic:e,run:n,unknownKeys:r.unknownKeys}),o=Et(e,s),a={...n,currentStep:o,iteration:n.iteration+1,status:o==="completed"?"completed":"running"};await sr(t,{classic:e,run:a,unknownKeys:r.unknownKeys});let c=await Vi(t,a.trajectoryRef);return await mn(t,a.trajectoryRef,{sequence:c.length+1,timestamp:new Date().toISOString(),type:"state_transitioned",runId:a.runId,data:{kind:"classic",fromStep:n.currentStep,toStep:o,...i}}),a}var Mu={"full.open":["openspec.proposal","openspec.tasks"],"full.design.handoff":["openspec.proposal","openspec.design","openspec.tasks"],"full.design.document":["design.handoff"],"full.build.plan":["openspec.tasks"],"full.build.plan-ready":["build.plan"],"full.build.configure":["build.plan"],"full.build.execute":["build.plan"],"full.build.complete":["build.tasks-complete"],"full.verify.run":["build.tasks-complete"],"full.verify.branch":["verification.report"],"full.archive.confirm":["verification.report"],"full.archive.execute":["archive.confirmed"]};function oy(t){return Mu[t]?Mu[t]:t.endsWith(".open")?["openspec.proposal","openspec.tasks"]:t.endsWith(".build.execute")?[]:t.endsWith(".build.complete")?["build.tasks-complete"]:t.endsWith(".verify.run")?["build.tasks-complete"]:t.endsWith(".verify.branch")?["verification.report"]:t.endsWith(".archive.confirm")?["verification.report"]:t.endsWith(".archive.execute")?["archive.confirmed"]:[]}function Wu(t,e){let n=oy(t),i=n.filter(r=>!ot(e,r));return{stepId:t,passed:i.length===0,requiredEvidence:n,missingEvidence:i}}function ay(t){switch(t){case"open":return"/comet-open";case"design":return"/comet-design";case"build":return"/comet-build";case"verify":return"/comet-verify";case"archive":return"/comet-archive";default:return null}}async function Bu(t,e){try{let n=await Du(t),i=await Be(t,{classic:n.classic,run:n.run,unknownKeys:[]}),r=Et(n.classic,i);return{name:e,valid:!0,workflow:n.classic.workflow,phase:n.classic.phase,currentStep:r,nextCommand:ay(n.classic.phase),runtimeMode:"engine-projection",runtimeEval:Wu(r,i),evidence:i}}catch(n){return{name:e,valid:!1,workflow:"unknown",phase:"invalid",currentStep:null,nextCommand:null,runtimeMode:"invalid",runtimeEval:null,evidence:[],error:n instanceof Error?n.message:String(n)}}}Yi();import cy from"path";var ly=cy.join(".comet","state-events.jsonl"),uy=8*1024*1024;async function Ku(t,e){let n={schemaVersion:1,timestamp:new Date().toISOString(),...e};return await Ki(t,ly,`${JSON.stringify(n)} -`,uy,"Classic state event log"),n}var fy={"open-complete":{event:"open-complete",from:"open",guardRefs:["open-artifacts-present"]},"design-complete":{event:"design-complete",from:"design",guardRefs:["design-evidence-present"]},"build-complete":{event:"build-complete",from:"build",guardRefs:["build-decisions-selected"]},"verify-pass":{event:"verify-pass",from:"verify",guardRefs:["verification-report-present"]},"verify-fail":{event:"verify-fail",from:"verify",guardRefs:["verification-failed"]},"archive-confirm":{event:"archive-confirm",from:"archive",guardRefs:["archive-final-confirmation"]},"archive-reopen":{event:"archive-reopen",from:"archive",guardRefs:["archive-not-finalized"]},archived:{event:"archived",from:"archive",guardRefs:["verify-result-pass","archive-confirmed"]},"preset-escalate":{event:"preset-escalate",from:"build",guardRefs:["preset-workflow"]}},Yu={open:"open-complete",design:"design-complete",build:"build-complete",verify:"verify-pass"};function dy(t){return t.toISOString().slice(0,10)}function R(t,e,n,i){let r=t[n];t[n]=i,r!==i&&e.push({field:n,from:r,to:i})}function Uu(t,e,n={}){let i=fy[e];if(t.phase!==i.from)throw new Error(`Cannot apply ${e}: phase is '${t.phase}', expected '${i.from}'`);let r={...t},s=[],o=n.now??new Date;if(e==="open-complete")R(r,s,"phase",r.workflow==="full"?"design":"build");else if(e==="design-complete")R(r,s,"phase","build");else if(e==="build-complete"){let a=r.verifyResult==="fail";R(r,s,"phase","verify"),R(r,s,"verifyResult","pending"),R(r,s,"branchStatus","pending"),a||R(r,s,"verificationReport",null)}else if(e==="verify-pass")R(r,s,"verifyResult","pass"),R(r,s,"verifyFailures",0),R(r,s,"phase","archive"),R(r,s,"verifiedAt",dy(o)),R(r,s,"archiveConfirmation","pending"),R(r,s,"branchStatus","pending");else if(e==="verify-fail")R(r,s,"verifyResult","fail"),R(r,s,"verifyFailures",r.verifyFailures+1),R(r,s,"phase","build"),R(r,s,"branchStatus","pending");else if(e==="preset-escalate"){if(r.workflow!=="hotfix"&&r.workflow!=="tweak")throw new Error(`Cannot apply ${e}: workflow must be hotfix or tweak, got '${r.workflow}'`);R(r,s,"workflow","full"),R(r,s,"classicProfile","full"),R(r,s,"phase","design"),R(r,s,"designDoc",null),R(r,s,"buildPause",null),R(r,s,"buildMode",null),R(r,s,"subagentDispatch",null),R(r,s,"tddMode",null),R(r,s,"reviewMode",null),R(r,s,"isolation",null),R(r,s,"boundBranch",null),R(r,s,"verifyMode",null),R(r,s,"directOverride",null)}else if(e==="archive-confirm"){if(r.verifyResult!=="pass")throw new Error(`Cannot apply ${e}: verifyResult must be pass`);if(r.archived)throw new Error(`Cannot apply ${e}: already archived`);R(r,s,"archiveConfirmation","confirmed")}else if(e==="archive-reopen"){if(r.archived)throw new Error(`Cannot apply ${e}: already archived`);R(r,s,"verifyResult","pending"),R(r,s,"verifyFailures",0),R(r,s,"phase","verify"),R(r,s,"verifiedAt",null),R(r,s,"archiveConfirmation",null),R(r,s,"branchStatus","pending")}else{if(r.verifyResult!=="pass")throw new Error(`Cannot apply ${e}: verifyResult must be pass`);if(r.archiveConfirmation!=="confirmed")throw new Error(`Cannot apply ${e}: archiveConfirmation must be confirmed`);R(r,s,"archived",!0)}return{classic:r,effects:s,definition:i}}var Nn=Ve(Ie(),1);import Ju from"path";import{AsyncLocalStorage as py}from"async_hooks";import{promises as Vu}from"fs";import _n from"path";var fr=new py;function my(t,e){let n=_n.relative(t,e);return n===""||!_n.isAbsolute(n)&&n!==".."&&!n.startsWith(`..${_n.sep}`)}async function hy(t){let e=_n.resolve(t.invocationCwd??process.cwd()),n=_n.resolve(t.projectRoot??await st(e)),[i,r]=await Promise.all([Vu.realpath(e),Vu.realpath(n)]);if(!my(r,i))throw new Error(`Classic command invocation cwd is outside the discovered project: ${e}`);return{invocationCwd:e,projectRoot:n}}async function dr(t,e){let n=fr.getStore();if(n)return e(n);let i=await hy(t);return fr.run(i,()=>e(i))}function I(){let t=fr.getStore();if(!t)throw new Error("Classic command project context is unavailable");return t.projectRoot}function pr(){let t=fr.getStore();if(!t)throw new Error("Classic command invocation context is unavailable");return t.invocationCwd}var gy="\x1B[32m",Pn="\x1B[31m",wy="\x1B[33m",yy="\x1B[0m",vy=["workflow","phase","design_doc","plan","build_mode","isolation","verify_mode","verify_result","verified_at","archived"],by={workflow:["full","hotfix","tweak"],language:["en","zh-CN"],phase:["open","design","build","verify","archive"],context_compression:["off","beta"],build_mode:["subagent-driven-development","executing-plans","direct"],build_pause:["plan-ready"],subagent_dispatch:["confirmed"],tdd_mode:["tdd","direct"],review_mode:["off","standard","thorough"],isolation:["current","branch","worktree"],verify_mode:["light","full"],auto_transition:["true","false"],verify_result:["pending","pass","fail"],branch_status:["pending","handled"],archive_confirmation:["pending","confirmed"],archived:["true","false"],direct_override:["true","false"],classic_profile:["full","hotfix","tweak"],classic_migration:["1"]},ky=new Set([..._t,...So,"classic_profile","classic_migration"]);function lt(t,e){return`${t}${e}${yy}`}function Rn(t){return t==null?"":typeof t=="object"?JSON.stringify(t):String(t)}var Hu=async(t,e)=>dr(e,async()=>{let n=t[0],i=vn(n);if(i)return{exitCode:1,stderr:lt(Pn,`ERROR: ${i}`)};let r=I(),{directory:s,label:o}=await zi(n,r),a=Ju.join(s,".comet.yaml"),c=[`[VALIDATE] ${o}/.comet.yaml`],l=0,f=0,u=m=>{l+=1,c.push(lt(Pn,` FAIL: ${m}`))},d=m=>{f+=1,c.push(lt(wy,` WARN: ${m}`))},h;try{h=await te(r,a,{label:`Classic state ${o}/.comet.yaml`})}catch(m){if(m.code==="ENOENT")return u(".comet.yaml does not exist"),c.push("",lt(Pn,`${l} error(s), ${f} warning(s) — validation FAILED`)),{exitCode:1,stderr:c.join(` -`)};throw m}let w=(0,Nn.parseDocument)(h);if(w.errors.length>0||!(0,Nn.isMap)(w.contents)){for(let m of w.errors)u(m.message);return(0,Nn.isMap)(w.contents)||u("document root must be a mapping"),c.push("",lt(Pn,`${l} error(s), ${f} warning(s) — validation FAILED`)),{exitCode:1,stderr:c.join(` -`)}}let p=w.toJS();for(let m of vy)Object.prototype.hasOwnProperty.call(p,m)||u(`missing required field '${m}'`);for(let[m,g]of Object.entries(by)){if(!Object.prototype.hasOwnProperty.call(p,m))continue;let y=Rn(p[m]);if(!y){m==="auto_transition"&&u(`${m}='' is not valid. Expected: ${g.join(" ")}`);continue}g.includes(y)||u(`${m}='${y}' is not valid. Expected: ${g.join(" ")}`)}if(Object.prototype.hasOwnProperty.call(p,"bound_branch")){let m=p.bound_branch;m!==null&&typeof m!="string"&&u(`bound_branch='${Rn(m)}' is not a string or null`)}if(Object.prototype.hasOwnProperty.call(p,"verify_failures")){let m=p.verify_failures;(typeof m!="number"||!Number.isInteger(m)||m<0)&&u(`verify_failures='${Rn(m)}' is not a non-negative integer`)}for(let m of["design_doc","plan","handoff_context","verification_report"]){let g=Rn(p[m]);if(g){if(/^(?:[A-Za-z]:|[\\/]|~)/u.test(g)||g.split(/[\\/]/u).includes("..")){u(`${m}='${g}' must be a relative repository path`);continue}try{await yn(r,Ju.resolve(r,g),{label:`${m} artifact pointer`,expected:"file"})||u(`${m}='${g}' does not exist on disk`)}catch(y){u(`${m}='${g}' is unsafe: ${y instanceof Error?y.message:String(y)}`)}}}for(let m of["handoff_hash"]){let g=Rn(p[m]);g&&!/^[a-f0-9]{64}$/u.test(g)&&u(`${m}='${g}' is not a sha256 hex digest`)}for(let m of Object.keys(p))ky.has(m)||d(`unknown field '${m}' found`);return c.push(""),l>0?(c.push(lt(Pn,`${l} error(s), ${f} warning(s) — validation FAILED`)),{exitCode:1,stderr:c.join(` -`)}):(c.push(lt(gy,`0 errors, ${f} warning(s) — validation PASSED`)),{exitCode:0,stderr:c.join(` -`)})});co();nt();import Sy from"os";import mr from"path";function Cy(t={}){let e=t.cwd??process.cwd(),n=t.homeDir??Sy.homedir(),i=[{file:mr.resolve(e,".comet","config.yaml"),source:".comet/config.yaml",scope:"project"},{file:mr.resolve(n,".comet","config.yaml"),source:"~/.comet/config.yaml",scope:"global"}];return i.filter((r,s)=>i.findIndex(o=>o.file===r.file)===s)}async function Gu(t,e={}){for(let n of Cy(e)){let i=mr.dirname(mr.dirname(n.file)),r=n.scope==="global"?(await ao(i))?.classic:(await Me(i,{allowPartialProject:!0}))?.value.classic;if(!r||typeof r!="object"||Array.isArray(r))continue;let s=r[t];if(s!=null)return{value:String(s),source:n.source}}return null}nt();var Oo=Ve(Ie(),1);import{execFileSync as zu}from"child_process";import{randomUUID as _y}from"crypto";import{promises as On}from"fs";import Qu from"path";var Ey=null;function xy(t,e){let n=t;for(let i of e)n+="\0"+(typeof i=="string"?i:JSON.stringify(i));return n}function No(t,e){return(...n)=>{let i=Ey;if(i===null)return e(...n);let r=xy(`sync:${t}`,n),s=i.entries.get(r);if(s)return s.value;let o=e(...n);return i.entries.set(r,{value:o}),o}}function Py(t){try{let e=zu("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();return e&&e!=="HEAD"?e:null}catch{return null}}var Ry=No("liveGitBranch",t=>Py(t));function Ny(t){try{return zu("git",["rev-parse","--is-inside-work-tree"],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()==="true"}catch{return!1}}var Oy=No("isGitWorkTree",t=>Ny(t)),Ay=["current","branch","worktree"];function Xu(t){return Ay.includes(t)}function jy(t){return Xu(t.isolation)?t.boundBranch===null&&t.currentBranch===null&&t.gitWorkTree===!1?{status:"not-applicable"}:t.boundBranch===null?t.currentBranch===null?{status:"unbound-detached"}:{status:"needs-heal",branch:t.currentBranch}:t.currentBranch===t.boundBranch?{status:"ok"}:{status:"drift",boundBranch:t.boundBranch,currentBranch:t.currentBranch}:{status:"not-applicable"}}async function Zu(t,e){let n=Qu.join(t,".comet.yaml"),i=(0,Oo.parseDocument)(await On.readFile(n,"utf8"),{uniqueKeys:!1});if(i.errors.length>0)throw new Error(`Invalid .comet.yaml: ${i.errors[0].message}`);let r=i.toJS()??{},s=typeof r.isolation=="string"?r.isolation:null,o=typeof r.bound_branch=="string"&&r.bound_branch!==""?r.bound_branch:null,a=Xu(s),c=Ry(e.cwd),l=a&&o===null&&c===null?Oy(e.cwd):!0,f=jy({isolation:s,boundBranch:o,currentBranch:c,gitWorkTree:l});return f.status==="needs-heal"&&e.heal?(await Ty(t,f.branch),{status:"healed",branch:f.branch,bindingRequired:a,currentBranch:c}):{...f,bindingRequired:a,currentBranch:c}}async function Ty(t,e){let n=Qu.join(t,".comet.yaml"),i=(0,Oo.parseDocument)(await On.readFile(n,"utf8"),{uniqueKeys:!1});i.set("bound_branch",e);let r=`${n}.${_y()}.tmp`;try{await On.writeFile(r,i.toString(),"utf8"),await On.rename(r,n)}catch(s){throw await On.rm(r,{force:!0}),s}}function Iy(t){return t??"detached HEAD"}function ef(t,e,n){return`change '${t}' is bound to branch '${e}', but current branch is '${Iy(n)}'. -Next: ask the user to confirm — switch back to '${e}', or run \`comet state rebind ${t}\` after explicit confirmation.`}function tf(t){return`change '${t}' uses a branch-bound workspace mode but has no bound branch and HEAD is detached; checkout a branch first before continuing.`}var Ly="\x1B[32m",Dy="\x1B[31m",Fy="\x1B[33m",Io="\x1B[0m",My=["open","design","build","verify","archive"],Wy={open:"=== Guard: open → next ===",design:"=== Guard: design → build ===",build:"=== Guard: build → verify ===",verify:"=== Guard: verify → archive ===",archive:"=== Guard: archive completeness ==="},By={open:" [APPLY] .comet.yaml updated: phase=PLACEHOLDER",design:" [APPLY] .comet.yaml updated: phase=build",build:" [APPLY] .comet.yaml updated: phase=verify, verify_result=pending",verify:" [APPLY] .comet.yaml updated: phase=archive, verify_result=pass"},Ky={branchStatus:"branch_status",phase:"phase",verificationReport:"verification_report",verifiedAt:"verified_at",verifyResult:"verify_result"};function Rt(t){return`${Ly}${t}${Io}`}function Se(t){return`${Dy}${t}${Io}`}function Yy(t){return`${Fy}${t}${Io}`}function Uy(t){return Ky[t]??String(t)}function Vy(t){return t===null?"null":t===void 0?"":typeof t=="object"?JSON.stringify(t):String(t)}var fe=class extends Error{constructor(n,i=1){super(n);this.exitCode=i}exitCode},To=class{stderr=[];diagnostics;toResult(e=0){return{exitCode:e,...this.diagnostics?{stdout:JSON.stringify({diagnostics:this.diagnostics})+` +`,n)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let n=Ri(e),i=kt(n);return i.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let n=Ri(e),i=kt(n);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,n){return this.type!=="comment"||this.indent<=n?!1:e.every(i=>i.type==="newline"||i.type==="space")}*documentEnd(e){this.type!=="doc-mode"&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};bl.Parser=Hs});var xl=v(on=>{"use strict";var kl=$s(),Ph=zt(),sn=Zt(),Rh=Tr(),Nh=N(),Oh=Js(),Sl=Gs();function Cl(t){let e=t.prettyErrors!==!1;return{lineCounter:t.lineCounter||e&&new Oh.LineCounter||null,prettyErrors:e}}function Ah(t,e={}){let{lineCounter:n,prettyErrors:i}=Cl(e),r=new Sl.Parser(n?.addNewLine),s=new kl.Composer(e),o=Array.from(s.compose(r.parse(t)));if(i&&n)for(let a of o)a.errors.forEach(sn.prettifyError(t,n)),a.warnings.forEach(sn.prettifyError(t,n));return o.length>0?o:Object.assign([],{empty:!0},s.streamInfo())}function El(t,e={}){let{lineCounter:n,prettyErrors:i}=Cl(e),r=new Sl.Parser(n?.addNewLine),s=new kl.Composer(e),o=null;for(let a of s.compose(r.parse(t),!0,t.length))if(!o)o=a;else if(o.options.logLevel!=="silent"){o.errors.push(new sn.YAMLParseError(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return i&&n&&(o.errors.forEach(sn.prettifyError(t,n)),o.warnings.forEach(sn.prettifyError(t,n))),o}function jh(t,e,n){let i;typeof e=="function"?i=e:n===void 0&&e&&typeof e=="object"&&(n=e);let r=El(t,n);if(!r)return null;if(r.warnings.forEach(s=>Rh.warn(r.options.logLevel,s)),r.errors.length>0){if(r.options.logLevel!=="silent")throw r.errors[0];r.errors=[]}return r.toJS(Object.assign({reviver:i},n))}function Th(t,e,n){let i=null;if(typeof e=="function"||Array.isArray(e)?i=e:n===void 0&&e&&(n=e),typeof n=="string"&&(n=n.length),typeof n=="number"){let r=Math.round(n);n=r<1?void 0:r>8?{indent:8}:{indent:r}}if(t===void 0){let{keepUndefined:r}=n??e??{};if(!r)return}return Nh.isDocument(t)&&!i?t.toString(n):new Ph.Document(t,i,n).toString(n)}on.parse=jh;on.parseAllDocuments=Ah;on.parseDocument=El;on.stringify=Th});var Ie=v(O=>{"use strict";var Ih=$s(),$h=zt(),qh=hs(),zs=Zt(),Lh=It(),Te=N(),Dh=Re(),Fh=q(),Mh=Oe(),Wh=Ae(),Bh=_i(),Kh=Us(),Yh=Js(),Uh=Gs(),Oi=xl(),_l=Ot();O.Composer=Ih.Composer;O.Document=$h.Document;O.Schema=qh.Schema;O.YAMLError=zs.YAMLError;O.YAMLParseError=zs.YAMLParseError;O.YAMLWarning=zs.YAMLWarning;O.Alias=Lh.Alias;O.isAlias=Te.isAlias;O.isCollection=Te.isCollection;O.isDocument=Te.isDocument;O.isMap=Te.isMap;O.isNode=Te.isNode;O.isPair=Te.isPair;O.isScalar=Te.isScalar;O.isSeq=Te.isSeq;O.Pair=Dh.Pair;O.Scalar=Fh.Scalar;O.YAMLMap=Mh.YAMLMap;O.YAMLSeq=Wh.YAMLSeq;O.CST=Bh;O.Lexer=Kh.Lexer;O.LineCounter=Yh.LineCounter;O.Parser=Uh.Parser;O.parse=Oi.parse;O.parseAllDocuments=Oi.parseAllDocuments;O.parseDocument=Oi.parseDocument;O.stringify=Oi.stringify;O.visit=_l.visit;O.visitAsync=_l.visitAsync});var Ai=G(()=>{"use strict"});function $e(t){return t!==0&&t!==0n&&t!=="0"}function ji(t,e){return $e(t.dev)&&$e(e.dev)&&$e(t.ino)&&$e(e.ino)}function ye(t,e){let n=$e(t.dev)&&$e(e.dev);if(n&&t.dev!==e.dev)return!1;let i=$e(t.ino)&&$e(e.ino);return i&&t.ino!==e.ino?!1:n&&i?!0:t.birthtime===e.birthtime}var Ti=G(()=>{"use strict"});import{randomUUID as Vh}from"crypto";import{constants as Jh,promises as L}from"fs";import V from"path";async function Qs(t,e){try{return await L.link(t,e),{linked:!0}}catch(n){let i=n.code;if(i!=="ENOTSUP"&&i!=="EOPNOTSUPP")throw n}return await L.copyFile(t,e,Jh.COPYFILE_EXCL),{linked:!1}}function St(t,e){let n=V.relative(t,e);return n===""||!V.isAbsolute(n)&&n!==".."&&!n.startsWith(`..${V.sep}`)}function $i(t){return{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs}}function Hh(t,e){return ye(t,$i(e))}function Ii(t,e){let n=$i(t),i=$i(e);return ji(n,i)?ye(n,i):ye(n,i)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.size===e.size}async function qi(t){let e=await L.lstat(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Contained atomic write parent must be a real directory: ${t}`);return{path:t,realPath:await L.realpath(t),...$i(e)}}async function qe(t){for(let e of t){let n=await L.lstat(e.path);if(!n.isDirectory()||n.isSymbolicLink()||!Hh(e,n)||await L.realpath(e.path)!==e.realPath)throw new Error(`Contained atomic write parent changed before commit: ${e.path}`)}}async function Gh(t,e){let n=V.resolve(t),i=V.resolve(e);if(!St(n,i))throw new Error(`Contained atomic write parent is outside its managed root: ${e}`);let r=[await qi(n)],s=V.relative(n,i).split(V.sep).filter(Boolean),o=n;for(let a of s){await qe(r),o=V.join(o,a);try{await L.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await qi(o);if(!St(r[0].realPath,c.realPath))throw new Error(`Contained atomic write parent resolves outside its managed root: ${o}`);r.push(c)}return await qe(r),r}async function zh(t,e){let n=V.resolve(t),i=V.resolve(e);if(!St(n,i))throw new Error(`Contained file parent is outside its managed root: ${e}`);let r=[await qi(n)],s=V.relative(n,i).split(V.sep).filter(Boolean),o=n;for(let a of s){o=V.join(o,a);try{let c=await qi(o);if(!St(r[0].realPath,c.realPath))throw new Error(`Contained file parent resolves outside its managed root: ${o}`);r.push(c)}catch(c){if(c.code==="ENOENT")return null;throw c}}return await qe(r),r}async function Pl(t){let e;try{e=await L.open(t,"r"),await e.sync()}catch(n){let i=n.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(i??""))throw n}finally{await e?.close()}}async function Qh(t,e,n){let i=V.dirname(t),r=await Gh(n.containedRoot,i),s=V.join(i,`.${V.basename(t)}.${Vh()}.tmp`),o,a;try{await n.beforeTemporaryOpen?.(),o=await L.open(s,"wx"),a=await o.stat();let[c,l]=await Promise.all([L.lstat(s),L.realpath(s)]);if(await qe(r),!c.isFile()||c.isSymbolicLink()||!Ii(a,c)||!St(r[0].realPath,l))throw new Error("Contained atomic write temporary file opened outside its managed parent");if(typeof e=="string"?await o.writeFile(e,"utf8"):await o.writeFile(e),await o.sync(),!Ii(a,await o.stat()))throw new Error("Contained atomic write temporary file changed while writing");await o.close(),o=void 0,await n.beforeCommit?.(),await qe(r);let d=await L.lstat(s);if(!d.isFile()||d.isSymbolicLink()||!Ii(d,a))throw new Error("Contained atomic write temporary file changed before commit");n.exclusive?(await Qs(s,t),await L.unlink(s)):await L.rename(s,t),await Pl(i)}catch(c){await o?.close();try{await qe(r),await L.rm(s,{force:!0})}catch{}throw c}}async function me(t,e,n){await Qh(t,e,n)}async function Xs(t,e){let n=V.dirname(t),i=await zh(e.containedRoot,n);if(!i)return!1;let r,s;try{r=await L.lstat(t),s=await L.realpath(t)}catch(c){if(c.code==="ENOENT")return!1;throw c}if(!r.isFile()||r.isSymbolicLink()||!St(i[0].realPath,s))throw new Error("Contained file removal target must be a regular file inside its managed root");await e.beforeRemove?.(),await qe(i);let[o,a]=await Promise.all([L.lstat(t),L.realpath(t)]);if(!o.isFile()||o.isSymbolicLink()||!Ii(r,o)||a!==s)throw new Error("Contained file removal target changed before removal");return await L.unlink(t),await qe(i),await Pl(n),!0}var et=G(()=>{"use strict";Ti()});var Rl=G(()=>{"use strict"});var Zs=G(()=>{"use strict";Ai()});var Nl=G(()=>{"use strict";Ai();Zs()});import Li from"path";function rg(t,e){if(typeof t!="string")throw new Error(`${e} must be a string`);let n=t.trim();if(n.length===0||Li.posix.isAbsolute(n)||Li.win32.isAbsolute(n)||/^(?:~|[\\/])/u.test(n))throw new Error(`${e} must be a project-relative path`);if(n===".")return[];let i=n.replaceAll("\\","/").split("/");if(i.some(r=>r===".."))throw new Error(`${e} must stay inside the project root`);if(i.some(r=>r===""||r==="."))throw new Error(`${e} must not contain empty or dot path segments`);return i}function an(t){let e=rg(t,"native.artifact_root");return e.length===0?".":e.join("/")}function jl(t,e="docs"){let n=t??e;if(n!=="legacy"&&n!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return n}function tt(t,e,n=!1){if(typeof t!="string")throw new Error(`${e} must be a string`);let i=t.trim().replaceAll("\\","/");if(i.length===0||Li.posix.isAbsolute(i)||Li.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${e} must be relative to its declared path base`);let r=i.split("/");if(r.some(s=>s===".."))throw new Error(`${e} must stay inside its declared path base`);if(r.some(s=>s===""||s==="."))throw new Error(`${e} must not contain empty or dot path segments`);if(!n&&/[*?]/u.test(i))throw new Error(`${e} cannot contain wildcards`);return r.join("/")}function cn(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function Tl(t,e,n){let i=t??e;if(i!=="en"&&i!=="zh-CN")throw new Error(`${n} must be en or zh-CN`);return i}function Il(t,e){if(typeof t!="string"||t.length===0||t.includes("\\")||t.includes("\0")||t.startsWith("/")||t.split("/").includes(".."))throw new Error(`${e} contains an unsafe pattern`);if(t.length>to)throw new Error(`${e} exceeds ${to} characters`);let n=0;for(let i=0;ino)throw new Error(`${e} contains more than ${no} wildcard tokens`);return t}function Ol(t,e,n){if(t===void 0)return[...n];if(!Array.isArray(t))throw new Error(`${e} contains an unsafe pattern`);return[...new Set(t.map(i=>Il(i,e)))].sort((i,r)=>i.localeCompare(r,"en"))}function eo(t,e,n){let i=t??e;if(!Number.isSafeInteger(i)||i<1)throw new Error(`${n} must be a positive integer`);return i}function sg(t){if(t===void 0)return{...se,include:[...se.include],exclude:[...se.exclude]};let e=cn(t,"native.snapshot");return{include:Ol(e.include,"native.snapshot.include",se.include),exclude:Ol(e.exclude,"native.snapshot.exclude",se.exclude),max_files:eo(e.max_files,se.max_files,"native.snapshot.max_files"),max_total_bytes:eo(e.max_total_bytes,se.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:eo(e.max_duration_ms,se.max_duration_ms,"native.snapshot.max_duration_ms")}}function og(t){if(t===void 0)return;let e=cn(t,"native.pending_root_move"),n=e.id,i=e.from_artifact_root,r=e.to_artifact_root,s=e.stage;if(typeof n!="string"||!/^[a-f0-9-]{8,}$/u.test(n))throw new Error("native.pending_root_move.id is invalid");if(typeof i!="string"||typeof r!="string")throw new Error("native.pending_root_move roots must be strings");if(s!=="copying"&&s!=="ready"&&s!=="switched")throw new Error("native.pending_root_move.stage is invalid");let o;if(e.cleanup!==void 0){let a=cn(e.cleanup,"native.pending_root_move.cleanup"),c=a.kind,l=a.state,d=a.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof d!="string"||!/^[a-f0-9]{64}$/u.test(d))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:d}}return{id:n,fromArtifactRoot:an(i),toArtifactRoot:an(r),stage:s,...o?{cleanup:o}:{}}}function ag(t,e={}){let n=cn(t,"native"),i=n.artifact_root??(e.allowMissingArtifactRoot?"docs":void 0);if(typeof i!="string")throw new Error("native.artifact_root must be a string");let r=n.clarification_mode??"sequential";if(r!=="sequential"&&r!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let s=n.archive_confirmation??"automatic";if(s!=="automatic"&&s!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=n.max_verify_failures??Al;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let a=og(n.pending_root_move);return{artifact_root:an(i),language:Tl(n.language,"en","native.language"),clarification_mode:r,archive_confirmation:s,max_verify_failures:o,snapshot:sg(n.snapshot),...a?{pending_root_move:a}:{}}}function cg(t){let e=cn(t,"classic"),n=e.context_compression??"off";if(n!=="off"&&n!=="beta")throw new Error("classic.context_compression must be off or beta");let i=e.review_mode??"standard";if(i!=="off"&&i!=="standard"&&i!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let r=e.auto_transition??!0;if(typeof r!="boolean")throw new Error("classic.auto_transition must be true or false");return{artifact_layout:jl(e.artifact_layout),language:Tl(e.language,"zh-CN","classic.language"),context_compression:n,review_mode:i,auto_transition:r}}function lg(t){let e=t??!0;if(typeof e!="boolean")throw new Error("ambient_resume must be true or false");return e}function ug(t,e,n,i,r){let s=t.schema!==void 0;if(!(s||t.default_workflow!==void 0||t.workflows!==void 0||!r.allowPartialProject&&t.native!==void 0)||r.allowPartialProject&&!s)return null;if(t.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(t.default_workflow!=="native"&&t.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let a=t.workflows??[t.default_workflow];if(!Array.isArray(a)||a.length===0||a.some(l=>l!=="native"&&l!=="classic"))throw new Error("workflows must contain native and/or classic");let c=[...new Set(a)];if(!c.includes(t.default_workflow))throw new Error("workflows must include default_workflow");if(c.includes("native")&&!e)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:t.default_workflow,workflows:c,ambient_resume:i,...e?{native:e}:{},...n?{classic:n}:{}}}function Le(t,e={}){let n=(0,io.parseDocument)(t,{uniqueKeys:!0});if(n.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${n.errors[0].message}`);let i=n.toJS();if(i==null)return{value:{},config:null,ambient_resume:!0};if(typeof i!="object"||Array.isArray(i))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let r=i,s=lg(r.ambient_resume),o=r.native===void 0?void 0:ag(r.native,{allowMissingArtifactRoot:e.allowMissingNativeFields}),a=r.classic===void 0?void 0:cg(r.classic),c=ug(r,o,a,s,{allowPartialProject:e.allowPartialProject??!1});return{value:r,config:c,ambient_resume:s,...o?{native:o}:{},...a?{classic:a}:{}}}function ro(t="docs",e="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,native:{artifact_root:an(t),language:e,clarification_mode:"sequential",archive_confirmation:"automatic",max_verify_failures:Al,snapshot:{...se,include:[...se.include],exclude:[...se.exclude]}}}}var io,Ct,to,no,Al,ig,se,ve=G(()=>{"use strict";io=Je(Ie(),1),Ct=64*1024,to=1024,no=64,Al=5,ig=[".agents/skills/**",".amazonq/skills/**",".augment/skills/**",".bob/skills/**",".claude/skills/**",".cline/skills/**",".codebuddy/skills/**",".continue/skills/**",".cospec/skills/**",".crush/skills/**",".cursor/skills/**",".factory/skills/**",".forge/skills/**",".gemini/skills/**",".github/skills/**",".iflow/skills/**",".junie/skills/**",".kilocode/skills/**",".kimi-code/skills/**",".kiro/skills/**",".lingma/skills/**",".mimocode/skills/**",".opencode/skills/**",".pi/skills/**",".qoder/skills/**",".qwen/skills/**",".roo/skills/**",".trae-cn/skills/**",".trae/skills/**",".windsurf/skills/**",".zcode/skills/**"],se={include:["**/*"],exclude:[...ig],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4}});import{constants as Di,promises as nt}from"fs";function so(t){return"birthtimeNs"in t&&typeof t.birthtimeNs=="bigint"?t.birthtimeNs:t.birthtimeMs}function $l(t){return"ctimeNs"in t&&typeof t.ctimeNs=="bigint"?t.ctimeNs:t.ctimeMs}function ln(t){return{dev:t.dev,ino:t.ino,birthtime:so(t)}}function Fi(t,e){let n=ln(t),i=ln(e);return ji(n,i)?ye(n,i):ye(n,i)&&so(t)===so(e)&&$l(t)===$l(e)&&t.size===e.size}async function ql(t,e,n={}){if(!Number.isSafeInteger(e)||e<1)throw new Error("race-safe read byte limit must be a positive integer");let i=n.label??"file",r=n.bigint===!0,s=await nt.lstat(t,{bigint:r});if(!s.isFile()||s.isSymbolicLink())throw new De("not-regular-file",`${i} must be a regular file`);if(BigInt(s.size)>BigInt(e))throw new De("too-large",`${i} exceeds ${e} bytes`);let o=await nt.realpath(t);await n.verify?.("pre-open",{realPath:o,identity:ln(s)});let a=process.platform==="win32"?Di.O_RDONLY:Di.O_RDONLY|Di.O_NOFOLLOW|Di.O_NONBLOCK,c;try{c=await nt.open(t,a)}catch(l){throw l.code==="ELOOP"?new De("not-regular-file",`${i} must be a regular file`,{cause:l}):l}try{let[l,d,u]=await Promise.all([c.stat({bigint:r}),nt.lstat(t,{bigint:r}),nt.realpath(t)]);if(!l.isFile()||!d.isFile()||d.isSymbolicLink()||u!==o||!Fi(s,l)||!Fi(s,d))throw new De("changed",`${i} changed while opening`);await n.verify?.("post-open",{realPath:u,identity:ln(l)}),await n.hooks?.afterOpen?.();let f=[],h=0,w=Buffer.allocUnsafe(Math.min(64*1024,e+1));for(;;){let y=e+1-h,{bytesRead:k}=await c.read(w,0,Math.min(w.length,y),null);if(k===0)break;if(h+=k,h>e)throw new De("too-large",`${i} exceeds ${e} bytes`);f.push(Buffer.from(w.subarray(0,k)))}await n.hooks?.beforeFinalCheck?.();let[p,m,g]=await Promise.all([c.stat({bigint:r}),nt.lstat(t,{bigint:r}),nt.realpath(t)]);if(!m.isFile()||m.isSymbolicLink()||g!==o||!Fi(s,p)||!Fi(s,m))throw new De("changed",`${i} changed while reading`);return await n.verify?.("post-read",{realPath:g,identity:ln(p)}),{bytes:Buffer.concat(f,h),stat:p,realPath:g}}finally{await c.close()}}var De,Ll=G(()=>{"use strict";Ti();De=class extends Error{reason;constructor(e,n,i){super(n,i),this.name="RaceSafeReadError",this.reason=e}}});import{promises as Mi}from"fs";import Fe from"path";function fg(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}function oo(t,e){let n=Fe.relative(t,e);return n===""||!Fe.isAbsolute(n)&&n!==".."&&!n.startsWith(`..${Fe.sep}`)}async function Dl(t,e){let n=Fe.resolve(t),i=await Mi.lstat(n);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${e} project root must be a real directory`);return Mi.realpath(n)}async function Fl(t,e,n,i){let r=t;for(let s=0;s{if(!oo(s,a.realPath))throw new Error(`${i.label} resolves outside the project root`);await Fl(r.projectRoot,s,r.relative.split("/"),{label:i.label,expected:"file"})}})}var le=G(()=>{"use strict";Ll();ve()});function dg(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}function pg(t){let e=(0,Wl.parseDocument)(t,{uniqueKeys:!0});if(e.errors.length>0)throw new Error(`Invalid global Comet config: ${e.errors[0].message}`);let n=e.toJS();if(n==null)return{};if(typeof n!="object"||Array.isArray(n))throw new Error("Invalid global Comet config: root must be a mapping");return n}function Kl(t){if(t.native?.pending_root_move)throw new Error("Global Comet config cannot contain native.pending_root_move");let e=t.native?(({pending_root_move:n,...i})=>i)(t.native):void 0;return{...t,schema:"comet.global.v1",...e?{native:e}:{}}}function mg(t){let e=Le(JSON.stringify({...t,schema:"comet.project.v1"})).config;if(!e)throw new Error("Invalid global Comet config: workflow template is incomplete");return Kl(e)}function hg(t){let e=Le(t,{allowPartialProject:!0,allowMissingNativeFields:!0});if(!e.native&&!e.classic)return null;let n=e.native?"native":"classic",i=e.native?.language??e.classic?.language??"en",r=ro(e.native?.artifact_root??"docs",i);return{schema:"comet.global.v1",default_workflow:n,workflows:[n],ambient_resume:e.ambient_resume,...e.native?{native:{...r.native,...e.native}}:{},...e.classic?{classic:e.classic}:{}}}function Yl(t){let e=pg(t);if(Object.keys(e).length===0)return null;if(e.schema===void 0)return hg(t);if(e.schema!=="comet.global.v1")throw new Error("Unsupported Comet global schema");return mg(e)}async function co(t){try{let e=await J(t,Bl,Ct,{label:"global Comet config"});return Yl(e.bytes.toString("utf8"))}catch(e){if(dg(e))return null;throw e}}var Wl,Bl,lo=G(()=>{"use strict";Wl=Je(Ie(),1);et();ve();le();Bl=".comet/config.yaml"});import{createHash as gg}from"crypto";function wg(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function Me(t,e={}){return(await Bi(t,e)).document}async function yg(t){try{return(await J(t,un,Ct,{label:un})).bytes}catch(e){if(wg(e))return null;throw e}}function vg(t){return t?{exists:!0,sha256:gg("sha256").update(t).digest("hex")}:{exists:!1,sha256:null}}async function Bi(t,e={}){let n=await yg(t);return{document:n?Le(n.toString("utf8"),e):null,identity:vg(n)}}var un,it=G(()=>{"use strict";ve();le();un=".comet/config.yaml"});var Nk,uo=G(()=>{"use strict";et();it();le();Nk=16*1024});var fo=G(()=>{"use strict";et();ve();it();le();uo()});var Vl=G(()=>{"use strict";Ai();et();Rl();Nl();ve();lo();le();it();fo();uo();Zs()});import{TextDecoder as xg}from"util";function Jl(t){return{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs}}function _g(t,e){try{return new xg("utf-8",{fatal:!0}).decode(t.bytes)}catch(n){throw new Error(`${e} is not valid UTF-8`,{cause:n})}}async function po(t,e,n,i,r={}){try{let s=await J(t,e,n,{label:i,hooks:r.hooks});return{result:s,text:_g(s,i)}}catch(s){let o=s.code;if(o==="ENOENT"||o==="ENOTDIR")return null;throw s}}async function fn(t,e,n,i,r={}){return(await po(t,e,n,i,r))?.text??null}async function rt(t,e,n,i,r,s={}){if(Buffer.byteLength(n,"utf8")>i)throw new Error(`${r} exceeds ${i} bytes`);let o=await po(t,e,i,r),a=await D(t,e,{label:r,expected:"file"});await me(a.target,n,{containedRoot:a.projectRoot,beforeCommit:async()=>{await s.beforeCommit?.();let c=await po(t,e,i,r);if(!(!o&&!c)){if(!o||!c)throw new Error(`${r} changed before commit`);if(o.result.realPath!==c.result.realPath||!ye(Jl(o.result.stat),Jl(c.result.stat))||o.text!==c.text)throw new Error(`${r} changed before commit`)}}})}async function Ki(t,e,n,i,r,s={}){let o=await fn(t,e,i,r);await rt(t,e,`${o??""}${n}`,i,r,s)}async function mo(t,e,n,i={}){let r=await D(t,e,{label:n,expected:"file"});return r.exists?Xs(r.target,{containedRoot:r.projectRoot,beforeRemove:i.beforeRemove}):!1}var Yi=G(()=>{"use strict";Vl();Ti()});var cu={};wf(cu,{RUN_STATE_FILE:()=>er,applyRunStateToDocument:()=>yo,readRunState:()=>vo,removeRunState:()=>bo,runStateFromDocument:()=>Zi,writeRunState:()=>tr});import Zg from"path";function En(t,e){let n=t[e];if(typeof n!="string"||n.length===0)throw new Error(`Invalid Run state: ${e} must be a non-empty string`);return n}function Cn(t,e){let n=En(t,e);if(Zg.isAbsolute(n)||/^(?:[A-Za-z]:|[\\/]|~)/u.test(n)||n.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Run state: ${e} must stay inside the change directory`);return n}function ew(t){let e=t.run_retries??"{}",n;try{n=typeof e=="string"?JSON.parse(e):e}catch(i){throw new Error("Invalid Run state: run_retries must be a JSON object",{cause:i})}if(!n||typeof n!="object"||Array.isArray(n))throw new Error("Invalid Run state: run_retries must be a JSON object");for(let i of Object.values(n))if(!Number.isInteger(i)||Number(i)<0)throw new Error("Invalid Run state: retry counts must be non-negative integers");return n}function Zi(t){if(!t.run_id)return null;let e=En(t,"run_id"),n=En(t,"skill"),i=En(t,"skill_version"),r=En(t,"skill_hash"),s=Cn(t,"pending_ref"),o=Cn(t,"trajectory_ref"),a=Cn(t,"context_ref"),c=Cn(t,"artifacts_ref"),l=Cn(t,"checkpoint_ref"),d=Number(t.iteration);if(!Number.isInteger(d)||d<0)throw new Error("Invalid Run state: iteration must be a non-negative integer");if(t.orchestration!=="deterministic"&&t.orchestration!=="adaptive")throw new Error("Invalid Run state: orchestration must be deterministic or adaptive");if(t.run_status!=="running"&&t.run_status!=="waiting"&&t.run_status!=="completed"&&t.run_status!=="failed")throw new Error("Invalid Run state: run_status is invalid");return{runId:e,skill:n,skillVersion:i,skillHash:r,orchestration:t.orchestration,currentStep:ou(t,"current_step"),iteration:d,pending:ou(t,"pending"),pendingRef:s,trajectoryRef:o,contextRef:a,artifactsRef:c,checkpointRef:l,status:t.run_status,retries:ew(t)}}function yo(t,e){e?t.run_id=e.runId:delete t.run_id}function tw(t){return{runId:t.runId,skill:t.skill,skillVersion:t.skillVersion,skillHash:t.skillHash,orchestration:t.orchestration,currentStep:t.currentStep,iteration:t.iteration,pending:t.pending,pendingRef:t.pendingRef,trajectoryRef:t.trajectoryRef,contextRef:t.contextRef,artifactsRef:t.artifactsRef,checkpointRef:t.checkpointRef,status:t.status,retries:t.retries}}function nw(t){let e={run_id:t.runId,skill:t.skill,skill_version:t.skillVersion,skill_hash:t.skillHash,orchestration:t.orchestration,current_step:t.currentStep,iteration:t.iteration,pending:t.pending,pending_ref:t.pendingRef,trajectory_ref:t.trajectoryRef,context_ref:t.contextRef,artifacts_ref:t.artifactsRef,checkpoint_ref:t.checkpointRef,run_status:t.status,run_retries:JSON.stringify(t.retries)};return Zi(e)}async function vo(t,e={}){let n=await fn(t,er,au,"Run state",e);if(n===null)return null;let i=JSON.parse(n);return nw(i)}async function tr(t,e,n={}){await rt(t,er,JSON.stringify(tw(e),null,2),au,"Run state",n)}async function bo(t,e={}){await mo(t,er,"Run state",e)}var ou,er,au,nr=G(()=>{"use strict";Yi();ou=(t,e)=>{let n=t[e];return n==null?null:String(n)};er=".comet/run-state.json",au=256*1024});var of=Je(Ie(),1);import{spawnSync as $y}from"child_process";import{createHash as sf}from"crypto";import{promises as qy}from"fs";import T from"path";import Ji from"path";Yi();import Ui from"path";var dn={trajectory:8*1024*1024,artifacts:1024*1024,context:1024*1024,pendingAction:256*1024,checkpoint:256*1024};function pn(t,e){if(Ui.isAbsolute(e))throw new Error("Run path must stay inside the change directory");let n=Ui.resolve(t),i=Ui.resolve(n,e);if(i!==n&&!i.startsWith(n+Ui.sep))throw new Error("Run path must stay inside the change directory")}async function mn(t,e,n,i={}){pn(t,e),await Ki(t,e,`${JSON.stringify(n)} +`,dn.trajectory,"Run trajectory",i)}async function Vi(t,e,n={}){pn(t,e);let i=await fn(t,e,dn.trajectory,"Run trajectory",n);return i===null?[]:i.split(/\r?\n/).map((r,s)=>({line:r,number:s+1})).filter(({line:r})=>r.length>0).map(({line:r,number:s})=>{try{return JSON.parse(r)}catch(o){throw new Error(`Invalid Trajectory event at line ${s}`,{cause:o})}})}async function Hl(t,e,n,i={}){pn(t,e),await rt(t,e,JSON.stringify(n,null,2)+` +`,dn.artifacts,"Run artifacts",i)}async function Gl(t,e,n,i={}){pn(t,e),await rt(t,e,n,dn.context,"Run context",i)}async function zl(t,e,n,i={}){pn(t,e),await rt(t,e,JSON.stringify(n,null,2)+` +`,dn.checkpoint,"Run checkpoint",i)}function Pg(t){if(t!=="build"&&t!=="verify")throw new Error(`Invalid command check scope: '${String(t)}'`)}function Rg(t,e="."){if(e.trim().length===0)throw new Error("Command check cwd cannot be blank");let n=Ji.resolve(t),i=Ji.resolve(n,e);if(i!==n&&!i.startsWith(n+Ji.sep))throw new Error(`Command check cwd must resolve within the project root: '${e}'`);return Ji.relative(n,i).replaceAll("\\","/")||"."}function Ng(t,e){if(e.type!=="command_check_recorded")return null;let n=e.data;if(typeof n!="object"||n===null||Array.isArray(n))return null;let{scope:i,command:r,exitCode:s,cwd:o}=n;if(i!=="build"&&i!=="verify"||typeof r!="string"||r.trim().length===0||!Number.isInteger(s)||typeof o!="string")return null;let a;try{a=Rg(t,o)}catch{return null}return{sequence:e.sequence,timestamp:e.timestamp,runId:e.runId,scope:i,command:r,exitCode:s,cwd:a}}async function Ql(t,e,n,i){Pg(i);let r=await Vi(e,n.trajectoryRef);for(let s=r.length-1;s>=0;s-=1){let o=r[s];if(o.runId!==n.runId)continue;let a=Ng(t,o);if(a?.scope===i)return a}return null}import{promises as Kg}from"fs";import be from"path";import{promises as Zl}from"fs";import $ from"path";import{promises as Og}from"fs";async function hn(t){try{return await Og.access(t),!0}catch(e){if(Ag(e))return!1;throw e}}function Ag(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}ve();it();fo();le();var gn=class extends Error{code="classic-layout-unavailable";constructor(e="Classic artifact layout is unavailable from .comet/config.yaml"){super(e),this.name="ClassicLayoutUnavailableError"}},Xl=".comet/config.yaml";function eu(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function tu(t){await D(t,Xl,{label:Xl,expected:"file"})}function Hi(t,e){let n=$.resolve(t),i=e==="docs"?$.join(n,"docs"):n,r=$.join(i,"openspec"),s=$.join(n,"docs","superpowers");return{projectRoot:n,artifactLayout:e,openSpecBase:i,openSpecRoot:r,changesDir:$.join(r,"changes"),archiveDir:$.join(r,"changes","archive"),specsDir:$.join(r,"specs"),superpowersRoot:s,superpowersSpecsDir:$.join(s,"specs"),superpowersPlansDir:$.join(s,"plans"),superpowersReportsDir:$.join(s,"reports")}}async function jg(t){await tu(t);let e=await Me(t,{allowPartialProject:!0,allowMissingNativeFields:!0});if(!e?.config)throw new gn;if(!(e.config.workflows??[e.config.default_workflow]).includes("classic"))throw new gn("Classic artifact layout is unavailable because Classic is not enabled");return e.classic?.artifact_layout??"legacy"}async function Tg(t,e){return Hi(t,e??await jg(t))}async function Ig(t){try{return await Zl.lstat(t),!0}catch(e){if(eu(e))return!1;throw e}}async function $g(t,e){let n=await Tg(t,e),i=n.artifactLayout==="legacy"?"docs":"legacy",r=Hi(t,i).openSpecRoot,[s,o]=await Promise.all([D(n.projectRoot,z(n.projectRoot,n.openSpecRoot),{label:"Configured Classic OpenSpec root",expected:"directory"}),Ig(r)]),a=s.exists;return{paths:n,configuredRootExists:a,alternateRoot:r,alternateRootExists:o,dualRoots:a&&o}}async function qg(t){let e=[t.openSpecRoot,t.changesDir,t.archiveDir,t.specsDir,t.superpowersRoot,t.superpowersSpecsDir,t.superpowersPlansDir,t.superpowersReportsDir];for(let n of e){let i=z(t.projectRoot,n);await D(t.projectRoot,i,{label:`Classic managed physical path ${i}`,expected:"directory"})}}async function We(t,e){let n=await $g(t,e);if(await qg(n.paths),!n.configuredRootExists){let i=z(n.paths.projectRoot,n.paths.openSpecRoot),r=z(n.paths.projectRoot,n.alternateRoot);throw new gn(`Configured Classic OpenSpec root is missing: ${i} (alternate ${r} is ${n.alternateRootExists?"present":"missing"})`)}return n.paths}async function ho(t,e){let n=$.join($.resolve(t),".comet","classic-root-move.json");if(await hn(n))throw new Error("Classic root move transaction is incomplete; inspect it with comet doctor and recover it explicitly before writing");let i=await We(t,e);if(!await hn(i.openSpecRoot))throw new Error(`Configured Classic OpenSpec root is missing: ${z(i.projectRoot,i.openSpecRoot)}`);return i}async function st(t){let e=$.resolve(t),n=null;try{(await Zl.lstat(e)).isDirectory()||(e=$.dirname(e))}catch(i){if(!eu(i))throw i}for(;;){$.basename(e)==="openspec"&&(n=$.dirname(e));let i=$.join(e,".comet","config.yaml"),r=!1;if(await hn(i))try{await tu(e);let o=(await Me(e))?.value;r=!!o&&typeof o=="object"&&!Array.isArray(o)&&(o.schema==="comet.project.v1"||o.default_workflow!==void 0||o.native!==void 0)}catch{}if(r||await hn($.join(e,".git")))return e;let s=$.dirname(e);if(s===e)return n??$.resolve(t);e=s}}function z(t,e){return $.relative($.resolve(t),e).replaceAll("\\","/")}le();ve();import bn from"path";import{promises as Dg}from"fs";import zi from"path";et();ve();le();import wn from"path";var Lg=2*1024*1024;function nu(t,e,n){let i=wn.resolve(t),r=wn.isAbsolute(e)?wn.resolve(e):wn.resolve(i,e),s=wn.relative(i,r).replaceAll("\\","/");return{root:i,relative:tt(s,n),target:r}}async function Be(t,e,n){let i=nu(t,e,n.label);return D(i.root,i.relative,n)}async function yn(t,e,n){return(await Be(t,e,{label:n.label,expected:n.expected??"any"})).exists}async function iu(t,e,n,i){return await yn(t,e,{label:n,expected:"file"})?(await Gi(t,e,{label:n,hooks:i})).byteLength>0:!1}async function te(t,e,n){return(await Gi(t,e,n)).toString("utf8")}async function Gi(t,e,n){let i=nu(t,e,n.label);return(await J(i.root,i.relative,n.maxBytes??Lg,{label:n.label,hooks:n.hooks})).bytes}function vn(t){return t?/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t)?t.includes("..")?"Change name cannot contain '..' (path traversal not allowed)":null:`Invalid change name: '${t}' +Valid format: lowercase kebab-case (a-z, 0-9, single hyphens)`:"Change name cannot be empty"}function wo(t){let e=vn(t);if(e)throw new Error(e)}function Fg(t,e){return{label:z(t,e),directory:e}}async function go(t,e,n){let i=Fg(t,e);if(!(await Be(t,e,{label:n,expected:"directory"})).exists)return{change:i,exists:!1,stateExists:!1};let s=await Be(t,zi.join(e,".comet.yaml"),{label:`${n} state`,expected:"file"});return{change:i,exists:!0,stateExists:s.exists}}function Mg(t,e){let n=e.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&");return new RegExp(`^\\d{4}-\\d{2}-\\d{2}-${n}$`,"u").test(t)}async function Wg(t,e,n,i={}){if(!i.skipExactCompatibility){let o=await go(t,zi.join(e,n),`Classic archived change ${n}`);if(o.exists)return o.change}if(!(await Be(t,e,{label:"Classic archive directory",expected:"directory"})).exists)return null;let s=[];for(let o of await Dg.readdir(e,{withFileTypes:!0})){if(!Mg(o.name,n))continue;let a=await go(t,zi.join(e,o.name),`Classic archived change ${o.name}`);a.exists&&a.stateExists&&s.push(a.change)}return s.sort((o,a)=>a.directory.localeCompare(o.directory))[0]??null}async function Qi(t,e=process.cwd()){wo(t);let n=await We(e),i=await go(n.projectRoot,zi.join(n.changesDir,t),`Classic active change ${t}`);if(i.exists)return i.change;let r=await Wg(n.projectRoot,n.archiveDir,t);return r||i.change}function Bg(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function ru(t,e,n,i){let r=tt(n,"Classic handoff artifact pointer");if((await D(t,r,{label:"Classic handoff artifact",expected:"file"})).exists)return null;let o=await We(t),a=`${z(t,o.changesDir)}/`,l=(o.artifactLayout==="docs"?[a,"openspec/changes/"]:[a]).find(y=>r.startsWith(y));if(!l)return null;let d=r.slice(l.length).split("/");if(d.length<4||d[1]!==".comet"||d.slice(2).some(y=>y.length===0))return null;let u=d[0];wo(u);let f=d.slice(2),h=bn.resolve(e);if(bn.dirname(h)!==bn.resolve(o.archiveDir))return null;let w=bn.basename(h),p=/^\d{4}-\d{2}-\d{2}-(.+)$/u.exec(w);if(w!==u&&p?.[1]!==u)return null;await D(t,z(t,h),{label:"Classic archived change directory",expected:"directory"});let m=bn.join(h,".comet",...f),g=z(t,m);try{return await J(t,g,i,{label:"Historical Classic archived handoff artifact"}),g}catch(y){if(Bg(y))return null;throw y}}le();var su=2*1024*1024;function kn(t,e){return be.relative(t,e).split(be.sep).join("/")}async function Sn(t,e,n,i,r){if(!n)return{code:e,satisfied:!1};let s=n.replaceAll("\\","/");if(r)return{code:e,satisfied:!1,source:s,detail:`Classic layout is unsafe or unavailable: ${r instanceof Error?r.message:String(r)}`};try{if(i){let a=i.artifactLayout==="legacy"?"docs":"legacy",c=z(t,Hi(t,a).openSpecRoot);if((s===c||s.startsWith(`${c}/`))&&(await D(t,s,{label:`${e} artifact`,expected:"file"})).exists)return{code:e,satisfied:!1,source:s,detail:"standalone OpenSpec root is not a Comet artifact root"}}let o=await Wi(t,s,{label:`${e} artifact`});return{code:e,satisfied:o,source:s,...o?{resolvedSource:s}:{}}}catch(o){return{code:e,satisfied:!1,source:s,detail:`unsafe artifact pointer outside the project or through a special path: ${o instanceof Error?o.message:String(o)}`}}}async function Yg(t,e,n,i){try{i??=await We(t)}catch(s){return{code:"design.handoff",satisfied:!1,...n?{source:n.replaceAll("\\","/")}:{},detail:`Classic layout is unsafe or unavailable for handoff evidence: ${s instanceof Error?s.message:String(s)}`}}let r=await Sn(t,"design.handoff",n,i);if(!n||r.satisfied||r.detail)return r;try{let s=await ru(t,e,n,su);return s?{...r,satisfied:!0,resolvedSource:s,detail:`resolved historical legacy pointer from archived change: ${s}`}:r}catch(s){return{...r,satisfied:!1,detail:`unsafe archived handoff fallback: ${s instanceof Error?s.message:String(s)}`}}}async function Xi(t,e,n){return Sn(t,e,kn(t,n))}async function Ug(t,e){let n=be.join(e,"specs"),i;try{let o=kn(t,n);if(!(await D(t,o,{label:"OpenSpec delta-spec directory",expected:"directory"})).exists)return{code:"openspec.delta-spec",satisfied:!1};i=await Kg.readdir(n)}catch(o){return o.code==="ENOENT"?{code:"openspec.delta-spec",satisfied:!1}:{code:"openspec.delta-spec",satisfied:!1,detail:`unsafe delta-spec path: ${o instanceof Error?o.message:String(o)}`}}let r=i.map(o=>be.join(n,o,"spec.md")),s=(await Promise.all(r.map(async o=>{try{return await Wi(t,kn(t,o),{label:"OpenSpec delta spec"})?o:null}catch{return null}}))).filter(o=>o!==null);return{code:"openspec.delta-spec",satisfied:s.length>0,source:s[0]?kn(t,s[0]):void 0,detail:`${s.length} delta spec${s.length===1?"":"s"}`}}async function Vg(t,e){let n,i=kn(t,e);try{n=(await J(t,i,su,{label:"Classic tasks artifact"})).bytes.toString("utf8")}catch(o){return o.code==="ENOENT"?{code:"build.tasks-complete",satisfied:!1}:{code:"build.tasks-complete",satisfied:!1,source:i,detail:`unsafe tasks artifact: ${o instanceof Error?o.message:String(o)}`}}let r=[...n.matchAll(/^\s*[-*]\s+\[([ xX])\]\s+/gmu)],s=r.filter(o=>o[1].toLowerCase()==="x").length;return{code:"build.tasks-complete",satisfied:r.length>0&&s===r.length,source:i,detail:`${s} of ${r.length} tasks complete`}}function ot(t,e){return t.some(n=>n.code===e&&n.satisfied)}async function Ke(t,e){let n=await st(t),i=e.classic,r=be.join(t,"proposal.md"),s=be.join(t,"design.md"),o=be.join(t,"tasks.md"),a=e.run?be.resolve(t,e.run.checkpointRef):be.join(t,".comet","checkpoint.json"),c,l;try{c=await We(n)}catch(f){l=f}let d=await Promise.all([Xi(n,"openspec.proposal",r),Xi(n,"openspec.design",s),Xi(n,"openspec.tasks",o),Ug(n,t),Sn(n,"design.document",i?.designDoc??null,c,l),Sn(n,"build.plan",i?.plan??null,c,l),Vg(n,o),Sn(n,"verification.report",i?.verificationReport??null,c,l),Yg(n,t,i?.handoffContext??null,c),Xi(n,"run.checkpoint",a)]),u=d.find(f=>f.code==="design.handoff");return u&&!i?.handoffHash&&(u.satisfied=!1,u.detail="handoff hash is missing"),d.push({code:"archive.confirmed",satisfied:i?.archiveConfirmation==="confirmed"}),d}import{promises as Lu}from"fs";import ie from"path";import{fileURLToPath as Du}from"url";import{createHash as Hw,randomUUID as Gw}from"crypto";import{promises as Ro}from"fs";import ke from"path";function Jg(t){return t.classicProfile??t.workflow}function Hg(t){return!t.buildMode||!t.tddMode||!t.isolation||!t.verifyMode?!1:t.buildMode==="subagent-driven-development"?t.subagentDispatch==="confirmed":t.buildMode==="direct"?t.directOverride===!0:!0}function Gg(t){return t.buildMode==="direct"&&t.tddMode==="direct"&&t.isolation!==null&&t.verifyMode==="light"}function zg(t,e,n){if(e.verifyResult==="fail")return t==="full"?"full.build.fix":`${t}.build.execute`;if(t==="full"){if(!ot(n,"build.plan"))return"full.build.plan";if(e.buildPause==="plan-ready")return"full.build.plan-ready";if(!Hg(e))return"full.build.configure"}else if(!Gg(e))throw new Error(`${t} build configuration is incomplete`);return ot(n,"build.tasks-complete")?`${t}.build.complete`:`${t}.build.execute`}function Qg(t,e,n){return e.verifyResult!=="pass"||!ot(n,"verification.report")?`${t}.verify.run`:`${t}.verify.branch`}function Xg(t,e){if(e.verifyResult!=="pass")throw new Error("archive requires verify_result=pass");return e.archiveConfirmation==="confirmed"?`${t}.archive.execute`:`${t}.archive.confirm`}function Et(t,e){let n=Jg(t);if(t.archived&&t.phase!=="archive")throw new Error("archived=true requires phase=archive");if(t.archived)return"completed";if(n!=="full"&&t.phase==="design")throw new Error(`${n} workflow cannot enter design`);switch(t.phase){case"open":return`${n}.open`;case"design":return ot(e,"design.handoff")?"full.design.document":"full.design.handoff";case"build":return zg(n,t,e);case"verify":return Qg(n,t,e);case"archive":return Xg(n,t)}}var sr=Je(Ie(),1);et();le();import rr from"path";nr();var lu=["full","hotfix","tweak"],at=1,iw=["open","design","build","verify","archive"],rw=["en","zh-CN"],sw=["off","beta"],ow=["subagent-driven-development","executing-plans","direct"],aw=["plan-ready"],cw=["confirmed"],lw=["tdd","direct"],uw=["off","standard","thorough"],fw=["current","branch","worktree"],dw=["light","full"],pw=["pending","pass","fail"],mw=["pending","handled"],hw=["pending","confirmed"],_t=["workflow","language","phase","context_compression","build_mode","build_pause","subagent_dispatch","tdd_mode","review_mode","isolation","bound_branch","verify_mode","auto_transition","base_ref","design_doc","plan","verify_result","verify_failures","verification_report","branch_status","created_at","verified_at","archive_confirmation","archived","direct_override","handoff_context","handoff_hash","classic_profile","classic_migration"],So=["run_id"],gw=new Set([..._t,...So]),ww=["workflow","phase","design_doc","plan","build_mode","isolation","verify_mode","verify_result","verified_at","archived"];function uu(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function xt(t,e){let n=t[e];if(n==null||n==="")return null;if(typeof n!="string")throw new Error(`Invalid Classic state: ${e} must be a string or null`);return n}function Q(t,e,n,i=!0){let r=t[e];if(r==null||r===""){if(i)return null;throw new Error(`Invalid Classic state: ${e} is required`)}if(typeof r!="string"||!n.includes(r))throw new Error(`Invalid Classic state: ${e} must be one of ${n.join(", ")}${i?" or null":""}`);return r}function ko(t,e,n=!0){let i=t[e];if(i==null||i===""){if(n)return null;throw new Error(`Invalid Classic state: ${e} is required`)}if(typeof i!="boolean")throw new Error(`Invalid Classic state: ${e} must be true or false`);return i}function yw(t,e,n=0){let i=t[e];if(i==null||i==="")return n;if(typeof i!="number"||!Number.isInteger(i)||i<0)throw new Error(`Invalid Classic state: ${e} must be a non-negative integer`);return i}function ir(t,e){let n=xt(t,e);if(n===null)return null;if(/^(?:[A-Za-z]:|[\\/]|~)/u.test(n)||n.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Classic state: ${e} must be a relative repository path`);return n}function vw(t,e){let n=xt(t,e);if(n!==null&&!/^[a-f0-9]{64}$/u.test(n))throw new Error(`Invalid Classic state: ${e} must be a sha256 hex digest`);return n}function bw(t){let e=t.classic_migration;if(e==null||e==="")return null;if(e!==at)throw new Error(`Invalid Classic state: classic_migration must be ${at}`);return e}function kw(t){if(!_t.some(n=>uu(t,n)))return null;for(let n of ww)if(!uu(t,n))return null;return{workflow:Q(t,"workflow",lu,!1),language:Q(t,"language",rw),phase:Q(t,"phase",iw,!1),contextCompression:Q(t,"context_compression",sw),buildMode:Q(t,"build_mode",ow),buildPause:Q(t,"build_pause",aw),subagentDispatch:Q(t,"subagent_dispatch",cw),tddMode:Q(t,"tdd_mode",lw),reviewMode:Q(t,"review_mode",uw),isolation:Q(t,"isolation",fw),boundBranch:xt(t,"bound_branch"),verifyMode:Q(t,"verify_mode",dw),autoTransition:ko(t,"auto_transition"),baseRef:xt(t,"base_ref"),designDoc:ir(t,"design_doc"),plan:ir(t,"plan"),verifyResult:Q(t,"verify_result",pw,!1),verifyFailures:yw(t,"verify_failures"),verificationReport:ir(t,"verification_report"),branchStatus:Q(t,"branch_status",mw),createdAt:xt(t,"created_at"),verifiedAt:xt(t,"verified_at"),archiveConfirmation:Q(t,"archive_confirmation",hw),archived:ko(t,"archived",!1),directOverride:ko(t,"direct_override"),handoffContext:ir(t,"handoff_context"),handoffHash:vw(t,"handoff_hash"),classicProfile:Q(t,"classic_profile",lu),classicMigration:bw(t)}}function Co(t,e){let n=e??null;if(n===null&&e===void 0&&t.run_id&&t.skill)try{n=Zi(t)}catch(i){let r=i instanceof Error?i.message:String(i);throw new Error(r.replace(/^Invalid Run state:/u,"Invalid Classic state:"),{cause:i})}return{classic:kw(t),run:n,unknownKeys:Object.keys(t).filter(i=>!gw.has(i))}}function fu(t){return{workflow:t.workflow,language:t.language,phase:t.phase,context_compression:t.contextCompression,build_mode:t.buildMode,build_pause:t.buildPause,subagent_dispatch:t.subagentDispatch,tdd_mode:t.tddMode,review_mode:t.reviewMode,isolation:t.isolation,bound_branch:t.boundBranch,verify_mode:t.verifyMode,auto_transition:t.autoTransition,base_ref:t.baseRef,design_doc:t.designDoc,plan:t.plan,verify_result:t.verifyResult,verify_failures:t.verifyFailures,verification_report:t.verificationReport,branch_status:t.branchStatus,created_at:t.createdAt,verified_at:t.verifiedAt,archive_confirmation:t.archiveConfirmation,archived:t.archived,direct_override:t.directOverride,handoff_context:t.handoffContext,handoff_hash:t.handoffHash,classic_profile:t.classicProfile,classic_migration:t.classicMigration}}nr();var Sw=2*1024*1024;function xn(t){let e=t.toJS();if(e===null)return{};if(typeof e!="object"||Array.isArray(e))throw new Error("Invalid Classic state document: root must be a mapping");return e}function du(t,e,n){t.get(e)!==n&&t.set(e,n)}function Cw(t,e){if(e.classic)for(let[n,i]of Object.entries(fu(e.classic)))du(t,n,i);else for(let n of _t)t.delete(n);yo(t.toJS(),e.run),e.run?du(t,"run_id",e.run.runId):t.delete("run_id")}function Ew(t){let e=["skill","skill_version","skill_hash","orchestration","current_step","iteration","pending","pending_ref","trajectory_ref","context_ref","artifacts_ref","checkpoint_ref","run_status","run_retries"];for(let n of e)t.delete(n)}function xw(t){let e=!1;for(let n of["build_command","verify_command"])t.has(n)&&(t.delete(n),e=!0);return e}async function pu(t){let e;try{e=(await J(rr.dirname(t),rr.basename(t),Sw,{label:"Classic state document"})).bytes.toString("utf8")}catch(i){if(i.code!=="ENOENT")throw i;return new sr.Document({})}let n=(0,sr.parseDocument)(e);if(n.errors.length>0)throw new Error(`Invalid Classic state document: ${n.errors[0].message}`);return xn(n),n}async function Ye(t,e={}){let n=e.migrate!==!1,i=rr.join(t,".comet.yaml"),r=await pu(i),s=xn(r),o=xw(r);o&&(s=xn(r));let a=await vo(t);if(!a&&s.run_id&&s.skill){let{runStateFromDocument:c}=await Promise.resolve().then(()=>(nr(),cu));a=c(s),a&&n&&(await tr(t,a),Ew(r),o=!0)}return o&&n&&await me(i,r.toString(),{containedRoot:t}),Co(xn(r),a)}async function or(t,e,n={}){let i=rr.join(t,".comet.yaml"),r=await pu(i);Cw(r,{...e,unknownKeys:e.unknownKeys??[]}),Co(xn(r),e.run??null),await me(i,r.toString(),{containedRoot:t,beforeCommit:n.beforeCommit}),e.run?await tr(t,e.run):await bo(t)}function mu(t,e,n){return{runId:e,skill:t.definition.metadata.name,skillVersion:t.definition.metadata.version,skillHash:n,orchestration:t.definition.orchestration.mode,currentStep:t.definition.orchestration.entry??null,iteration:0,pending:null,pendingRef:".comet/pending-action.json",trajectoryRef:".comet/trajectory.jsonl",contextRef:".comet/context.md",artifactsRef:".comet/artifacts.json",checkpointRef:".comet/checkpoint.json",status:"running",retries:{}}}import{createHash as Ru,randomUUID as Kw}from"crypto";import{promises as K}from"fs";import F from"path";var wu=Je(Ie(),1);import{promises as Eo}from"fs";import oe from"path";var _w=["invoke_skill","call_tool","handoff","ask_user","checkpoint"],Pw=["deterministic","adaptive"],Rw=["function","mcp","script","agent"],Nw=["none","read","write","external"],Ow=["progress","step","completion"],Aw=["artifact_exists","state_equals"];function ct(t,e,n){return new Error(`${t}: ${e} ${n}`)}function ne(t,e,n="document"){if(t===null||typeof t!="object"||Array.isArray(t))throw ct(e,n,"must be an object")}function Ue(t,e,n){if(!Array.isArray(t))throw ct(e,n,"must be an array")}function X(t,e,n){if(typeof t!="string")throw ct(e,n,"must be a string")}function ue(t,e,n,i){e in t&&X(t[e],n,`${i}.${e}`)}function yu(t,e,n,i){if(e in t&&typeof t[e]!="boolean")throw ct(n,`${i}.${e}`,"must be a boolean")}function Ve(t,e,n,i){if(typeof t!="string"||!e.includes(t))throw ct(n,i,`must be one of ${e.join(", ")}`)}function ar(t,e,n){Ue(t,e,n),t.forEach((i,r)=>{X(i,e,`${n}[${r}]`)})}function hu(t,e,n){ne(t,e,n),X(t.name,e,`${n}.name`),X(t.description,e,`${n}.description`),yu(t,"required",e,n)}function jw(t,e,n){ne(t,e,n),X(t.id,e,`${n}.id`),ue(t,"source",e,n),ue(t,"version",e,n)}function Tw(t,e,n){ne(t,e,n),X(t.id,e,`${n}.id`),X(t.role,e,`${n}.role`),ue(t,"instructions",e,n)}function Iw(t,e,n){ne(t,e,n),X(t.id,e,`${n}.id`),Ve(t.kind,Rw,e,`${n}.kind`),X(t.source,e,`${n}.source`),Ve(t.sideEffect,Nw,e,`${n}.sideEffect`),yu(t,"requiresConfirmation",e,n)}function $w(t,e,n){ne(t,e,n),Ve(t.type,_w,e,`${n}.type`),ue(t,"ref",e,n),ue(t,"prompt",e,n),ue(t,"question",e,n),"options"in t&&ar(t.options,e,`${n}.options`)}function qw(t,e,n){ne(t,e,n),X(t.id,e,`${n}.id`),$w(t.action,e,`${n}.action`),ue(t,"next",e,n),"completionEvals"in t&&ar(t.completionEvals,e,`${n}.completionEvals`)}function Lw(t,e){let n="goal";ne(t,e,n),X(t.statement,e,`${n}.statement`),Ue(t.inputs,e,`${n}.inputs`),t.inputs.forEach((i,r)=>{hu(i,e,`${n}.inputs[${r}]`)}),Ue(t.outputs,e,`${n}.outputs`),t.outputs.forEach((i,r)=>{hu(i,e,`${n}.outputs[${r}]`)}),ar(t.success,e,`${n}.success`)}function Dw(t,e){let n="orchestration";ne(t,e,n),Ve(t.mode,Pw,e,`${n}.mode`),ue(t,"entry",e,n),"steps"in t&&(Ue(t.steps,e,`${n}.steps`),t.steps.forEach((i,r)=>{qw(i,e,`${n}.steps[${r}]`)}))}function vu(t,e){return ne(t,e),Ve(t.apiVersion,["comet/v1alpha1"],e,"apiVersion"),Ve(t.kind,["Skill"],e,"kind"),ne(t.metadata,e,"metadata"),X(t.metadata.name,e,"metadata.name"),X(t.metadata.version,e,"metadata.version"),X(t.metadata.description,e,"metadata.description"),Lw(t.goal,e),Dw(t.orchestration,e),Ue(t.skills,e,"skills"),t.skills.forEach((n,i)=>{jw(n,e,`skills[${i}]`)}),Ue(t.agents,e,"agents"),t.agents.forEach((n,i)=>{Tw(n,e,`agents[${i}]`)}),Ue(t.tools,e,"tools"),t.tools.forEach((n,i)=>{Iw(n,e,`tools[${i}]`)}),t}function bu(t,e){ne(t,e);for(let n of["allowedSkills","allowedAgents","allowedTools","confirmationRequiredFor"])n in t&&ar(t[n],e,n);for(let n of["maxIterations","maxRetriesPerAction"])if(n in t&&(typeof t[n]!="number"||!Number.isFinite(t[n])))throw ct(e,n,"must be a finite number");return t}function Fw(t,e){return ne(t,e),"runtime"in t&&ku(t.runtime,e,"runtime"),t}function ku(t,e,n){return Ue(t,e,n),t.forEach((i,r)=>{let s=`${n}[${r}]`;ne(i,e,s),X(i.id,e,`${s}.id`),Ve(i.scope,Ow,e,`${s}.scope`),Ve(i.type,Aw,e,`${s}.type`),ue(i,"artifact",e,s),ue(i,"field",e,s),ue(i,"equals",e,s)}),t}async function xo(t){let e=await Eo.readFile(t,"utf8");try{return(0,wu.parse)(e)}catch(n){let i=n instanceof Error?n.message:String(n);throw ct(t,"document",i)}}async function Mw(t){try{return await xo(t)}catch(e){if(e.code==="ENOENT")return null;throw e}}async function gu(t){try{return await Eo.access(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function Ww(t){let e=oe.join(t,"checks.yaml"),n=oe.join(t,"evals.yaml"),[i,r]=await Promise.all([gu(e),gu(n)]);if(r)throw new Error(`${n}: evals.yaml is no longer supported; use checks.yaml`);return i?{document:Fw(await xo(e),e)}:{document:null}}async function Su(t){let e=oe.resolve(t.root),n=oe.resolve(t.controlRoot);t.requireSkillMarkdown&&await Eo.access(oe.join(e,"SKILL.md"));let i=oe.join(n,"skill.yaml"),r=oe.join(n,"guardrails.yaml"),s=vu(await xo(i),i),o=await Mw(r),a=o===null?null:bu(o,r),c=await Ww(n),l={allowedSkills:s.skills.map(d=>d.id),allowedAgents:s.agents.map(d=>d.id),allowedTools:s.tools.map(d=>d.id),maxIterations:50,maxRetriesPerAction:3,confirmationRequiredFor:s.tools.filter(d=>d.requiresConfirmation).map(d=>d.id)};return{root:e,packageKind:t.packageKind==="runtime"?"runtime":void 0,definition:s,guardrails:{...l,...a},evals:c.document?.runtime??[]}}async function Cu(t){let e=oe.resolve(t);return Su({root:e,controlRoot:oe.join(e,"comet"),packageKind:"skill",requireSkillMarkdown:!0})}async function Eu(t){let e=oe.resolve(t);return Su({root:e,controlRoot:e,packageKind:"runtime",requireSkillMarkdown:!1})}function xu(t,e,n=oe.join(e,"package.json")){ne(t,n);let i=t.packageKind==="runtime"?"runtime":void 0,r=vu(t.definition,n),s=bu(t.guardrails,n),o=ku(t.evals,n,"evals"),a={allowedSkills:r.skills.map(c=>c.id),allowedAgents:r.agents.map(c=>c.id),allowedTools:r.tools.map(c=>c.id),maxIterations:50,maxRetriesPerAction:3,confirmationRequiredFor:r.tools.filter(c=>c.requiresConfirmation).map(c=>c.id)};return{root:oe.resolve(e),packageKind:i,definition:r,guardrails:{...a,...s},evals:o}}import _u from"path";function Bw(t,e,n,i){t.type==="invoke_skill"&&!e.definition.skills.some(r=>r.id===t.ref)&&n.push(`step ${i} references undeclared skill: ${t.ref??"(missing)"}`),t.type==="call_tool"&&!e.definition.tools.some(r=>r.id===t.ref)&&n.push(`step ${i} references undeclared tool: ${t.ref??"(missing)"}`),t.type==="handoff"&&!e.definition.agents.some(r=>r.id===t.ref)&&n.push(`step ${i} references undeclared agent: ${t.ref??"(missing)"}`),t.type==="ask_user"&&!t.question&&n.push(`step ${i} ask_user action requires question`)}function Pu(t){let e=[],{definition:n,guardrails:i,evals:r}=t;n.apiVersion!=="comet/v1alpha1"&&e.push("unsupported apiVersion"),n.kind!=="Skill"&&e.push("kind must be Skill"),n.metadata.name||e.push("metadata.name is required"),n.goal.statement||e.push("goal.statement is required"),i.maxIterations<1&&e.push("maxIterations must be at least 1"),i.maxRetriesPerAction<0&&e.push("maxRetriesPerAction must not be negative");let s=n.orchestration.steps??[];if(n.orchestration.mode==="adaptive")(n.orchestration.entry||s.length>0)&&e.push("adaptive orchestration must not define entry or steps");else{let o=new Set;for(let a of s)o.has(a.id)&&e.push(`duplicate step id: ${a.id}`),o.add(a.id),Bw(a.action,t,e,a.id);(!n.orchestration.entry||!o.has(n.orchestration.entry))&&e.push(`orchestration.entry references unknown step: ${n.orchestration.entry??"(missing)"}`);for(let a of s){a.next&&!o.has(a.next)&&e.push(`step ${a.id} has unknown next step: ${a.next}`);for(let c of a.completionEvals??[])r.some(l=>l.id===c)||e.push(`step ${a.id} references unknown eval: ${c}`)}}for(let o of n.tools){if(o.kind!=="script")continue;let a=_u.posix.normalize(o.source.replaceAll("\\","/"));(_u.isAbsolute(o.source)||a===".."||a.startsWith("../"))&&e.push(`script tool ${o.id} must reference a relative path inside the Skill package`)}for(let o of i.allowedSkills)n.skills.some(a=>a.id===o)||e.push(`guardrails allow undeclared skill: ${o}`);for(let o of i.allowedAgents)n.agents.some(a=>a.id===o)||e.push(`guardrails allow undeclared agent: ${o}`);for(let o of i.allowedTools)n.tools.some(a=>a.id===o)||e.push(`guardrails allow undeclared tool: ${o}`);return e}function cr(t){return Array.isArray(t)?t.map(cr):t&&typeof t=="object"?Object.fromEntries(Object.entries(t).sort(([e],[n])=>e.localeCompare(n)).map(([e,n])=>[e,cr(n)])):t}function Yw(t){return cr({...t.packageKind==="runtime"?{packageKind:"runtime"}:{},definition:t.definition,guardrails:t.guardrails,evals:t.evals})}function Uw(t){return F.posix.normalize(t.replaceAll("\\","/"))}function Pt(t,e,n){let i=F.relative(t,e);if(!(i===""||!F.isAbsolute(i)&&!i.startsWith(`..${F.sep}`)))throw new Error(`${n} resolves outside the Skill package`)}async function Nu(t,e,n){let i=Uw(e);if(F.posix.isAbsolute(i)||i===".."||i.startsWith("../"))throw new Error(`${n} resolves outside the Skill package`);let r=F.resolve(t,...i.split("/"));Pt(t,r,n);let s;try{s=await K.realpath(r)}catch(o){throw o.code==="ENOENT"?new Error(`${n} does not exist: ${e}`,{cause:o}):o}if(Pt(t,s,n),!(await K.stat(s)).isFile())throw new Error(`${n} is not a file: ${e}`);return{path:i,content:await K.readFile(s)}}async function Vw(t){let e=await K.realpath(t.root),n=t.packageKind==="runtime"?[]:[await Nu(e,"SKILL.md","SKILL.md")];for(let i of t.definition.tools)i.kind==="script"&&n.push(await Nu(e,i.source,`Script tool ${i.id}`));return n.sort((i,r)=>i.path.localeCompare(r.path))}function Jw(t,e){let n=e.map(i=>({path:i.path,sha256:Ru("sha256").update(i.content).digest("hex")}));return Ru("sha256").update(JSON.stringify(cr({package:t,files:n}))).digest("hex")}function ju(t){return JSON.stringify(t,null,2)+` +`}async function Tu(t){let e=Yw(t),n=await Vw(t);return{document:e,files:n,hash:Jw(e,n)}}async function lr(t){return(await Tu(t)).hash}async function Ou(t){try{return await K.access(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function Au(t,e){try{if((await K.readFile(F.join(t,"sha256"),"utf8")).trim()!==e.hash)throw new Error("hash mismatch");if(await K.readFile(F.join(t,"package.json"),"utf8")!==ju(e.document))throw new Error("package mismatch");for(let r of e.files)if(!(await K.readFile(F.join(t,...r.path.split("/")))).equals(r.content))throw new Error(`file mismatch: ${r.path}`)}catch(n){throw new Error(`Existing Skill snapshot is invalid: ${e.hash}`,{cause:n})}}async function _o(t,e){let n=await Tu(t),i=F.resolve(e,".comet","skill-snapshots"),r=F.join(i,n.hash);if(await K.mkdir(i,{recursive:!0}),await Ou(r))return await Au(r,n),{hash:n.hash,snapshotDir:r};let s=F.join(i,`.tmp-${Kw()}`);Pt(i,s,"Temporary snapshot"),Pt(i,r,"Published snapshot");try{await K.mkdir(s);for(let o of n.files){let a=F.join(s,...o.path.split("/"));Pt(s,a,`Snapshot file ${o.path}`),await K.mkdir(F.dirname(a),{recursive:!0}),await K.writeFile(a,o.content)}await K.writeFile(F.join(s,"package.json"),ju(n.document)),await K.writeFile(F.join(s,"sha256"),n.hash+` +`),await K.rename(s,r)}catch(o){if(await Ou(r)){try{await Au(r,n)}finally{await K.rm(s,{recursive:!0,force:!0})}return{hash:n.hash,snapshotDir:r}}throw await K.rm(s,{recursive:!0,force:!0}),o}return{hash:n.hash,snapshotDir:r}}async function Po(t,e){if(!/^[a-f0-9]{64}$/u.test(e))throw new Error(`Invalid Skill snapshot hash: ${e}`);let n=F.resolve(t,".comet","skill-snapshots"),i=F.join(n,e);Pt(n,i,"Skill snapshot");try{let r=(await K.readFile(F.join(i,"sha256"),"utf8")).trim();if(r!==e)throw new Error(`stored hash is ${r||"(empty)"}`);let s=F.join(i,"package.json"),o=JSON.parse(await K.readFile(s,"utf8")),a=xu(o,i,s),c=Pu(a);if(c.length>0)throw new Error(c.map(d=>` - ${d}`).join(` +`));let l=await lr(a);if(l!==e)throw new Error(`calculated hash is ${l}`);return a}catch(r){throw new Error(`Skill snapshot is invalid or missing: ${e}`,{cause:r})}}async function Iu(t){try{return await Ro.access(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}function $u(t){return Hw("sha256").update(t).digest("hex")}function zw(t){return $u(JSON.stringify(Object.fromEntries(Object.entries(t).sort(([e],[n])=>e.localeCompare(n)))))}function Qw(t){return t.replaceAll(".","_").replaceAll("-","_")}async function Xw(t,e){let n=await st(t),i=Object.fromEntries(e.filter(o=>o.satisfied&&o.source).map(o=>[Qw(o.code),o.source])),r=ke.join(t,"subagent-progress.md");await Iu(r)&&(i.subagent_progress=ke.relative(n,r).split(ke.sep).join("/"));let s=e.find(o=>o.code==="design.handoff"&&o.satisfied);return s?.source&&(i.handoff_context=s.source),i}function Zw(t,e,n){return[{sequence:1,timestamp:n,type:"run_started",runId:t.runId,data:{skill:t.skill,skillVersion:t.skillVersion,skillHash:t.skillHash}},{sequence:2,timestamp:n,type:"state_migrated",runId:t.runId,data:{kind:"classic",migrationVersion:at,profile:e,source:"pre-migration"}}]}async function ey(t){await Promise.all(t.map(e=>Ro.rm(e,{recursive:!0,force:!0})))}async function qu(t,e){let n=await Ye(t);if(!n.classic)throw new Error("Classic migration requires a legacy state projection");let i=n.classic,r=i.classicProfile??i.workflow;if(n.run){if(i.classicMigration!==at)throw new Error("Classic Run exists without a supported classic_migration marker");if(n.run.skill!==e.skillPackage.definition.metadata.name)throw new Error(`Classic Run skill mismatch: expected ${e.skillPackage.definition.metadata.name}, got ${n.run.skill}`);if(await lr(e.skillPackage)!==n.run.skillHash)return await Po(t,n.run.skillHash),{classic:i,run:n.run,evidence:await Ke(t,n),migrated:!1,snapshotDir:ke.join(t,".comet","skill-snapshots",n.run.skillHash)};let f=await _o(e.skillPackage,t);return{classic:i,run:n.run,evidence:await Ke(t,n),migrated:!1,snapshotDir:f.snapshotDir}}let s=await Ke(t,n),o=Et(i,s);if(!e.skillPackage.definition.orchestration.steps?.some(u=>u.id===o))throw new Error(`Classic Skill package does not define resolved step: ${o}`);let a=await lr(e.skillPackage),c=ke.join(t,".comet","skill-snapshots",a),l=await Iu(c),d=[];try{let u=await _o(e.skillPackage,t),f=mu(e.skillPackage,e.runId?.()??Gw(),u.hash);f.currentStep=o,o==="completed"&&(f.status="completed");let h={...i,classicProfile:r,classicMigration:at},w=await Xw(t,s),p=await st(t),m=s.find(C=>C.code==="design.handoff"&&C.satisfied),g=null;m?.source&&(g=await te(p,m.resolvedSource??m.source,{label:"Classic migration handoff context",hooks:e.handoffReadHooks}),await Gl(t,f.contextRef,g),d.push(ke.resolve(t,f.contextRef))),await Hl(t,f.artifactsRef,w),d.push(ke.resolve(t,f.artifactsRef));let y=(e.now?.()??new Date).toISOString(),k={runId:f.runId,stateVersion:1,trajectoryOffset:2,contextHash:g===null?null:$u(g),artifactsHash:zw(w),createdAt:y};await zl(t,f.checkpointRef,k),d.push(ke.resolve(t,f.checkpointRef)),d.push(ke.resolve(t,f.trajectoryRef));for(let C of Zw(f,r,y))await mn(t,f.trajectoryRef,C);return await or(t,{classic:h,run:f,unknownKeys:n.unknownKeys}),{classic:h,run:f,evidence:s,migrated:!0,snapshotDir:u.snapshotDir}}catch(u){throw await ey(d),l||await Ro.rm(c,{recursive:!0,force:!0}),u}}async function ty(t){try{return(await Lu.stat(t)).isDirectory()}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function ur(t){try{return(await Lu.stat(t)).isFile()}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function ny(t){return await ty(t)?await ur(ie.join(t,"skill.yaml"))?!0:await ur(ie.join(t,"SKILL.md"))&&await ur(ie.join(t,"comet","skill.yaml")):!1}function iy(t){return{root:t,packageKind:"runtime",definition:{apiVersion:"comet/v1alpha1",kind:"Skill",metadata:{name:"comet-classic",version:"1",description:"Internal compatibility orchestration for classic Comet full, hotfix, and tweak workflows"},goal:{statement:"Advance or restore a classic Comet Run without changing the user command surface",inputs:[{name:"classic-state",description:"Validated ClassicState consistent with the Run projection",required:!0},{name:"evidence",description:"Structured evidence produced by the Classic Evidence collector",required:!0}],outputs:[{name:"run-state",description:"Atomically synchronized Classic and Run state",required:!0}],success:["Legacy fields and Run fields remain consistent","Every step invokes only a declared public Comet Skill","The completed state passes its completion eval"]},orchestration:{mode:"deterministic",entry:"full.open",steps:[{id:"full.open",action:{type:"invoke_skill",ref:"comet-open"},next:"full.design.handoff"},{id:"full.design.handoff",action:{type:"invoke_skill",ref:"comet-design"},next:"full.design.document"},{id:"full.design.document",action:{type:"invoke_skill",ref:"comet-design"},next:"full.build.plan"},{id:"full.build.plan",action:{type:"invoke_skill",ref:"comet-build"},next:"full.build.plan-ready"},{id:"full.build.plan-ready",action:{type:"invoke_skill",ref:"comet-build"},next:"full.build.configure"},{id:"full.build.configure",action:{type:"invoke_skill",ref:"comet-build"},next:"full.build.execute"},{id:"full.build.execute",action:{type:"invoke_skill",ref:"comet-build"},next:"full.build.complete"},{id:"full.build.complete",action:{type:"invoke_skill",ref:"comet-build"},next:"full.verify.run"},{id:"full.build.fix",action:{type:"invoke_skill",ref:"comet-build"},next:"full.build.execute"},{id:"full.verify.run",action:{type:"invoke_skill",ref:"comet-verify"},next:"full.verify.branch"},{id:"full.verify.branch",action:{type:"invoke_skill",ref:"comet-verify"},next:"full.archive.confirm"},{id:"full.archive.confirm",action:{type:"invoke_skill",ref:"comet-archive"},next:"full.archive.execute"},{id:"full.archive.execute",action:{type:"invoke_skill",ref:"comet-archive"},next:"completed"},{id:"hotfix.open",action:{type:"invoke_skill",ref:"comet-hotfix"},next:"hotfix.build.execute"},{id:"hotfix.build.execute",action:{type:"invoke_skill",ref:"comet-build"},next:"hotfix.build.complete"},{id:"hotfix.build.complete",action:{type:"invoke_skill",ref:"comet-build"},next:"hotfix.verify.run"},{id:"hotfix.verify.run",action:{type:"invoke_skill",ref:"comet-verify"},next:"hotfix.verify.branch"},{id:"hotfix.verify.branch",action:{type:"invoke_skill",ref:"comet-verify"},next:"hotfix.archive.confirm"},{id:"hotfix.archive.confirm",action:{type:"invoke_skill",ref:"comet-archive"},next:"hotfix.archive.execute"},{id:"hotfix.archive.execute",action:{type:"invoke_skill",ref:"comet-archive"},next:"completed"},{id:"tweak.open",action:{type:"invoke_skill",ref:"comet-tweak"},next:"tweak.build.execute"},{id:"tweak.build.execute",action:{type:"invoke_skill",ref:"comet-build"},next:"tweak.build.complete"},{id:"tweak.build.complete",action:{type:"invoke_skill",ref:"comet-build"},next:"tweak.verify.run"},{id:"tweak.verify.run",action:{type:"invoke_skill",ref:"comet-verify"},next:"tweak.verify.branch"},{id:"tweak.verify.branch",action:{type:"invoke_skill",ref:"comet-verify"},next:"tweak.archive.confirm"},{id:"tweak.archive.confirm",action:{type:"invoke_skill",ref:"comet-archive"},next:"tweak.archive.execute"},{id:"tweak.archive.execute",action:{type:"invoke_skill",ref:"comet-archive"},next:"completed"},{id:"completed",action:{type:"checkpoint"},completionEvals:["classic-completed"]}]},skills:[{id:"comet-open"},{id:"comet-design"},{id:"comet-build"},{id:"comet-verify"},{id:"comet-archive"},{id:"comet-hotfix"},{id:"comet-tweak"}],agents:[],tools:[]},guardrails:{allowedSkills:["comet-open","comet-design","comet-build","comet-verify","comet-archive","comet-hotfix","comet-tweak"],allowedAgents:[],allowedTools:[],maxIterations:500,maxRetriesPerAction:3,confirmationRequiredFor:[]},evals:[{id:"classic-completed",scope:"completion",type:"state_equals",field:"status",equals:"completed"}]}}async function ry(){let t=ie.dirname(Du(import.meta.url)),e=[process.env.COMET_RUNTIME_CLASSIC_ROOT,ie.resolve(t,"..","runtime","classic"),ie.resolve(t,"..","..","comet","runtime","classic"),ie.resolve(t,"..","..","assets","skills","comet","runtime","classic"),ie.resolve("assets","skills","comet","runtime","classic"),process.env.COMET_CLASSIC_SKILL_ROOT,ie.resolve(t,"..","..","comet-classic"),ie.resolve(t,"..","..","assets","skills","comet-classic"),ie.resolve("assets","skills","comet-classic")].filter(n=>!!n);for(let n of e)if(await ny(n))return n;return null}async function sy(t){return await ur(ie.join(t,"skill.yaml"))?Eu(t):Cu(t)}async function fr(t){let e=await ry();return qu(t,{skillPackage:e?await sy(e):iy(ie.dirname(Du(import.meta.url)))})}async function Fu(t){let e=await Ye(t),n=Array.from(new Set(e.unknownKeys)).sort();if(n.length>0)throw new Error(`Invalid Classic state: unknown field(s): ${n.join(", ")}`);return fr(t)}async function Mu(t,e,n,i){let r=await Ye(t);if(!r.classic||!r.run)throw new Error("Classic transition requires synchronized Classic and Run projections");let s=await Ke(t,{classic:e,run:n,unknownKeys:r.unknownKeys}),o=Et(e,s),a={...n,currentStep:o,iteration:n.iteration+1,status:o==="completed"?"completed":"running"};await or(t,{classic:e,run:a,unknownKeys:r.unknownKeys});let c=await Vi(t,a.trajectoryRef);return await mn(t,a.trajectoryRef,{sequence:c.length+1,timestamp:new Date().toISOString(),type:"state_transitioned",runId:a.runId,data:{kind:"classic",fromStep:n.currentStep,toStep:o,...i}}),a}var Wu={"full.open":["openspec.proposal","openspec.tasks"],"full.design.handoff":["openspec.proposal","openspec.design","openspec.tasks"],"full.design.document":["design.handoff"],"full.build.plan":["openspec.tasks"],"full.build.plan-ready":["build.plan"],"full.build.configure":["build.plan"],"full.build.execute":["build.plan"],"full.build.complete":["build.tasks-complete"],"full.verify.run":["build.tasks-complete"],"full.verify.branch":["verification.report"],"full.archive.confirm":["verification.report"],"full.archive.execute":["archive.confirmed"]};function oy(t){return Wu[t]?Wu[t]:t.endsWith(".open")?["openspec.proposal","openspec.tasks"]:t.endsWith(".build.execute")?[]:t.endsWith(".build.complete")?["build.tasks-complete"]:t.endsWith(".verify.run")?["build.tasks-complete"]:t.endsWith(".verify.branch")?["verification.report"]:t.endsWith(".archive.confirm")?["verification.report"]:t.endsWith(".archive.execute")?["archive.confirmed"]:[]}function Bu(t,e){let n=oy(t),i=n.filter(r=>!ot(e,r));return{stepId:t,passed:i.length===0,requiredEvidence:n,missingEvidence:i}}function ay(t){switch(t){case"open":return"/comet-open";case"design":return"/comet-design";case"build":return"/comet-build";case"verify":return"/comet-verify";case"archive":return"/comet-archive";default:return null}}async function Ku(t,e){try{let n=await Fu(t),i=await Ke(t,{classic:n.classic,run:n.run,unknownKeys:[]}),r=Et(n.classic,i);return{name:e,valid:!0,workflow:n.classic.workflow,phase:n.classic.phase,currentStep:r,nextCommand:ay(n.classic.phase),runtimeMode:"engine-projection",runtimeEval:Bu(r,i),evidence:i}}catch(n){return{name:e,valid:!1,workflow:"unknown",phase:"invalid",currentStep:null,nextCommand:null,runtimeMode:"invalid",runtimeEval:null,evidence:[],error:n instanceof Error?n.message:String(n)}}}Yi();import cy from"path";var ly=cy.join(".comet","state-events.jsonl"),uy=8*1024*1024;async function Yu(t,e){let n={schemaVersion:1,timestamp:new Date().toISOString(),...e};return await Ki(t,ly,`${JSON.stringify(n)} +`,uy,"Classic state event log"),n}var fy={"open-complete":{event:"open-complete",from:"open",guardRefs:["open-artifacts-present"]},"design-complete":{event:"design-complete",from:"design",guardRefs:["design-evidence-present"]},"build-complete":{event:"build-complete",from:"build",guardRefs:["build-decisions-selected"]},"verify-pass":{event:"verify-pass",from:"verify",guardRefs:["verification-report-present"]},"verify-fail":{event:"verify-fail",from:"verify",guardRefs:["verification-failed"]},"archive-confirm":{event:"archive-confirm",from:"archive",guardRefs:["archive-final-confirmation"]},"archive-reopen":{event:"archive-reopen",from:"archive",guardRefs:["archive-not-finalized"]},archived:{event:"archived",from:"archive",guardRefs:["verify-result-pass","archive-confirmed"]},"preset-escalate":{event:"preset-escalate",from:"build",guardRefs:["preset-workflow"]}},Uu={open:"open-complete",design:"design-complete",build:"build-complete",verify:"verify-pass"};function dy(t){return t.toISOString().slice(0,10)}function R(t,e,n,i){let r=t[n];t[n]=i,r!==i&&e.push({field:n,from:r,to:i})}function Vu(t,e,n={}){let i=fy[e];if(t.phase!==i.from)throw new Error(`Cannot apply ${e}: phase is '${t.phase}', expected '${i.from}'`);let r={...t},s=[],o=n.now??new Date;if(e==="open-complete")R(r,s,"phase",r.workflow==="full"?"design":"build");else if(e==="design-complete")R(r,s,"phase","build");else if(e==="build-complete"){let a=r.verifyResult==="fail";R(r,s,"phase","verify"),R(r,s,"verifyResult","pending"),R(r,s,"branchStatus","pending"),a||R(r,s,"verificationReport",null)}else if(e==="verify-pass")R(r,s,"verifyResult","pass"),R(r,s,"verifyFailures",0),R(r,s,"phase","archive"),R(r,s,"verifiedAt",dy(o)),R(r,s,"archiveConfirmation","pending"),R(r,s,"branchStatus","pending");else if(e==="verify-fail")R(r,s,"verifyResult","fail"),R(r,s,"verifyFailures",r.verifyFailures+1),R(r,s,"phase","build"),R(r,s,"branchStatus","pending");else if(e==="preset-escalate"){if(r.workflow!=="hotfix"&&r.workflow!=="tweak")throw new Error(`Cannot apply ${e}: workflow must be hotfix or tweak, got '${r.workflow}'`);R(r,s,"workflow","full"),R(r,s,"classicProfile","full"),R(r,s,"phase","design"),R(r,s,"designDoc",null),R(r,s,"buildPause",null),R(r,s,"buildMode",null),R(r,s,"subagentDispatch",null),R(r,s,"tddMode",null),R(r,s,"reviewMode",null),R(r,s,"isolation",null),R(r,s,"boundBranch",null),R(r,s,"verifyMode",null),R(r,s,"directOverride",null)}else if(e==="archive-confirm"){if(r.verifyResult!=="pass")throw new Error(`Cannot apply ${e}: verifyResult must be pass`);if(r.archived)throw new Error(`Cannot apply ${e}: already archived`);R(r,s,"archiveConfirmation","confirmed")}else if(e==="archive-reopen"){if(r.archived)throw new Error(`Cannot apply ${e}: already archived`);R(r,s,"verifyResult","pending"),R(r,s,"verifyFailures",0),R(r,s,"phase","verify"),R(r,s,"verifiedAt",null),R(r,s,"archiveConfirmation",null),R(r,s,"branchStatus","pending")}else{if(r.verifyResult!=="pass")throw new Error(`Cannot apply ${e}: verifyResult must be pass`);if(r.archiveConfirmation!=="confirmed")throw new Error(`Cannot apply ${e}: archiveConfirmation must be confirmed`);R(r,s,"archived",!0)}return{classic:r,effects:s,definition:i}}var Nn=Je(Ie(),1);import Hu from"path";import{AsyncLocalStorage as py}from"async_hooks";import{promises as Ju}from"fs";import _n from"path";var dr=new py;function my(t,e){let n=_n.relative(t,e);return n===""||!_n.isAbsolute(n)&&n!==".."&&!n.startsWith(`..${_n.sep}`)}async function hy(t){let e=_n.resolve(t.invocationCwd??process.cwd()),n=_n.resolve(t.projectRoot??await st(e)),[i,r]=await Promise.all([Ju.realpath(e),Ju.realpath(n)]);if(!my(r,i))throw new Error(`Classic command invocation cwd is outside the discovered project: ${e}`);return{invocationCwd:e,projectRoot:n}}async function pr(t,e){let n=dr.getStore();if(n)return e(n);let i=await hy(t);return dr.run(i,()=>e(i))}function I(){let t=dr.getStore();if(!t)throw new Error("Classic command project context is unavailable");return t.projectRoot}function mr(){let t=dr.getStore();if(!t)throw new Error("Classic command invocation context is unavailable");return t.invocationCwd}var gy="\x1B[32m",Pn="\x1B[31m",wy="\x1B[33m",yy="\x1B[0m",vy=["workflow","phase","design_doc","plan","build_mode","isolation","verify_mode","verify_result","verified_at","archived"],by={workflow:["full","hotfix","tweak"],language:["en","zh-CN"],phase:["open","design","build","verify","archive"],context_compression:["off","beta"],build_mode:["subagent-driven-development","executing-plans","direct"],build_pause:["plan-ready"],subagent_dispatch:["confirmed"],tdd_mode:["tdd","direct"],review_mode:["off","standard","thorough"],isolation:["current","branch","worktree"],verify_mode:["light","full"],auto_transition:["true","false"],verify_result:["pending","pass","fail"],branch_status:["pending","handled"],archive_confirmation:["pending","confirmed"],archived:["true","false"],direct_override:["true","false"],classic_profile:["full","hotfix","tweak"],classic_migration:["1"]},ky=new Set([..._t,...So,"classic_profile","classic_migration"]);function lt(t,e){return`${t}${e}${yy}`}function Rn(t){return t==null?"":typeof t=="object"?JSON.stringify(t):String(t)}var Gu=async(t,e)=>pr(e,async()=>{let n=t[0],i=vn(n);if(i)return{exitCode:1,stderr:lt(Pn,`ERROR: ${i}`)};let r=I(),{directory:s,label:o}=await Qi(n,r),a=Hu.join(s,".comet.yaml"),c=[`[VALIDATE] ${o}/.comet.yaml`],l=0,d=0,u=m=>{l+=1,c.push(lt(Pn,` FAIL: ${m}`))},f=m=>{d+=1,c.push(lt(wy,` WARN: ${m}`))},h;try{h=await te(r,a,{label:`Classic state ${o}/.comet.yaml`})}catch(m){if(m.code==="ENOENT")return u(".comet.yaml does not exist"),c.push("",lt(Pn,`${l} error(s), ${d} warning(s) — validation FAILED`)),{exitCode:1,stderr:c.join(` +`)};throw m}let w=(0,Nn.parseDocument)(h);if(w.errors.length>0||!(0,Nn.isMap)(w.contents)){for(let m of w.errors)u(m.message);return(0,Nn.isMap)(w.contents)||u("document root must be a mapping"),c.push("",lt(Pn,`${l} error(s), ${d} warning(s) — validation FAILED`)),{exitCode:1,stderr:c.join(` +`)}}let p=w.toJS();for(let m of vy)Object.prototype.hasOwnProperty.call(p,m)||u(`missing required field '${m}'`);for(let[m,g]of Object.entries(by)){if(!Object.prototype.hasOwnProperty.call(p,m))continue;let y=Rn(p[m]);if(!y){m==="auto_transition"&&u(`${m}='' is not valid. Expected: ${g.join(" ")}`);continue}g.includes(y)||u(`${m}='${y}' is not valid. Expected: ${g.join(" ")}`)}if(Object.prototype.hasOwnProperty.call(p,"bound_branch")){let m=p.bound_branch;m!==null&&typeof m!="string"&&u(`bound_branch='${Rn(m)}' is not a string or null`)}if(Object.prototype.hasOwnProperty.call(p,"verify_failures")){let m=p.verify_failures;(typeof m!="number"||!Number.isInteger(m)||m<0)&&u(`verify_failures='${Rn(m)}' is not a non-negative integer`)}for(let m of["design_doc","plan","handoff_context","verification_report"]){let g=Rn(p[m]);if(g){if(/^(?:[A-Za-z]:|[\\/]|~)/u.test(g)||g.split(/[\\/]/u).includes("..")){u(`${m}='${g}' must be a relative repository path`);continue}try{await yn(r,Hu.resolve(r,g),{label:`${m} artifact pointer`,expected:"file"})||u(`${m}='${g}' does not exist on disk`)}catch(y){u(`${m}='${g}' is unsafe: ${y instanceof Error?y.message:String(y)}`)}}}for(let m of["handoff_hash"]){let g=Rn(p[m]);g&&!/^[a-f0-9]{64}$/u.test(g)&&u(`${m}='${g}' is not a sha256 hex digest`)}for(let m of Object.keys(p))ky.has(m)||f(`unknown field '${m}' found`);return c.push(""),l>0?(c.push(lt(Pn,`${l} error(s), ${d} warning(s) — validation FAILED`)),{exitCode:1,stderr:c.join(` +`)}):(c.push(lt(gy,`0 errors, ${d} warning(s) — validation PASSED`)),{exitCode:0,stderr:c.join(` +`)})});lo();it();import Sy from"os";import hr from"path";function Cy(t={}){let e=t.cwd??process.cwd(),n=t.homeDir??Sy.homedir(),i=[{file:hr.resolve(e,".comet","config.yaml"),source:".comet/config.yaml",scope:"project"},{file:hr.resolve(n,".comet","config.yaml"),source:"~/.comet/config.yaml",scope:"global"}];return i.filter((r,s)=>i.findIndex(o=>o.file===r.file)===s)}async function zu(t,e={}){for(let n of Cy(e)){let i=hr.dirname(hr.dirname(n.file)),r=n.scope==="global"?(await co(i))?.classic:(await Me(i,{allowPartialProject:!0}))?.value.classic;if(!r||typeof r!="object"||Array.isArray(r))continue;let s=r[t];if(s!=null)return{value:String(s),source:n.source}}return null}it();var Oo=Je(Ie(),1);import{execFileSync as Qu}from"child_process";import{randomUUID as _y}from"crypto";import{promises as On}from"fs";import Xu from"path";var Ey=null;function xy(t,e){let n=t;for(let i of e)n+="\0"+(typeof i=="string"?i:JSON.stringify(i));return n}function No(t,e){return(...n)=>{let i=Ey;if(i===null)return e(...n);let r=xy(`sync:${t}`,n),s=i.entries.get(r);if(s)return s.value;let o=e(...n);return i.entries.set(r,{value:o}),o}}function Py(t){try{let e=Qu("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();return e&&e!=="HEAD"?e:null}catch{return null}}var Ry=No("liveGitBranch",t=>Py(t));function Ny(t){try{return Qu("git",["rev-parse","--is-inside-work-tree"],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()==="true"}catch{return!1}}var Oy=No("isGitWorkTree",t=>Ny(t)),Ay=["current","branch","worktree"];function Zu(t){return Ay.includes(t)}function jy(t){return Zu(t.isolation)?t.boundBranch===null&&t.currentBranch===null&&t.gitWorkTree===!1?{status:"not-applicable"}:t.boundBranch===null?t.currentBranch===null?{status:"unbound-detached"}:{status:"needs-heal",branch:t.currentBranch}:t.currentBranch===t.boundBranch?{status:"ok"}:{status:"drift",boundBranch:t.boundBranch,currentBranch:t.currentBranch}:{status:"not-applicable"}}async function ef(t,e){let n=Xu.join(t,".comet.yaml"),i=(0,Oo.parseDocument)(await On.readFile(n,"utf8"),{uniqueKeys:!1});if(i.errors.length>0)throw new Error(`Invalid .comet.yaml: ${i.errors[0].message}`);let r=i.toJS()??{},s=typeof r.isolation=="string"?r.isolation:null,o=typeof r.bound_branch=="string"&&r.bound_branch!==""?r.bound_branch:null,a=Zu(s),c=Ry(e.cwd),l=a&&o===null&&c===null?Oy(e.cwd):!0,d=jy({isolation:s,boundBranch:o,currentBranch:c,gitWorkTree:l});return d.status==="needs-heal"&&e.heal?(await Ty(t,d.branch),{status:"healed",branch:d.branch,bindingRequired:a,currentBranch:c}):{...d,bindingRequired:a,currentBranch:c}}async function Ty(t,e){let n=Xu.join(t,".comet.yaml"),i=(0,Oo.parseDocument)(await On.readFile(n,"utf8"),{uniqueKeys:!1});i.set("bound_branch",e);let r=`${n}.${_y()}.tmp`;try{await On.writeFile(r,i.toString(),"utf8"),await On.rename(r,n)}catch(s){throw await On.rm(r,{force:!0}),s}}function Iy(t){return t??"detached HEAD"}function tf(t,e,n){return`change '${t}' is bound to branch '${e}', but current branch is '${Iy(n)}'. +Next: ask the user to confirm — switch back to '${e}', or run \`comet state rebind ${t}\` after explicit confirmation.`}function nf(t){return`change '${t}' uses a branch-bound workspace mode but has no bound branch and HEAD is detached; checkout a branch first before continuing.`}var Ly="\x1B[32m",Dy="\x1B[31m",Fy="\x1B[33m",Io="\x1B[0m",My=["open","design","build","verify","archive"],Wy={open:"=== Guard: open → next ===",design:"=== Guard: design → build ===",build:"=== Guard: build → verify ===",verify:"=== Guard: verify → archive ===",archive:"=== Guard: archive completeness ==="},By={open:" [APPLY] .comet.yaml updated: phase=PLACEHOLDER",design:" [APPLY] .comet.yaml updated: phase=build",build:" [APPLY] .comet.yaml updated: phase=verify, verify_result=pending",verify:" [APPLY] .comet.yaml updated: phase=archive, verify_result=pass"},Ky={branchStatus:"branch_status",phase:"phase",verificationReport:"verification_report",verifiedAt:"verified_at",verifyResult:"verify_result"};function Rt(t){return`${Ly}${t}${Io}`}function Se(t){return`${Dy}${t}${Io}`}function Yy(t){return`${Fy}${t}${Io}`}function Uy(t){return Ky[t]??String(t)}function Vy(t){return t===null?"null":t===void 0?"":typeof t=="object"?JSON.stringify(t):String(t)}var fe=class extends Error{constructor(n,i=1){super(n);this.exitCode=i}exitCode},To=class{stderr=[];diagnostics;toResult(e=0){return{exitCode:e,...this.diagnostics?{stdout:JSON.stringify({diagnostics:this.diagnostics})+` `}:{},...this.stderr.length>0?{stderr:this.stderr.join(` `)+` -`}:{}}}};async function Y(t){let e=I();return yn(e,t,{label:`Classic guard path ${T.relative(e,T.resolve(e,t)).replaceAll("\\","/")}`})}async function H(t){let e=I();return nu(e,t,`Classic guard file ${T.relative(e,T.resolve(e,t)).replaceAll("\\","/")}`)}function Jy(t){let e=vn(t);if(e)throw new fe(Se(`ERROR: ${e}`))}async function Hy(t){return(await zi(t,I())).directory}async function A(t,e){let n=T.join(t,".comet.yaml"),i=(0,sf.parseDocument)(await te(I(),n,{label:`Classic state ${t}/.comet.yaml`}),{uniqueKeys:!1});if(i.errors.length>0)throw new fe(`ERROR: Invalid .comet.yaml: ${i.errors[0].message}`);let s=i.toJS()[e];return s==null?"":typeof s=="object"?JSON.stringify(s):String(s)}async function Gy(t,e){let n=await A(e,t);return n&&n!=="null"?n:(await Gu(t,{cwd:I()}))?.value??""}async function zy(t){let e=await Gy("language",t);if(!e)return"en";if(e==="en"||e==="zh-CN")return e;throw new Error(`configured language '${e}' is invalid; expected en or zh-CN.`)}function Qy(t){let e=[],n=!1;for(let i of t.split(/\r?\n/u)){if(/^\s*```/u.test(i)){n=!n;continue}n||e.push(i)}return e.join(` +`}:{}}}};async function Y(t){let e=I();return yn(e,t,{label:`Classic guard path ${T.relative(e,T.resolve(e,t)).replaceAll("\\","/")}`})}async function H(t){let e=I();return iu(e,t,`Classic guard file ${T.relative(e,T.resolve(e,t)).replaceAll("\\","/")}`)}function Jy(t){let e=vn(t);if(e)throw new fe(Se(`ERROR: ${e}`))}async function Hy(t){return(await Qi(t,I())).directory}async function A(t,e){let n=T.join(t,".comet.yaml"),i=(0,of.parseDocument)(await te(I(),n,{label:`Classic state ${t}/.comet.yaml`}),{uniqueKeys:!1});if(i.errors.length>0)throw new fe(`ERROR: Invalid .comet.yaml: ${i.errors[0].message}`);let s=i.toJS()[e];return s==null?"":typeof s=="object"?JSON.stringify(s):String(s)}async function Gy(t,e){let n=await A(e,t);return n&&n!=="null"?n:(await zu(t,{cwd:I()}))?.value??""}async function zy(t){let e=await Gy("language",t);if(!e)return"en";if(e==="en"||e==="zh-CN")return e;throw new Error(`configured language '${e}' is invalid; expected en or zh-CN.`)}function Qy(t){let e=[],n=!1;for(let i of t.split(/\r?\n/u)){if(/^\s*```/u.test(i)){n=!n;continue}n||e.push(i)}return e.join(` `)}function Xy(t){return t.match(/[\u4e00-\u9fff]/gu)?.length??0}function Zy(t){return t.match(/[A-Za-z][A-Za-z0-9_-]{2,}/gu)?.length??0}async function he(t,e){let n=await zy(t),i=Qy(await te(I(),e,{label:`Classic language-check artifact ${e}`})),r=Xy(i),s=Zy(i);return n==="zh-CN"&&r<20&&s>=20?S(`configured language is zh-CN, but ${e} appears to be English-dominant (cjk_chars=${r}, english_words=${s}). Next: regenerate or rewrite this artifact in Chinese while preserving necessary technical terms.`):n==="en"&&r>20&&r>s?S(`configured language is en, but ${e} appears to be Chinese-dominant (cjk_chars=${r}, english_words=${s}). -Next: regenerate or rewrite this artifact in English while preserving necessary technical terms.`):_()}async function of(t){return rf("sha256").update(await Hi(I(),t,{label:`Classic handoff source ${t}`})).digest("hex")}async function $o(t){let e=z(I(),t),n=[`${e}/proposal.md`,`${e}/design.md`,`${e}/tasks.md`],i=`${e}/specs`;if(await Y(i)){await We(I(),i,{label:`Classic delta-spec directory ${i}`,expected:"directory"});for(let r of(await qy.readdir(i)).sort()){let s=`${i}/${r}/spec.md`;await Y(s)&&n.push(s)}}return n}async function ev(t){let e=[];for(let n of await $o(t))await Y(n)&&e.push(`path:${n}`,`sha256:${await of(n)}`);return rf("sha256").update(e.join(` -`)).digest("hex")}async function tv(t,e){if(!await Y(t))throw new fe(Se(`FATAL: change directory not found: ${t}`));if(!await Y(T.join(t,".comet.yaml")))throw new fe(Se(`FATAL: .comet.yaml not found in ${t}`));await We(I(),T.join(t,".comet"),{label:`Classic runtime directory for ${e}`,expected:"directory"});let n=await Hu([e],{json:!1});if(n.exitCode!==0)throw n.stderr&&process.stderr.write(n.stderr.endsWith(` +Next: regenerate or rewrite this artifact in English while preserving necessary technical terms.`):_()}async function af(t){return sf("sha256").update(await Gi(I(),t,{label:`Classic handoff source ${t}`})).digest("hex")}async function $o(t){let e=z(I(),t),n=[`${e}/proposal.md`,`${e}/design.md`,`${e}/tasks.md`],i=`${e}/specs`;if(await Y(i)){await Be(I(),i,{label:`Classic delta-spec directory ${i}`,expected:"directory"});for(let r of(await qy.readdir(i)).sort()){let s=`${i}/${r}/spec.md`;await Y(s)&&n.push(s)}}return n}async function ev(t){let e=[];for(let n of await $o(t))await Y(n)&&e.push(`path:${n}`,`sha256:${await af(n)}`);return sf("sha256").update(e.join(` +`)).digest("hex")}async function tv(t,e){if(!await Y(t))throw new fe(Se(`FATAL: change directory not found: ${t}`));if(!await Y(T.join(t,".comet.yaml")))throw new fe(Se(`FATAL: .comet.yaml not found in ${t}`));await Be(I(),T.join(t,".comet"),{label:`Classic runtime directory for ${e}`,expected:"directory"});let n=await Gu([e],{json:!1});if(n.exitCode!==0)throw n.stderr&&process.stderr.write(n.stderr.endsWith(` `)?n.stderr:`${n.stderr} -`),new fe(Se("FATAL: .comet.yaml schema validation failed"));let i=await Ke(t),r=Array.from(new Set(i.unknownKeys)).sort();if(r.length>0)throw new fe(Se(`FATAL: .comet.yaml has unknown field(s): ${r.join(", ")}`))}function nv(t,e){if(e.passed){if(t.stderr.push(Rt(` [PASS] ${e.description}`)),e.detail)for(let n of e.detail.split(` +`),new fe(Se("FATAL: .comet.yaml schema validation failed"));let i=await Ye(t),r=Array.from(new Set(i.unknownKeys)).sort();if(r.length>0)throw new fe(Se(`FATAL: .comet.yaml has unknown field(s): ${r.join(", ")}`))}function nv(t,e){if(e.passed){if(t.stderr.push(Rt(` [PASS] ${e.description}`)),e.detail)for(let n of e.detail.split(` `))t.stderr.push(Rt(` ${n}`))}else if(t.stderr.push(Se(` [FAIL] ${e.description}`)),e.detail)for(let n of e.detail.split(` -`))t.stderr.push(Se(` ${n}`))}function E(t,e){return async()=>{try{let n=await e();return{description:t,passed:n.passed,detail:("detail"in n?n.detail:"")??""}}catch(n){return{description:t,passed:!1,detail:n instanceof Error?n.message:String(n)}}}}function _(t){return{passed:!0,...t?{detail:t}:{}}}function S(t){return{passed:!1,detail:t}}async function Nt(t,e){let n=!1;for(let i of e){let r=await i();nv(t,r),r.passed||(n=!0)}return n}var iv=["package.json with a build script","pom.xml","Cargo.toml"];async function rv(t){try{let e=await Me(I(),{allowPartialProject:!0});return e?Object.prototype.hasOwnProperty.call(e.value,t):!1}catch(e){throw new Error(`.comet/config.yaml is invalid YAML (${e instanceof Error?e.message:String(e)}); cannot check for removed "${t}" field. Fix the config and retry.`,{cause:e})}}function sv(t){return{status:1,output:`${t} has been removed from .comet/config.yaml. Delete this field and run any required ${t==="build_command"?"build":"verification"} command manually before retrying.`}}function ov(t){let e=$y(t,{shell:!0,cwd:pr(),encoding:"utf8",timeout:3e5});return{status:e.status??1,output:`${e.stdout??""}${e.stderr??""}`.replace(/\n+$/u,"")}}function An(t){return T.resolve(pr(),t)}async function av(){let t=An("package.json");return await Y(t)&&typeof JSON.parse(await te(I(),t,{label:"package.json"})).scripts?.build=="string"?"npm run build":await Y(An("pom.xml"))?process.platform==="win32"?await Y(An("mvnw.cmd"))?"mvnw.cmd compile -q":"mvn.cmd compile -q":await Y(An("mvnw"))?"./mvnw compile -q":"mvn compile -q":await Y(An("Cargo.toml"))?"cargo build":null}function nf(t){return`Evidence: recorded command-check at ${t.timestamp}; command: ${t.command}; cwd: ${t.cwd}`}function Ao(t,e,n){return`comet state record-check ${t} ${e} --command "${n}" --exit-code 0`}async function af(t,e,n,i){if(process.env.COMET_SKIP_BUILD==="1")return{status:0,output:"SKIPPED via COMET_SKIP_BUILD=1"};let r=i==="build"?["build_command"]:["verify_command","build_command"];for(let a of r)if(await rv(a))return sv(a);let s=i==="build"?await av():null;if(s)return ov(s);let o=await Ql(I(),t,n,i);return o?o.exitCode!==0?{status:o.exitCode,output:`Latest recorded ${i} check failed with exit code ${o.exitCode}. -${nf(o)} +`))t.stderr.push(Se(` ${n}`))}function E(t,e){return async()=>{try{let n=await e();return{description:t,passed:n.passed,detail:("detail"in n?n.detail:"")??""}}catch(n){return{description:t,passed:!1,detail:n instanceof Error?n.message:String(n)}}}}function _(t){return{passed:!0,...t?{detail:t}:{}}}function S(t){return{passed:!1,detail:t}}async function Nt(t,e){let n=!1;for(let i of e){let r=await i();nv(t,r),r.passed||(n=!0)}return n}var iv=["package.json with a build script","pom.xml","Cargo.toml"];async function rv(t){try{let e=await Me(I(),{allowPartialProject:!0});return e?Object.prototype.hasOwnProperty.call(e.value,t):!1}catch(e){throw new Error(`.comet/config.yaml is invalid YAML (${e instanceof Error?e.message:String(e)}); cannot check for removed "${t}" field. Fix the config and retry.`,{cause:e})}}function sv(t){return{status:1,output:`${t} has been removed from .comet/config.yaml. Delete this field and run any required ${t==="build_command"?"build":"verification"} command manually before retrying.`}}function ov(t){let e=$y(t,{shell:!0,cwd:mr(),encoding:"utf8",timeout:3e5});return{status:e.status??1,output:`${e.stdout??""}${e.stderr??""}`.replace(/\n+$/u,"")}}function An(t){return T.resolve(mr(),t)}async function av(){let t=An("package.json");return await Y(t)&&typeof JSON.parse(await te(I(),t,{label:"package.json"})).scripts?.build=="string"?"npm run build":await Y(An("pom.xml"))?process.platform==="win32"?await Y(An("mvnw.cmd"))?"mvnw.cmd compile -q":"mvn.cmd compile -q":await Y(An("mvnw"))?"./mvnw compile -q":"mvn compile -q":await Y(An("Cargo.toml"))?"cargo build":null}function rf(t){return`Evidence: recorded command-check at ${t.timestamp}; command: ${t.command}; cwd: ${t.cwd}`}function Ao(t,e,n){return`comet state record-check ${t} ${e} --command "${n}" --exit-code 0`}async function cf(t,e,n,i){if(process.env.COMET_SKIP_BUILD==="1")return{status:0,output:"SKIPPED via COMET_SKIP_BUILD=1"};let r=i==="build"?["build_command"]:["verify_command","build_command"];for(let a of r)if(await rv(a))return sv(a);let s=i==="build"?await av():null;if(s)return ov(s);let o=await Ql(I(),t,n,i);return o?o.exitCode!==0?{status:o.exitCode,output:`Latest recorded ${i} check failed with exit code ${o.exitCode}. +${rf(o)} Next: rerun the command successfully, then record it with: -${Ao(e,i,o.command)}`}:{status:0,output:nf(o)}:{status:1,output:i==="build"?`No inferred build command or recorded build check. Detection searched: ${iv.join(", ")}. +${Ao(e,i,o.command)}`}:{status:0,output:rf(o)}:{status:1,output:i==="build"?`No inferred build command or recorded build check. Detection searched: ${iv.join(", ")}. Next: run the required command, then record it with: ${Ao(e,i,"")}`:`No recorded verify check. Next: run the required verification command, then record it with: @@ -179,7 +179,7 @@ Next: complete or explicitly remove unfinished tasks, then mark tasks.md with '- Next: restore the Superpowers plan file or update .comet.yaml plan before leaving build.`);let i=(await te(I(),e,{label:`Classic plan ${e}`})).split(/\r?\n/u).map((r,s)=>({line:r,number:s+1})).filter(r=>/^\s*- \[ \]/u.test(r.line));return i.length>0?S(`Unfinished Superpowers plan tasks: ${i.map(r=>`${r.number}:${r.line}`).join(` `)} -Next: check off corresponding completed plan tasks, then commit the plan update.`):_()}async function Lo(t,e){let n;try{n=await Zu(t,{heal:!0,cwd:pr()})}catch(i){throw new fe(`ERROR: ${i instanceof Error?i.message:String(i)}`)}switch(n.status){case"drift":return S(ef(e,n.boundBranch,n.currentBranch));case"unbound-detached":return S(tf(e));case"healed":return _(`bound_branch lazily set to ${n.branch}`);case"needs-heal":case"ok":case"not-applicable":return _();default:{let i=n;throw new Error(`unhandled branch binding status: ${JSON.stringify(i)}`)}}}async function uv(t,e){let n=await A(t,"isolation");return n==="current"||n==="branch"||n==="worktree"?_():S(`isolation must be current, branch, or worktree, got '${n||"null"}' +Next: check off corresponding completed plan tasks, then commit the plan update.`):_()}async function Lo(t,e){let n;try{n=await ef(t,{heal:!0,cwd:mr()})}catch(i){throw new fe(`ERROR: ${i instanceof Error?i.message:String(i)}`)}switch(n.status){case"drift":return S(tf(e,n.boundBranch,n.currentBranch));case"unbound-detached":return S(nf(e));case"healed":return _(`bound_branch lazily set to ${n.branch}`);case"needs-heal":case"ok":case"not-applicable":return _();default:{let i=n;throw new Error(`unhandled branch binding status: ${JSON.stringify(i)}`)}}}async function uv(t,e){let n=await A(t,"isolation");return n==="current"||n==="branch"||n==="worktree"?_():S(`isolation must be current, branch, or worktree, got '${n||"null"}' Next: choose a valid workspace mode, prepare it when needed, then run: comet state set ${e} isolation `)}async function fv(t,e){let n=await A(t,"build_mode");return["subagent-driven-development","executing-plans","direct"].includes(n)?_():S(`build_mode must be selected before leaving build, got '${n||"null"}' Next: ask the user to choose an execution mode, then run: @@ -198,11 +198,11 @@ Next: regenerate the design handoff with comet handoff ${e} design --write.`);le Expected handoff_hash: ${i} Actual handoff_hash: ${r} Next: run comet handoff ${e} design --write so Superpowers receives the current OpenSpec context.`);let s=`${n.replace(/\.json$/u,"")}.md`;return await H(s)?_():S(`design handoff markdown is missing or empty: ${s} -Next: regenerate the design handoff with comet handoff ${e} design --write.`)}async function kv(t){let e=await A(t,"handoff_context");if(!e||e==="null")return S("handoff_context is missing from .comet.yaml");let n=`${e.replace(/\.json$/u,"")}.md`;if(!await H(n))return S(`design handoff markdown is missing or empty: ${n}`);let i=await te(I(),n,{label:`Classic handoff markdown ${n}`}),r=new Set(i.split(/\r?\n/u)),s=[];/^Generated-by: comet-handoff\.sh$/mu.test(i)||s.push("handoff markdown is missing Generated-by marker"),/^- Mode: (compact|full|beta)$/mu.test(i)||s.push("handoff markdown is missing Mode marker");for(let o of await $o(t))await Y(o)&&(r.has(`- Source: ${o}`)||s.push(`handoff markdown is missing source reference: ${o}`),r.has(`- SHA256: ${await of(o)}`)||s.push(`handoff markdown is missing current sha256 for: ${o}`));return s.length===0?_():S(s.join(` -`))}async function cf(t){return await A(t,"context_compression")||"off"}async function Sv(t){if(await cf(t)!=="beta")return _();let e=await A(t,"handoff_context");if(!e||e==="null")return S("handoff_context is missing from .comet.yaml");if(!await H(e))return S(`spec-context.json is missing or empty: ${e}`);let n=await te(I(),e,{label:`Classic handoff context ${e}`}),i=[],r;try{r=JSON.parse(n)}catch(a){return S(`spec-context.json invalid JSON: ${a instanceof Error?a.message:String(a)}`)}if(!r||typeof r!="object"||Array.isArray(r))return S("spec-context.json root must be an object");let s=r;typeof s.change!="string"&&i.push("spec-context.json missing 'change' field"),typeof s.phase!="string"&&i.push("spec-context.json missing 'phase' field"),s.mode!=="beta"&&i.push("spec-context.json mode is not beta"),typeof s.context_hash!="string"&&i.push("spec-context.json missing 'context_hash' field"),Array.isArray(s.files)||i.push("spec-context.json missing 'files' field");let o=Array.isArray(s.files)?s.files.filter(a=>!!a&&typeof a=="object"&&!Array.isArray(a)):[];for(let a of await $o(t))await Y(a)&&(o.some(c=>c.path===a&&typeof c.sha256=="string")||i.push(`spec-context.json missing source file reference: ${a}`));return i.length===0?_():S(i.join(` -`))}async function Cv(t,e){let n=await A(e,"workflow"),i=[E("proposal.md exists and non-empty",async()=>await H(T.join(e,"proposal.md"))?_():S("")),E("proposal.md matches configured language",()=>he(e,T.join(e,"proposal.md"))),E("tasks.md exists and non-empty",async()=>await H(T.join(e,"tasks.md"))?_():S("")),E("tasks.md matches configured language",()=>he(e,T.join(e,"tasks.md"))),E("tasks.md has at least one task",async()=>await cv(e)?_():S(""))];return n==="full"&&i.splice(1,0,E("design.md exists and non-empty",async()=>await H(T.join(e,"design.md"))?_():S("")),E("design.md matches configured language",()=>he(e,T.join(e,"design.md")))),Nt(t,i)}async function Ev(t,e,n){let i=await A(e,"design_doc"),r=await A(e,"workflow"),s=[E("proposal.md exists",async()=>await H(T.join(e,"proposal.md"))?_():S("")),E("proposal.md matches configured language",()=>he(e,T.join(e,"proposal.md"))),E("design.md exists",async()=>await H(T.join(e,"design.md"))?_():S("")),E("design.md matches configured language",()=>he(e,T.join(e,"design.md"))),E("tasks.md exists",async()=>await H(T.join(e,"tasks.md"))?_():S("")),E("tasks.md matches configured language",()=>he(e,T.join(e,"tasks.md"))),E("design handoff context exists",()=>bv(e,n)),E("design handoff markdown is traceable",()=>kv(e))];await cf(e)==="beta"&&s.push(E("beta spec-context.json is structurally valid",()=>Sv(e))),r==="full"&&s.push(E("design_doc is recorded for full workflow",()=>vv(e,n)));let o=await Nt(t,s);return i&&i!=="null"?o=await Nt(t,[E(`Design Doc (${i}) exists`,async()=>await H(i)?_():S("")),E("Design Doc matches configured language",()=>he(e,i)),E("Design Doc frontmatter links current change",async()=>await H(i)&&await jo(i,"comet_change",n)?_():S("")),E("Design Doc declares technical design role",async()=>await H(i)&&await jo(i,"role","technical-design")?_():S("")),E("Design Doc declares OpenSpec as canonical spec",async()=>await H(i)&&await jo(i,"canonical_spec","openspec")?_():S(""))])||o:r!=="full"&&t.stderr.push(Yy(" [WARN] No design_doc recorded in .comet.yaml (optional for hotfix/tweak)")),o}async function xv(t,e,n,i){return Nt(t,[E("bound branch matches workspace mode",()=>Lo(e,n)),E("isolation selected",()=>uv(e,n)),E("build_mode selected",()=>fv(e,n)),E("build_mode allowed for workflow",()=>dv(e)),E("subagent dispatch confirmed",()=>pv(e,n)),E("tdd_mode selected",()=>mv(e,n)),E("review_mode selected",()=>hv(e,n)),E("tasks.md all tasks checked",()=>qo(e)),E("Superpowers plan all tasks checked",()=>lv(e)),E("proposal.md exists",async()=>await H(T.join(e,"proposal.md"))?_():S("")),E("proposal.md matches configured language",()=>he(e,T.join(e,"proposal.md"))),E("Superpowers plan matches configured language",async()=>{let r=await A(e,"plan");return!r||r==="null"||!await Y(r)?_():he(e,r)}),E("Build passes",async()=>{let r=await af(e,n,i,"build");return r.status===0?_(r.output):S(r.output)})])}async function _v(t,e,n,i){return Nt(t,[E("bound branch matches workspace mode",()=>Lo(e,n)),E("tasks.md all tasks checked",()=>qo(e)),E("Verification passes",async()=>{let r=await af(e,n,i,"verify");return r.status===0?_(r.output):S(r.output)}),E("verification_report exists",async()=>await gv(e)?_():S("")),E("verification_report matches configured language",async()=>{let r=await A(e,"verification_report");return!r||r==="null"||!await Y(r)?_():he(e,r)})])}async function Pv(t,e,n){return Nt(t,[E("bound branch matches workspace mode",()=>Lo(e,n)),E("archived is true",async()=>await yv(e)?_():S("")),E("proposal.md exists",async()=>await H(T.join(e,"proposal.md"))?_():S("")),E("design.md exists",async()=>await H(T.join(e,"design.md"))?_():S("")),E("tasks.md all tasks checked",()=>qo(e)),E("branch_status=handled",async()=>await wv(e)?_():S(""))])}async function Rv(t,e,n,i){let r=Yu[i];if(!r)return;let s=await ur(n),o=Uu(s.classic,r);await Fu(n,o.classic,s.run,{event:r,phase:i,source:"comet-guard"}),await Ku(n,{change:e,event:r,source:"comet-guard",from:s.classic,to:o.classic,effects:o.effects});for(let l of o.effects)t.stderr.push(Rt(`[SET] ${Uy(l.field)}=${Vy(l.to)}`));t.stderr.push(Rt(`[TRANSITION] ${r}`));let a=By[i],c=i==="open"?a.replace("PLACEHOLDER",o.classic.phase):a;t.stderr.push(Rt(c))}var lf=async(t,e)=>dr(e,async()=>{let n=new To,[i,r,s]=t;try{if(Jy(i),!r||!My.includes(r))throw new fe(`${Se(`Unknown phase: ${r??""}`)} -Valid phases: open, design, build, verify, archive`);await ho(I());let o=await Hy(i);await tv(o,i);let a=await ur(o),c=await Bu(o,i);e.json&&(n.diagnostics={change:i,phase:r,currentStep:c.currentStep,runtimeEval:c.runtimeEval}),n.stderr.push(Wy[r]);let l;return r==="open"?l=await Cv(n,o):r==="design"?l=await Ev(n,o,i):r==="build"?l=await xv(n,o,i,a.run):r==="verify"?l=await _v(n,o,i,a.run):l=await Pv(n,o,i),l?(n.stderr.push(""),n.stderr.push(Se("BLOCKED — fix failing checks before proceeding to next phase")),n.toResult(1)):(n.stderr.push(""),n.stderr.push(Rt("ALL CHECKS PASSED — ready for next phase")),s==="--apply"&&await Rv(n,i,o,r),n.toResult(0))}catch(o){if(o instanceof fe){for(let a of o.message.split(` +Next: regenerate the design handoff with comet handoff ${e} design --write.`)}async function kv(t){let e=await A(t,"handoff_context");if(!e||e==="null")return S("handoff_context is missing from .comet.yaml");let n=`${e.replace(/\.json$/u,"")}.md`;if(!await H(n))return S(`design handoff markdown is missing or empty: ${n}`);let i=await te(I(),n,{label:`Classic handoff markdown ${n}`}),r=new Set(i.split(/\r?\n/u)),s=[];/^Generated-by: comet-handoff\.sh$/mu.test(i)||s.push("handoff markdown is missing Generated-by marker"),/^- Mode: (compact|full|beta)$/mu.test(i)||s.push("handoff markdown is missing Mode marker");for(let o of await $o(t))await Y(o)&&(r.has(`- Source: ${o}`)||s.push(`handoff markdown is missing source reference: ${o}`),r.has(`- SHA256: ${await af(o)}`)||s.push(`handoff markdown is missing current sha256 for: ${o}`));return s.length===0?_():S(s.join(` +`))}async function lf(t){return await A(t,"context_compression")||"off"}async function Sv(t){if(await lf(t)!=="beta")return _();let e=await A(t,"handoff_context");if(!e||e==="null")return S("handoff_context is missing from .comet.yaml");if(!await H(e))return S(`spec-context.json is missing or empty: ${e}`);let n=await te(I(),e,{label:`Classic handoff context ${e}`}),i=[],r;try{r=JSON.parse(n)}catch(a){return S(`spec-context.json invalid JSON: ${a instanceof Error?a.message:String(a)}`)}if(!r||typeof r!="object"||Array.isArray(r))return S("spec-context.json root must be an object");let s=r;typeof s.change!="string"&&i.push("spec-context.json missing 'change' field"),typeof s.phase!="string"&&i.push("spec-context.json missing 'phase' field"),s.mode!=="beta"&&i.push("spec-context.json mode is not beta"),typeof s.context_hash!="string"&&i.push("spec-context.json missing 'context_hash' field"),Array.isArray(s.files)||i.push("spec-context.json missing 'files' field");let o=Array.isArray(s.files)?s.files.filter(a=>!!a&&typeof a=="object"&&!Array.isArray(a)):[];for(let a of await $o(t))await Y(a)&&(o.some(c=>c.path===a&&typeof c.sha256=="string")||i.push(`spec-context.json missing source file reference: ${a}`));return i.length===0?_():S(i.join(` +`))}async function Cv(t,e){let n=await A(e,"workflow"),i=[E("proposal.md exists and non-empty",async()=>await H(T.join(e,"proposal.md"))?_():S("")),E("proposal.md matches configured language",()=>he(e,T.join(e,"proposal.md"))),E("tasks.md exists and non-empty",async()=>await H(T.join(e,"tasks.md"))?_():S("")),E("tasks.md matches configured language",()=>he(e,T.join(e,"tasks.md"))),E("tasks.md has at least one task",async()=>await cv(e)?_():S(""))];return n==="full"&&i.splice(1,0,E("design.md exists and non-empty",async()=>await H(T.join(e,"design.md"))?_():S("")),E("design.md matches configured language",()=>he(e,T.join(e,"design.md")))),Nt(t,i)}async function Ev(t,e,n){let i=await A(e,"design_doc"),r=await A(e,"workflow"),s=[E("proposal.md exists",async()=>await H(T.join(e,"proposal.md"))?_():S("")),E("proposal.md matches configured language",()=>he(e,T.join(e,"proposal.md"))),E("design.md exists",async()=>await H(T.join(e,"design.md"))?_():S("")),E("design.md matches configured language",()=>he(e,T.join(e,"design.md"))),E("tasks.md exists",async()=>await H(T.join(e,"tasks.md"))?_():S("")),E("tasks.md matches configured language",()=>he(e,T.join(e,"tasks.md"))),E("design handoff context exists",()=>bv(e,n)),E("design handoff markdown is traceable",()=>kv(e))];await lf(e)==="beta"&&s.push(E("beta spec-context.json is structurally valid",()=>Sv(e))),r==="full"&&s.push(E("design_doc is recorded for full workflow",()=>vv(e,n)));let o=await Nt(t,s);return i&&i!=="null"?o=await Nt(t,[E(`Design Doc (${i}) exists`,async()=>await H(i)?_():S("")),E("Design Doc matches configured language",()=>he(e,i)),E("Design Doc frontmatter links current change",async()=>await H(i)&&await jo(i,"comet_change",n)?_():S("")),E("Design Doc declares technical design role",async()=>await H(i)&&await jo(i,"role","technical-design")?_():S("")),E("Design Doc declares OpenSpec as canonical spec",async()=>await H(i)&&await jo(i,"canonical_spec","openspec")?_():S(""))])||o:r!=="full"&&t.stderr.push(Yy(" [WARN] No design_doc recorded in .comet.yaml (optional for hotfix/tweak)")),o}async function xv(t,e,n,i){return Nt(t,[E("bound branch matches workspace mode",()=>Lo(e,n)),E("isolation selected",()=>uv(e,n)),E("build_mode selected",()=>fv(e,n)),E("build_mode allowed for workflow",()=>dv(e)),E("subagent dispatch confirmed",()=>pv(e,n)),E("tdd_mode selected",()=>mv(e,n)),E("review_mode selected",()=>hv(e,n)),E("tasks.md all tasks checked",()=>qo(e)),E("Superpowers plan all tasks checked",()=>lv(e)),E("proposal.md exists",async()=>await H(T.join(e,"proposal.md"))?_():S("")),E("proposal.md matches configured language",()=>he(e,T.join(e,"proposal.md"))),E("Superpowers plan matches configured language",async()=>{let r=await A(e,"plan");return!r||r==="null"||!await Y(r)?_():he(e,r)}),E("Build passes",async()=>{let r=await cf(e,n,i,"build");return r.status===0?_(r.output):S(r.output)})])}async function _v(t,e,n,i){return Nt(t,[E("bound branch matches workspace mode",()=>Lo(e,n)),E("tasks.md all tasks checked",()=>qo(e)),E("Verification passes",async()=>{let r=await cf(e,n,i,"verify");return r.status===0?_(r.output):S(r.output)}),E("verification_report exists",async()=>await gv(e)?_():S("")),E("verification_report matches configured language",async()=>{let r=await A(e,"verification_report");return!r||r==="null"||!await Y(r)?_():he(e,r)})])}async function Pv(t,e,n){return Nt(t,[E("bound branch matches workspace mode",()=>Lo(e,n)),E("archived is true",async()=>await yv(e)?_():S("")),E("proposal.md exists",async()=>await H(T.join(e,"proposal.md"))?_():S("")),E("design.md exists",async()=>await H(T.join(e,"design.md"))?_():S("")),E("tasks.md all tasks checked",()=>qo(e)),E("branch_status=handled",async()=>await wv(e)?_():S(""))])}async function Rv(t,e,n,i){let r=Uu[i];if(!r)return;let s=await fr(n),o=Vu(s.classic,r);await Mu(n,o.classic,s.run,{event:r,phase:i,source:"comet-guard"}),await Yu(n,{change:e,event:r,source:"comet-guard",from:s.classic,to:o.classic,effects:o.effects});for(let l of o.effects)t.stderr.push(Rt(`[SET] ${Uy(l.field)}=${Vy(l.to)}`));t.stderr.push(Rt(`[TRANSITION] ${r}`));let a=By[i],c=i==="open"?a.replace("PLACEHOLDER",o.classic.phase):a;t.stderr.push(Rt(c))}var uf=async(t,e)=>pr(e,async()=>{let n=new To,[i,r,s]=t;try{if(Jy(i),!r||!My.includes(r))throw new fe(`${Se(`Unknown phase: ${r??""}`)} +Valid phases: open, design, build, verify, archive`);await ho(I());let o=await Hy(i);await tv(o,i);let a=await fr(o),c=await Ku(o,i);e.json&&(n.diagnostics={change:i,phase:r,currentStep:c.currentStep,runtimeEval:c.runtimeEval}),n.stderr.push(Wy[r]);let l;return r==="open"?l=await Cv(n,o):r==="design"?l=await Ev(n,o,i):r==="build"?l=await xv(n,o,i,a.run):r==="verify"?l=await _v(n,o,i,a.run):l=await Pv(n,o,i),l?(n.stderr.push(""),n.stderr.push(Se("BLOCKED — fix failing checks before proceeding to next phase")),n.toResult(1)):(n.stderr.push(""),n.stderr.push(Rt("ALL CHECKS PASSED — ready for next phase")),s==="--apply"&&await Rv(n,i,o,r),n.toResult(0))}catch(o){if(o instanceof fe){for(let a of o.message.split(` `))n.stderr.push(a);return n.toResult(o.exitCode)}throw o}});function Nv(t,e){return{exitCode:e.exitCode,stdout:JSON.stringify({command:t,exitCode:e.exitCode,...e.stdout===void 0?{}:{stdout:e.stdout},...e.stderr===void 0?{}:{stderr:e.stderr}})+` -`}}async function uf(t,e,n=process.argv.slice(2)){let i=n.includes("--json"),r=n.filter(a=>a!=="--json"),s;try{s=await e(r,{json:i})}catch(a){s={exitCode:70,stderr:a instanceof Error?a.message:String(a)}}let o=i?Nv(t,s):s;return o.stdout&&process.stdout.write(o.stdout),o.stderr&&process.stderr.write(o.stderr+(o.stderr.endsWith(` +`}}async function ff(t,e,n=process.argv.slice(2)){let i=n.includes("--json"),r=n.filter(a=>a!=="--json"),s;try{s=await e(r,{json:i})}catch(a){s={exitCode:70,stderr:a instanceof Error?a.message:String(a)}}let o=i?Nv(t,s):s;return o.stdout&&process.stdout.write(o.stdout),o.stderr&&process.stderr.write(o.stderr+(o.stderr.endsWith(` `)?"":` -`)),o.exitCode}process.exitCode=await uf("guard",lf); +`)),o.exitCode}process.exitCode=await ff("guard",uf); diff --git a/assets/skills/comet/scripts/comet-handoff.mjs b/assets/skills/comet/scripts/comet-handoff.mjs index 533c21b29..92bc7ebfc 100644 --- a/assets/skills/comet/scripts/comet-handoff.mjs +++ b/assets/skills/comet/scripts/comet-handoff.mjs @@ -1,40 +1,40 @@ #!/usr/bin/env node import { createRequire as __cometCreateRequire } from 'module'; const require = __cometCreateRequire(import.meta.url); -var qu=Object.create;var tr=Object.defineProperty;var $u=Object.getOwnPropertyDescriptor;var Lu=Object.getOwnPropertyNames;var Du=Object.getPrototypeOf,Fu=Object.prototype.hasOwnProperty;var vn=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var W=(t,e,n)=>()=>{if(n)throw n[0];try{return t&&(e=t(t=0)),e}catch(i){throw n=[i],i}};var v=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(n){throw e=0,n}},Mu=(t,e)=>{for(var n in e)tr(t,n,{get:e[n],enumerable:!0})},Wu=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Lu(e))!Fu.call(t,r)&&r!==n&&tr(t,r,{get:()=>e[r],enumerable:!(i=$u(e,r))||i.enumerable});return t};var Ct=(t,e,n)=>(n=t!=null?qu(Du(t)):{},Wu(e||!t||!t.__esModule?tr(n,"default",{value:t,enumerable:!0}):n,t));var _=v(D=>{"use strict";var nr=Symbol.for("yaml.alias"),ko=Symbol.for("yaml.document"),kn=Symbol.for("yaml.map"),bo=Symbol.for("yaml.pair"),ir=Symbol.for("yaml.scalar"),bn=Symbol.for("yaml.seq"),fe=Symbol.for("yaml.node.type"),Bu=t=>!!t&&typeof t=="object"&&t[fe]===nr,Ku=t=>!!t&&typeof t=="object"&&t[fe]===ko,Yu=t=>!!t&&typeof t=="object"&&t[fe]===kn,Ju=t=>!!t&&typeof t=="object"&&t[fe]===bo,So=t=>!!t&&typeof t=="object"&&t[fe]===ir,Uu=t=>!!t&&typeof t=="object"&&t[fe]===bn;function Co(t){if(t&&typeof t=="object")switch(t[fe]){case kn:case bn:return!0}return!1}function Hu(t){if(t&&typeof t=="object")switch(t[fe]){case nr:case kn:case ir:case bn:return!0}return!1}var Vu=t=>(So(t)||Co(t))&&!!t.anchor;D.ALIAS=nr;D.DOC=ko;D.MAP=kn;D.NODE_TYPE=fe;D.PAIR=bo;D.SCALAR=ir;D.SEQ=bn;D.hasAnchor=Vu;D.isAlias=Bu;D.isCollection=Co;D.isDocument=Ku;D.isMap=Yu;D.isNode=Hu;D.isPair=Ju;D.isScalar=So;D.isSeq=Uu});var Et=v(rr=>{"use strict";var q=_(),U=Symbol("break visit"),Eo=Symbol("skip children"),ae=Symbol("remove node");function Sn(t,e){let n=xo(e);q.isDocument(t)?nt(null,t.contents,n,Object.freeze([t]))===ae&&(t.contents=null):nt(null,t,n,Object.freeze([]))}Sn.BREAK=U;Sn.SKIP=Eo;Sn.REMOVE=ae;function nt(t,e,n,i){let r=_o(t,e,n,i);if(q.isNode(r)||q.isPair(r))return Po(t,i,r),nt(t,r,n,i);if(typeof r!="symbol"){if(q.isCollection(e)){i=Object.freeze(i.concat(e));for(let s=0;s{"use strict";var Ro=_(),Gu=Et(),zu={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Qu=t=>t.replace(/[!,[\]{}]/g,e=>zu[e]),xt=class t{constructor(e,n){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},t.defaultYaml,e),this.tags=Object.assign({},t.defaultTags,n)}clone(){let e=new t(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){let e=new t(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:t.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},t.defaultTags);break}return e}add(e,n){this.atNextDocument&&(this.yaml={explicit:t.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},t.defaultTags),this.atNextDocument=!1);let i=e.trim().split(/[ \t]+/),r=i.shift();switch(r){case"%TAG":{if(i.length!==2&&(n(0,"%TAG directive should contain exactly two parts"),i.length<2))return!1;let[s,o]=i;return this.tags[s]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,i.length!==1)return n(0,"%YAML directive should contain exactly one part"),!1;let[s]=i;if(s==="1.1"||s==="1.2")return this.yaml.version=s,!0;{let o=/^\d+\.\d+$/.test(s);return n(6,`Unsupported YAML version ${s}`,o),!1}}default:return n(0,`Unknown directive ${r}`,!0),!1}}tagName(e,n){if(e==="!")return"!";if(e[0]!=="!")return n(`Not a valid tag: ${e}`),null;if(e[1]==="<"){let o=e.slice(2,-1);return o==="!"||o==="!!"?(n(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&n("Verbatim tags must end with a >"),o)}let[,i,r]=e.match(/^(.*!)([^!]*)$/s);r||n(`The ${e} tag has no suffix`);let s=this.tags[i];if(s)try{return s+decodeURIComponent(r)}catch(o){return n(String(o)),null}return i==="!"?e:(n(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[n,i]of Object.entries(this.tags))if(e.startsWith(i))return n+Qu(e.substring(i.length));return e[0]==="!"?e:`!<${e}>`}toString(e){let n=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],i=Object.entries(this.tags),r;if(e&&i.length>0&&Ro.isNode(e.contents)){let s={};Gu.visit(e.contents,(o,a)=>{Ro.isNode(a)&&a.tag&&(s[a.tag]=!0)}),r=Object.keys(s)}else r=[];for(let[s,o]of i)s==="!!"&&o==="tag:yaml.org,2002:"||(!e||r.some(a=>a.startsWith(o)))&&n.push(`%TAG ${s} ${o}`);return n.join(` -`)}};xt.defaultYaml={explicit:!1,version:"1.2"};xt.defaultTags={"!!":"tag:yaml.org,2002:"};Oo.Directives=xt});var En=v(_t=>{"use strict";var No=_(),Xu=Et();function Zu(t){if(/[\x00-\x19\s,[\]{}]/.test(t)){let n=`Anchor must not contain whitespace or control characters: ${JSON.stringify(t)}`;throw new Error(n)}return!0}function Ao(t){let e=new Set;return Xu.visit(t,{Value(n,i){i.anchor&&e.add(i.anchor)}}),e}function jo(t,e){for(let n=1;;++n){let i=`${t}${n}`;if(!e.has(i))return i}}function ef(t,e){let n=[],i=new Map,r=null;return{onAnchor:s=>{n.push(s),r??(r=Ao(t));let o=jo(e,r);return r.add(o),o},setAnchors:()=>{for(let s of n){let o=i.get(s);if(typeof o=="object"&&o.anchor&&(No.isScalar(o.node)||No.isCollection(o.node)))o.node.anchor=o.anchor;else{let a=new Error("Failed to resolve repeated object (this should not happen)");throw a.source=s,a}}},sourceObjects:i}}_t.anchorIsValid=Zu;_t.anchorNames=Ao;_t.createNodeAnchors=ef;_t.findNewAnchor=jo});var or=v(Io=>{"use strict";function Pt(t,e,n,i){if(i&&typeof i=="object")if(Array.isArray(i))for(let r=0,s=i.length;r{"use strict";var tf=_();function To(t,e,n){if(Array.isArray(t))return t.map((i,r)=>To(i,String(r),n));if(t&&typeof t.toJSON=="function"){if(!n||!tf.hasAnchor(t))return t.toJSON(e,n);let i={aliasCount:0,count:1,res:void 0};n.anchors.set(t,i),n.onCreate=s=>{i.res=s,delete n.onCreate};let r=t.toJSON(e,n);return n.onCreate&&n.onCreate(r),r}return typeof t=="bigint"&&!n?.keep?Number(t):t}qo.toJS=To});var xn=v(Lo=>{"use strict";var nf=or(),$o=_(),rf=ke(),ar=class{constructor(e){Object.defineProperty(this,$o.NODE_TYPE,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:n,maxAliasCount:i,onAnchor:r,reviver:s}={}){if(!$o.isDocument(e))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:e,keep:!0,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},a=rf.toJS(this,"",o);if(typeof r=="function")for(let{count:c,res:l}of o.anchors.values())r(l,c);return typeof s=="function"?nf.applyReviver(s,{"":a},"",a):a}};Lo.NodeBase=ar});var Rt=v(Do=>{"use strict";var sf=En(),of=Et(),rt=_(),af=xn(),cf=ke(),cr=class extends af.NodeBase{constructor(e){super(rt.ALIAS),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,n){if(n?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let i;n?.aliasResolveCache?i=n.aliasResolveCache:(i=[],of.visit(e,{Node:(s,o)=>{(rt.isAlias(o)||rt.hasAnchor(o))&&i.push(o)}}),n&&(n.aliasResolveCache=i));let r;for(let s of i){if(s===this)break;s.anchor===this.source&&(r=s)}return r}toJSON(e,n){if(!n)return{source:this.source};let{anchors:i,doc:r,maxAliasCount:s}=n,o=this.resolve(r,n);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let a=i.get(o);if(a||(cf.toJS(o,null,n),a=i.get(o)),a?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(s>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=_n(r,o,i)),a.count*a.aliasCount>s)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return a.res}toString(e,n,i){let r=`*${this.source}`;if(e){if(sf.anchorIsValid(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let s=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(s)}if(e.implicitKey)return`${r} `}return r}};function _n(t,e,n){if(rt.isAlias(e)){let i=e.resolve(t),r=n&&i&&n.get(i);return r?r.count*r.aliasCount:0}else if(rt.isCollection(e)){let i=0;for(let r of e.items){let s=_n(t,r,n);s>i&&(i=s)}return i}else if(rt.isPair(e)){let i=_n(t,e.key,n),r=_n(t,e.value,n);return Math.max(i,r)}return 1}Do.Alias=cr});var j=v(lr=>{"use strict";var lf=_(),uf=xn(),ff=ke(),df=t=>!t||typeof t!="function"&&typeof t!="object",be=class extends uf.NodeBase{constructor(e){super(lf.SCALAR),this.value=e}toJSON(e,n){return n?.keep?this.value:ff.toJS(this.value,e,n)}toString(){return String(this.value)}};be.BLOCK_FOLDED="BLOCK_FOLDED";be.BLOCK_LITERAL="BLOCK_LITERAL";be.PLAIN="PLAIN";be.QUOTE_DOUBLE="QUOTE_DOUBLE";be.QUOTE_SINGLE="QUOTE_SINGLE";lr.Scalar=be;lr.isScalarValue=df});var Ot=v(Mo=>{"use strict";var pf=Rt(),Ke=_(),Fo=j(),mf="tag:yaml.org,2002:";function hf(t,e,n){if(e){let i=n.filter(s=>s.tag===e),r=i.find(s=>!s.format)??i[0];if(!r)throw new Error(`Tag ${e} not found`);return r}return n.find(i=>i.identify?.(t)&&!i.format)}function gf(t,e,n){if(Ke.isDocument(t)&&(t=t.contents),Ke.isNode(t))return t;if(Ke.isPair(t)){let f=n.schema[Ke.MAP].createNode?.(n.schema,null,n);return f.items.push(t),f}(t instanceof String||t instanceof Number||t instanceof Boolean||typeof BigInt<"u"&&t instanceof BigInt)&&(t=t.valueOf());let{aliasDuplicateObjects:i,onAnchor:r,onTagObj:s,schema:o,sourceObjects:a}=n,c;if(i&&t&&typeof t=="object"){if(c=a.get(t),c)return c.anchor??(c.anchor=r(t)),new pf.Alias(c.anchor);c={anchor:null,node:null},a.set(t,c)}e?.startsWith("!!")&&(e=mf+e.slice(2));let l=hf(t,e,o.tags);if(!l){if(t&&typeof t.toJSON=="function"&&(t=t.toJSON()),!t||typeof t!="object"){let f=new Fo.Scalar(t);return c&&(c.node=f),f}l=t instanceof Map?o[Ke.MAP]:Symbol.iterator in Object(t)?o[Ke.SEQ]:o[Ke.MAP]}s&&(s(l),delete n.onTagObj);let u=l?.createNode?l.createNode(n.schema,t,n):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(n.schema,t,n):new Fo.Scalar(t);return e?u.tag=e:l.default||(u.tag=l.tag),c&&(c.node=u),u}Mo.createNode=gf});var Rn=v(Pn=>{"use strict";var wf=Ot(),ce=_(),yf=xn();function ur(t,e,n){let i=n;for(let r=e.length-1;r>=0;--r){let s=e[r];if(typeof s=="number"&&Number.isInteger(s)&&s>=0){let o=[];o[s]=i,i=o}else i=new Map([[s,i]])}return wf.createNode(i,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:t,sourceObjects:new Map})}var Wo=t=>t==null||typeof t=="object"&&!!t[Symbol.iterator]().next().done,fr=class extends yf.NodeBase{constructor(e,n){super(e),Object.defineProperty(this,"schema",{value:n,configurable:!0,enumerable:!1,writable:!0})}clone(e){let n=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(n.schema=e),n.items=n.items.map(i=>ce.isNode(i)||ce.isPair(i)?i.clone(e):i),this.range&&(n.range=this.range.slice()),n}addIn(e,n){if(Wo(e))this.add(n);else{let[i,...r]=e,s=this.get(i,!0);if(ce.isCollection(s))s.addIn(r,n);else if(s===void 0&&this.schema)this.set(i,ur(this.schema,r,n));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${r}`)}}deleteIn(e){let[n,...i]=e;if(i.length===0)return this.delete(n);let r=this.get(n,!0);if(ce.isCollection(r))return r.deleteIn(i);throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}getIn(e,n){let[i,...r]=e,s=this.get(i,!0);return r.length===0?!n&&ce.isScalar(s)?s.value:s:ce.isCollection(s)?s.getIn(r,n):void 0}hasAllNullValues(e){return this.items.every(n=>{if(!ce.isPair(n))return!1;let i=n.value;return i==null||e&&ce.isScalar(i)&&i.value==null&&!i.commentBefore&&!i.comment&&!i.tag})}hasIn(e){let[n,...i]=e;if(i.length===0)return this.has(n);let r=this.get(n,!0);return ce.isCollection(r)?r.hasIn(i):!1}setIn(e,n){let[i,...r]=e;if(r.length===0)this.set(i,n);else{let s=this.get(i,!0);if(ce.isCollection(s))s.setIn(r,n);else if(s===void 0&&this.schema)this.set(i,ur(this.schema,r,n));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${r}`)}}};Pn.Collection=fr;Pn.collectionFromPath=ur;Pn.isEmptyPath=Wo});var Nt=v(On=>{"use strict";var vf=t=>t.replace(/^(?!$)(?: $)?/gm,"#");function dr(t,e){return/^\n+$/.test(t)?t.substring(1):e?t.replace(/^(?! *$)/gm,e):t}var kf=(t,e,n)=>t.endsWith(` -`)?dr(n,e):n.includes(` +var $u=Object.create;var nr=Object.defineProperty;var Lu=Object.getOwnPropertyDescriptor;var Du=Object.getOwnPropertyNames;var Fu=Object.getPrototypeOf,Mu=Object.prototype.hasOwnProperty;var vn=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var W=(t,e,n)=>()=>{if(n)throw n[0];try{return t&&(e=t(t=0)),e}catch(i){throw n=[i],i}};var v=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(n){throw e=0,n}},Wu=(t,e)=>{for(var n in e)nr(t,n,{get:e[n],enumerable:!0})},Bu=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Du(e))!Mu.call(t,r)&&r!==n&&nr(t,r,{get:()=>e[r],enumerable:!(i=Lu(e,r))||i.enumerable});return t};var Ct=(t,e,n)=>(n=t!=null?$u(Fu(t)):{},Bu(e||!t||!t.__esModule?nr(n,"default",{value:t,enumerable:!0}):n,t));var P=v(L=>{"use strict";var ir=Symbol.for("yaml.alias"),ko=Symbol.for("yaml.document"),kn=Symbol.for("yaml.map"),bo=Symbol.for("yaml.pair"),rr=Symbol.for("yaml.scalar"),bn=Symbol.for("yaml.seq"),fe=Symbol.for("yaml.node.type"),Ku=t=>!!t&&typeof t=="object"&&t[fe]===ir,Yu=t=>!!t&&typeof t=="object"&&t[fe]===ko,Ju=t=>!!t&&typeof t=="object"&&t[fe]===kn,Uu=t=>!!t&&typeof t=="object"&&t[fe]===bo,So=t=>!!t&&typeof t=="object"&&t[fe]===rr,Hu=t=>!!t&&typeof t=="object"&&t[fe]===bn;function Co(t){if(t&&typeof t=="object")switch(t[fe]){case kn:case bn:return!0}return!1}function Vu(t){if(t&&typeof t=="object")switch(t[fe]){case ir:case kn:case rr:case bn:return!0}return!1}var Gu=t=>(So(t)||Co(t))&&!!t.anchor;L.ALIAS=ir;L.DOC=ko;L.MAP=kn;L.NODE_TYPE=fe;L.PAIR=bo;L.SCALAR=rr;L.SEQ=bn;L.hasAnchor=Gu;L.isAlias=Ku;L.isCollection=Co;L.isDocument=Yu;L.isMap=Ju;L.isNode=Vu;L.isPair=Uu;L.isScalar=So;L.isSeq=Hu});var Et=v(sr=>{"use strict";var q=P(),U=Symbol("break visit"),Eo=Symbol("skip children"),ae=Symbol("remove node");function Sn(t,e){let n=xo(e);q.isDocument(t)?nt(null,t.contents,n,Object.freeze([t]))===ae&&(t.contents=null):nt(null,t,n,Object.freeze([]))}Sn.BREAK=U;Sn.SKIP=Eo;Sn.REMOVE=ae;function nt(t,e,n,i){let r=Po(t,e,n,i);if(q.isNode(r)||q.isPair(r))return _o(t,i,r),nt(t,r,n,i);if(typeof r!="symbol"){if(q.isCollection(e)){i=Object.freeze(i.concat(e));for(let s=0;s{"use strict";var Ro=P(),zu=Et(),Qu={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Xu=t=>t.replace(/[!,[\]{}]/g,e=>Qu[e]),xt=class t{constructor(e,n){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},t.defaultYaml,e),this.tags=Object.assign({},t.defaultTags,n)}clone(){let e=new t(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){let e=new t(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:t.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},t.defaultTags);break}return e}add(e,n){this.atNextDocument&&(this.yaml={explicit:t.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},t.defaultTags),this.atNextDocument=!1);let i=e.trim().split(/[ \t]+/),r=i.shift();switch(r){case"%TAG":{if(i.length!==2&&(n(0,"%TAG directive should contain exactly two parts"),i.length<2))return!1;let[s,o]=i;return this.tags[s]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,i.length!==1)return n(0,"%YAML directive should contain exactly one part"),!1;let[s]=i;if(s==="1.1"||s==="1.2")return this.yaml.version=s,!0;{let o=/^\d+\.\d+$/.test(s);return n(6,`Unsupported YAML version ${s}`,o),!1}}default:return n(0,`Unknown directive ${r}`,!0),!1}}tagName(e,n){if(e==="!")return"!";if(e[0]!=="!")return n(`Not a valid tag: ${e}`),null;if(e[1]==="<"){let o=e.slice(2,-1);return o==="!"||o==="!!"?(n(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&n("Verbatim tags must end with a >"),o)}let[,i,r]=e.match(/^(.*!)([^!]*)$/s);r||n(`The ${e} tag has no suffix`);let s=this.tags[i];if(s)try{return s+decodeURIComponent(r)}catch(o){return n(String(o)),null}return i==="!"?e:(n(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[n,i]of Object.entries(this.tags))if(e.startsWith(i))return n+Xu(e.substring(i.length));return e[0]==="!"?e:`!<${e}>`}toString(e){let n=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],i=Object.entries(this.tags),r;if(e&&i.length>0&&Ro.isNode(e.contents)){let s={};zu.visit(e.contents,(o,a)=>{Ro.isNode(a)&&a.tag&&(s[a.tag]=!0)}),r=Object.keys(s)}else r=[];for(let[s,o]of i)s==="!!"&&o==="tag:yaml.org,2002:"||(!e||r.some(a=>a.startsWith(o)))&&n.push(`%TAG ${s} ${o}`);return n.join(` +`)}};xt.defaultYaml={explicit:!1,version:"1.2"};xt.defaultTags={"!!":"tag:yaml.org,2002:"};Oo.Directives=xt});var En=v(Pt=>{"use strict";var No=P(),Zu=Et();function ef(t){if(/[\x00-\x19\s,[\]{}]/.test(t)){let n=`Anchor must not contain whitespace or control characters: ${JSON.stringify(t)}`;throw new Error(n)}return!0}function Ao(t){let e=new Set;return Zu.visit(t,{Value(n,i){i.anchor&&e.add(i.anchor)}}),e}function jo(t,e){for(let n=1;;++n){let i=`${t}${n}`;if(!e.has(i))return i}}function tf(t,e){let n=[],i=new Map,r=null;return{onAnchor:s=>{n.push(s),r??(r=Ao(t));let o=jo(e,r);return r.add(o),o},setAnchors:()=>{for(let s of n){let o=i.get(s);if(typeof o=="object"&&o.anchor&&(No.isScalar(o.node)||No.isCollection(o.node)))o.node.anchor=o.anchor;else{let a=new Error("Failed to resolve repeated object (this should not happen)");throw a.source=s,a}}},sourceObjects:i}}Pt.anchorIsValid=ef;Pt.anchorNames=Ao;Pt.createNodeAnchors=tf;Pt.findNewAnchor=jo});var ar=v(Io=>{"use strict";function _t(t,e,n,i){if(i&&typeof i=="object")if(Array.isArray(i))for(let r=0,s=i.length;r{"use strict";var nf=P();function To(t,e,n){if(Array.isArray(t))return t.map((i,r)=>To(i,String(r),n));if(t&&typeof t.toJSON=="function"){if(!n||!nf.hasAnchor(t))return t.toJSON(e,n);let i={aliasCount:0,count:1,res:void 0};n.anchors.set(t,i),n.onCreate=s=>{i.res=s,delete n.onCreate};let r=t.toJSON(e,n);return n.onCreate&&n.onCreate(r),r}return typeof t=="bigint"&&!n?.keep?Number(t):t}qo.toJS=To});var xn=v(Lo=>{"use strict";var rf=ar(),$o=P(),sf=ke(),cr=class{constructor(e){Object.defineProperty(this,$o.NODE_TYPE,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:n,maxAliasCount:i,onAnchor:r,reviver:s}={}){if(!$o.isDocument(e))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:e,keep:!0,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},a=sf.toJS(this,"",o);if(typeof r=="function")for(let{count:c,res:l}of o.anchors.values())r(l,c);return typeof s=="function"?rf.applyReviver(s,{"":a},"",a):a}};Lo.NodeBase=cr});var Rt=v(Do=>{"use strict";var of=En(),af=Et(),rt=P(),cf=xn(),lf=ke(),lr=class extends cf.NodeBase{constructor(e){super(rt.ALIAS),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,n){if(n?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let i;n?.aliasResolveCache?i=n.aliasResolveCache:(i=[],af.visit(e,{Node:(s,o)=>{(rt.isAlias(o)||rt.hasAnchor(o))&&i.push(o)}}),n&&(n.aliasResolveCache=i));let r;for(let s of i){if(s===this)break;s.anchor===this.source&&(r=s)}return r}toJSON(e,n){if(!n)return{source:this.source};let{anchors:i,doc:r,maxAliasCount:s}=n,o=this.resolve(r,n);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let a=i.get(o);if(a||(lf.toJS(o,null,n),a=i.get(o)),a?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(s>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=Pn(r,o,i)),a.count*a.aliasCount>s)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return a.res}toString(e,n,i){let r=`*${this.source}`;if(e){if(of.anchorIsValid(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let s=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(s)}if(e.implicitKey)return`${r} `}return r}};function Pn(t,e,n){if(rt.isAlias(e)){let i=e.resolve(t),r=n&&i&&n.get(i);return r?r.count*r.aliasCount:0}else if(rt.isCollection(e)){let i=0;for(let r of e.items){let s=Pn(t,r,n);s>i&&(i=s)}return i}else if(rt.isPair(e)){let i=Pn(t,e.key,n),r=Pn(t,e.value,n);return Math.max(i,r)}return 1}Do.Alias=lr});var j=v(ur=>{"use strict";var uf=P(),ff=xn(),df=ke(),pf=t=>!t||typeof t!="function"&&typeof t!="object",be=class extends ff.NodeBase{constructor(e){super(uf.SCALAR),this.value=e}toJSON(e,n){return n?.keep?this.value:df.toJS(this.value,e,n)}toString(){return String(this.value)}};be.BLOCK_FOLDED="BLOCK_FOLDED";be.BLOCK_LITERAL="BLOCK_LITERAL";be.PLAIN="PLAIN";be.QUOTE_DOUBLE="QUOTE_DOUBLE";be.QUOTE_SINGLE="QUOTE_SINGLE";ur.Scalar=be;ur.isScalarValue=pf});var Ot=v(Mo=>{"use strict";var mf=Rt(),Ye=P(),Fo=j(),hf="tag:yaml.org,2002:";function gf(t,e,n){if(e){let i=n.filter(s=>s.tag===e),r=i.find(s=>!s.format)??i[0];if(!r)throw new Error(`Tag ${e} not found`);return r}return n.find(i=>i.identify?.(t)&&!i.format)}function wf(t,e,n){if(Ye.isDocument(t)&&(t=t.contents),Ye.isNode(t))return t;if(Ye.isPair(t)){let f=n.schema[Ye.MAP].createNode?.(n.schema,null,n);return f.items.push(t),f}(t instanceof String||t instanceof Number||t instanceof Boolean||typeof BigInt<"u"&&t instanceof BigInt)&&(t=t.valueOf());let{aliasDuplicateObjects:i,onAnchor:r,onTagObj:s,schema:o,sourceObjects:a}=n,c;if(i&&t&&typeof t=="object"){if(c=a.get(t),c)return c.anchor??(c.anchor=r(t)),new mf.Alias(c.anchor);c={anchor:null,node:null},a.set(t,c)}e?.startsWith("!!")&&(e=hf+e.slice(2));let l=gf(t,e,o.tags);if(!l){if(t&&typeof t.toJSON=="function"&&(t=t.toJSON()),!t||typeof t!="object"){let f=new Fo.Scalar(t);return c&&(c.node=f),f}l=t instanceof Map?o[Ye.MAP]:Symbol.iterator in Object(t)?o[Ye.SEQ]:o[Ye.MAP]}s&&(s(l),delete n.onTagObj);let u=l?.createNode?l.createNode(n.schema,t,n):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(n.schema,t,n):new Fo.Scalar(t);return e?u.tag=e:l.default||(u.tag=l.tag),c&&(c.node=u),u}Mo.createNode=wf});var Rn=v(_n=>{"use strict";var yf=Ot(),ce=P(),vf=xn();function fr(t,e,n){let i=n;for(let r=e.length-1;r>=0;--r){let s=e[r];if(typeof s=="number"&&Number.isInteger(s)&&s>=0){let o=[];o[s]=i,i=o}else i=new Map([[s,i]])}return yf.createNode(i,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:t,sourceObjects:new Map})}var Wo=t=>t==null||typeof t=="object"&&!!t[Symbol.iterator]().next().done,dr=class extends vf.NodeBase{constructor(e,n){super(e),Object.defineProperty(this,"schema",{value:n,configurable:!0,enumerable:!1,writable:!0})}clone(e){let n=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(n.schema=e),n.items=n.items.map(i=>ce.isNode(i)||ce.isPair(i)?i.clone(e):i),this.range&&(n.range=this.range.slice()),n}addIn(e,n){if(Wo(e))this.add(n);else{let[i,...r]=e,s=this.get(i,!0);if(ce.isCollection(s))s.addIn(r,n);else if(s===void 0&&this.schema)this.set(i,fr(this.schema,r,n));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${r}`)}}deleteIn(e){let[n,...i]=e;if(i.length===0)return this.delete(n);let r=this.get(n,!0);if(ce.isCollection(r))return r.deleteIn(i);throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}getIn(e,n){let[i,...r]=e,s=this.get(i,!0);return r.length===0?!n&&ce.isScalar(s)?s.value:s:ce.isCollection(s)?s.getIn(r,n):void 0}hasAllNullValues(e){return this.items.every(n=>{if(!ce.isPair(n))return!1;let i=n.value;return i==null||e&&ce.isScalar(i)&&i.value==null&&!i.commentBefore&&!i.comment&&!i.tag})}hasIn(e){let[n,...i]=e;if(i.length===0)return this.has(n);let r=this.get(n,!0);return ce.isCollection(r)?r.hasIn(i):!1}setIn(e,n){let[i,...r]=e;if(r.length===0)this.set(i,n);else{let s=this.get(i,!0);if(ce.isCollection(s))s.setIn(r,n);else if(s===void 0&&this.schema)this.set(i,fr(this.schema,r,n));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${r}`)}}};_n.Collection=dr;_n.collectionFromPath=fr;_n.isEmptyPath=Wo});var Nt=v(On=>{"use strict";var kf=t=>t.replace(/^(?!$)(?: $)?/gm,"#");function pr(t,e){return/^\n+$/.test(t)?t.substring(1):e?t.replace(/^(?! *$)/gm,e):t}var bf=(t,e,n)=>t.endsWith(` +`)?pr(n,e):n.includes(` `)?` -`+dr(n,e):(t.endsWith(" ")?"":" ")+n;On.indentComment=dr;On.lineComment=kf;On.stringifyComment=vf});var Ko=v(At=>{"use strict";var bf="flow",pr="block",Nn="quoted";function Sf(t,e,n="flow",{indentAtStart:i,lineWidth:r=80,minContentWidth:s=20,onFold:o,onOverflow:a}={}){if(!r||r<0)return t;rr-Math.max(2,s)?l.push(0):f=r-i);let d,h,w=!1,p=-1,m=-1,y=-1;n===pr&&(p=Bo(t,p,e.length),p!==-1&&(f=p+c));for(let b;b=t[p+=1];){if(n===Nn&&b==="\\"){switch(m=p,t[p+1]){case"x":p+=3;break;case"u":p+=5;break;case"U":p+=9;break;default:p+=1}y=p}if(b===` -`)n===pr&&(p=Bo(t,p,e.length)),f=p+e.length+c,d=void 0;else{if(b===" "&&h&&h!==" "&&h!==` +`+pr(n,e):(t.endsWith(" ")?"":" ")+n;On.indentComment=pr;On.lineComment=bf;On.stringifyComment=kf});var Ko=v(At=>{"use strict";var Sf="flow",mr="block",Nn="quoted";function Cf(t,e,n="flow",{indentAtStart:i,lineWidth:r=80,minContentWidth:s=20,onFold:o,onOverflow:a}={}){if(!r||r<0)return t;rr-Math.max(2,s)?l.push(0):f=r-i);let d,h,w=!1,p=-1,m=-1,y=-1;n===mr&&(p=Bo(t,p,e.length),p!==-1&&(f=p+c));for(let b;b=t[p+=1];){if(n===Nn&&b==="\\"){switch(m=p,t[p+1]){case"x":p+=3;break;case"u":p+=5;break;case"U":p+=9;break;default:p+=1}y=p}if(b===` +`)n===mr&&(p=Bo(t,p,e.length)),f=p+e.length+c,d=void 0;else{if(b===" "&&h&&h!==" "&&h!==` `&&h!==" "){let S=t[p+1];S&&S!==" "&&S!==` `&&S!==" "&&(d=p)}if(p>=f)if(d)l.push(d),f=d+c,d=void 0;else if(n===Nn){for(;h===" "||h===" ";)h=b,b=t[p+=1],w=!0;let S=p>y+1?p-2:m-1;if(u[S])return t;l.push(S),u[S]=!0,f=S+c,d=void 0}else w=!0}h=b}if(w&&a&&a(),l.length===0)return t;o&&o();let g=t.slice(0,l[0]);for(let b=0;b{"use strict";var Z=j(),Se=Ko(),jn=(t,e)=>({indentAtStart:e?t.indent.length:t.indentAtStart,lineWidth:t.options.lineWidth,minContentWidth:t.options.minContentWidth}),In=t=>/^(%|---|\.\.\.)/m.test(t);function Cf(t,e,n){if(!e||e<0)return!1;let i=e-n,r=t.length;if(r<=i)return!1;for(let s=0,o=0;s{"use strict";var Z=j(),Se=Ko(),jn=(t,e)=>({indentAtStart:e?t.indent.length:t.indentAtStart,lineWidth:t.options.lineWidth,minContentWidth:t.options.minContentWidth}),In=t=>/^(%|---|\.\.\.)/m.test(t);function Ef(t,e,n){if(!e||e<0)return!1;let i=e-n,r=t.length;if(r<=i)return!1;for(let s=0,o=0;si)return!0;if(o=s+1,r-o<=i)return!1}return!0}function jt(t,e){let n=JSON.stringify(t);if(e.options.doubleQuotedAsJSON)return n;let{implicitKey:i}=e,r=e.options.doubleQuotedMinMultiLineLength,s=e.indent||(In(t)?" ":""),o="",a=0;for(let c=0,l=n[c];l;l=n[++c])if(l===" "&&n[c+1]==="\\"&&n[c+2]==="n"&&(o+=n.slice(a,c)+"\\ ",c+=1,a=c,l="\\"),l==="\\")switch(n[c+1]){case"u":{o+=n.slice(a,c);let u=n.substr(c+2,4);switch(u){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:u.substr(0,2)==="00"?o+="\\x"+u.substr(2):o+=n.substr(c,6)}c+=5,a=c+1}break;case"n":if(i||n[c+2]==='"'||n.length `;let f,d;for(d=n.length;d>0;--d){let C=n[d-1];if(C!==` `&&C!==" "&&C!==" ")break}let h=n.substring(d),w=h.indexOf(` `);w===-1?f="-":n===h||w!==h.length-1?(f="+",s&&s()):f="",h&&(n=n.slice(0,-h.length),h[h.length-1]===` -`&&(h=h.slice(0,-1)),h=h.replace(hr,`$&${l}`));let p=!1,m,y=-1;for(m=0;m{E=!0});let k=Se.foldFlowLines(`${g}${C}${h}`,l,Se.FOLD_BLOCK,x);if(!E)return`>${S} ${l}${k}`}return n=n.replace(/\n+/g,`$&${l}`),`|${S} -${l}${g}${n}${h}`}function Ef(t,e,n,i){let{type:r,value:s}=t,{actualString:o,implicitKey:a,indent:c,indentStep:l,inFlow:u}=e;if(a&&s.includes(` +${l}${g}${n}${h}`}function xf(t,e,n,i){let{type:r,value:s}=t,{actualString:o,implicitKey:a,indent:c,indentStep:l,inFlow:u}=e;if(a&&s.includes(` `)||u&&/[[\]{},]/.test(s))return st(s,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(s))return a||u||!s.includes(` `)?st(s,e):An(t,e,n,i);if(!a&&!u&&r!==Z.Scalar.PLAIN&&s.includes(` `))return An(t,e,n,i);if(In(s)){if(c==="")return e.forceBlockIndent=!0,An(t,e,n,i);if(a&&c===l)return st(s,e)}let f=s.replace(/\n+/g,`$& -${c}`);if(o){let d=p=>p.default&&p.tag!=="tag:yaml.org,2002:str"&&p.test?.test(f),{compat:h,tags:w}=e.doc.schema;if(w.some(d)||h?.some(d))return st(s,e)}return a?f:Se.foldFlowLines(f,c,Se.FOLD_FLOW,jn(e,!1))}function xf(t,e,n,i){let{implicitKey:r,inFlow:s}=e,o=typeof t.value=="string"?t:Object.assign({},t,{value:String(t.value)}),{type:a}=t;a!==Z.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=Z.Scalar.QUOTE_DOUBLE);let c=u=>{switch(u){case Z.Scalar.BLOCK_FOLDED:case Z.Scalar.BLOCK_LITERAL:return r||s?st(o.value,e):An(o,e,n,i);case Z.Scalar.QUOTE_DOUBLE:return jt(o.value,e);case Z.Scalar.QUOTE_SINGLE:return mr(o.value,e);case Z.Scalar.PLAIN:return Ef(o,e,n,i);default:return null}},l=c(a);if(l===null){let{defaultKeyType:u,defaultStringType:f}=e.options,d=r&&u||f;if(l=c(d),l===null)throw new Error(`Unsupported default string type ${d}`)}return l}Yo.stringifyString=xf});var Tt=v(gr=>{"use strict";var _f=En(),Ce=_(),Pf=Nt(),Rf=It();function Of(t,e){let n=Object.assign({blockQuote:!0,commentString:Pf.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},t.schema.toStringOptions,e),i;switch(n.collectionStyle){case"block":i=!1;break;case"flow":i=!0;break;default:i=null}return{anchors:new Set,doc:t,flowCollectionPadding:n.flowCollectionPadding?" ":"",indent:"",indentStep:typeof n.indent=="number"?" ".repeat(n.indent):" ",inFlow:i,options:n}}function Nf(t,e){if(e.tag){let r=t.filter(s=>s.tag===e.tag);if(r.length>0)return r.find(s=>s.format===e.format)??r[0]}let n,i;if(Ce.isScalar(e)){i=e.value;let r=t.filter(s=>s.identify?.(i));if(r.length>1){let s=r.filter(o=>o.test);s.length>0&&(r=s)}n=r.find(s=>s.format===e.format)??r.find(s=>!s.format)}else i=e,n=t.find(r=>r.nodeClass&&i instanceof r.nodeClass);if(!n){let r=i?.constructor?.name??(i===null?"null":typeof i);throw new Error(`Tag not resolved for ${r} value`)}return n}function Af(t,e,{anchors:n,doc:i}){if(!i.directives)return"";let r=[],s=(Ce.isScalar(t)||Ce.isCollection(t))&&t.anchor;s&&_f.anchorIsValid(s)&&(n.add(s),r.push(`&${s}`));let o=t.tag??(e.default?null:e.tag);return o&&r.push(i.directives.tagString(o)),r.join(" ")}function jf(t,e,n,i){if(Ce.isPair(t))return t.toString(e,n,i);if(Ce.isAlias(t)){if(e.doc.directives)return t.toString(e);if(e.resolvedAliases?.has(t))throw new TypeError("Cannot stringify circular structure without alias nodes");e.resolvedAliases?e.resolvedAliases.add(t):e.resolvedAliases=new Set([t]),t=t.resolve(e.doc)}let r,s=Ce.isNode(t)?t:e.doc.createNode(t,{onTagObj:c=>r=c});r??(r=Nf(e.doc.schema.tags,s));let o=Af(s,r,e);o.length>0&&(e.indentAtStart=(e.indentAtStart??0)+o.length+1);let a=typeof r.stringify=="function"?r.stringify(s,e,n,i):Ce.isScalar(s)?Rf.stringifyString(s,e,n,i):s.toString(e,n,i);return o?Ce.isScalar(s)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o} -${e.indent}${a}`:a}gr.createStringifyContext=Of;gr.stringify=jf});var Vo=v(Ho=>{"use strict";var de=_(),Jo=j(),Uo=Tt(),qt=Nt();function If({key:t,value:e},n,i,r){let{allNullValues:s,doc:o,indent:a,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:f}}=n,d=de.isNode(t)&&t.comment||null;if(f){if(d)throw new Error("With simple keys, key nodes cannot have comments");if(de.isCollection(t)||!de.isNode(t)&&typeof t=="object"){let x="With simple keys, collection cannot be used as a key value";throw new Error(x)}}let h=!f&&(!t||d&&e==null&&!n.inFlow||de.isCollection(t)||(de.isScalar(t)?t.type===Jo.Scalar.BLOCK_FOLDED||t.type===Jo.Scalar.BLOCK_LITERAL:typeof t=="object"));n=Object.assign({},n,{allNullValues:!1,implicitKey:!h&&(f||!s),indent:a+c});let w=!1,p=!1,m=Uo.stringify(t,n,()=>w=!0,()=>p=!0);if(!h&&!n.inFlow&&m.length>1024){if(f)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");h=!0}if(n.inFlow){if(s||e==null)return w&&i&&i(),m===""?"?":h?`? ${m}`:m}else if(s&&!f||e==null&&h)return m=`? ${m}`,d&&!w?m+=qt.lineComment(m,n.indent,l(d)):p&&r&&r(),m;w&&(d=null),h?(d&&(m+=qt.lineComment(m,n.indent,l(d))),m=`? ${m} +${c}`);if(o){let d=p=>p.default&&p.tag!=="tag:yaml.org,2002:str"&&p.test?.test(f),{compat:h,tags:w}=e.doc.schema;if(w.some(d)||h?.some(d))return st(s,e)}return a?f:Se.foldFlowLines(f,c,Se.FOLD_FLOW,jn(e,!1))}function Pf(t,e,n,i){let{implicitKey:r,inFlow:s}=e,o=typeof t.value=="string"?t:Object.assign({},t,{value:String(t.value)}),{type:a}=t;a!==Z.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=Z.Scalar.QUOTE_DOUBLE);let c=u=>{switch(u){case Z.Scalar.BLOCK_FOLDED:case Z.Scalar.BLOCK_LITERAL:return r||s?st(o.value,e):An(o,e,n,i);case Z.Scalar.QUOTE_DOUBLE:return jt(o.value,e);case Z.Scalar.QUOTE_SINGLE:return hr(o.value,e);case Z.Scalar.PLAIN:return xf(o,e,n,i);default:return null}},l=c(a);if(l===null){let{defaultKeyType:u,defaultStringType:f}=e.options,d=r&&u||f;if(l=c(d),l===null)throw new Error(`Unsupported default string type ${d}`)}return l}Yo.stringifyString=Pf});var Tt=v(wr=>{"use strict";var _f=En(),Ce=P(),Rf=Nt(),Of=It();function Nf(t,e){let n=Object.assign({blockQuote:!0,commentString:Rf.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},t.schema.toStringOptions,e),i;switch(n.collectionStyle){case"block":i=!1;break;case"flow":i=!0;break;default:i=null}return{anchors:new Set,doc:t,flowCollectionPadding:n.flowCollectionPadding?" ":"",indent:"",indentStep:typeof n.indent=="number"?" ".repeat(n.indent):" ",inFlow:i,options:n}}function Af(t,e){if(e.tag){let r=t.filter(s=>s.tag===e.tag);if(r.length>0)return r.find(s=>s.format===e.format)??r[0]}let n,i;if(Ce.isScalar(e)){i=e.value;let r=t.filter(s=>s.identify?.(i));if(r.length>1){let s=r.filter(o=>o.test);s.length>0&&(r=s)}n=r.find(s=>s.format===e.format)??r.find(s=>!s.format)}else i=e,n=t.find(r=>r.nodeClass&&i instanceof r.nodeClass);if(!n){let r=i?.constructor?.name??(i===null?"null":typeof i);throw new Error(`Tag not resolved for ${r} value`)}return n}function jf(t,e,{anchors:n,doc:i}){if(!i.directives)return"";let r=[],s=(Ce.isScalar(t)||Ce.isCollection(t))&&t.anchor;s&&_f.anchorIsValid(s)&&(n.add(s),r.push(`&${s}`));let o=t.tag??(e.default?null:e.tag);return o&&r.push(i.directives.tagString(o)),r.join(" ")}function If(t,e,n,i){if(Ce.isPair(t))return t.toString(e,n,i);if(Ce.isAlias(t)){if(e.doc.directives)return t.toString(e);if(e.resolvedAliases?.has(t))throw new TypeError("Cannot stringify circular structure without alias nodes");e.resolvedAliases?e.resolvedAliases.add(t):e.resolvedAliases=new Set([t]),t=t.resolve(e.doc)}let r,s=Ce.isNode(t)?t:e.doc.createNode(t,{onTagObj:c=>r=c});r??(r=Af(e.doc.schema.tags,s));let o=jf(s,r,e);o.length>0&&(e.indentAtStart=(e.indentAtStart??0)+o.length+1);let a=typeof r.stringify=="function"?r.stringify(s,e,n,i):Ce.isScalar(s)?Of.stringifyString(s,e,n,i):s.toString(e,n,i);return o?Ce.isScalar(s)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o} +${e.indent}${a}`:a}wr.createStringifyContext=Nf;wr.stringify=If});var Vo=v(Ho=>{"use strict";var de=P(),Jo=j(),Uo=Tt(),qt=Nt();function Tf({key:t,value:e},n,i,r){let{allNullValues:s,doc:o,indent:a,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:f}}=n,d=de.isNode(t)&&t.comment||null;if(f){if(d)throw new Error("With simple keys, key nodes cannot have comments");if(de.isCollection(t)||!de.isNode(t)&&typeof t=="object"){let x="With simple keys, collection cannot be used as a key value";throw new Error(x)}}let h=!f&&(!t||d&&e==null&&!n.inFlow||de.isCollection(t)||(de.isScalar(t)?t.type===Jo.Scalar.BLOCK_FOLDED||t.type===Jo.Scalar.BLOCK_LITERAL:typeof t=="object"));n=Object.assign({},n,{allNullValues:!1,implicitKey:!h&&(f||!s),indent:a+c});let w=!1,p=!1,m=Uo.stringify(t,n,()=>w=!0,()=>p=!0);if(!h&&!n.inFlow&&m.length>1024){if(f)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");h=!0}if(n.inFlow){if(s||e==null)return w&&i&&i(),m===""?"?":h?`? ${m}`:m}else if(s&&!f||e==null&&h)return m=`? ${m}`,d&&!w?m+=qt.lineComment(m,n.indent,l(d)):p&&r&&r(),m;w&&(d=null),h?(d&&(m+=qt.lineComment(m,n.indent,l(d))),m=`? ${m} ${a}:`):(m=`${m}:`,d&&(m+=qt.lineComment(m,n.indent,l(d))));let y,g,b;de.isNode(e)?(y=!!e.spaceBefore,g=e.commentBefore,b=e.comment):(y=!1,g=null,b=null,e&&typeof e=="object"&&(e=o.createNode(e))),n.implicitKey=!1,!h&&!d&&de.isScalar(e)&&(n.indentAtStart=m.length+1),p=!1,!u&&c.length>=2&&!n.inFlow&&!h&&de.isSeq(e)&&!e.flow&&!e.tag&&!e.anchor&&(n.indent=n.indent.substring(2));let S=!1,C=Uo.stringify(e,n,()=>S=!0,()=>p=!0),E=" ";if(d||y||g){if(E=y?` `:"",g){let x=l(g);E+=` ${qt.indentComment(x,n.indent)}`}C===""&&!n.inFlow?E===` @@ -44,34 +44,34 @@ ${qt.indentComment(x,n.indent)}`}C===""&&!n.inFlow?E===` ${n.indent}`}else if(!h&&de.isCollection(e)){let x=C[0],k=C.indexOf(` `),N=k!==-1,oe=n.inFlow??e.flow??e.items.length===0;if(N||!oe){let J=!1;if(N&&(x==="&"||x==="!")){let R=C.indexOf(" ");x==="&"&&R!==-1&&R{"use strict";var Go=vn("process");function Tf(t,...e){t==="debug"&&console.log(...e)}function qf(t,e){(t==="debug"||t==="warn")&&(typeof Go.emitWarning=="function"?Go.emitWarning(e):console.warn(e))}wr.debug=Tf;wr.warn=qf});var Dn=v(Ln=>{"use strict";var $n=_(),zo=j(),Tn="<<",qn={identify:t=>t===Tn||typeof t=="symbol"&&t.description===Tn,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new zo.Scalar(Symbol(Tn)),{addToJSMap:Qo}),stringify:()=>Tn},$f=(t,e)=>(qn.identify(e)||$n.isScalar(e)&&(!e.type||e.type===zo.Scalar.PLAIN)&&qn.identify(e.value))&&t?.doc.schema.tags.some(n=>n.tag===qn.tag&&n.default);function Qo(t,e,n){let i=Xo(t,n);if($n.isSeq(i))for(let r of i.items)vr(t,e,r);else if(Array.isArray(i))for(let r of i)vr(t,e,r);else vr(t,e,i)}function vr(t,e,n){let i=Xo(t,n);if(!$n.isMap(i))throw new Error("Merge sources must be maps or map aliases");let r=i.toJSON(null,t,Map);for(let[s,o]of r)e instanceof Map?e.has(s)||e.set(s,o):e instanceof Set?e.add(s):Object.prototype.hasOwnProperty.call(e,s)||Object.defineProperty(e,s,{value:o,writable:!0,enumerable:!0,configurable:!0});return e}function Xo(t,e){return t&&$n.isAlias(e)?e.resolve(t.doc,t):e}Ln.addMergeToJSMap=Qo;Ln.isMergeKey=$f;Ln.merge=qn});var br=v(ta=>{"use strict";var Lf=yr(),Zo=Dn(),Df=Tt(),ea=_(),kr=ke();function Ff(t,e,{key:n,value:i}){if(ea.isNode(n)&&n.addToJSMap)n.addToJSMap(t,e,i);else if(Zo.isMergeKey(t,n))Zo.addMergeToJSMap(t,e,i);else{let r=kr.toJS(n,"",t);if(e instanceof Map)e.set(r,kr.toJS(i,r,t));else if(e instanceof Set)e.add(r);else{let s=Mf(n,r,t),o=kr.toJS(i,s,t);s in e?Object.defineProperty(e,s,{value:o,writable:!0,enumerable:!0,configurable:!0}):e[s]=o}}return e}function Mf(t,e,n){if(e===null)return"";if(typeof e!="object")return String(e);if(ea.isNode(t)&&n?.doc){let i=Df.createStringifyContext(n.doc,{});i.anchors=new Set;for(let s of n.anchors.keys())i.anchors.add(s.anchor);i.inFlow=!0,i.inStringifyKey=!0;let r=t.toString(i);if(!n.mapKeyWarned){let s=JSON.stringify(r);s.length>40&&(s=s.substring(0,36)+'..."'),Lf.warn(n.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${s}. Set mapAsMap: true to use object keys.`),n.mapKeyWarned=!0}return r}return JSON.stringify(e)}ta.addPairToJSMap=Ff});var Ee=v(Sr=>{"use strict";var na=Ot(),Wf=Vo(),Bf=br(),Fn=_();function Kf(t,e,n){let i=na.createNode(t,void 0,n),r=na.createNode(e,void 0,n);return new Mn(i,r)}var Mn=class t{constructor(e,n=null){Object.defineProperty(this,Fn.NODE_TYPE,{value:Fn.PAIR}),this.key=e,this.value=n}clone(e){let{key:n,value:i}=this;return Fn.isNode(n)&&(n=n.clone(e)),Fn.isNode(i)&&(i=i.clone(e)),new t(n,i)}toJSON(e,n){let i=n?.mapAsMap?new Map:{};return Bf.addPairToJSMap(n,i,this)}toString(e,n,i){return e?.doc?Wf.stringifyPair(this,e,n,i):JSON.stringify(this)}};Sr.Pair=Mn;Sr.createPair=Kf});var Cr=v(ra=>{"use strict";var Ye=_(),ia=Tt(),Wn=Nt();function Yf(t,e,n){return(e.inFlow??t.flow?Uf:Jf)(t,e,n)}function Jf({comment:t,items:e},n,{blockItemPrefix:i,flowChars:r,itemIndent:s,onChompKeep:o,onComment:a}){let{indent:c,options:{commentString:l}}=n,u=Object.assign({},n,{indent:s,type:null}),f=!1,d=[];for(let w=0;wm=null,()=>f=!0);m&&(y+=Wn.lineComment(y,s,l(m))),f&&m&&(f=!1),d.push(i+y)}let h;if(d.length===0)h=r.start+r.end;else{h=d[0];for(let w=1;w{"use strict";var Go=vn("process");function qf(t,...e){t==="debug"&&console.log(...e)}function $f(t,e){(t==="debug"||t==="warn")&&(typeof Go.emitWarning=="function"?Go.emitWarning(e):console.warn(e))}yr.debug=qf;yr.warn=$f});var Dn=v(Ln=>{"use strict";var $n=P(),zo=j(),Tn="<<",qn={identify:t=>t===Tn||typeof t=="symbol"&&t.description===Tn,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new zo.Scalar(Symbol(Tn)),{addToJSMap:Qo}),stringify:()=>Tn},Lf=(t,e)=>(qn.identify(e)||$n.isScalar(e)&&(!e.type||e.type===zo.Scalar.PLAIN)&&qn.identify(e.value))&&t?.doc.schema.tags.some(n=>n.tag===qn.tag&&n.default);function Qo(t,e,n){let i=Xo(t,n);if($n.isSeq(i))for(let r of i.items)kr(t,e,r);else if(Array.isArray(i))for(let r of i)kr(t,e,r);else kr(t,e,i)}function kr(t,e,n){let i=Xo(t,n);if(!$n.isMap(i))throw new Error("Merge sources must be maps or map aliases");let r=i.toJSON(null,t,Map);for(let[s,o]of r)e instanceof Map?e.has(s)||e.set(s,o):e instanceof Set?e.add(s):Object.prototype.hasOwnProperty.call(e,s)||Object.defineProperty(e,s,{value:o,writable:!0,enumerable:!0,configurable:!0});return e}function Xo(t,e){return t&&$n.isAlias(e)?e.resolve(t.doc,t):e}Ln.addMergeToJSMap=Qo;Ln.isMergeKey=Lf;Ln.merge=qn});var Sr=v(ta=>{"use strict";var Df=vr(),Zo=Dn(),Ff=Tt(),ea=P(),br=ke();function Mf(t,e,{key:n,value:i}){if(ea.isNode(n)&&n.addToJSMap)n.addToJSMap(t,e,i);else if(Zo.isMergeKey(t,n))Zo.addMergeToJSMap(t,e,i);else{let r=br.toJS(n,"",t);if(e instanceof Map)e.set(r,br.toJS(i,r,t));else if(e instanceof Set)e.add(r);else{let s=Wf(n,r,t),o=br.toJS(i,s,t);s in e?Object.defineProperty(e,s,{value:o,writable:!0,enumerable:!0,configurable:!0}):e[s]=o}}return e}function Wf(t,e,n){if(e===null)return"";if(typeof e!="object")return String(e);if(ea.isNode(t)&&n?.doc){let i=Ff.createStringifyContext(n.doc,{});i.anchors=new Set;for(let s of n.anchors.keys())i.anchors.add(s.anchor);i.inFlow=!0,i.inStringifyKey=!0;let r=t.toString(i);if(!n.mapKeyWarned){let s=JSON.stringify(r);s.length>40&&(s=s.substring(0,36)+'..."'),Df.warn(n.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${s}. Set mapAsMap: true to use object keys.`),n.mapKeyWarned=!0}return r}return JSON.stringify(e)}ta.addPairToJSMap=Mf});var Ee=v(Cr=>{"use strict";var na=Ot(),Bf=Vo(),Kf=Sr(),Fn=P();function Yf(t,e,n){let i=na.createNode(t,void 0,n),r=na.createNode(e,void 0,n);return new Mn(i,r)}var Mn=class t{constructor(e,n=null){Object.defineProperty(this,Fn.NODE_TYPE,{value:Fn.PAIR}),this.key=e,this.value=n}clone(e){let{key:n,value:i}=this;return Fn.isNode(n)&&(n=n.clone(e)),Fn.isNode(i)&&(i=i.clone(e)),new t(n,i)}toJSON(e,n){let i=n?.mapAsMap?new Map:{};return Kf.addPairToJSMap(n,i,this)}toString(e,n,i){return e?.doc?Bf.stringifyPair(this,e,n,i):JSON.stringify(this)}};Cr.Pair=Mn;Cr.createPair=Yf});var Er=v(ra=>{"use strict";var Je=P(),ia=Tt(),Wn=Nt();function Jf(t,e,n){return(e.inFlow??t.flow?Hf:Uf)(t,e,n)}function Uf({comment:t,items:e},n,{blockItemPrefix:i,flowChars:r,itemIndent:s,onChompKeep:o,onComment:a}){let{indent:c,options:{commentString:l}}=n,u=Object.assign({},n,{indent:s,type:null}),f=!1,d=[];for(let w=0;wm=null,()=>f=!0);m&&(y+=Wn.lineComment(y,s,l(m))),f&&m&&(f=!1),d.push(i+y)}let h;if(d.length===0)h=r.start+r.end;else{h=d[0];for(let w=1;wm=null);l||(l=f.length>u||y.includes(` +`+Wn.indentComment(l(t),c),a&&a()):f&&o&&o(),h}function Hf({items:t},e,{flowChars:n,itemIndent:i}){let{indent:r,indentStep:s,flowCollectionPadding:o,options:{commentString:a}}=e;i+=s;let c=Object.assign({},e,{indent:i,inFlow:!0,type:null}),l=!1,u=0,f=[];for(let w=0;wm=null);l||(l=f.length>u||y.includes(` `)),w0&&(l||(l=f.reduce((g,b)=>g+b.length+2,2)+(y.length+2)>e.options.lineWidth)),l&&(y+=",")),m&&(y+=Wn.lineComment(y,i,a(m))),f.push(y),u=f.length}let{start:d,end:h}=n;if(f.length===0)return d+h;if(!l){let w=f.reduce((p,m)=>p+m.length+2,2);l=e.options.lineWidth>0&&w>e.options.lineWidth}if(l){let w=d;for(let p of f)w+=p?` ${s}${r}${p}`:` `;return`${w} -${r}${h}`}else return`${d}${o}${f.join(" ")}${o}${h}`}function Bn({indent:t,options:{commentString:e}},n,i,r){if(i&&r&&(i=i.replace(/^\n+/,"")),i){let s=Wn.indentComment(e(i),t);n.push(s.trimStart())}}ra.stringifyCollection=Yf});var _e=v(xr=>{"use strict";var Hf=Cr(),Vf=br(),Gf=Rn(),xe=_(),Kn=Ee(),zf=j();function $t(t,e){let n=xe.isScalar(e)?e.value:e;for(let i of t)if(xe.isPair(i)&&(i.key===e||i.key===n||xe.isScalar(i.key)&&i.key.value===n))return i}var Er=class extends Gf.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(xe.MAP,e),this.items=[]}static from(e,n,i){let{keepUndefined:r,replacer:s}=i,o=new this(e),a=(c,l)=>{if(typeof s=="function")l=s.call(n,c,l);else if(Array.isArray(s)&&!s.includes(c))return;(l!==void 0||r)&&o.items.push(Kn.createPair(c,l,i))};if(n instanceof Map)for(let[c,l]of n)a(c,l);else if(n&&typeof n=="object")for(let c of Object.keys(n))a(c,n[c]);return typeof e.sortMapEntries=="function"&&o.items.sort(e.sortMapEntries),o}add(e,n){let i;xe.isPair(e)?i=e:!e||typeof e!="object"||!("key"in e)?i=new Kn.Pair(e,e?.value):i=new Kn.Pair(e.key,e.value);let r=$t(this.items,i.key),s=this.schema?.sortMapEntries;if(r){if(!n)throw new Error(`Key ${i.key} already set`);xe.isScalar(r.value)&&zf.isScalarValue(i.value)?r.value.value=i.value:r.value=i.value}else if(s){let o=this.items.findIndex(a=>s(i,a)<0);o===-1?this.items.push(i):this.items.splice(o,0,i)}else this.items.push(i)}delete(e){let n=$t(this.items,e);return n?this.items.splice(this.items.indexOf(n),1).length>0:!1}get(e,n){let r=$t(this.items,e)?.value;return(!n&&xe.isScalar(r)?r.value:r)??void 0}has(e){return!!$t(this.items,e)}set(e,n){this.add(new Kn.Pair(e,n),!0)}toJSON(e,n,i){let r=i?new i:n?.mapAsMap?new Map:{};n?.onCreate&&n.onCreate(r);for(let s of this.items)Vf.addPairToJSMap(n,r,s);return r}toString(e,n,i){if(!e)return JSON.stringify(this);for(let r of this.items)if(!xe.isPair(r))throw new Error(`Map items must all be pairs; found ${JSON.stringify(r)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),Hf.stringifyCollection(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:i,onComment:n})}};xr.YAMLMap=Er;xr.findPair=$t});var ot=v(oa=>{"use strict";var Qf=_(),sa=_e(),Xf={collection:"map",default:!0,nodeClass:sa.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(t,e){return Qf.isMap(t)||e("Expected a mapping for this tag"),t},createNode:(t,e,n)=>sa.YAMLMap.from(t,e,n)};oa.map=Xf});var Pe=v(aa=>{"use strict";var Zf=Ot(),ed=Cr(),td=Rn(),Jn=_(),nd=j(),id=ke(),_r=class extends td.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(Jn.SEQ,e),this.items=[]}add(e){this.items.push(e)}delete(e){let n=Yn(e);return typeof n!="number"?!1:this.items.splice(n,1).length>0}get(e,n){let i=Yn(e);if(typeof i!="number")return;let r=this.items[i];return!n&&Jn.isScalar(r)?r.value:r}has(e){let n=Yn(e);return typeof n=="number"&&n=0?e:null}aa.YAMLSeq=_r});var at=v(la=>{"use strict";var rd=_(),ca=Pe(),sd={collection:"seq",default:!0,nodeClass:ca.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(t,e){return rd.isSeq(t)||e("Expected a sequence for this tag"),t},createNode:(t,e,n)=>ca.YAMLSeq.from(t,e,n)};la.seq=sd});var Lt=v(ua=>{"use strict";var od=It(),ad={identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify(t,e,n,i){return e=Object.assign({actualString:!0},e),od.stringifyString(t,e,n,i)}};ua.string=ad});var Un=v(pa=>{"use strict";var fa=j(),da={identify:t=>t==null,createNode:()=>new fa.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new fa.Scalar(null),stringify:({source:t},e)=>typeof t=="string"&&da.test.test(t)?t:e.options.nullStr};pa.nullTag=da});var Pr=v(ha=>{"use strict";var cd=j(),ma={identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:t=>new cd.Scalar(t[0]==="t"||t[0]==="T"),stringify({source:t,value:e},n){if(t&&ma.test.test(t)){let i=t[0]==="t"||t[0]==="T";if(e===i)return t}return e?n.options.trueStr:n.options.falseStr}};ha.boolTag=ma});var ct=v(ga=>{"use strict";function ld({format:t,minFractionDigits:e,tag:n,value:i}){if(typeof i=="bigint")return String(i);let r=typeof i=="number"?i:Number(i);if(!isFinite(r))return isNaN(r)?".nan":r<0?"-.inf":".inf";let s=Object.is(i,-0)?"-0":JSON.stringify(i);if(!t&&e&&(!n||n==="tag:yaml.org,2002:float")&&/^-?\d/.test(s)&&!s.includes("e")){let o=s.indexOf(".");o<0&&(o=s.length,s+=".");let a=e-(s.length-o-1);for(;a-- >0;)s+="0"}return s}ga.stringifyNumber=ld});var Or=v(Hn=>{"use strict";var ud=j(),Rr=ct(),fd={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:t=>t.slice(-3).toLowerCase()==="nan"?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Rr.stringifyNumber},dd={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t),stringify(t){let e=Number(t.value);return isFinite(e)?e.toExponential():Rr.stringifyNumber(t)}},pd={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(t){let e=new ud.Scalar(parseFloat(t)),n=t.indexOf(".");return n!==-1&&t[t.length-1]==="0"&&(e.minFractionDigits=t.length-n-1),e},stringify:Rr.stringifyNumber};Hn.float=pd;Hn.floatExp=dd;Hn.floatNaN=fd});var Ar=v(Gn=>{"use strict";var wa=ct(),Vn=t=>typeof t=="bigint"||Number.isInteger(t),Nr=(t,e,n,{intAsBigInt:i})=>i?BigInt(t):parseInt(t.substring(e),n);function ya(t,e,n){let{value:i}=t;return Vn(i)&&i>=0?n+i.toString(e):wa.stringifyNumber(t)}var md={identify:t=>Vn(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(t,e,n)=>Nr(t,2,8,n),stringify:t=>ya(t,8,"0o")},hd={identify:Vn,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(t,e,n)=>Nr(t,0,10,n),stringify:wa.stringifyNumber},gd={identify:t=>Vn(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(t,e,n)=>Nr(t,2,16,n),stringify:t=>ya(t,16,"0x")};Gn.int=hd;Gn.intHex=gd;Gn.intOct=md});var ka=v(va=>{"use strict";var wd=ot(),yd=Un(),vd=at(),kd=Lt(),bd=Pr(),jr=Or(),Ir=Ar(),Sd=[wd.map,vd.seq,kd.string,yd.nullTag,bd.boolTag,Ir.intOct,Ir.int,Ir.intHex,jr.floatNaN,jr.floatExp,jr.float];va.schema=Sd});var Ca=v(Sa=>{"use strict";var Cd=j(),Ed=ot(),xd=at();function ba(t){return typeof t=="bigint"||Number.isInteger(t)}var zn=({value:t})=>JSON.stringify(t),_d=[{identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify:zn},{identify:t=>t==null,createNode:()=>new Cd.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:zn},{identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:t=>t==="true",stringify:zn},{identify:ba,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(t,e,{intAsBigInt:n})=>n?BigInt(t):parseInt(t,10),stringify:({value:t})=>ba(t)?t.toString():JSON.stringify(t)},{identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:t=>parseFloat(t),stringify:zn}],Pd={default:!0,tag:"",test:/^/,resolve(t,e){return e(`Unresolved plain scalar ${JSON.stringify(t)}`),t}},Rd=[Ed.map,xd.seq].concat(_d,Pd);Sa.schema=Rd});var qr=v(Ea=>{"use strict";var Dt=vn("buffer"),Tr=j(),Od=It(),Nd={identify:t=>t instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(t,e){if(typeof Dt.Buffer=="function")return Dt.Buffer.from(t,"base64");if(typeof atob=="function"){let n=atob(t.replace(/[\n\r]/g,"")),i=new Uint8Array(n.length);for(let r=0;r{"use strict";var Qn=_(),$r=Ee(),Ad=j(),jd=Pe();function xa(t,e){if(Qn.isSeq(t))for(let n=0;n1&&e("Each pair must have its own sequence indicator");let r=i.items[0]||new $r.Pair(new Ad.Scalar(null));if(i.commentBefore&&(r.key.commentBefore=r.key.commentBefore?`${i.commentBefore} +${r}${h}`}else return`${d}${o}${f.join(" ")}${o}${h}`}function Bn({indent:t,options:{commentString:e}},n,i,r){if(i&&r&&(i=i.replace(/^\n+/,"")),i){let s=Wn.indentComment(e(i),t);n.push(s.trimStart())}}ra.stringifyCollection=Jf});var Pe=v(Pr=>{"use strict";var Vf=Er(),Gf=Sr(),zf=Rn(),xe=P(),Kn=Ee(),Qf=j();function $t(t,e){let n=xe.isScalar(e)?e.value:e;for(let i of t)if(xe.isPair(i)&&(i.key===e||i.key===n||xe.isScalar(i.key)&&i.key.value===n))return i}var xr=class extends zf.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(xe.MAP,e),this.items=[]}static from(e,n,i){let{keepUndefined:r,replacer:s}=i,o=new this(e),a=(c,l)=>{if(typeof s=="function")l=s.call(n,c,l);else if(Array.isArray(s)&&!s.includes(c))return;(l!==void 0||r)&&o.items.push(Kn.createPair(c,l,i))};if(n instanceof Map)for(let[c,l]of n)a(c,l);else if(n&&typeof n=="object")for(let c of Object.keys(n))a(c,n[c]);return typeof e.sortMapEntries=="function"&&o.items.sort(e.sortMapEntries),o}add(e,n){let i;xe.isPair(e)?i=e:!e||typeof e!="object"||!("key"in e)?i=new Kn.Pair(e,e?.value):i=new Kn.Pair(e.key,e.value);let r=$t(this.items,i.key),s=this.schema?.sortMapEntries;if(r){if(!n)throw new Error(`Key ${i.key} already set`);xe.isScalar(r.value)&&Qf.isScalarValue(i.value)?r.value.value=i.value:r.value=i.value}else if(s){let o=this.items.findIndex(a=>s(i,a)<0);o===-1?this.items.push(i):this.items.splice(o,0,i)}else this.items.push(i)}delete(e){let n=$t(this.items,e);return n?this.items.splice(this.items.indexOf(n),1).length>0:!1}get(e,n){let r=$t(this.items,e)?.value;return(!n&&xe.isScalar(r)?r.value:r)??void 0}has(e){return!!$t(this.items,e)}set(e,n){this.add(new Kn.Pair(e,n),!0)}toJSON(e,n,i){let r=i?new i:n?.mapAsMap?new Map:{};n?.onCreate&&n.onCreate(r);for(let s of this.items)Gf.addPairToJSMap(n,r,s);return r}toString(e,n,i){if(!e)return JSON.stringify(this);for(let r of this.items)if(!xe.isPair(r))throw new Error(`Map items must all be pairs; found ${JSON.stringify(r)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),Vf.stringifyCollection(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:i,onComment:n})}};Pr.YAMLMap=xr;Pr.findPair=$t});var ot=v(oa=>{"use strict";var Xf=P(),sa=Pe(),Zf={collection:"map",default:!0,nodeClass:sa.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(t,e){return Xf.isMap(t)||e("Expected a mapping for this tag"),t},createNode:(t,e,n)=>sa.YAMLMap.from(t,e,n)};oa.map=Zf});var _e=v(aa=>{"use strict";var ed=Ot(),td=Er(),nd=Rn(),Jn=P(),id=j(),rd=ke(),_r=class extends nd.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(Jn.SEQ,e),this.items=[]}add(e){this.items.push(e)}delete(e){let n=Yn(e);return typeof n!="number"?!1:this.items.splice(n,1).length>0}get(e,n){let i=Yn(e);if(typeof i!="number")return;let r=this.items[i];return!n&&Jn.isScalar(r)?r.value:r}has(e){let n=Yn(e);return typeof n=="number"&&n=0?e:null}aa.YAMLSeq=_r});var at=v(la=>{"use strict";var sd=P(),ca=_e(),od={collection:"seq",default:!0,nodeClass:ca.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(t,e){return sd.isSeq(t)||e("Expected a sequence for this tag"),t},createNode:(t,e,n)=>ca.YAMLSeq.from(t,e,n)};la.seq=od});var Lt=v(ua=>{"use strict";var ad=It(),cd={identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify(t,e,n,i){return e=Object.assign({actualString:!0},e),ad.stringifyString(t,e,n,i)}};ua.string=cd});var Un=v(pa=>{"use strict";var fa=j(),da={identify:t=>t==null,createNode:()=>new fa.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new fa.Scalar(null),stringify:({source:t},e)=>typeof t=="string"&&da.test.test(t)?t:e.options.nullStr};pa.nullTag=da});var Rr=v(ha=>{"use strict";var ld=j(),ma={identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:t=>new ld.Scalar(t[0]==="t"||t[0]==="T"),stringify({source:t,value:e},n){if(t&&ma.test.test(t)){let i=t[0]==="t"||t[0]==="T";if(e===i)return t}return e?n.options.trueStr:n.options.falseStr}};ha.boolTag=ma});var ct=v(ga=>{"use strict";function ud({format:t,minFractionDigits:e,tag:n,value:i}){if(typeof i=="bigint")return String(i);let r=typeof i=="number"?i:Number(i);if(!isFinite(r))return isNaN(r)?".nan":r<0?"-.inf":".inf";let s=Object.is(i,-0)?"-0":JSON.stringify(i);if(!t&&e&&(!n||n==="tag:yaml.org,2002:float")&&/^-?\d/.test(s)&&!s.includes("e")){let o=s.indexOf(".");o<0&&(o=s.length,s+=".");let a=e-(s.length-o-1);for(;a-- >0;)s+="0"}return s}ga.stringifyNumber=ud});var Nr=v(Hn=>{"use strict";var fd=j(),Or=ct(),dd={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:t=>t.slice(-3).toLowerCase()==="nan"?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Or.stringifyNumber},pd={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t),stringify(t){let e=Number(t.value);return isFinite(e)?e.toExponential():Or.stringifyNumber(t)}},md={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(t){let e=new fd.Scalar(parseFloat(t)),n=t.indexOf(".");return n!==-1&&t[t.length-1]==="0"&&(e.minFractionDigits=t.length-n-1),e},stringify:Or.stringifyNumber};Hn.float=md;Hn.floatExp=pd;Hn.floatNaN=dd});var jr=v(Gn=>{"use strict";var wa=ct(),Vn=t=>typeof t=="bigint"||Number.isInteger(t),Ar=(t,e,n,{intAsBigInt:i})=>i?BigInt(t):parseInt(t.substring(e),n);function ya(t,e,n){let{value:i}=t;return Vn(i)&&i>=0?n+i.toString(e):wa.stringifyNumber(t)}var hd={identify:t=>Vn(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(t,e,n)=>Ar(t,2,8,n),stringify:t=>ya(t,8,"0o")},gd={identify:Vn,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(t,e,n)=>Ar(t,0,10,n),stringify:wa.stringifyNumber},wd={identify:t=>Vn(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(t,e,n)=>Ar(t,2,16,n),stringify:t=>ya(t,16,"0x")};Gn.int=gd;Gn.intHex=wd;Gn.intOct=hd});var ka=v(va=>{"use strict";var yd=ot(),vd=Un(),kd=at(),bd=Lt(),Sd=Rr(),Ir=Nr(),Tr=jr(),Cd=[yd.map,kd.seq,bd.string,vd.nullTag,Sd.boolTag,Tr.intOct,Tr.int,Tr.intHex,Ir.floatNaN,Ir.floatExp,Ir.float];va.schema=Cd});var Ca=v(Sa=>{"use strict";var Ed=j(),xd=ot(),Pd=at();function ba(t){return typeof t=="bigint"||Number.isInteger(t)}var zn=({value:t})=>JSON.stringify(t),_d=[{identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify:zn},{identify:t=>t==null,createNode:()=>new Ed.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:zn},{identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:t=>t==="true",stringify:zn},{identify:ba,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(t,e,{intAsBigInt:n})=>n?BigInt(t):parseInt(t,10),stringify:({value:t})=>ba(t)?t.toString():JSON.stringify(t)},{identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:t=>parseFloat(t),stringify:zn}],Rd={default:!0,tag:"",test:/^/,resolve(t,e){return e(`Unresolved plain scalar ${JSON.stringify(t)}`),t}},Od=[xd.map,Pd.seq].concat(_d,Rd);Sa.schema=Od});var $r=v(Ea=>{"use strict";var Dt=vn("buffer"),qr=j(),Nd=It(),Ad={identify:t=>t instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(t,e){if(typeof Dt.Buffer=="function")return Dt.Buffer.from(t,"base64");if(typeof atob=="function"){let n=atob(t.replace(/[\n\r]/g,"")),i=new Uint8Array(n.length);for(let r=0;r{"use strict";var Qn=P(),Lr=Ee(),jd=j(),Id=_e();function xa(t,e){if(Qn.isSeq(t))for(let n=0;n1&&e("Each pair must have its own sequence indicator");let r=i.items[0]||new Lr.Pair(new jd.Scalar(null));if(i.commentBefore&&(r.key.commentBefore=r.key.commentBefore?`${i.commentBefore} ${r.key.commentBefore}`:i.commentBefore),i.comment){let s=r.value??r.key;s.comment=s.comment?`${i.comment} -${s.comment}`:i.comment}i=r}t.items[n]=Qn.isPair(i)?i:new $r.Pair(i)}}else e("Expected a sequence for this tag");return t}function _a(t,e,n){let{replacer:i}=n,r=new jd.YAMLSeq(t);r.tag="tag:yaml.org,2002:pairs";let s=0;if(e&&Symbol.iterator in Object(e))for(let o of e){typeof i=="function"&&(o=i.call(e,String(s++),o));let a,c;if(Array.isArray(o))if(o.length===2)a=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)a=l[0],c=o[a];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else a=o;r.items.push($r.createPair(a,c,n))}return r}var Id={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:xa,createNode:_a};Xn.createPairs=_a;Xn.pairs=Id;Xn.resolvePairs=xa});var Fr=v(Dr=>{"use strict";var Pa=_(),Lr=ke(),Ft=_e(),Td=Pe(),Ra=Zn(),Je=class t extends Td.YAMLSeq{constructor(){super(),this.add=Ft.YAMLMap.prototype.add.bind(this),this.delete=Ft.YAMLMap.prototype.delete.bind(this),this.get=Ft.YAMLMap.prototype.get.bind(this),this.has=Ft.YAMLMap.prototype.has.bind(this),this.set=Ft.YAMLMap.prototype.set.bind(this),this.tag=t.tag}toJSON(e,n){if(!n)return super.toJSON(e);let i=new Map;n?.onCreate&&n.onCreate(i);for(let r of this.items){let s,o;if(Pa.isPair(r)?(s=Lr.toJS(r.key,"",n),o=Lr.toJS(r.value,s,n)):s=Lr.toJS(r,"",n),i.has(s))throw new Error("Ordered maps must not include duplicate keys");i.set(s,o)}return i}static from(e,n,i){let r=Ra.createPairs(e,n,i),s=new this;return s.items=r.items,s}};Je.tag="tag:yaml.org,2002:omap";var qd={collection:"seq",identify:t=>t instanceof Map,nodeClass:Je,default:!1,tag:"tag:yaml.org,2002:omap",resolve(t,e){let n=Ra.resolvePairs(t,e),i=[];for(let{key:r}of n.items)Pa.isScalar(r)&&(i.includes(r.value)?e(`Ordered maps must not include duplicate keys: ${r.value}`):i.push(r.value));return Object.assign(new Je,n)},createNode:(t,e,n)=>Je.from(t,e,n)};Dr.YAMLOMap=Je;Dr.omap=qd});var Ia=v(Mr=>{"use strict";var Oa=j();function Na({value:t,source:e},n){return e&&(t?Aa:ja).test.test(e)?e:t?n.options.trueStr:n.options.falseStr}var Aa={identify:t=>t===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new Oa.Scalar(!0),stringify:Na},ja={identify:t=>t===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new Oa.Scalar(!1),stringify:Na};Mr.falseTag=ja;Mr.trueTag=Aa});var Ta=v(ei=>{"use strict";var $d=j(),Wr=ct(),Ld={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:t=>t.slice(-3).toLowerCase()==="nan"?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Wr.stringifyNumber},Dd={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t.replace(/_/g,"")),stringify(t){let e=Number(t.value);return isFinite(e)?e.toExponential():Wr.stringifyNumber(t)}},Fd={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(t){let e=new $d.Scalar(parseFloat(t.replace(/_/g,""))),n=t.indexOf(".");if(n!==-1){let i=t.substring(n+1).replace(/_/g,"");i[i.length-1]==="0"&&(e.minFractionDigits=i.length)}return e},stringify:Wr.stringifyNumber};ei.float=Fd;ei.floatExp=Dd;ei.floatNaN=Ld});var $a=v(Wt=>{"use strict";var qa=ct(),Mt=t=>typeof t=="bigint"||Number.isInteger(t);function ti(t,e,n,{intAsBigInt:i}){let r=t[0];if((r==="-"||r==="+")&&(e+=1),t=t.substring(e).replace(/_/g,""),i){switch(n){case 2:t=`0b${t}`;break;case 8:t=`0o${t}`;break;case 16:t=`0x${t}`;break}let o=BigInt(t);return r==="-"?BigInt(-1)*o:o}let s=parseInt(t,n);return r==="-"?-1*s:s}function Br(t,e,n){let{value:i}=t;if(Mt(i)){let r=i.toString(e);return i<0?"-"+n+r.substr(1):n+r}return qa.stringifyNumber(t)}var Md={identify:Mt,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(t,e,n)=>ti(t,2,2,n),stringify:t=>Br(t,2,"0b")},Wd={identify:Mt,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(t,e,n)=>ti(t,1,8,n),stringify:t=>Br(t,8,"0")},Bd={identify:Mt,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(t,e,n)=>ti(t,0,10,n),stringify:qa.stringifyNumber},Kd={identify:Mt,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(t,e,n)=>ti(t,2,16,n),stringify:t=>Br(t,16,"0x")};Wt.int=Bd;Wt.intBin=Md;Wt.intHex=Kd;Wt.intOct=Wd});var Yr=v(Kr=>{"use strict";var ri=_(),ni=Ee(),ii=_e(),Ue=class t extends ii.YAMLMap{constructor(e){super(e),this.tag=t.tag}add(e){let n;ri.isPair(e)?n=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?n=new ni.Pair(e.key,null):n=new ni.Pair(e,null),ii.findPair(this.items,n.key)||this.items.push(n)}get(e,n){let i=ii.findPair(this.items,e);return!n&&ri.isPair(i)?ri.isScalar(i.key)?i.key.value:i.key:i}set(e,n){if(typeof n!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof n}`);let i=ii.findPair(this.items,e);i&&!n?this.items.splice(this.items.indexOf(i),1):!i&&n&&this.items.push(new ni.Pair(e))}toJSON(e,n){return super.toJSON(e,n,Set)}toString(e,n,i){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),n,i);throw new Error("Set items must all have null values")}static from(e,n,i){let{replacer:r}=i,s=new this(e);if(n&&Symbol.iterator in Object(n))for(let o of n)typeof r=="function"&&(o=r.call(n,o,o)),s.items.push(ni.createPair(o,null,i));return s}};Ue.tag="tag:yaml.org,2002:set";var Yd={collection:"map",identify:t=>t instanceof Set,nodeClass:Ue,default:!1,tag:"tag:yaml.org,2002:set",createNode:(t,e,n)=>Ue.from(t,e,n),resolve(t,e){if(ri.isMap(t)){if(t.hasAllNullValues(!0))return Object.assign(new Ue,t);e("Set items must all have null values")}else e("Expected a mapping for this tag");return t}};Kr.YAMLSet=Ue;Kr.set=Yd});var Ur=v(si=>{"use strict";var Jd=ct();function Jr(t,e){let n=t[0],i=n==="-"||n==="+"?t.substring(1):t,r=o=>e?BigInt(o):Number(o),s=i.replace(/_/g,"").split(":").reduce((o,a)=>o*r(60)+r(a),r(0));return n==="-"?r(-1)*s:s}function La(t){let{value:e}=t,n=o=>o;if(typeof e=="bigint")n=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return Jd.stringifyNumber(t);let i="";e<0&&(i="-",e*=n(-1));let r=n(60),s=[e%r];return e<60?s.unshift(0):(e=(e-s[0])/r,s.unshift(e%r),e>=60&&(e=(e-s[0])/r,s.unshift(e))),i+s.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var Ud={identify:t=>typeof t=="bigint"||Number.isInteger(t),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(t,e,{intAsBigInt:n})=>Jr(t,n),stringify:La},Hd={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:t=>Jr(t,!1),stringify:La},Da={identify:t=>t instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(t){let e=t.match(Da.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,n,i,r,s,o,a]=e.map(Number),c=e[7]?Number((e[7]+"00").substr(1,3)):0,l=Date.UTC(n,i-1,r,s||0,o||0,a||0,c),u=e[8];if(u&&u!=="Z"){let f=Jr(u,!1);Math.abs(f)<30&&(f*=60),l-=6e4*f}return new Date(l)},stringify:({value:t})=>t?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};si.floatTime=Hd;si.intTime=Ud;si.timestamp=Da});var Wa=v(Ma=>{"use strict";var Vd=ot(),Gd=Un(),zd=at(),Qd=Lt(),Xd=qr(),Fa=Ia(),Hr=Ta(),oi=$a(),Zd=Dn(),ep=Fr(),tp=Zn(),np=Yr(),Vr=Ur(),ip=[Vd.map,zd.seq,Qd.string,Gd.nullTag,Fa.trueTag,Fa.falseTag,oi.intBin,oi.intOct,oi.int,oi.intHex,Hr.floatNaN,Hr.floatExp,Hr.float,Xd.binary,Zd.merge,ep.omap,tp.pairs,np.set,Vr.intTime,Vr.floatTime,Vr.timestamp];Ma.schema=ip});var Qa=v(Qr=>{"use strict";var Ja=ot(),rp=Un(),Ua=at(),sp=Lt(),op=Pr(),Gr=Or(),zr=Ar(),ap=ka(),cp=Ca(),Ha=qr(),Bt=Dn(),Va=Fr(),Ga=Zn(),Ba=Wa(),za=Yr(),ai=Ur(),Ka=new Map([["core",ap.schema],["failsafe",[Ja.map,Ua.seq,sp.string]],["json",cp.schema],["yaml11",Ba.schema],["yaml-1.1",Ba.schema]]),Ya={binary:Ha.binary,bool:op.boolTag,float:Gr.float,floatExp:Gr.floatExp,floatNaN:Gr.floatNaN,floatTime:ai.floatTime,int:zr.int,intHex:zr.intHex,intOct:zr.intOct,intTime:ai.intTime,map:Ja.map,merge:Bt.merge,null:rp.nullTag,omap:Va.omap,pairs:Ga.pairs,seq:Ua.seq,set:za.set,timestamp:ai.timestamp},lp={"tag:yaml.org,2002:binary":Ha.binary,"tag:yaml.org,2002:merge":Bt.merge,"tag:yaml.org,2002:omap":Va.omap,"tag:yaml.org,2002:pairs":Ga.pairs,"tag:yaml.org,2002:set":za.set,"tag:yaml.org,2002:timestamp":ai.timestamp};function up(t,e,n){let i=Ka.get(e);if(i&&!t)return n&&!i.includes(Bt.merge)?i.concat(Bt.merge):i.slice();let r=i;if(!r)if(Array.isArray(t))r=[];else{let s=Array.from(Ka.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${e}"; use one of ${s} or define customTags array`)}if(Array.isArray(t))for(let s of t)r=r.concat(s);else typeof t=="function"&&(r=t(r.slice()));return n&&(r=r.concat(Bt.merge)),r.reduce((s,o)=>{let a=typeof o=="string"?Ya[o]:o;if(!a){let c=JSON.stringify(o),l=Object.keys(Ya).map(u=>JSON.stringify(u)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return s.includes(a)||s.push(a),s},[])}Qr.coreKnownTags=lp;Qr.getTags=up});var es=v(Xa=>{"use strict";var Xr=_(),fp=ot(),dp=at(),pp=Lt(),ci=Qa(),mp=(t,e)=>t.keye.key?1:0,Zr=class t{constructor({compat:e,customTags:n,merge:i,resolveKnownTags:r,schema:s,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?ci.getTags(e,"compat"):e?ci.getTags(null,e):null,this.name=typeof s=="string"&&s||"core",this.knownTags=r?ci.coreKnownTags:{},this.tags=ci.getTags(n,this.name,i),this.toStringOptions=a??null,Object.defineProperty(this,Xr.MAP,{value:fp.map}),Object.defineProperty(this,Xr.SCALAR,{value:pp.string}),Object.defineProperty(this,Xr.SEQ,{value:dp.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?mp:null}clone(){let e=Object.create(t.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};Xa.Schema=Zr});var ec=v(Za=>{"use strict";var hp=_(),ts=Tt(),Kt=Nt();function gp(t,e){let n=[],i=e.directives===!0;if(e.directives!==!1&&t.directives){let c=t.directives.toString(t);c?(n.push(c),i=!0):t.directives.docStart&&(i=!0)}i&&n.push("---");let r=ts.createStringifyContext(t,e),{commentString:s}=r.options;if(t.commentBefore){n.length!==1&&n.unshift("");let c=s(t.commentBefore);n.unshift(Kt.indentComment(c,""))}let o=!1,a=null;if(t.contents){if(hp.isNode(t.contents)){if(t.contents.spaceBefore&&i&&n.push(""),t.contents.commentBefore){let u=s(t.contents.commentBefore);n.push(Kt.indentComment(u,""))}r.forceBlockIndent=!!t.comment,a=t.contents.comment}let c=a?void 0:()=>o=!0,l=ts.stringify(t.contents,r,()=>a=null,c);a&&(l+=Kt.lineComment(l,"",s(a))),(l[0]==="|"||l[0]===">")&&n[n.length-1]==="---"?n[n.length-1]=`--- ${l}`:n.push(l)}else n.push(ts.stringify(t.contents,r));if(t.directives?.docEnd)if(t.comment){let c=s(t.comment);c.includes(` +${s.comment}`:i.comment}i=r}t.items[n]=Qn.isPair(i)?i:new Lr.Pair(i)}}else e("Expected a sequence for this tag");return t}function Pa(t,e,n){let{replacer:i}=n,r=new Id.YAMLSeq(t);r.tag="tag:yaml.org,2002:pairs";let s=0;if(e&&Symbol.iterator in Object(e))for(let o of e){typeof i=="function"&&(o=i.call(e,String(s++),o));let a,c;if(Array.isArray(o))if(o.length===2)a=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)a=l[0],c=o[a];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else a=o;r.items.push(Lr.createPair(a,c,n))}return r}var Td={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:xa,createNode:Pa};Xn.createPairs=Pa;Xn.pairs=Td;Xn.resolvePairs=xa});var Mr=v(Fr=>{"use strict";var _a=P(),Dr=ke(),Ft=Pe(),qd=_e(),Ra=Zn(),Ue=class t extends qd.YAMLSeq{constructor(){super(),this.add=Ft.YAMLMap.prototype.add.bind(this),this.delete=Ft.YAMLMap.prototype.delete.bind(this),this.get=Ft.YAMLMap.prototype.get.bind(this),this.has=Ft.YAMLMap.prototype.has.bind(this),this.set=Ft.YAMLMap.prototype.set.bind(this),this.tag=t.tag}toJSON(e,n){if(!n)return super.toJSON(e);let i=new Map;n?.onCreate&&n.onCreate(i);for(let r of this.items){let s,o;if(_a.isPair(r)?(s=Dr.toJS(r.key,"",n),o=Dr.toJS(r.value,s,n)):s=Dr.toJS(r,"",n),i.has(s))throw new Error("Ordered maps must not include duplicate keys");i.set(s,o)}return i}static from(e,n,i){let r=Ra.createPairs(e,n,i),s=new this;return s.items=r.items,s}};Ue.tag="tag:yaml.org,2002:omap";var $d={collection:"seq",identify:t=>t instanceof Map,nodeClass:Ue,default:!1,tag:"tag:yaml.org,2002:omap",resolve(t,e){let n=Ra.resolvePairs(t,e),i=[];for(let{key:r}of n.items)_a.isScalar(r)&&(i.includes(r.value)?e(`Ordered maps must not include duplicate keys: ${r.value}`):i.push(r.value));return Object.assign(new Ue,n)},createNode:(t,e,n)=>Ue.from(t,e,n)};Fr.YAMLOMap=Ue;Fr.omap=$d});var Ia=v(Wr=>{"use strict";var Oa=j();function Na({value:t,source:e},n){return e&&(t?Aa:ja).test.test(e)?e:t?n.options.trueStr:n.options.falseStr}var Aa={identify:t=>t===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new Oa.Scalar(!0),stringify:Na},ja={identify:t=>t===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new Oa.Scalar(!1),stringify:Na};Wr.falseTag=ja;Wr.trueTag=Aa});var Ta=v(ei=>{"use strict";var Ld=j(),Br=ct(),Dd={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:t=>t.slice(-3).toLowerCase()==="nan"?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Br.stringifyNumber},Fd={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t.replace(/_/g,"")),stringify(t){let e=Number(t.value);return isFinite(e)?e.toExponential():Br.stringifyNumber(t)}},Md={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(t){let e=new Ld.Scalar(parseFloat(t.replace(/_/g,""))),n=t.indexOf(".");if(n!==-1){let i=t.substring(n+1).replace(/_/g,"");i[i.length-1]==="0"&&(e.minFractionDigits=i.length)}return e},stringify:Br.stringifyNumber};ei.float=Md;ei.floatExp=Fd;ei.floatNaN=Dd});var $a=v(Wt=>{"use strict";var qa=ct(),Mt=t=>typeof t=="bigint"||Number.isInteger(t);function ti(t,e,n,{intAsBigInt:i}){let r=t[0];if((r==="-"||r==="+")&&(e+=1),t=t.substring(e).replace(/_/g,""),i){switch(n){case 2:t=`0b${t}`;break;case 8:t=`0o${t}`;break;case 16:t=`0x${t}`;break}let o=BigInt(t);return r==="-"?BigInt(-1)*o:o}let s=parseInt(t,n);return r==="-"?-1*s:s}function Kr(t,e,n){let{value:i}=t;if(Mt(i)){let r=i.toString(e);return i<0?"-"+n+r.substr(1):n+r}return qa.stringifyNumber(t)}var Wd={identify:Mt,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(t,e,n)=>ti(t,2,2,n),stringify:t=>Kr(t,2,"0b")},Bd={identify:Mt,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(t,e,n)=>ti(t,1,8,n),stringify:t=>Kr(t,8,"0")},Kd={identify:Mt,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(t,e,n)=>ti(t,0,10,n),stringify:qa.stringifyNumber},Yd={identify:Mt,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(t,e,n)=>ti(t,2,16,n),stringify:t=>Kr(t,16,"0x")};Wt.int=Kd;Wt.intBin=Wd;Wt.intHex=Yd;Wt.intOct=Bd});var Jr=v(Yr=>{"use strict";var ri=P(),ni=Ee(),ii=Pe(),He=class t extends ii.YAMLMap{constructor(e){super(e),this.tag=t.tag}add(e){let n;ri.isPair(e)?n=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?n=new ni.Pair(e.key,null):n=new ni.Pair(e,null),ii.findPair(this.items,n.key)||this.items.push(n)}get(e,n){let i=ii.findPair(this.items,e);return!n&&ri.isPair(i)?ri.isScalar(i.key)?i.key.value:i.key:i}set(e,n){if(typeof n!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof n}`);let i=ii.findPair(this.items,e);i&&!n?this.items.splice(this.items.indexOf(i),1):!i&&n&&this.items.push(new ni.Pair(e))}toJSON(e,n){return super.toJSON(e,n,Set)}toString(e,n,i){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),n,i);throw new Error("Set items must all have null values")}static from(e,n,i){let{replacer:r}=i,s=new this(e);if(n&&Symbol.iterator in Object(n))for(let o of n)typeof r=="function"&&(o=r.call(n,o,o)),s.items.push(ni.createPair(o,null,i));return s}};He.tag="tag:yaml.org,2002:set";var Jd={collection:"map",identify:t=>t instanceof Set,nodeClass:He,default:!1,tag:"tag:yaml.org,2002:set",createNode:(t,e,n)=>He.from(t,e,n),resolve(t,e){if(ri.isMap(t)){if(t.hasAllNullValues(!0))return Object.assign(new He,t);e("Set items must all have null values")}else e("Expected a mapping for this tag");return t}};Yr.YAMLSet=He;Yr.set=Jd});var Hr=v(si=>{"use strict";var Ud=ct();function Ur(t,e){let n=t[0],i=n==="-"||n==="+"?t.substring(1):t,r=o=>e?BigInt(o):Number(o),s=i.replace(/_/g,"").split(":").reduce((o,a)=>o*r(60)+r(a),r(0));return n==="-"?r(-1)*s:s}function La(t){let{value:e}=t,n=o=>o;if(typeof e=="bigint")n=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return Ud.stringifyNumber(t);let i="";e<0&&(i="-",e*=n(-1));let r=n(60),s=[e%r];return e<60?s.unshift(0):(e=(e-s[0])/r,s.unshift(e%r),e>=60&&(e=(e-s[0])/r,s.unshift(e))),i+s.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var Hd={identify:t=>typeof t=="bigint"||Number.isInteger(t),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(t,e,{intAsBigInt:n})=>Ur(t,n),stringify:La},Vd={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:t=>Ur(t,!1),stringify:La},Da={identify:t=>t instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(t){let e=t.match(Da.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,n,i,r,s,o,a]=e.map(Number),c=e[7]?Number((e[7]+"00").substr(1,3)):0,l=Date.UTC(n,i-1,r,s||0,o||0,a||0,c),u=e[8];if(u&&u!=="Z"){let f=Ur(u,!1);Math.abs(f)<30&&(f*=60),l-=6e4*f}return new Date(l)},stringify:({value:t})=>t?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};si.floatTime=Vd;si.intTime=Hd;si.timestamp=Da});var Wa=v(Ma=>{"use strict";var Gd=ot(),zd=Un(),Qd=at(),Xd=Lt(),Zd=$r(),Fa=Ia(),Vr=Ta(),oi=$a(),ep=Dn(),tp=Mr(),np=Zn(),ip=Jr(),Gr=Hr(),rp=[Gd.map,Qd.seq,Xd.string,zd.nullTag,Fa.trueTag,Fa.falseTag,oi.intBin,oi.intOct,oi.int,oi.intHex,Vr.floatNaN,Vr.floatExp,Vr.float,Zd.binary,ep.merge,tp.omap,np.pairs,ip.set,Gr.intTime,Gr.floatTime,Gr.timestamp];Ma.schema=rp});var Qa=v(Xr=>{"use strict";var Ja=ot(),sp=Un(),Ua=at(),op=Lt(),ap=Rr(),zr=Nr(),Qr=jr(),cp=ka(),lp=Ca(),Ha=$r(),Bt=Dn(),Va=Mr(),Ga=Zn(),Ba=Wa(),za=Jr(),ai=Hr(),Ka=new Map([["core",cp.schema],["failsafe",[Ja.map,Ua.seq,op.string]],["json",lp.schema],["yaml11",Ba.schema],["yaml-1.1",Ba.schema]]),Ya={binary:Ha.binary,bool:ap.boolTag,float:zr.float,floatExp:zr.floatExp,floatNaN:zr.floatNaN,floatTime:ai.floatTime,int:Qr.int,intHex:Qr.intHex,intOct:Qr.intOct,intTime:ai.intTime,map:Ja.map,merge:Bt.merge,null:sp.nullTag,omap:Va.omap,pairs:Ga.pairs,seq:Ua.seq,set:za.set,timestamp:ai.timestamp},up={"tag:yaml.org,2002:binary":Ha.binary,"tag:yaml.org,2002:merge":Bt.merge,"tag:yaml.org,2002:omap":Va.omap,"tag:yaml.org,2002:pairs":Ga.pairs,"tag:yaml.org,2002:set":za.set,"tag:yaml.org,2002:timestamp":ai.timestamp};function fp(t,e,n){let i=Ka.get(e);if(i&&!t)return n&&!i.includes(Bt.merge)?i.concat(Bt.merge):i.slice();let r=i;if(!r)if(Array.isArray(t))r=[];else{let s=Array.from(Ka.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${e}"; use one of ${s} or define customTags array`)}if(Array.isArray(t))for(let s of t)r=r.concat(s);else typeof t=="function"&&(r=t(r.slice()));return n&&(r=r.concat(Bt.merge)),r.reduce((s,o)=>{let a=typeof o=="string"?Ya[o]:o;if(!a){let c=JSON.stringify(o),l=Object.keys(Ya).map(u=>JSON.stringify(u)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return s.includes(a)||s.push(a),s},[])}Xr.coreKnownTags=up;Xr.getTags=fp});var ts=v(Xa=>{"use strict";var Zr=P(),dp=ot(),pp=at(),mp=Lt(),ci=Qa(),hp=(t,e)=>t.keye.key?1:0,es=class t{constructor({compat:e,customTags:n,merge:i,resolveKnownTags:r,schema:s,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?ci.getTags(e,"compat"):e?ci.getTags(null,e):null,this.name=typeof s=="string"&&s||"core",this.knownTags=r?ci.coreKnownTags:{},this.tags=ci.getTags(n,this.name,i),this.toStringOptions=a??null,Object.defineProperty(this,Zr.MAP,{value:dp.map}),Object.defineProperty(this,Zr.SCALAR,{value:mp.string}),Object.defineProperty(this,Zr.SEQ,{value:pp.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?hp:null}clone(){let e=Object.create(t.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};Xa.Schema=es});var ec=v(Za=>{"use strict";var gp=P(),ns=Tt(),Kt=Nt();function wp(t,e){let n=[],i=e.directives===!0;if(e.directives!==!1&&t.directives){let c=t.directives.toString(t);c?(n.push(c),i=!0):t.directives.docStart&&(i=!0)}i&&n.push("---");let r=ns.createStringifyContext(t,e),{commentString:s}=r.options;if(t.commentBefore){n.length!==1&&n.unshift("");let c=s(t.commentBefore);n.unshift(Kt.indentComment(c,""))}let o=!1,a=null;if(t.contents){if(gp.isNode(t.contents)){if(t.contents.spaceBefore&&i&&n.push(""),t.contents.commentBefore){let u=s(t.contents.commentBefore);n.push(Kt.indentComment(u,""))}r.forceBlockIndent=!!t.comment,a=t.contents.comment}let c=a?void 0:()=>o=!0,l=ns.stringify(t.contents,r,()=>a=null,c);a&&(l+=Kt.lineComment(l,"",s(a))),(l[0]==="|"||l[0]===">")&&n[n.length-1]==="---"?n[n.length-1]=`--- ${l}`:n.push(l)}else n.push(ns.stringify(t.contents,r));if(t.directives?.docEnd)if(t.comment){let c=s(t.comment);c.includes(` `)?(n.push("..."),n.push(Kt.indentComment(c,""))):n.push(`... ${c}`)}else n.push("...");else{let c=t.comment;c&&o&&(c=c.replace(/^\n+/,"")),c&&((!o||a)&&n[n.length-1]!==""&&n.push(""),n.push(Kt.indentComment(s(c),"")))}return n.join(` `)+` -`}Za.stringifyDocument=gp});var Yt=v(tc=>{"use strict";var wp=Rt(),lt=Rn(),Q=_(),yp=Ee(),vp=ke(),kp=es(),bp=ec(),ns=En(),Sp=or(),Cp=Ot(),is=sr(),rs=class t{constructor(e,n,i){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,Q.NODE_TYPE,{value:Q.DOC});let r=null;typeof n=="function"||Array.isArray(n)?r=n:i===void 0&&n&&(i=n,n=void 0);let s=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},i);this.options=s;let{version:o}=s;i?._directives?(this.directives=i._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new is.Directives({version:o}),this.setSchema(o,i),this.contents=e===void 0?null:this.createNode(e,r,i)}clone(){let e=Object.create(t.prototype,{[Q.NODE_TYPE]:{value:Q.DOC}});return e.commentBefore=this.commentBefore,e.comment=this.comment,e.errors=this.errors.slice(),e.warnings=this.warnings.slice(),e.options=Object.assign({},this.options),this.directives&&(e.directives=this.directives.clone()),e.schema=this.schema.clone(),e.contents=Q.isNode(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){ut(this.contents)&&this.contents.add(e)}addIn(e,n){ut(this.contents)&&this.contents.addIn(e,n)}createAlias(e,n){if(!e.anchor){let i=ns.anchorNames(this);e.anchor=!n||i.has(n)?ns.findNewAnchor(n||"a",i):n}return new wp.Alias(e.anchor)}createNode(e,n,i){let r;if(typeof n=="function")e=n.call({"":e},"",e),r=n;else if(Array.isArray(n)){let m=g=>typeof g=="number"||g instanceof String||g instanceof Number,y=n.filter(m).map(String);y.length>0&&(n=n.concat(y)),r=n}else i===void 0&&n&&(i=n,n=void 0);let{aliasDuplicateObjects:s,anchorPrefix:o,flow:a,keepUndefined:c,onTagObj:l,tag:u}=i??{},{onAnchor:f,setAnchors:d,sourceObjects:h}=ns.createNodeAnchors(this,o||"a"),w={aliasDuplicateObjects:s??!0,keepUndefined:c??!1,onAnchor:f,onTagObj:l,replacer:r,schema:this.schema,sourceObjects:h},p=Cp.createNode(e,u,w);return a&&Q.isCollection(p)&&(p.flow=!0),d(),p}createPair(e,n,i={}){let r=this.createNode(e,null,i),s=this.createNode(n,null,i);return new yp.Pair(r,s)}delete(e){return ut(this.contents)?this.contents.delete(e):!1}deleteIn(e){return lt.isEmptyPath(e)?this.contents==null?!1:(this.contents=null,!0):ut(this.contents)?this.contents.deleteIn(e):!1}get(e,n){return Q.isCollection(this.contents)?this.contents.get(e,n):void 0}getIn(e,n){return lt.isEmptyPath(e)?!n&&Q.isScalar(this.contents)?this.contents.value:this.contents:Q.isCollection(this.contents)?this.contents.getIn(e,n):void 0}has(e){return Q.isCollection(this.contents)?this.contents.has(e):!1}hasIn(e){return lt.isEmptyPath(e)?this.contents!==void 0:Q.isCollection(this.contents)?this.contents.hasIn(e):!1}set(e,n){this.contents==null?this.contents=lt.collectionFromPath(this.schema,[e],n):ut(this.contents)&&this.contents.set(e,n)}setIn(e,n){lt.isEmptyPath(e)?this.contents=n:this.contents==null?this.contents=lt.collectionFromPath(this.schema,Array.from(e),n):ut(this.contents)&&this.contents.setIn(e,n)}setSchema(e,n={}){typeof e=="number"&&(e=String(e));let i;switch(e){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new is.Directives({version:"1.1"}),i={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=e:this.directives=new is.Directives({version:e}),i={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,i=null;break;default:{let r=JSON.stringify(e);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${r}`)}}if(n.schema instanceof Object)this.schema=n.schema;else if(i)this.schema=new kp.Schema(Object.assign(i,n));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:e,jsonArg:n,mapAsMap:i,maxAliasCount:r,onAnchor:s,reviver:o}={}){let a={anchors:new Map,doc:this,keep:!e,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},c=vp.toJS(this.contents,n??"",a);if(typeof s=="function")for(let{count:l,res:u}of a.anchors.values())s(u,l);return typeof o=="function"?Sp.applyReviver(o,{"":c},"",c):c}toJSON(e,n){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:n})}toString(e={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let n=JSON.stringify(e.indent);throw new Error(`"indent" option must be a positive integer, not ${n}`)}return bp.stringifyDocument(this,e)}};function ut(t){if(Q.isCollection(t))return!0;throw new Error("Expected a YAML collection as document contents")}tc.Document=rs});var Ht=v(Ut=>{"use strict";var Jt=class extends Error{constructor(e,n,i,r){super(),this.name=e,this.code=i,this.message=r,this.pos=n}},ss=class extends Jt{constructor(e,n,i){super("YAMLParseError",e,n,i)}},os=class extends Jt{constructor(e,n,i){super("YAMLWarning",e,n,i)}},Ep=(t,e)=>n=>{if(n.pos[0]===-1)return;n.linePos=n.pos.map(a=>e.linePos(a));let{line:i,col:r}=n.linePos[0];n.message+=` at line ${i}, column ${r}`;let s=r-1,o=t.substring(e.lineStarts[i-1],e.lineStarts[i]).replace(/[\n\r]+$/,"");if(s>=60&&o.length>80){let a=Math.min(s-39,o.length-79);o="…"+o.substring(a),s-=a-1}if(o.length>80&&(o=o.substring(0,79)+"…"),i>1&&/^ *$/.test(o.substring(0,s))){let a=t.substring(e.lineStarts[i-2],e.lineStarts[i-1]);a.length>80&&(a=a.substring(0,79)+`… +`}Za.stringifyDocument=wp});var Yt=v(tc=>{"use strict";var yp=Rt(),lt=Rn(),Q=P(),vp=Ee(),kp=ke(),bp=ts(),Sp=ec(),is=En(),Cp=ar(),Ep=Ot(),rs=or(),ss=class t{constructor(e,n,i){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,Q.NODE_TYPE,{value:Q.DOC});let r=null;typeof n=="function"||Array.isArray(n)?r=n:i===void 0&&n&&(i=n,n=void 0);let s=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},i);this.options=s;let{version:o}=s;i?._directives?(this.directives=i._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new rs.Directives({version:o}),this.setSchema(o,i),this.contents=e===void 0?null:this.createNode(e,r,i)}clone(){let e=Object.create(t.prototype,{[Q.NODE_TYPE]:{value:Q.DOC}});return e.commentBefore=this.commentBefore,e.comment=this.comment,e.errors=this.errors.slice(),e.warnings=this.warnings.slice(),e.options=Object.assign({},this.options),this.directives&&(e.directives=this.directives.clone()),e.schema=this.schema.clone(),e.contents=Q.isNode(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){ut(this.contents)&&this.contents.add(e)}addIn(e,n){ut(this.contents)&&this.contents.addIn(e,n)}createAlias(e,n){if(!e.anchor){let i=is.anchorNames(this);e.anchor=!n||i.has(n)?is.findNewAnchor(n||"a",i):n}return new yp.Alias(e.anchor)}createNode(e,n,i){let r;if(typeof n=="function")e=n.call({"":e},"",e),r=n;else if(Array.isArray(n)){let m=g=>typeof g=="number"||g instanceof String||g instanceof Number,y=n.filter(m).map(String);y.length>0&&(n=n.concat(y)),r=n}else i===void 0&&n&&(i=n,n=void 0);let{aliasDuplicateObjects:s,anchorPrefix:o,flow:a,keepUndefined:c,onTagObj:l,tag:u}=i??{},{onAnchor:f,setAnchors:d,sourceObjects:h}=is.createNodeAnchors(this,o||"a"),w={aliasDuplicateObjects:s??!0,keepUndefined:c??!1,onAnchor:f,onTagObj:l,replacer:r,schema:this.schema,sourceObjects:h},p=Ep.createNode(e,u,w);return a&&Q.isCollection(p)&&(p.flow=!0),d(),p}createPair(e,n,i={}){let r=this.createNode(e,null,i),s=this.createNode(n,null,i);return new vp.Pair(r,s)}delete(e){return ut(this.contents)?this.contents.delete(e):!1}deleteIn(e){return lt.isEmptyPath(e)?this.contents==null?!1:(this.contents=null,!0):ut(this.contents)?this.contents.deleteIn(e):!1}get(e,n){return Q.isCollection(this.contents)?this.contents.get(e,n):void 0}getIn(e,n){return lt.isEmptyPath(e)?!n&&Q.isScalar(this.contents)?this.contents.value:this.contents:Q.isCollection(this.contents)?this.contents.getIn(e,n):void 0}has(e){return Q.isCollection(this.contents)?this.contents.has(e):!1}hasIn(e){return lt.isEmptyPath(e)?this.contents!==void 0:Q.isCollection(this.contents)?this.contents.hasIn(e):!1}set(e,n){this.contents==null?this.contents=lt.collectionFromPath(this.schema,[e],n):ut(this.contents)&&this.contents.set(e,n)}setIn(e,n){lt.isEmptyPath(e)?this.contents=n:this.contents==null?this.contents=lt.collectionFromPath(this.schema,Array.from(e),n):ut(this.contents)&&this.contents.setIn(e,n)}setSchema(e,n={}){typeof e=="number"&&(e=String(e));let i;switch(e){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new rs.Directives({version:"1.1"}),i={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=e:this.directives=new rs.Directives({version:e}),i={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,i=null;break;default:{let r=JSON.stringify(e);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${r}`)}}if(n.schema instanceof Object)this.schema=n.schema;else if(i)this.schema=new bp.Schema(Object.assign(i,n));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:e,jsonArg:n,mapAsMap:i,maxAliasCount:r,onAnchor:s,reviver:o}={}){let a={anchors:new Map,doc:this,keep:!e,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},c=kp.toJS(this.contents,n??"",a);if(typeof s=="function")for(let{count:l,res:u}of a.anchors.values())s(u,l);return typeof o=="function"?Cp.applyReviver(o,{"":c},"",c):c}toJSON(e,n){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:n})}toString(e={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let n=JSON.stringify(e.indent);throw new Error(`"indent" option must be a positive integer, not ${n}`)}return Sp.stringifyDocument(this,e)}};function ut(t){if(Q.isCollection(t))return!0;throw new Error("Expected a YAML collection as document contents")}tc.Document=ss});var Ht=v(Ut=>{"use strict";var Jt=class extends Error{constructor(e,n,i,r){super(),this.name=e,this.code=i,this.message=r,this.pos=n}},os=class extends Jt{constructor(e,n,i){super("YAMLParseError",e,n,i)}},as=class extends Jt{constructor(e,n,i){super("YAMLWarning",e,n,i)}},xp=(t,e)=>n=>{if(n.pos[0]===-1)return;n.linePos=n.pos.map(a=>e.linePos(a));let{line:i,col:r}=n.linePos[0];n.message+=` at line ${i}, column ${r}`;let s=r-1,o=t.substring(e.lineStarts[i-1],e.lineStarts[i]).replace(/[\n\r]+$/,"");if(s>=60&&o.length>80){let a=Math.min(s-39,o.length-79);o="…"+o.substring(a),s-=a-1}if(o.length>80&&(o=o.substring(0,79)+"…"),i>1&&/^ *$/.test(o.substring(0,s))){let a=t.substring(e.lineStarts[i-2],e.lineStarts[i-1]);a.length>80&&(a=a.substring(0,79)+`… `),o=a+o}if(/[^ ]/.test(o)){let a=1,c=n.linePos[1];c?.line===i&&c.col>r&&(a=Math.max(1,Math.min(c.col-r,80-s)));let l=" ".repeat(s)+"^".repeat(a);n.message+=`: ${o} ${l} -`}};Ut.YAMLError=Jt;Ut.YAMLParseError=ss;Ut.YAMLWarning=os;Ut.prettifyError=Ep});var Vt=v(nc=>{"use strict";function xp(t,{flow:e,indicator:n,next:i,offset:r,onError:s,parentIndent:o,startOnNewline:a}){let c=!1,l=a,u=a,f="",d="",h=!1,w=!1,p=null,m=null,y=null,g=null,b=null,S=null,C=null;for(let k of t)switch(w&&(k.type!=="space"&&k.type!=="newline"&&k.type!=="comma"&&s(k.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),w=!1),p&&(l&&k.type!=="comment"&&k.type!=="newline"&&s(p,"TAB_AS_INDENT","Tabs are not allowed as indentation"),p=null),k.type){case"space":!e&&(n!=="doc-start"||i?.type!=="flow-collection")&&k.source.includes(" ")&&(p=k),u=!0;break;case"comment":{u||s(k,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let N=k.source.substring(1)||" ";f?f+=d+N:f=N,d="",l=!1;break}case"newline":l?f?f+=k.source:(!S||n!=="seq-item-ind")&&(c=!0):d+=k.source,l=!0,h=!0,(m||y)&&(g=k),u=!0;break;case"anchor":m&&s(k,"MULTIPLE_ANCHORS","A node can have at most one anchor"),k.source.endsWith(":")&&s(k.offset+k.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),m=k,C??(C=k.offset),l=!1,u=!1,w=!0;break;case"tag":{y&&s(k,"MULTIPLE_TAGS","A node can have at most one tag"),y=k,C??(C=k.offset),l=!1,u=!1,w=!0;break}case n:(m||y)&&s(k,"BAD_PROP_ORDER",`Anchors and tags must be after the ${k.source} indicator`),S&&s(k,"UNEXPECTED_TOKEN",`Unexpected ${k.source} in ${e??"collection"}`),S=k,l=n==="seq-item-ind"||n==="explicit-key-ind",u=!1;break;case"comma":if(e){b&&s(k,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),b=k,l=!1,u=!1;break}default:s(k,"UNEXPECTED_TOKEN",`Unexpected ${k.type} token`),l=!1,u=!1}let E=t[t.length-1],x=E?E.offset+E.source.length:r;return w&&i&&i.type!=="space"&&i.type!=="newline"&&i.type!=="comma"&&(i.type!=="scalar"||i.source!=="")&&s(i.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),p&&(l&&p.indent<=o||i?.type==="block-map"||i?.type==="block-seq")&&s(p,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:b,found:S,spaceBefore:c,comment:f,hasNewline:h,anchor:m,tag:y,newlineAfterProp:g,end:x,start:C??x}}nc.resolveProps=xp});var li=v(ic=>{"use strict";function as(t){if(!t)return null;switch(t.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(t.source.includes(` -`))return!0;if(t.end){for(let e of t.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(let e of t.items){for(let n of e.start)if(n.type==="newline")return!0;if(e.sep){for(let n of e.sep)if(n.type==="newline")return!0}if(as(e.key)||as(e.value))return!0}return!1;default:return!0}}ic.containsNewline=as});var cs=v(rc=>{"use strict";var _p=li();function Pp(t,e,n){if(e?.type==="flow-collection"){let i=e.end[0];i.indent===t&&(i.source==="]"||i.source==="}")&&_p.containsNewline(e)&&n(i,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}rc.flowIndentCheck=Pp});var ls=v(oc=>{"use strict";var sc=_();function Rp(t,e,n){let{uniqueKeys:i}=t.options;if(i===!1)return!1;let r=typeof i=="function"?i:(s,o)=>s===o||sc.isScalar(s)&&sc.isScalar(o)&&s.value===o.value;return e.some(s=>r(s.key,n))}oc.mapIncludes=Rp});var dc=v(fc=>{"use strict";var ac=Ee(),Op=_e(),cc=Vt(),Np=li(),lc=cs(),Ap=ls(),uc="All mapping items must start at the same column";function jp({composeNode:t,composeEmptyNode:e},n,i,r,s){let o=s?.nodeClass??Op.YAMLMap,a=new o(n.schema);n.atRoot&&(n.atRoot=!1);let c=i.offset,l=null;for(let u of i.items){let{start:f,key:d,sep:h,value:w}=u,p=cc.resolveProps(f,{indicator:"explicit-key-ind",next:d??h?.[0],offset:c,onError:r,parentIndent:i.indent,startOnNewline:!0}),m=!p.found;if(m){if(d&&(d.type==="block-seq"?r(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in d&&d.indent!==i.indent&&r(c,"BAD_INDENT",uc)),!p.anchor&&!p.tag&&!h){l=p.end,p.comment&&(a.comment?a.comment+=` -`+p.comment:a.comment=p.comment);continue}(p.newlineAfterProp||Np.containsNewline(d))&&r(d??f[f.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else p.found?.indent!==i.indent&&r(c,"BAD_INDENT",uc);n.atKey=!0;let y=p.end,g=d?t(n,d,p,r):e(n,y,f,null,p,r);n.schema.compat&&lc.flowIndentCheck(i.indent,d,r),n.atKey=!1,Ap.mapIncludes(n,a.items,g)&&r(y,"DUPLICATE_KEY","Map keys must be unique");let b=cc.resolveProps(h??[],{indicator:"map-value-ind",next:w,offset:g.range[2],onError:r,parentIndent:i.indent,startOnNewline:!d||d.type==="block-scalar"});if(c=b.end,b.found){m&&(w?.type==="block-map"&&!b.hasNewline&&r(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),n.options.strict&&p.start{"use strict";var Ip=Pe(),Tp=Vt(),qp=cs();function $p({composeNode:t,composeEmptyNode:e},n,i,r,s){let o=s?.nodeClass??Ip.YAMLSeq,a=new o(n.schema);n.atRoot&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let c=i.offset,l=null;for(let{start:u,value:f}of i.items){let d=Tp.resolveProps(u,{indicator:"seq-item-ind",next:f,offset:c,onError:r,parentIndent:i.indent,startOnNewline:!0});if(!d.found)if(d.anchor||d.tag||f)f?.type==="block-seq"?r(d.end,"BAD_INDENT","All sequence items must start at the same column"):r(c,"MISSING_CHAR","Sequence item without - indicator");else{l=d.end,d.comment&&(a.comment=d.comment);continue}let h=f?t(n,f,d,r):e(n,d.end,u,null,d,r);n.schema.compat&&qp.flowIndentCheck(i.indent,f,r),c=h.range[2],a.items.push(h)}return a.range=[i.offset,c,l??c],a}pc.resolveBlockSeq=$p});var ft=v(hc=>{"use strict";function Lp(t,e,n,i){let r="";if(t){let s=!1,o="";for(let a of t){let{source:c,type:l}=a;switch(l){case"space":s=!0;break;case"comment":{n&&!s&&i(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let u=c.substring(1)||" ";r?r+=o+u:r=u,o="";break}case"newline":r&&(o+=c),s=!0;break;default:i(a,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}e+=c.length}}return{comment:r,offset:e}}hc.resolveEnd=Lp});var vc=v(yc=>{"use strict";var Dp=_(),Fp=Ee(),gc=_e(),Mp=Pe(),Wp=ft(),wc=Vt(),Bp=li(),Kp=ls(),us="Block collections are not allowed within flow collections",fs=t=>t&&(t.type==="block-map"||t.type==="block-seq");function Yp({composeNode:t,composeEmptyNode:e},n,i,r,s){let o=i.start.source==="{",a=o?"flow map":"flow sequence",c=s?.nodeClass??(o?gc.YAMLMap:Mp.YAMLSeq),l=new c(n.schema);l.flow=!0;let u=n.atRoot;u&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let f=i.offset+i.start.source.length;for(let m=0;m0){let m=Wp.resolveEnd(w,p,n.options.strict,r);m.comment&&(l.comment?l.comment+=` -`+m.comment:l.comment=m.comment),l.range=[i.offset,p,m.offset]}else l.range=[i.offset,p,p];return l}yc.resolveFlowCollection=Yp});var bc=v(kc=>{"use strict";var Jp=_(),Up=j(),Hp=_e(),Vp=Pe(),Gp=dc(),zp=mc(),Qp=vc();function ds(t,e,n,i,r,s){let o=n.type==="block-map"?Gp.resolveBlockMap(t,e,n,i,s):n.type==="block-seq"?zp.resolveBlockSeq(t,e,n,i,s):Qp.resolveFlowCollection(t,e,n,i,s),a=o.constructor;return r==="!"||r===a.tagName?(o.tag=a.tagName,o):(r&&(o.tag=r),o)}function Xp(t,e,n,i,r){let s=i.tag,o=s?e.directives.tagName(s.source,d=>r(s,"TAG_RESOLVE_FAILED",d)):null;if(n.type==="block-seq"){let{anchor:d,newlineAfterProp:h}=i,w=d&&s?d.offset>s.offset?d:s:d??s;w&&(!h||h.offsetd.tag===o&&d.collection===a);if(!c){let d=e.schema.knownTags[o];if(d?.collection===a)e.schema.tags.push(Object.assign({},d,{default:!1})),c=d;else return d?r(s,"BAD_COLLECTION_TYPE",`${d.tag} used for ${a} collection, but expects ${d.collection??"scalar"}`,!0):r(s,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),ds(t,e,n,r,o)}let l=ds(t,e,n,r,o,c),u=c.resolve?.(l,d=>r(s,"TAG_RESOLVE_FAILED",d),e.options)??l,f=Jp.isNode(u)?u:new Up.Scalar(u);return f.range=l.range,f.tag=o,c?.format&&(f.format=c.format),f}kc.composeCollection=Xp});var ms=v(Sc=>{"use strict";var ps=j();function Zp(t,e,n){let i=e.offset,r=em(e,t.options.strict,n);if(!r)return{value:"",type:null,comment:"",range:[i,i,i]};let s=r.mode===">"?ps.Scalar.BLOCK_FOLDED:ps.Scalar.BLOCK_LITERAL,o=e.source?tm(e.source):[],a=o.length;for(let p=o.length-1;p>=0;--p){let m=o[p][1];if(m===""||m==="\r")a=p;else break}if(a===0){let p=r.chomp==="+"&&o.length>0?` +`}};Ut.YAMLError=Jt;Ut.YAMLParseError=os;Ut.YAMLWarning=as;Ut.prettifyError=xp});var Vt=v(nc=>{"use strict";function Pp(t,{flow:e,indicator:n,next:i,offset:r,onError:s,parentIndent:o,startOnNewline:a}){let c=!1,l=a,u=a,f="",d="",h=!1,w=!1,p=null,m=null,y=null,g=null,b=null,S=null,C=null;for(let k of t)switch(w&&(k.type!=="space"&&k.type!=="newline"&&k.type!=="comma"&&s(k.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),w=!1),p&&(l&&k.type!=="comment"&&k.type!=="newline"&&s(p,"TAB_AS_INDENT","Tabs are not allowed as indentation"),p=null),k.type){case"space":!e&&(n!=="doc-start"||i?.type!=="flow-collection")&&k.source.includes(" ")&&(p=k),u=!0;break;case"comment":{u||s(k,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let N=k.source.substring(1)||" ";f?f+=d+N:f=N,d="",l=!1;break}case"newline":l?f?f+=k.source:(!S||n!=="seq-item-ind")&&(c=!0):d+=k.source,l=!0,h=!0,(m||y)&&(g=k),u=!0;break;case"anchor":m&&s(k,"MULTIPLE_ANCHORS","A node can have at most one anchor"),k.source.endsWith(":")&&s(k.offset+k.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),m=k,C??(C=k.offset),l=!1,u=!1,w=!0;break;case"tag":{y&&s(k,"MULTIPLE_TAGS","A node can have at most one tag"),y=k,C??(C=k.offset),l=!1,u=!1,w=!0;break}case n:(m||y)&&s(k,"BAD_PROP_ORDER",`Anchors and tags must be after the ${k.source} indicator`),S&&s(k,"UNEXPECTED_TOKEN",`Unexpected ${k.source} in ${e??"collection"}`),S=k,l=n==="seq-item-ind"||n==="explicit-key-ind",u=!1;break;case"comma":if(e){b&&s(k,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),b=k,l=!1,u=!1;break}default:s(k,"UNEXPECTED_TOKEN",`Unexpected ${k.type} token`),l=!1,u=!1}let E=t[t.length-1],x=E?E.offset+E.source.length:r;return w&&i&&i.type!=="space"&&i.type!=="newline"&&i.type!=="comma"&&(i.type!=="scalar"||i.source!=="")&&s(i.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),p&&(l&&p.indent<=o||i?.type==="block-map"||i?.type==="block-seq")&&s(p,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:b,found:S,spaceBefore:c,comment:f,hasNewline:h,anchor:m,tag:y,newlineAfterProp:g,end:x,start:C??x}}nc.resolveProps=Pp});var li=v(ic=>{"use strict";function cs(t){if(!t)return null;switch(t.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(t.source.includes(` +`))return!0;if(t.end){for(let e of t.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(let e of t.items){for(let n of e.start)if(n.type==="newline")return!0;if(e.sep){for(let n of e.sep)if(n.type==="newline")return!0}if(cs(e.key)||cs(e.value))return!0}return!1;default:return!0}}ic.containsNewline=cs});var ls=v(rc=>{"use strict";var _p=li();function Rp(t,e,n){if(e?.type==="flow-collection"){let i=e.end[0];i.indent===t&&(i.source==="]"||i.source==="}")&&_p.containsNewline(e)&&n(i,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}rc.flowIndentCheck=Rp});var us=v(oc=>{"use strict";var sc=P();function Op(t,e,n){let{uniqueKeys:i}=t.options;if(i===!1)return!1;let r=typeof i=="function"?i:(s,o)=>s===o||sc.isScalar(s)&&sc.isScalar(o)&&s.value===o.value;return e.some(s=>r(s.key,n))}oc.mapIncludes=Op});var dc=v(fc=>{"use strict";var ac=Ee(),Np=Pe(),cc=Vt(),Ap=li(),lc=ls(),jp=us(),uc="All mapping items must start at the same column";function Ip({composeNode:t,composeEmptyNode:e},n,i,r,s){let o=s?.nodeClass??Np.YAMLMap,a=new o(n.schema);n.atRoot&&(n.atRoot=!1);let c=i.offset,l=null;for(let u of i.items){let{start:f,key:d,sep:h,value:w}=u,p=cc.resolveProps(f,{indicator:"explicit-key-ind",next:d??h?.[0],offset:c,onError:r,parentIndent:i.indent,startOnNewline:!0}),m=!p.found;if(m){if(d&&(d.type==="block-seq"?r(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in d&&d.indent!==i.indent&&r(c,"BAD_INDENT",uc)),!p.anchor&&!p.tag&&!h){l=p.end,p.comment&&(a.comment?a.comment+=` +`+p.comment:a.comment=p.comment);continue}(p.newlineAfterProp||Ap.containsNewline(d))&&r(d??f[f.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else p.found?.indent!==i.indent&&r(c,"BAD_INDENT",uc);n.atKey=!0;let y=p.end,g=d?t(n,d,p,r):e(n,y,f,null,p,r);n.schema.compat&&lc.flowIndentCheck(i.indent,d,r),n.atKey=!1,jp.mapIncludes(n,a.items,g)&&r(y,"DUPLICATE_KEY","Map keys must be unique");let b=cc.resolveProps(h??[],{indicator:"map-value-ind",next:w,offset:g.range[2],onError:r,parentIndent:i.indent,startOnNewline:!d||d.type==="block-scalar"});if(c=b.end,b.found){m&&(w?.type==="block-map"&&!b.hasNewline&&r(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),n.options.strict&&p.start{"use strict";var Tp=_e(),qp=Vt(),$p=ls();function Lp({composeNode:t,composeEmptyNode:e},n,i,r,s){let o=s?.nodeClass??Tp.YAMLSeq,a=new o(n.schema);n.atRoot&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let c=i.offset,l=null;for(let{start:u,value:f}of i.items){let d=qp.resolveProps(u,{indicator:"seq-item-ind",next:f,offset:c,onError:r,parentIndent:i.indent,startOnNewline:!0});if(!d.found)if(d.anchor||d.tag||f)f?.type==="block-seq"?r(d.end,"BAD_INDENT","All sequence items must start at the same column"):r(c,"MISSING_CHAR","Sequence item without - indicator");else{l=d.end,d.comment&&(a.comment=d.comment);continue}let h=f?t(n,f,d,r):e(n,d.end,u,null,d,r);n.schema.compat&&$p.flowIndentCheck(i.indent,f,r),c=h.range[2],a.items.push(h)}return a.range=[i.offset,c,l??c],a}pc.resolveBlockSeq=Lp});var ft=v(hc=>{"use strict";function Dp(t,e,n,i){let r="";if(t){let s=!1,o="";for(let a of t){let{source:c,type:l}=a;switch(l){case"space":s=!0;break;case"comment":{n&&!s&&i(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let u=c.substring(1)||" ";r?r+=o+u:r=u,o="";break}case"newline":r&&(o+=c),s=!0;break;default:i(a,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}e+=c.length}}return{comment:r,offset:e}}hc.resolveEnd=Dp});var vc=v(yc=>{"use strict";var Fp=P(),Mp=Ee(),gc=Pe(),Wp=_e(),Bp=ft(),wc=Vt(),Kp=li(),Yp=us(),fs="Block collections are not allowed within flow collections",ds=t=>t&&(t.type==="block-map"||t.type==="block-seq");function Jp({composeNode:t,composeEmptyNode:e},n,i,r,s){let o=i.start.source==="{",a=o?"flow map":"flow sequence",c=s?.nodeClass??(o?gc.YAMLMap:Wp.YAMLSeq),l=new c(n.schema);l.flow=!0;let u=n.atRoot;u&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let f=i.offset+i.start.source.length;for(let m=0;m0){let m=Bp.resolveEnd(w,p,n.options.strict,r);m.comment&&(l.comment?l.comment+=` +`+m.comment:l.comment=m.comment),l.range=[i.offset,p,m.offset]}else l.range=[i.offset,p,p];return l}yc.resolveFlowCollection=Jp});var bc=v(kc=>{"use strict";var Up=P(),Hp=j(),Vp=Pe(),Gp=_e(),zp=dc(),Qp=mc(),Xp=vc();function ps(t,e,n,i,r,s){let o=n.type==="block-map"?zp.resolveBlockMap(t,e,n,i,s):n.type==="block-seq"?Qp.resolveBlockSeq(t,e,n,i,s):Xp.resolveFlowCollection(t,e,n,i,s),a=o.constructor;return r==="!"||r===a.tagName?(o.tag=a.tagName,o):(r&&(o.tag=r),o)}function Zp(t,e,n,i,r){let s=i.tag,o=s?e.directives.tagName(s.source,d=>r(s,"TAG_RESOLVE_FAILED",d)):null;if(n.type==="block-seq"){let{anchor:d,newlineAfterProp:h}=i,w=d&&s?d.offset>s.offset?d:s:d??s;w&&(!h||h.offsetd.tag===o&&d.collection===a);if(!c){let d=e.schema.knownTags[o];if(d?.collection===a)e.schema.tags.push(Object.assign({},d,{default:!1})),c=d;else return d?r(s,"BAD_COLLECTION_TYPE",`${d.tag} used for ${a} collection, but expects ${d.collection??"scalar"}`,!0):r(s,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),ps(t,e,n,r,o)}let l=ps(t,e,n,r,o,c),u=c.resolve?.(l,d=>r(s,"TAG_RESOLVE_FAILED",d),e.options)??l,f=Up.isNode(u)?u:new Hp.Scalar(u);return f.range=l.range,f.tag=o,c?.format&&(f.format=c.format),f}kc.composeCollection=Zp});var hs=v(Sc=>{"use strict";var ms=j();function em(t,e,n){let i=e.offset,r=tm(e,t.options.strict,n);if(!r)return{value:"",type:null,comment:"",range:[i,i,i]};let s=r.mode===">"?ms.Scalar.BLOCK_FOLDED:ms.Scalar.BLOCK_LITERAL,o=e.source?nm(e.source):[],a=o.length;for(let p=o.length-1;p>=0;--p){let m=o[p][1];if(m===""||m==="\r")a=p;else break}if(a===0){let p=r.chomp==="+"&&o.length>0?` `.repeat(Math.max(1,o.length-1)):"",m=i+r.length;return e.source&&(m+=e.source.length),{value:p,type:s,comment:r.comment,range:[i,m,m]}}let c=e.indent+r.indent,l=e.offset+r.length,u=0;for(let p=0;pc&&(c=m.length);else{m.length=a;--p)o[p][0].length>c&&(a=p+1);let f="",d="",h=!1;for(let p=0;pc||y[0]===" "?(d===" "?d=` `:!h&&d===` `&&(d=` @@ -84,46 +84,46 @@ ${l} `+o[p][0].slice(c);f[f.length-1]!==` `&&(f+=` `);break;default:f+=` -`}let w=i+r.length+e.source.length;return{value:f,type:s,comment:r.comment,range:[i,w,w]}}function em({offset:t,props:e},n,i){if(e[0].type!=="block-scalar-header")return i(e[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:r}=e[0],s=r[0],o=0,a="",c=-1;for(let d=1;d{"use strict";var hs=j(),nm=ft();function im(t,e,n){let{offset:i,type:r,source:s,end:o}=t,a,c,l=(d,h,w)=>n(i+d,h,w);switch(r){case"scalar":a=hs.Scalar.PLAIN,c=rm(s,l);break;case"single-quoted-scalar":a=hs.Scalar.QUOTE_SINGLE,c=sm(s,l);break;case"double-quoted-scalar":a=hs.Scalar.QUOTE_DOUBLE,c=om(s,l);break;default:return n(t,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${r}`),{value:"",type:null,comment:"",range:[i,i+s.length,i+s.length]}}let u=i+s.length,f=nm.resolveEnd(o,u,e,n);return{value:c,type:a,comment:f.comment,range:[i,u,f.offset]}}function rm(t,e){let n="";switch(t[0]){case" ":n="a tab character";break;case",":n="flow indicator character ,";break;case"%":n="directive indicator character %";break;case"|":case">":{n=`block scalar indicator ${t[0]}`;break}case"@":case"`":{n=`reserved character ${t[0]}`;break}}return n&&e(0,"BAD_SCALAR_START",`Plain value cannot start with ${n}`),Cc(t)}function sm(t,e){return(t[t.length-1]!=="'"||t.length===1)&&e(t.length,"MISSING_CHAR","Missing closing 'quote"),Cc(t.slice(1,-1)).replace(/''/g,"'")}function Cc(t){let e,n;try{e=new RegExp(`(.*?)(?{"use strict";var gs=j(),im=ft();function rm(t,e,n){let{offset:i,type:r,source:s,end:o}=t,a,c,l=(d,h,w)=>n(i+d,h,w);switch(r){case"scalar":a=gs.Scalar.PLAIN,c=sm(s,l);break;case"single-quoted-scalar":a=gs.Scalar.QUOTE_SINGLE,c=om(s,l);break;case"double-quoted-scalar":a=gs.Scalar.QUOTE_DOUBLE,c=am(s,l);break;default:return n(t,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${r}`),{value:"",type:null,comment:"",range:[i,i+s.length,i+s.length]}}let u=i+s.length,f=im.resolveEnd(o,u,e,n);return{value:c,type:a,comment:f.comment,range:[i,u,f.offset]}}function sm(t,e){let n="";switch(t[0]){case" ":n="a tab character";break;case",":n="flow indicator character ,";break;case"%":n="directive indicator character %";break;case"|":case">":{n=`block scalar indicator ${t[0]}`;break}case"@":case"`":{n=`reserved character ${t[0]}`;break}}return n&&e(0,"BAD_SCALAR_START",`Plain value cannot start with ${n}`),Cc(t)}function om(t,e){return(t[t.length-1]!=="'"||t.length===1)&&e(t.length,"MISSING_CHAR","Missing closing 'quote"),Cc(t.slice(1,-1)).replace(/''/g,"'")}function Cc(t){let e,n;try{e=new RegExp(`(.*?)(?s?t.slice(s,i+1):r)}else n+=r}return(t[t.length-1]!=='"'||t.length===1)&&e(t.length,"MISSING_CHAR",'Missing closing "quote'),n}function am(t,e){let n="",i=t[e+1];for(;(i===" "||i===" "||i===` +`)&&(n+=i>s?t.slice(s,i+1):r)}else n+=r}return(t[t.length-1]!=='"'||t.length===1)&&e(t.length,"MISSING_CHAR",'Missing closing "quote'),n}function cm(t,e){let n="",i=t[e+1];for(;(i===" "||i===" "||i===` `||i==="\r")&&!(i==="\r"&&t[e+2]!==` `);)i===` `&&(n+=` -`),e+=1,i=t[e+1];return n||(n=" "),{fold:n,offset:e}}var cm={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:` -`,r:"\r",t:" ",v:"\v",N:"…",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function lm(t,e,n,i){let r=t.substr(e,n),o=r.length===n&&/^[0-9a-fA-F]+$/.test(r)?parseInt(r,16):NaN;try{return String.fromCodePoint(o)}catch{let a=t.substr(e-2,n+2);return i(e-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),a}}Ec.resolveFlowScalar=im});var Pc=v(_c=>{"use strict";var He=_(),xc=j(),um=ms(),fm=gs();function dm(t,e,n,i){let{value:r,type:s,comment:o,range:a}=e.type==="block-scalar"?um.resolveBlockScalar(t,e,i):fm.resolveFlowScalar(e,t.options.strict,i),c=n?t.directives.tagName(n.source,f=>i(n,"TAG_RESOLVE_FAILED",f)):null,l;t.options.stringKeys&&t.atKey?l=t.schema[He.SCALAR]:c?l=pm(t.schema,r,c,n,i):e.type==="scalar"?l=mm(t,r,e,i):l=t.schema[He.SCALAR];let u;try{let f=l.resolve(r,d=>i(n??e,"TAG_RESOLVE_FAILED",d),t.options);u=He.isScalar(f)?f:new xc.Scalar(f)}catch(f){let d=f instanceof Error?f.message:String(f);i(n??e,"TAG_RESOLVE_FAILED",d),u=new xc.Scalar(r)}return u.range=a,u.source=r,s&&(u.type=s),c&&(u.tag=c),l.format&&(u.format=l.format),o&&(u.comment=o),u}function pm(t,e,n,i,r){if(n==="!")return t[He.SCALAR];let s=[];for(let a of t.tags)if(!a.collection&&a.tag===n)if(a.default&&a.test)s.push(a);else return a;for(let a of s)if(a.test?.test(e))return a;let o=t.knownTags[n];return o&&!o.collection?(t.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(r(i,"TAG_RESOLVE_FAILED",`Unresolved tag: ${n}`,n!=="tag:yaml.org,2002:str"),t[He.SCALAR])}function mm({atKey:t,directives:e,schema:n},i,r,s){let o=n.tags.find(a=>(a.default===!0||t&&a.default==="key")&&a.test?.test(i))||n[He.SCALAR];if(n.compat){let a=n.compat.find(c=>c.default&&c.test?.test(i))??n[He.SCALAR];if(o.tag!==a.tag){let c=e.tagString(o.tag),l=e.tagString(a.tag),u=`Value may be parsed as either ${c} or ${l}`;s(r,"TAG_RESOLVE_FAILED",u,!0)}}return o}_c.composeScalar=dm});var Oc=v(Rc=>{"use strict";function hm(t,e,n){if(e){n??(n=e.length);for(let i=n-1;i>=0;--i){let r=e[i];switch(r.type){case"space":case"comment":case"newline":t-=r.source.length;continue}for(r=e[++i];r?.type==="space";)t+=r.source.length,r=e[++i];break}}return t}Rc.emptyScalarPosition=hm});var jc=v(ys=>{"use strict";var gm=Rt(),wm=_(),ym=bc(),Nc=Pc(),vm=ft(),km=Oc(),bm={composeNode:Ac,composeEmptyNode:ws};function Ac(t,e,n,i){let r=t.atKey,{spaceBefore:s,comment:o,anchor:a,tag:c}=n,l,u=!0;switch(e.type){case"alias":l=Sm(t,e,i),(a||c)&&i(e,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=Nc.composeScalar(t,e,c,i),a&&(l.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=ym.composeCollection(bm,t,e,n,i),a&&(l.anchor=a.source.substring(1))}catch(f){let d=f instanceof Error?f.message:String(f);i(e,"RESOURCE_EXHAUSTION",d)}break;default:{let f=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;i(e,"UNEXPECTED_TOKEN",f),u=!1}}return l??(l=ws(t,e.offset,void 0,null,n,i)),a&&l.anchor===""&&i(a,"BAD_ALIAS","Anchor cannot be an empty string"),r&&t.options.stringKeys&&(!wm.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&i(c??e,"NON_STRING_KEY","With stringKeys, all keys must be strings"),s&&(l.spaceBefore=!0),o&&(e.type==="scalar"&&e.source===""?l.comment=o:l.commentBefore=o),t.options.keepSourceTokens&&u&&(l.srcToken=e),l}function ws(t,e,n,i,{spaceBefore:r,comment:s,anchor:o,tag:a,end:c},l){let u={type:"scalar",offset:km.emptyScalarPosition(e,n,i),indent:-1,source:""},f=Nc.composeScalar(t,u,a,l);return o&&(f.anchor=o.source.substring(1),f.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),r&&(f.spaceBefore=!0),s&&(f.comment=s,f.range[2]=c),f}function Sm({options:t},{offset:e,source:n,end:i},r){let s=new gm.Alias(n.substring(1));s.source===""&&r(e,"BAD_ALIAS","Alias cannot be an empty string"),s.source.endsWith(":")&&r(e+n.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=e+n.length,a=vm.resolveEnd(i,o,t.strict,r);return s.range=[e,o,a.offset],a.comment&&(s.comment=a.comment),s}ys.composeEmptyNode=ws;ys.composeNode=Ac});var qc=v(Tc=>{"use strict";var Cm=Yt(),Ic=jc(),Em=ft(),xm=Vt();function _m(t,e,{offset:n,start:i,value:r,end:s},o){let a=Object.assign({_directives:e},t),c=new Cm.Document(void 0,a),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=xm.resolveProps(i,{indicator:"doc-start",next:r??s?.[0],offset:n,onError:o,parentIndent:0,startOnNewline:!0});u.found&&(c.directives.docStart=!0,r&&(r.type==="block-map"||r.type==="block-seq")&&!u.hasNewline&&o(u.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=r?Ic.composeNode(l,r,u,o):Ic.composeEmptyNode(l,u.end,i,null,u,o);let f=c.contents.range[2],d=Em.resolveEnd(s,f,!1,o);return d.comment&&(c.comment=d.comment),c.range=[n,f,d.offset],c}Tc.composeDoc=_m});var ks=v(Dc=>{"use strict";var Pm=vn("process"),Rm=sr(),Om=Yt(),Gt=Ht(),$c=_(),Nm=qc(),Am=ft();function zt(t){if(typeof t=="number")return[t,t+1];if(Array.isArray(t))return t.length===2?t:[t[0],t[1]];let{offset:e,source:n}=t;return[e,e+(typeof n=="string"?n.length:1)]}function Lc(t){let e="",n=!1,i=!1;for(let r=0;r{"use strict";var Ve=P(),xc=j(),fm=hs(),dm=ws();function pm(t,e,n,i){let{value:r,type:s,comment:o,range:a}=e.type==="block-scalar"?fm.resolveBlockScalar(t,e,i):dm.resolveFlowScalar(e,t.options.strict,i),c=n?t.directives.tagName(n.source,f=>i(n,"TAG_RESOLVE_FAILED",f)):null,l;t.options.stringKeys&&t.atKey?l=t.schema[Ve.SCALAR]:c?l=mm(t.schema,r,c,n,i):e.type==="scalar"?l=hm(t,r,e,i):l=t.schema[Ve.SCALAR];let u;try{let f=l.resolve(r,d=>i(n??e,"TAG_RESOLVE_FAILED",d),t.options);u=Ve.isScalar(f)?f:new xc.Scalar(f)}catch(f){let d=f instanceof Error?f.message:String(f);i(n??e,"TAG_RESOLVE_FAILED",d),u=new xc.Scalar(r)}return u.range=a,u.source=r,s&&(u.type=s),c&&(u.tag=c),l.format&&(u.format=l.format),o&&(u.comment=o),u}function mm(t,e,n,i,r){if(n==="!")return t[Ve.SCALAR];let s=[];for(let a of t.tags)if(!a.collection&&a.tag===n)if(a.default&&a.test)s.push(a);else return a;for(let a of s)if(a.test?.test(e))return a;let o=t.knownTags[n];return o&&!o.collection?(t.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(r(i,"TAG_RESOLVE_FAILED",`Unresolved tag: ${n}`,n!=="tag:yaml.org,2002:str"),t[Ve.SCALAR])}function hm({atKey:t,directives:e,schema:n},i,r,s){let o=n.tags.find(a=>(a.default===!0||t&&a.default==="key")&&a.test?.test(i))||n[Ve.SCALAR];if(n.compat){let a=n.compat.find(c=>c.default&&c.test?.test(i))??n[Ve.SCALAR];if(o.tag!==a.tag){let c=e.tagString(o.tag),l=e.tagString(a.tag),u=`Value may be parsed as either ${c} or ${l}`;s(r,"TAG_RESOLVE_FAILED",u,!0)}}return o}Pc.composeScalar=pm});var Oc=v(Rc=>{"use strict";function gm(t,e,n){if(e){n??(n=e.length);for(let i=n-1;i>=0;--i){let r=e[i];switch(r.type){case"space":case"comment":case"newline":t-=r.source.length;continue}for(r=e[++i];r?.type==="space";)t+=r.source.length,r=e[++i];break}}return t}Rc.emptyScalarPosition=gm});var jc=v(vs=>{"use strict";var wm=Rt(),ym=P(),vm=bc(),Nc=_c(),km=ft(),bm=Oc(),Sm={composeNode:Ac,composeEmptyNode:ys};function Ac(t,e,n,i){let r=t.atKey,{spaceBefore:s,comment:o,anchor:a,tag:c}=n,l,u=!0;switch(e.type){case"alias":l=Cm(t,e,i),(a||c)&&i(e,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=Nc.composeScalar(t,e,c,i),a&&(l.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=vm.composeCollection(Sm,t,e,n,i),a&&(l.anchor=a.source.substring(1))}catch(f){let d=f instanceof Error?f.message:String(f);i(e,"RESOURCE_EXHAUSTION",d)}break;default:{let f=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;i(e,"UNEXPECTED_TOKEN",f),u=!1}}return l??(l=ys(t,e.offset,void 0,null,n,i)),a&&l.anchor===""&&i(a,"BAD_ALIAS","Anchor cannot be an empty string"),r&&t.options.stringKeys&&(!ym.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&i(c??e,"NON_STRING_KEY","With stringKeys, all keys must be strings"),s&&(l.spaceBefore=!0),o&&(e.type==="scalar"&&e.source===""?l.comment=o:l.commentBefore=o),t.options.keepSourceTokens&&u&&(l.srcToken=e),l}function ys(t,e,n,i,{spaceBefore:r,comment:s,anchor:o,tag:a,end:c},l){let u={type:"scalar",offset:bm.emptyScalarPosition(e,n,i),indent:-1,source:""},f=Nc.composeScalar(t,u,a,l);return o&&(f.anchor=o.source.substring(1),f.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),r&&(f.spaceBefore=!0),s&&(f.comment=s,f.range[2]=c),f}function Cm({options:t},{offset:e,source:n,end:i},r){let s=new wm.Alias(n.substring(1));s.source===""&&r(e,"BAD_ALIAS","Alias cannot be an empty string"),s.source.endsWith(":")&&r(e+n.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=e+n.length,a=km.resolveEnd(i,o,t.strict,r);return s.range=[e,o,a.offset],a.comment&&(s.comment=a.comment),s}vs.composeEmptyNode=ys;vs.composeNode=Ac});var qc=v(Tc=>{"use strict";var Em=Yt(),Ic=jc(),xm=ft(),Pm=Vt();function _m(t,e,{offset:n,start:i,value:r,end:s},o){let a=Object.assign({_directives:e},t),c=new Em.Document(void 0,a),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=Pm.resolveProps(i,{indicator:"doc-start",next:r??s?.[0],offset:n,onError:o,parentIndent:0,startOnNewline:!0});u.found&&(c.directives.docStart=!0,r&&(r.type==="block-map"||r.type==="block-seq")&&!u.hasNewline&&o(u.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=r?Ic.composeNode(l,r,u,o):Ic.composeEmptyNode(l,u.end,i,null,u,o);let f=c.contents.range[2],d=xm.resolveEnd(s,f,!1,o);return d.comment&&(c.comment=d.comment),c.range=[n,f,d.offset],c}Tc.composeDoc=_m});var bs=v(Dc=>{"use strict";var Rm=vn("process"),Om=or(),Nm=Yt(),Gt=Ht(),$c=P(),Am=qc(),jm=ft();function zt(t){if(typeof t=="number")return[t,t+1];if(Array.isArray(t))return t.length===2?t:[t[0],t[1]];let{offset:e,source:n}=t;return[e,e+(typeof n=="string"?n.length:1)]}function Lc(t){let e="",n=!1,i=!1;for(let r=0;r{let o=zt(n);s?this.warnings.push(new Gt.YAMLWarning(o,i,r)):this.errors.push(new Gt.YAMLParseError(o,i,r))},this.directives=new Rm.Directives({version:e.version||"1.2"}),this.options=e}decorate(e,n){let{comment:i,afterEmptyLine:r}=Lc(this.prelude);if(i){let s=e.contents;if(n)e.comment=e.comment?`${e.comment} +`)+(s.substring(1)||" "),n=!0,i=!1;break;case"%":t[r+1]?.[0]!=="#"&&(r+=1),n=!1;break;default:n||(i=!0),n=!1}}return{comment:e,afterEmptyLine:i}}var ks=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(n,i,r,s)=>{let o=zt(n);s?this.warnings.push(new Gt.YAMLWarning(o,i,r)):this.errors.push(new Gt.YAMLParseError(o,i,r))},this.directives=new Om.Directives({version:e.version||"1.2"}),this.options=e}decorate(e,n){let{comment:i,afterEmptyLine:r}=Lc(this.prelude);if(i){let s=e.contents;if(n)e.comment=e.comment?`${e.comment} ${i}`:i;else if(r||e.directives.docStart||!s)e.commentBefore=i;else if($c.isCollection(s)&&!s.flow&&s.items.length>0){let o=s.items[0];$c.isPair(o)&&(o=o.key);let a=o.commentBefore;o.commentBefore=a?`${i} ${a}`:i}else{let o=s.commentBefore;s.commentBefore=o?`${i} -${o}`:i}}if(n){for(let s=0;s{let s=zt(e);s[0]+=n,this.onError(s,"BAD_DIRECTIVE",i,r)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let n=Nm.composeDoc(this.options,this.directives,e,this.onError);this.atDirectives&&!n.directives.docStart&&this.onError(e,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(n,!1),this.doc&&(yield this.doc),this.doc=n,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(e.source);break;case"error":{let n=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,i=new Gt.YAMLParseError(zt(e),"UNEXPECTED_TOKEN",n);this.atDirectives||!this.doc?this.errors.push(i):this.doc.errors.push(i);break}case"doc-end":{if(!this.doc){let i="Unexpected doc-end without preceding document";this.errors.push(new Gt.YAMLParseError(zt(e),"UNEXPECTED_TOKEN",i));break}this.doc.directives.docEnd=!0;let n=Am.resolveEnd(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),n.comment){let i=this.doc.comment;this.doc.comment=i?`${i} -${n.comment}`:n.comment}this.doc.range[2]=n.offset;break}default:this.errors.push(new Gt.YAMLParseError(zt(e),"UNEXPECTED_TOKEN",`Unsupported token ${e.type}`))}}*end(e=!1,n=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let i=Object.assign({_directives:this.directives},this.options),r=new Om.Document(void 0,i);this.atDirectives&&this.onError(n,"MISSING_CHAR","Missing directives-end indicator line"),r.range=[0,n,n],this.decorate(r,!1),yield r}}};Dc.Composer=vs});var Wc=v(ui=>{"use strict";var jm=ms(),Im=gs(),Tm=Ht(),Fc=It();function qm(t,e=!0,n){if(t){let i=(r,s,o)=>{let a=typeof r=="number"?r:Array.isArray(r)?r[0]:r.offset;if(n)n(a,s,o);else throw new Tm.YAMLParseError([a,a+1],s,o)};switch(t.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return Im.resolveFlowScalar(t,e,i);case"block-scalar":return jm.resolveBlockScalar({options:{strict:e}},t,i)}}return null}function $m(t,e){let{implicitKey:n=!1,indent:i,inFlow:r=!1,offset:s=-1,type:o="PLAIN"}=e,a=Fc.stringifyString({type:o,value:t},{implicitKey:n,indent:i>0?" ".repeat(i):"",inFlow:r,options:{blockQuote:!0,lineWidth:-1}}),c=e.end??[{type:"newline",offset:-1,indent:i,source:` +${o}`:i}}if(n){for(let s=0;s{let s=zt(e);s[0]+=n,this.onError(s,"BAD_DIRECTIVE",i,r)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let n=Am.composeDoc(this.options,this.directives,e,this.onError);this.atDirectives&&!n.directives.docStart&&this.onError(e,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(n,!1),this.doc&&(yield this.doc),this.doc=n,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(e.source);break;case"error":{let n=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,i=new Gt.YAMLParseError(zt(e),"UNEXPECTED_TOKEN",n);this.atDirectives||!this.doc?this.errors.push(i):this.doc.errors.push(i);break}case"doc-end":{if(!this.doc){let i="Unexpected doc-end without preceding document";this.errors.push(new Gt.YAMLParseError(zt(e),"UNEXPECTED_TOKEN",i));break}this.doc.directives.docEnd=!0;let n=jm.resolveEnd(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),n.comment){let i=this.doc.comment;this.doc.comment=i?`${i} +${n.comment}`:n.comment}this.doc.range[2]=n.offset;break}default:this.errors.push(new Gt.YAMLParseError(zt(e),"UNEXPECTED_TOKEN",`Unsupported token ${e.type}`))}}*end(e=!1,n=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let i=Object.assign({_directives:this.directives},this.options),r=new Nm.Document(void 0,i);this.atDirectives&&this.onError(n,"MISSING_CHAR","Missing directives-end indicator line"),r.range=[0,n,n],this.decorate(r,!1),yield r}}};Dc.Composer=ks});var Wc=v(ui=>{"use strict";var Im=hs(),Tm=ws(),qm=Ht(),Fc=It();function $m(t,e=!0,n){if(t){let i=(r,s,o)=>{let a=typeof r=="number"?r:Array.isArray(r)?r[0]:r.offset;if(n)n(a,s,o);else throw new qm.YAMLParseError([a,a+1],s,o)};switch(t.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return Tm.resolveFlowScalar(t,e,i);case"block-scalar":return Im.resolveBlockScalar({options:{strict:e}},t,i)}}return null}function Lm(t,e){let{implicitKey:n=!1,indent:i,inFlow:r=!1,offset:s=-1,type:o="PLAIN"}=e,a=Fc.stringifyString({type:o,value:t},{implicitKey:n,indent:i>0?" ".repeat(i):"",inFlow:r,options:{blockQuote:!0,lineWidth:-1}}),c=e.end??[{type:"newline",offset:-1,indent:i,source:` `}];switch(a[0]){case"|":case">":{let l=a.indexOf(` `),u=a.substring(0,l),f=a.substring(l+1)+` `,d=[{type:"block-scalar-header",offset:s,indent:i,source:u}];return Mc(d,c)||d.push({type:"newline",offset:-1,indent:i,source:` -`}),{type:"block-scalar",offset:s,indent:i,props:d,source:f}}case'"':return{type:"double-quoted-scalar",offset:s,indent:i,source:a,end:c};case"'":return{type:"single-quoted-scalar",offset:s,indent:i,source:a,end:c};default:return{type:"scalar",offset:s,indent:i,source:a,end:c}}}function Lm(t,e,n={}){let{afterKey:i=!1,implicitKey:r=!1,inFlow:s=!1,type:o}=n,a="indent"in t?t.indent:null;if(i&&typeof a=="number"&&(a+=2),!o)switch(t.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let l=t.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let c=Fc.stringifyString({type:o,value:e},{implicitKey:r||a===null,indent:a!==null&&a>0?" ".repeat(a):"",inFlow:s,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":Dm(t,c);break;case'"':bs(t,c,"double-quoted-scalar");break;case"'":bs(t,c,"single-quoted-scalar");break;default:bs(t,c,"scalar")}}function Dm(t,e){let n=e.indexOf(` +`}),{type:"block-scalar",offset:s,indent:i,props:d,source:f}}case'"':return{type:"double-quoted-scalar",offset:s,indent:i,source:a,end:c};case"'":return{type:"single-quoted-scalar",offset:s,indent:i,source:a,end:c};default:return{type:"scalar",offset:s,indent:i,source:a,end:c}}}function Dm(t,e,n={}){let{afterKey:i=!1,implicitKey:r=!1,inFlow:s=!1,type:o}=n,a="indent"in t?t.indent:null;if(i&&typeof a=="number"&&(a+=2),!o)switch(t.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let l=t.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let c=Fc.stringifyString({type:o,value:e},{implicitKey:r||a===null,indent:a!==null&&a>0?" ".repeat(a):"",inFlow:s,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":Fm(t,c);break;case'"':Ss(t,c,"double-quoted-scalar");break;case"'":Ss(t,c,"single-quoted-scalar");break;default:Ss(t,c,"scalar")}}function Fm(t,e){let n=e.indexOf(` `),i=e.substring(0,n),r=e.substring(n+1)+` `;if(t.type==="block-scalar"){let s=t.props[0];if(s.type!=="block-scalar-header")throw new Error("Invalid block scalar header");s.source=i,t.source=r}else{let{offset:s}=t,o="indent"in t?t.indent:-1,a=[{type:"block-scalar-header",offset:s,indent:o,source:i}];Mc(a,"end"in t?t.end:void 0)||a.push({type:"newline",offset:-1,indent:o,source:` -`});for(let c of Object.keys(t))c!=="type"&&c!=="offset"&&delete t[c];Object.assign(t,{type:"block-scalar",indent:o,props:a,source:r})}}function Mc(t,e){if(e)for(let n of e)switch(n.type){case"space":case"comment":t.push(n);break;case"newline":return t.push(n),!0}return!1}function bs(t,e,n){switch(t.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":t.type=n,t.source=e;break;case"block-scalar":{let i=t.props.slice(1),r=e.length;t.props[0].type==="block-scalar-header"&&(r-=t.props[0].source.length);for(let s of i)s.offset+=r;delete t.props,Object.assign(t,{type:n,source:e,end:i});break}case"block-map":case"block-seq":{let r={type:"newline",offset:t.offset+e.length,indent:t.indent,source:` -`};delete t.items,Object.assign(t,{type:n,source:e,end:[r]});break}default:{let i="indent"in t?t.indent:-1,r="end"in t&&Array.isArray(t.end)?t.end.filter(s=>s.type==="space"||s.type==="comment"||s.type==="newline"):[];for(let s of Object.keys(t))s!=="type"&&s!=="offset"&&delete t[s];Object.assign(t,{type:n,indent:i,source:e,end:r})}}}ui.createScalarToken=$m;ui.resolveAsScalar=qm;ui.setScalarValue=Lm});var Kc=v(Bc=>{"use strict";var Fm=t=>"type"in t?di(t):fi(t);function di(t){switch(t.type){case"block-scalar":{let e="";for(let n of t.props)e+=di(n);return e+t.source}case"block-map":case"block-seq":{let e="";for(let n of t.items)e+=fi(n);return e}case"flow-collection":{let e=t.start.source;for(let n of t.items)e+=fi(n);for(let n of t.end)e+=n.source;return e}case"document":{let e=fi(t);if(t.end)for(let n of t.end)e+=n.source;return e}default:{let e=t.source;if("end"in t&&t.end)for(let n of t.end)e+=n.source;return e}}}function fi({start:t,key:e,sep:n,value:i}){let r="";for(let s of t)r+=s.source;if(e&&(r+=di(e)),n)for(let s of n)r+=s.source;return i&&(r+=di(i)),r}Bc.stringify=Fm});var Hc=v(Uc=>{"use strict";var Ss=Symbol("break visit"),Mm=Symbol("skip children"),Yc=Symbol("remove item");function Ve(t,e){"type"in t&&t.type==="document"&&(t={start:t.start,value:t.value}),Jc(Object.freeze([]),t,e)}Ve.BREAK=Ss;Ve.SKIP=Mm;Ve.REMOVE=Yc;Ve.itemAtPath=(t,e)=>{let n=t;for(let[i,r]of e){let s=n?.[i];if(s&&"items"in s)n=s.items[r];else return}return n};Ve.parentCollection=(t,e)=>{let n=Ve.itemAtPath(t,e.slice(0,-1)),i=e[e.length-1][0],r=n?.[i];if(r&&"items"in r)return r;throw new Error("Parent collection not found")};function Jc(t,e,n){let i=n(e,t);if(typeof i=="symbol")return i;for(let r of["key","value"]){let s=e[r];if(s&&"items"in s){for(let o=0;o{"use strict";var Cs=Wc(),Wm=Kc(),Bm=Hc(),Es="\uFEFF",xs="",_s="",Ps="",Km=t=>!!t&&"items"in t,Ym=t=>!!t&&(t.type==="scalar"||t.type==="single-quoted-scalar"||t.type==="double-quoted-scalar"||t.type==="block-scalar");function Jm(t){switch(t){case Es:return"";case xs:return"";case _s:return"";case Ps:return"";default:return JSON.stringify(t)}}function Um(t){switch(t){case Es:return"byte-order-mark";case xs:return"doc-mode";case _s:return"flow-error-end";case Ps:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case` +`});for(let c of Object.keys(t))c!=="type"&&c!=="offset"&&delete t[c];Object.assign(t,{type:"block-scalar",indent:o,props:a,source:r})}}function Mc(t,e){if(e)for(let n of e)switch(n.type){case"space":case"comment":t.push(n);break;case"newline":return t.push(n),!0}return!1}function Ss(t,e,n){switch(t.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":t.type=n,t.source=e;break;case"block-scalar":{let i=t.props.slice(1),r=e.length;t.props[0].type==="block-scalar-header"&&(r-=t.props[0].source.length);for(let s of i)s.offset+=r;delete t.props,Object.assign(t,{type:n,source:e,end:i});break}case"block-map":case"block-seq":{let r={type:"newline",offset:t.offset+e.length,indent:t.indent,source:` +`};delete t.items,Object.assign(t,{type:n,source:e,end:[r]});break}default:{let i="indent"in t?t.indent:-1,r="end"in t&&Array.isArray(t.end)?t.end.filter(s=>s.type==="space"||s.type==="comment"||s.type==="newline"):[];for(let s of Object.keys(t))s!=="type"&&s!=="offset"&&delete t[s];Object.assign(t,{type:n,indent:i,source:e,end:r})}}}ui.createScalarToken=Lm;ui.resolveAsScalar=$m;ui.setScalarValue=Dm});var Kc=v(Bc=>{"use strict";var Mm=t=>"type"in t?di(t):fi(t);function di(t){switch(t.type){case"block-scalar":{let e="";for(let n of t.props)e+=di(n);return e+t.source}case"block-map":case"block-seq":{let e="";for(let n of t.items)e+=fi(n);return e}case"flow-collection":{let e=t.start.source;for(let n of t.items)e+=fi(n);for(let n of t.end)e+=n.source;return e}case"document":{let e=fi(t);if(t.end)for(let n of t.end)e+=n.source;return e}default:{let e=t.source;if("end"in t&&t.end)for(let n of t.end)e+=n.source;return e}}}function fi({start:t,key:e,sep:n,value:i}){let r="";for(let s of t)r+=s.source;if(e&&(r+=di(e)),n)for(let s of n)r+=s.source;return i&&(r+=di(i)),r}Bc.stringify=Mm});var Hc=v(Uc=>{"use strict";var Cs=Symbol("break visit"),Wm=Symbol("skip children"),Yc=Symbol("remove item");function Ge(t,e){"type"in t&&t.type==="document"&&(t={start:t.start,value:t.value}),Jc(Object.freeze([]),t,e)}Ge.BREAK=Cs;Ge.SKIP=Wm;Ge.REMOVE=Yc;Ge.itemAtPath=(t,e)=>{let n=t;for(let[i,r]of e){let s=n?.[i];if(s&&"items"in s)n=s.items[r];else return}return n};Ge.parentCollection=(t,e)=>{let n=Ge.itemAtPath(t,e.slice(0,-1)),i=e[e.length-1][0],r=n?.[i];if(r&&"items"in r)return r;throw new Error("Parent collection not found")};function Jc(t,e,n){let i=n(e,t);if(typeof i=="symbol")return i;for(let r of["key","value"]){let s=e[r];if(s&&"items"in s){for(let o=0;o{"use strict";var Es=Wc(),Bm=Kc(),Km=Hc(),xs="\uFEFF",Ps="",_s="",Rs="",Ym=t=>!!t&&"items"in t,Jm=t=>!!t&&(t.type==="scalar"||t.type==="single-quoted-scalar"||t.type==="double-quoted-scalar"||t.type==="block-scalar");function Um(t){switch(t){case xs:return"";case Ps:return"";case _s:return"";case Rs:return"";default:return JSON.stringify(t)}}function Hm(t){switch(t){case xs:return"byte-order-mark";case Ps:return"doc-mode";case _s:return"flow-error-end";case Rs:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case` `:case`\r -`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(t[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}H.createScalarToken=Cs.createScalarToken;H.resolveAsScalar=Cs.resolveAsScalar;H.setScalarValue=Cs.setScalarValue;H.stringify=Wm.stringify;H.visit=Bm.visit;H.BOM=Es;H.DOCUMENT=xs;H.FLOW_END=_s;H.SCALAR=Ps;H.isCollection=Km;H.isScalar=Ym;H.prettyToken=Jm;H.tokenType=Um});var Ns=v(Gc=>{"use strict";var Qt=pi();function ee(t){switch(t){case void 0:case" ":case` -`:case"\r":case" ":return!0;default:return!1}}var Vc=new Set("0123456789ABCDEFabcdef"),Hm=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),mi=new Set(",[]{}"),Vm=new Set(` ,[]{} -\r `),Rs=t=>!t||Vm.has(t),Os=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,n=!1){if(e){if(typeof e!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!n;let i=this.next??"stream";for(;i&&(n||this.hasChars(1));)i=yield*this.parseNext(i)}atLineEnd(){let e=this.pos,n=this.buffer[e];for(;n===" "||n===" ";)n=this.buffer[++e];return!n||n==="#"||n===` +`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(t[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}H.createScalarToken=Es.createScalarToken;H.resolveAsScalar=Es.resolveAsScalar;H.setScalarValue=Es.setScalarValue;H.stringify=Bm.stringify;H.visit=Km.visit;H.BOM=xs;H.DOCUMENT=Ps;H.FLOW_END=_s;H.SCALAR=Rs;H.isCollection=Ym;H.isScalar=Jm;H.prettyToken=Um;H.tokenType=Hm});var As=v(Gc=>{"use strict";var Qt=pi();function ee(t){switch(t){case void 0:case" ":case` +`:case"\r":case" ":return!0;default:return!1}}var Vc=new Set("0123456789ABCDEFabcdef"),Vm=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),mi=new Set(",[]{}"),Gm=new Set(` ,[]{} +\r `),Os=t=>!t||Gm.has(t),Ns=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,n=!1){if(e){if(typeof e!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!n;let i=this.next??"stream";for(;i&&(n||this.hasChars(1));)i=yield*this.parseNext(i)}atLineEnd(){let e=this.pos,n=this.buffer[e];for(;n===" "||n===" ";)n=this.buffer[++e];return!n||n==="#"||n===` `?!0:n==="\r"?this.buffer[e+1]===` `:!1}charAt(e){return this.buffer[this.pos+e]}continueScalar(e){let n=this.buffer[e];if(this.indentNext>0){let i=0;for(;n===" ";)n=this.buffer[++i+e];if(n==="\r"){let r=this.buffer[i+e+1];if(r===` `||!r&&!this.atEnd)return e+i+1}return n===` `||i>=this.indentNext||!n&&!this.atEnd?e+i:-1}if(n==="-"||n==="."){let i=this.buffer.substr(e,3);if((i==="---"||i==="...")&&ee(this.buffer[e+3]))return-1}return e}getLine(){let e=this.lineEndPos;return(typeof e!="number"||e!==-1&&ethis.indentValue&&!ee(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[e,n]=this.peek(2);if(!n&&!this.atEnd)return this.setNext("block-start");if((e==="-"||e==="?"||e===":")&&ee(n)){let i=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=i,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let e=this.getLine();if(e===null)return this.setNext("doc");let n=yield*this.pushIndicators();switch(e[n]){case"#":yield*this.pushCount(e.length-n);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(Rs),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return n+=yield*this.parseBlockScalarHeader(),n+=yield*this.pushSpaces(!0),yield*this.pushCount(e.length-n),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,n,i=-1;do e=yield*this.pushNewline(),e>0?(n=yield*this.pushSpaces(!1),this.indentValue=i=n):n=0,n+=yield*this.pushSpaces(!0);while(e+n>0);let r=this.getLine();if(r===null)return this.setNext("flow");if((i!==-1&&ithis.indentValue&&!ee(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[e,n]=this.peek(2);if(!n&&!this.atEnd)return this.setNext("block-start");if((e==="-"||e==="?"||e===":")&&ee(n)){let i=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=i,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let e=this.getLine();if(e===null)return this.setNext("doc");let n=yield*this.pushIndicators();switch(e[n]){case"#":yield*this.pushCount(e.length-n);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(Os),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return n+=yield*this.parseBlockScalarHeader(),n+=yield*this.pushSpaces(!0),yield*this.pushCount(e.length-n),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,n,i=-1;do e=yield*this.pushNewline(),e>0?(n=yield*this.pushSpaces(!1),this.indentValue=i=n):n=0,n+=yield*this.pushSpaces(!0);while(e+n>0);let r=this.getLine();if(r===null)return this.setNext("flow");if((i!==-1&&i"0"&&n<="9")this.blockScalarIndent=Number(n)-1;else if(n!=="-")break}return yield*this.pushUntil(n=>ee(n)||n==="#")}*parseBlockScalar(){let e=this.pos-1,n=0,i;e:for(let s=this.pos;i=this.buffer[s];++s)switch(i){case" ":n+=1;break;case` `:e=s,n=0;break;case"\r":{let o=this.buffer[s+1];if(!o&&!this.atEnd)return this.setNext("block-scalar");if(o===` @@ -133,34 +133,34 @@ ${n.comment}`:n.comment}this.doc.range[2]=n.offset;break}default:this.errors.pus `&&s>=this.pos&&s+1+n>a)e=s;else break}while(!0);return yield Qt.SCALAR,yield*this.pushToIndex(e+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let e=this.flowLevel>0,n=this.pos-1,i=this.pos-1,r;for(;r=this.buffer[++i];)if(r===":"){let s=this.buffer[i+1];if(ee(s)||e&&mi.has(s))break;n=i}else if(ee(r)){let s=this.buffer[i+1];if(r==="\r"&&(s===` `?(i+=1,r=` `,s=this.buffer[i+1]):n=i),s==="#"||e&&mi.has(s))break;if(r===` -`){let o=this.continueScalar(i+1);if(o===-1)break;i=Math.max(i,o-2)}}else{if(e&&mi.has(r))break;n=i}return!r&&!this.atEnd?this.setNext("plain-scalar"):(yield Qt.SCALAR,yield*this.pushToIndex(n+1,!0),e?"flow":"doc")}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,n){let i=this.buffer.slice(this.pos,e);return i?(yield i,this.pos+=i.length,i.length):(n&&(yield""),0)}*pushIndicators(){let e=0;e:for(;;){switch(this.charAt(0)){case"!":e+=yield*this.pushTag(),e+=yield*this.pushSpaces(!0);continue e;case"&":e+=yield*this.pushUntil(Rs),e+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let n=this.flowLevel>0,i=this.charAt(1);if(ee(i)||n&&mi.has(i)){n?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,e+=yield*this.pushCount(1),e+=yield*this.pushSpaces(!0);continue e}}}break e}return e}*pushTag(){if(this.charAt(1)==="<"){let e=this.pos+2,n=this.buffer[e];for(;!ee(n)&&n!==">";)n=this.buffer[++e];return yield*this.pushToIndex(n===">"?e+1:e,!1)}else{let e=this.pos+1,n=this.buffer[e];for(;n;)if(Hm.has(n))n=this.buffer[++e];else if(n==="%"&&Vc.has(this.buffer[e+1])&&Vc.has(this.buffer[e+2]))n=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];return e===` +`){let o=this.continueScalar(i+1);if(o===-1)break;i=Math.max(i,o-2)}}else{if(e&&mi.has(r))break;n=i}return!r&&!this.atEnd?this.setNext("plain-scalar"):(yield Qt.SCALAR,yield*this.pushToIndex(n+1,!0),e?"flow":"doc")}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,n){let i=this.buffer.slice(this.pos,e);return i?(yield i,this.pos+=i.length,i.length):(n&&(yield""),0)}*pushIndicators(){let e=0;e:for(;;){switch(this.charAt(0)){case"!":e+=yield*this.pushTag(),e+=yield*this.pushSpaces(!0);continue e;case"&":e+=yield*this.pushUntil(Os),e+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let n=this.flowLevel>0,i=this.charAt(1);if(ee(i)||n&&mi.has(i)){n?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,e+=yield*this.pushCount(1),e+=yield*this.pushSpaces(!0);continue e}}}break e}return e}*pushTag(){if(this.charAt(1)==="<"){let e=this.pos+2,n=this.buffer[e];for(;!ee(n)&&n!==">";)n=this.buffer[++e];return yield*this.pushToIndex(n===">"?e+1:e,!1)}else{let e=this.pos+1,n=this.buffer[e];for(;n;)if(Vm.has(n))n=this.buffer[++e];else if(n==="%"&&Vc.has(this.buffer[e+1])&&Vc.has(this.buffer[e+2]))n=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];return e===` `?yield*this.pushCount(1):e==="\r"&&this.charAt(1)===` -`?yield*this.pushCount(2):0}*pushSpaces(e){let n=this.pos-1,i;do i=this.buffer[++n];while(i===" "||e&&i===" ");let r=n-this.pos;return r>0&&(yield this.buffer.substr(this.pos,r),this.pos=n),r}*pushUntil(e){let n=this.pos,i=this.buffer[n];for(;!e(i);)i=this.buffer[++n];return yield*this.pushToIndex(n,!1)}};Gc.Lexer=Os});var js=v(zc=>{"use strict";var As=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let n=0,i=this.lineStarts.length;for(;n>1;this.lineStarts[s]{"use strict";var Gm=vn("process"),Qc=pi(),zm=Ns();function Re(t,e){for(let n=0;n=0;)switch(t[e].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;t[++e]?.type==="space";);return t.splice(e,t.length)}function gi(t,e){if(e.length<1e5)Array.prototype.push.apply(t,e);else for(let n=0;n0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let e=this.peek(1);if(this.type==="doc-end"&&e?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!e)return yield*this.stream();switch(e.type){case"document":return yield*this.document(e);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(e);case"block-scalar":return yield*this.blockScalar(e);case"block-map":return yield*this.blockMap(e);case"block-seq":return yield*this.blockSequence(e);case"flow-collection":return yield*this.flowCollection(e);case"doc-end":return yield*this.documentEnd(e)}yield*this.pop()}peek(e){return this.stack[this.stack.length-e]}*pop(e){let n=e??this.stack.pop();if(!n)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield n;else{let i=this.peek(1);switch(n.type==="block-scalar"?n.indent="indent"in i?i.indent:0:n.type==="flow-collection"&&i.type==="document"&&(n.indent=0),n.type==="flow-collection"&&Zc(n),i.type){case"document":i.value=n;break;case"block-scalar":i.props.push(n);break;case"block-map":{let r=i.items[i.items.length-1];if(r.value){i.items.push({start:[],key:n,sep:[]}),this.onKeyLine=!0;return}else if(r.sep)r.value=n;else{Object.assign(r,{key:n,sep:[]}),this.onKeyLine=!r.explicitKey;return}break}case"block-seq":{let r=i.items[i.items.length-1];r.value?i.items.push({start:[],value:n}):r.value=n;break}case"flow-collection":{let r=i.items[i.items.length-1];!r||r.value?i.items.push({start:[],key:n,sep:[]}):r.sep?r.value=n:Object.assign(r,{key:n,sep:[]});return}default:yield*this.pop(),yield*this.pop(n)}if((i.type==="document"||i.type==="block-map"||i.type==="block-seq")&&(n.type==="block-map"||n.type==="block-seq")){let r=n.items[n.items.length-1];r&&!r.sep&&!r.value&&r.start.length>0&&Xc(r.start)===-1&&(n.indent===0||r.start.every(s=>s.type!=="comment"||s.indent0&&(yield this.buffer.substr(this.pos,r),this.pos=n),r}*pushUntil(e){let n=this.pos,i=this.buffer[n];for(;!e(i);)i=this.buffer[++n];return yield*this.pushToIndex(n,!1)}};Gc.Lexer=Ns});var Is=v(zc=>{"use strict";var js=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let n=0,i=this.lineStarts.length;for(;n>1;this.lineStarts[s]{"use strict";var zm=vn("process"),Qc=pi(),Qm=As();function Re(t,e){for(let n=0;n=0;)switch(t[e].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;t[++e]?.type==="space";);return t.splice(e,t.length)}function gi(t,e){if(e.length<1e5)Array.prototype.push.apply(t,e);else for(let n=0;n0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let e=this.peek(1);if(this.type==="doc-end"&&e?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!e)return yield*this.stream();switch(e.type){case"document":return yield*this.document(e);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(e);case"block-scalar":return yield*this.blockScalar(e);case"block-map":return yield*this.blockMap(e);case"block-seq":return yield*this.blockSequence(e);case"flow-collection":return yield*this.flowCollection(e);case"doc-end":return yield*this.documentEnd(e)}yield*this.pop()}peek(e){return this.stack[this.stack.length-e]}*pop(e){let n=e??this.stack.pop();if(!n)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield n;else{let i=this.peek(1);switch(n.type==="block-scalar"?n.indent="indent"in i?i.indent:0:n.type==="flow-collection"&&i.type==="document"&&(n.indent=0),n.type==="flow-collection"&&Zc(n),i.type){case"document":i.value=n;break;case"block-scalar":i.props.push(n);break;case"block-map":{let r=i.items[i.items.length-1];if(r.value){i.items.push({start:[],key:n,sep:[]}),this.onKeyLine=!0;return}else if(r.sep)r.value=n;else{Object.assign(r,{key:n,sep:[]}),this.onKeyLine=!r.explicitKey;return}break}case"block-seq":{let r=i.items[i.items.length-1];r.value?i.items.push({start:[],value:n}):r.value=n;break}case"flow-collection":{let r=i.items[i.items.length-1];!r||r.value?i.items.push({start:[],key:n,sep:[]}):r.sep?r.value=n:Object.assign(r,{key:n,sep:[]});return}default:yield*this.pop(),yield*this.pop(n)}if((i.type==="document"||i.type==="block-map"||i.type==="block-seq")&&(n.type==="block-map"||n.type==="block-seq")){let r=n.items[n.items.length-1];r&&!r.sep&&!r.value&&r.start.length>0&&Xc(r.start)===-1&&(n.indent===0||r.start.every(s=>s.type!=="comment"||s.indent=e.indent){let i=!this.onKeyLine&&this.indent===e.indent,r=i&&(n.sep||n.explicitKey)&&this.type!=="seq-item-ind",s=[];if(r&&n.sep&&!n.value){let o=[];for(let a=0;ae.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(s=n.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":r||n.value?(s.push(this.sourceToken),e.items.push({start:s}),this.onKeyLine=!0):n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"explicit-key-ind":!n.sep&&!n.explicitKey?(n.start.push(this.sourceToken),n.explicitKey=!0):r||n.value?(s.push(this.sourceToken),e.items.push({start:s,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(n.explicitKey)if(n.sep)if(n.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(Re(n.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:s,key:null,sep:[this.sourceToken]}]});else if(el(n.key)&&!Re(n.sep,"newline")){let o=dt(n.start),a=n.key,c=n.sep;c.push(this.sourceToken),delete n.key,delete n.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:a,sep:c}]})}else s.length>0?n.sep=n.sep.concat(s,this.sourceToken):n.sep.push(this.sourceToken);else if(Re(n.start,"newline"))Object.assign(n,{key:null,sep:[this.sourceToken]});else{let o=dt(n.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else n.sep?n.value||r?e.items.push({start:s,key:null,sep:[this.sourceToken]}):Re(n.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):n.sep.push(this.sourceToken):Object.assign(n,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);r||n.value?(e.items.push({start:s,key:o,sep:[]}),this.onKeyLine=!0):n.sep?this.stack.push(o):(Object.assign(n,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(e);if(o){if(o.type==="block-seq"){if(!n.explicitKey&&n.sep&&!Re(n.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else i&&e.items.push({start:s});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let n=e.items[e.items.length-1];switch(this.type){case"newline":if(n.value){let i="end"in n.value?n.value.end:void 0;(Array.isArray(i)?i[i.length-1]:void 0)?.type==="comment"?i?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else n.start.push(this.sourceToken);return;case"space":case"comment":if(n.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(n.start,e.indent)){let r=e.items[e.items.length-2]?.value?.end;if(Array.isArray(r)){gi(r,n.start),r.push(this.sourceToken),e.items.pop();return}}n.start.push(this.sourceToken)}return;case"anchor":case"tag":if(n.value||this.indent<=e.indent)break;n.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;n.value||Re(n.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):n.start.push(this.sourceToken);return}if(this.indent>e.indent){let i=this.startBlockValue(e);if(i){this.stack.push(i);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let n=e.items[e.items.length-1];if(this.type==="flow-error-end"){let i;do yield*this.pop(),i=this.peek(1);while(i?.type==="flow-collection")}else if(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!n||n.sep?e.items.push({start:[this.sourceToken]}):n.start.push(this.sourceToken);return;case"map-value-ind":!n||n.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):n.sep?n.sep.push(this.sourceToken):Object.assign(n,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!n||n.value?e.items.push({start:[this.sourceToken]}):n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let r=this.flowScalar(this.type);!n||n.value?e.items.push({start:[],key:r,sep:[]}):n.sep?this.stack.push(r):Object.assign(n,{key:r,sep:[]});return}case"flow-map-end":case"flow-seq-end":e.end.push(this.sourceToken);return}let i=this.startBlockValue(e);i?this.stack.push(i):(yield*this.pop(),yield*this.step())}else{let i=this.peek(2);if(i.type==="block-map"&&(this.type==="map-value-ind"&&i.indent===e.indent||this.type==="newline"&&!i.items[i.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&i.type!=="flow-collection"){let r=hi(i),s=dt(r);Zc(e);let o=e.end.splice(1,e.end.length);o.push(this.sourceToken);let a={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:s,key:e,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let n=this.source.indexOf(` `)+1;for(;n!==0;)this.onNewLine(this.offset+n),n=this.source.indexOf(` -`,n)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let n=hi(e),i=dt(n);return i.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let n=hi(e),i=dt(n);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,n){return this.type!=="comment"||this.indent<=n?!1:e.every(i=>i.type==="newline"||i.type==="space")}*documentEnd(e){this.type!=="doc-mode"&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};tl.Parser=Is});var ol=v(Zt=>{"use strict";var nl=ks(),Qm=Yt(),Xt=Ht(),Xm=yr(),Zm=_(),eh=js(),il=Ts();function rl(t){let e=t.prettyErrors!==!1;return{lineCounter:t.lineCounter||e&&new eh.LineCounter||null,prettyErrors:e}}function th(t,e={}){let{lineCounter:n,prettyErrors:i}=rl(e),r=new il.Parser(n?.addNewLine),s=new nl.Composer(e),o=Array.from(s.compose(r.parse(t)));if(i&&n)for(let a of o)a.errors.forEach(Xt.prettifyError(t,n)),a.warnings.forEach(Xt.prettifyError(t,n));return o.length>0?o:Object.assign([],{empty:!0},s.streamInfo())}function sl(t,e={}){let{lineCounter:n,prettyErrors:i}=rl(e),r=new il.Parser(n?.addNewLine),s=new nl.Composer(e),o=null;for(let a of s.compose(r.parse(t),!0,t.length))if(!o)o=a;else if(o.options.logLevel!=="silent"){o.errors.push(new Xt.YAMLParseError(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return i&&n&&(o.errors.forEach(Xt.prettifyError(t,n)),o.warnings.forEach(Xt.prettifyError(t,n))),o}function nh(t,e,n){let i;typeof e=="function"?i=e:n===void 0&&e&&typeof e=="object"&&(n=e);let r=sl(t,n);if(!r)return null;if(r.warnings.forEach(s=>Xm.warn(r.options.logLevel,s)),r.errors.length>0){if(r.options.logLevel!=="silent")throw r.errors[0];r.errors=[]}return r.toJS(Object.assign({reviver:i},n))}function ih(t,e,n){let i=null;if(typeof e=="function"||Array.isArray(e)?i=e:n===void 0&&e&&(n=e),typeof n=="string"&&(n=n.length),typeof n=="number"){let r=Math.round(n);n=r<1?void 0:r>8?{indent:8}:{indent:r}}if(t===void 0){let{keepUndefined:r}=n??e??{};if(!r)return}return Zm.isDocument(t)&&!i?t.toString(n):new Qm.Document(t,i,n).toString(n)}Zt.parse=nh;Zt.parseAllDocuments=th;Zt.parseDocument=sl;Zt.stringify=ih});var pt=v(P=>{"use strict";var rh=ks(),sh=Yt(),oh=es(),qs=Ht(),ah=Rt(),Oe=_(),ch=Ee(),lh=j(),uh=_e(),fh=Pe(),dh=pi(),ph=Ns(),mh=js(),hh=Ts(),wi=ol(),al=Et();P.Composer=rh.Composer;P.Document=sh.Document;P.Schema=oh.Schema;P.YAMLError=qs.YAMLError;P.YAMLParseError=qs.YAMLParseError;P.YAMLWarning=qs.YAMLWarning;P.Alias=ah.Alias;P.isAlias=Oe.isAlias;P.isCollection=Oe.isCollection;P.isDocument=Oe.isDocument;P.isMap=Oe.isMap;P.isNode=Oe.isNode;P.isPair=Oe.isPair;P.isScalar=Oe.isScalar;P.isSeq=Oe.isSeq;P.Pair=ch.Pair;P.Scalar=lh.Scalar;P.YAMLMap=uh.YAMLMap;P.YAMLSeq=fh.YAMLSeq;P.CST=dh;P.Lexer=ph.Lexer;P.LineCounter=mh.LineCounter;P.Parser=hh.Parser;P.parse=wi.parse;P.parseAllDocuments=wi.parseAllDocuments;P.parseDocument=wi.parseDocument;P.stringify=wi.stringify;P.visit=al.visit;P.visitAsync=al.visitAsync});import yi from"path";function kh(t,e){if(typeof t!="string")throw new Error(`${e} must be a string`);let n=t.trim();if(n.length===0||yi.posix.isAbsolute(n)||yi.win32.isAbsolute(n)||/^(?:~|[\\/])/u.test(n))throw new Error(`${e} must be a project-relative path`);if(n===".")return[];let i=n.replaceAll("\\","/").split("/");if(i.some(r=>r===".."))throw new Error(`${e} must stay inside the project root`);if(i.some(r=>r===""||r==="."))throw new Error(`${e} must not contain empty or dot path segments`);return i}function vi(t){let e=kh(t,"native.artifact_root");return e.length===0?".":e.join("/")}function ll(t,e="docs"){let n=t??e;if(n!=="legacy"&&n!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return n}function Ne(t,e,n=!1){if(typeof t!="string")throw new Error(`${e} must be a string`);let i=t.trim().replaceAll("\\","/");if(i.length===0||yi.posix.isAbsolute(i)||yi.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${e} must be relative to its declared path base`);let r=i.split("/");if(r.some(s=>s===".."))throw new Error(`${e} must stay inside its declared path base`);if(r.some(s=>s===""||s==="."))throw new Error(`${e} must not contain empty or dot path segments`);if(!n&&/[*?]/u.test(i))throw new Error(`${e} cannot contain wildcards`);return r.join("/")}function tn(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function ul(t,e,n){let i=t??e;if(i!=="en"&&i!=="zh-CN")throw new Error(`${n} must be en or zh-CN`);return i}function fl(t,e){if(typeof t!="string"||t.length===0||t.includes("\\")||t.includes("\0")||t.startsWith("/")||t.split("/").includes(".."))throw new Error(`${e} contains an unsafe pattern`);if(t.length>Ls)throw new Error(`${e} exceeds ${Ls} characters`);let n=0;for(let i=0;iDs)throw new Error(`${e} contains more than ${Ds} wildcard tokens`);return t}function cl(t,e,n){if(t===void 0)return[...n];if(!Array.isArray(t))throw new Error(`${e} contains an unsafe pattern`);return[...new Set(t.map(i=>fl(i,e)))].sort((i,r)=>i.localeCompare(r,"en"))}function $s(t,e,n){let i=t??e;if(!Number.isSafeInteger(i)||i<1)throw new Error(`${n} must be a positive integer`);return i}function bh(t){if(t===void 0)return{...pe,include:[...pe.include],exclude:[...pe.exclude]};let e=tn(t,"native.snapshot");return{include:cl(e.include,"native.snapshot.include",pe.include),exclude:cl(e.exclude,"native.snapshot.exclude",pe.exclude),max_files:$s(e.max_files,pe.max_files,"native.snapshot.max_files"),max_total_bytes:$s(e.max_total_bytes,pe.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:$s(e.max_duration_ms,pe.max_duration_ms,"native.snapshot.max_duration_ms")}}function Sh(t){if(t===void 0)return;let e=tn(t,"native.pending_root_move"),n=e.id,i=e.from_artifact_root,r=e.to_artifact_root,s=e.stage;if(typeof n!="string"||!/^[a-f0-9-]{8,}$/u.test(n))throw new Error("native.pending_root_move.id is invalid");if(typeof i!="string"||typeof r!="string")throw new Error("native.pending_root_move roots must be strings");if(s!=="copying"&&s!=="ready"&&s!=="switched")throw new Error("native.pending_root_move.stage is invalid");let o;if(e.cleanup!==void 0){let a=tn(e.cleanup,"native.pending_root_move.cleanup"),c=a.kind,l=a.state,u=a.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof u!="string"||!/^[a-f0-9]{64}$/u.test(u))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:u}}return{id:n,fromArtifactRoot:vi(i),toArtifactRoot:vi(r),stage:s,...o?{cleanup:o}:{}}}function Ch(t,e={}){let n=tn(t,"native"),i=n.artifact_root??(e.allowMissingArtifactRoot?"docs":void 0);if(typeof i!="string")throw new Error("native.artifact_root must be a string");let r=n.clarification_mode??"sequential";if(r!=="sequential"&&r!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let s=n.archive_confirmation??"automatic";if(s!=="automatic"&&s!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=n.max_verify_failures??yh;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let a=Sh(n.pending_root_move);return{artifact_root:vi(i),language:ul(n.language,"en","native.language"),clarification_mode:r,archive_confirmation:s,max_verify_failures:o,snapshot:bh(n.snapshot),...a?{pending_root_move:a}:{}}}function Eh(t){let e=tn(t,"classic"),n=e.context_compression??"off";if(n!=="off"&&n!=="beta")throw new Error("classic.context_compression must be off or beta");let i=e.review_mode??"standard";if(i!=="off"&&i!=="standard"&&i!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let r=e.auto_transition??!0;if(typeof r!="boolean")throw new Error("classic.auto_transition must be true or false");return{artifact_layout:ll(e.artifact_layout),language:ul(e.language,"zh-CN","classic.language"),context_compression:n,review_mode:i,auto_transition:r}}function xh(t){let e=t??!0;if(typeof e!="boolean")throw new Error("ambient_resume must be true or false");return e}function _h(t,e,n,i,r){let s=t.schema!==void 0;if(!(s||t.default_workflow!==void 0||t.workflows!==void 0||!r.allowPartialProject&&t.native!==void 0)||r.allowPartialProject&&!s)return null;if(t.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(t.default_workflow!=="native"&&t.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let a=t.workflows??[t.default_workflow];if(!Array.isArray(a)||a.length===0||a.some(l=>l!=="native"&&l!=="classic"))throw new Error("workflows must contain native and/or classic");let c=[...new Set(a)];if(!c.includes(t.default_workflow))throw new Error("workflows must include default_workflow");if(c.includes("native")&&!e)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:t.default_workflow,workflows:c,ambient_resume:i,...e?{native:e}:{},...n?{classic:n}:{}}}function mt(t,e={}){let n=(0,Fs.parseDocument)(t,{uniqueKeys:!0});if(n.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${n.errors[0].message}`);let i=n.toJS();if(i==null)return{value:{},config:null,ambient_resume:!0};if(typeof i!="object"||Array.isArray(i))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let r=i,s=xh(r.ambient_resume),o=r.native===void 0?void 0:Ch(r.native,{allowMissingArtifactRoot:e.allowMissingNativeFields}),a=r.classic===void 0?void 0:Eh(r.classic),c=_h(r,o,a,s,{allowPartialProject:e.allowPartialProject??!1});return{value:r,config:c,ambient_resume:s,...o?{native:o}:{},...a?{classic:a}:{}}}var Fs,nn,Ls,Ds,yh,vh,pe,me=W(()=>{"use strict";Fs=Ct(pt(),1),nn=64*1024,Ls=1024,Ds=64,yh=5,vh=[".agents/skills/**",".amazonq/skills/**",".augment/skills/**",".bob/skills/**",".claude/skills/**",".cline/skills/**",".codebuddy/skills/**",".continue/skills/**",".cospec/skills/**",".crush/skills/**",".cursor/skills/**",".factory/skills/**",".forge/skills/**",".gemini/skills/**",".github/skills/**",".iflow/skills/**",".junie/skills/**",".kilocode/skills/**",".kimi-code/skills/**",".kiro/skills/**",".lingma/skills/**",".mimocode/skills/**",".opencode/skills/**",".pi/skills/**",".qoder/skills/**",".qwen/skills/**",".roo/skills/**",".trae-cn/skills/**",".trae/skills/**",".windsurf/skills/**",".zcode/skills/**"],pe={include:["**/*"],exclude:[...vh],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4}});function Ae(t){return t!==0&&t!==0n&&t!=="0"}function ki(t,e){return Ae(t.dev)&&Ae(e.dev)&&Ae(t.ino)&&Ae(e.ino)}function he(t,e){let n=Ae(t.dev)&&Ae(e.dev);if(n&&t.dev!==e.dev)return!1;let i=Ae(t.ino)&&Ae(e.ino);return i&&t.ino!==e.ino?!1:n&&i?!0:t.birthtime===e.birthtime}var bi=W(()=>{"use strict"});import{constants as Si,promises as Ge}from"fs";function Ms(t){return"birthtimeNs"in t&&typeof t.birthtimeNs=="bigint"?t.birthtimeNs:t.birthtimeMs}function dl(t){return"ctimeNs"in t&&typeof t.ctimeNs=="bigint"?t.ctimeNs:t.ctimeMs}function rn(t){return{dev:t.dev,ino:t.ino,birthtime:Ms(t)}}function Ci(t,e){let n=rn(t),i=rn(e);return ki(n,i)?he(n,i):he(n,i)&&Ms(t)===Ms(e)&&dl(t)===dl(e)&&t.size===e.size}async function pl(t,e,n={}){if(!Number.isSafeInteger(e)||e<1)throw new Error("race-safe read byte limit must be a positive integer");let i=n.label??"file",r=n.bigint===!0,s=await Ge.lstat(t,{bigint:r});if(!s.isFile()||s.isSymbolicLink())throw new je("not-regular-file",`${i} must be a regular file`);if(BigInt(s.size)>BigInt(e))throw new je("too-large",`${i} exceeds ${e} bytes`);let o=await Ge.realpath(t);await n.verify?.("pre-open",{realPath:o,identity:rn(s)});let a=process.platform==="win32"?Si.O_RDONLY:Si.O_RDONLY|Si.O_NOFOLLOW|Si.O_NONBLOCK,c;try{c=await Ge.open(t,a)}catch(l){throw l.code==="ELOOP"?new je("not-regular-file",`${i} must be a regular file`,{cause:l}):l}try{let[l,u,f]=await Promise.all([c.stat({bigint:r}),Ge.lstat(t,{bigint:r}),Ge.realpath(t)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||f!==o||!Ci(s,l)||!Ci(s,u))throw new je("changed",`${i} changed while opening`);await n.verify?.("post-open",{realPath:f,identity:rn(l)}),await n.hooks?.afterOpen?.();let d=[],h=0,w=Buffer.allocUnsafe(Math.min(64*1024,e+1));for(;;){let g=e+1-h,{bytesRead:b}=await c.read(w,0,Math.min(w.length,g),null);if(b===0)break;if(h+=b,h>e)throw new je("too-large",`${i} exceeds ${e} bytes`);d.push(Buffer.from(w.subarray(0,b)))}await n.hooks?.beforeFinalCheck?.();let[p,m,y]=await Promise.all([c.stat({bigint:r}),Ge.lstat(t,{bigint:r}),Ge.realpath(t)]);if(!m.isFile()||m.isSymbolicLink()||y!==o||!Ci(s,p)||!Ci(s,m))throw new je("changed",`${i} changed while reading`);return await n.verify?.("post-read",{realPath:y,identity:rn(p)}),{bytes:Buffer.concat(d,h),stat:p,realPath:y}}finally{await c.close()}}var je,ml=W(()=>{"use strict";bi();je=class extends Error{reason;constructor(e,n,i){super(n,i),this.name="RaceSafeReadError",this.reason=e}}});import{promises as Ie}from"fs";import te from"path";function hl(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}function Ei(t,e){let n=te.relative(t,e);return n===""||!te.isAbsolute(n)&&n!==".."&&!n.startsWith(`..${te.sep}`)}async function Ws(t,e){let n=te.resolve(t),i=await Ie.lstat(n);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${e} project root must be a real directory`);return Ie.realpath(n)}async function Bs(t,e,n,i){let r=t;for(let s=0;s{if(!Ei(s,a.realPath))throw new Error(`${i.label} resolves outside the project root`);await Bs(r.projectRoot,s,r.relative.split("/"),{label:i.label,expected:"file"})}})}var ne=W(()=>{"use strict";ml();me()});import{createHash as Ph}from"crypto";function Rh(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function _i(t,e={}){return(await Pi(t,e)).document}async function Oh(t){try{return(await B(t,sn,nn,{label:sn})).bytes}catch(e){if(Rh(e))return null;throw e}}function Nh(t){return t?{exists:!0,sha256:Ph("sha256").update(t).digest("hex")}:{exists:!1,sha256:null}}async function Pi(t,e={}){let n=await Oh(t);return{document:n?mt(n.toString("utf8"),e):null,identity:Nh(n)}}var sn,on=W(()=>{"use strict";me();ne();sn=".comet/config.yaml"});import{randomUUID as Ah}from"crypto";import{constants as jh,promises as I}from"fs";import F from"path";async function Ys(t,e){try{return await I.link(t,e),{linked:!0}}catch(n){let i=n.code;if(i!=="ENOTSUP"&&i!=="EOPNOTSUPP")throw n}return await I.copyFile(t,e,jh.COPYFILE_EXCL),{linked:!1}}function ht(t,e){let n=F.relative(t,e);return n===""||!F.isAbsolute(n)&&n!==".."&&!n.startsWith(`..${F.sep}`)}function Oi(t){return{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs}}function Ih(t,e){return he(t,Oi(e))}function Ri(t,e){let n=Oi(t),i=Oi(e);return ki(n,i)?he(n,i):he(n,i)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.size===e.size}async function Ni(t){let e=await I.lstat(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Contained atomic write parent must be a real directory: ${t}`);return{path:t,realPath:await I.realpath(t),...Oi(e)}}async function Te(t){for(let e of t){let n=await I.lstat(e.path);if(!n.isDirectory()||n.isSymbolicLink()||!Ih(e,n)||await I.realpath(e.path)!==e.realPath)throw new Error(`Contained atomic write parent changed before commit: ${e.path}`)}}async function Th(t,e){let n=F.resolve(t),i=F.resolve(e);if(!ht(n,i))throw new Error(`Contained atomic write parent is outside its managed root: ${e}`);let r=[await Ni(n)],s=F.relative(n,i).split(F.sep).filter(Boolean),o=n;for(let a of s){await Te(r),o=F.join(o,a);try{await I.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await Ni(o);if(!ht(r[0].realPath,c.realPath))throw new Error(`Contained atomic write parent resolves outside its managed root: ${o}`);r.push(c)}return await Te(r),r}async function qh(t,e){let n=F.resolve(t),i=F.resolve(e);if(!ht(n,i))throw new Error(`Contained file parent is outside its managed root: ${e}`);let r=[await Ni(n)],s=F.relative(n,i).split(F.sep).filter(Boolean),o=n;for(let a of s){o=F.join(o,a);try{let c=await Ni(o);if(!ht(r[0].realPath,c.realPath))throw new Error(`Contained file parent resolves outside its managed root: ${o}`);r.push(c)}catch(c){if(c.code==="ENOENT")return null;throw c}}return await Te(r),r}async function gl(t){let e;try{e=await I.open(t,"r"),await e.sync()}catch(n){let i=n.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(i??""))throw n}finally{await e?.close()}}async function $h(t,e,n){let i=F.dirname(t),r=await Th(n.containedRoot,i),s=F.join(i,`.${F.basename(t)}.${Ah()}.tmp`),o,a;try{await n.beforeTemporaryOpen?.(),o=await I.open(s,"wx"),a=await o.stat();let[c,l]=await Promise.all([I.lstat(s),I.realpath(s)]);if(await Te(r),!c.isFile()||c.isSymbolicLink()||!Ri(a,c)||!ht(r[0].realPath,l))throw new Error("Contained atomic write temporary file opened outside its managed parent");if(typeof e=="string"?await o.writeFile(e,"utf8"):await o.writeFile(e),await o.sync(),!Ri(a,await o.stat()))throw new Error("Contained atomic write temporary file changed while writing");await o.close(),o=void 0,await n.beforeCommit?.(),await Te(r);let u=await I.lstat(s);if(!u.isFile()||u.isSymbolicLink()||!Ri(u,a))throw new Error("Contained atomic write temporary file changed before commit");n.exclusive?(await Ys(s,t),await I.unlink(s)):await I.rename(s,t),await gl(i)}catch(c){await o?.close();try{await Te(r),await I.rm(s,{force:!0})}catch{}throw c}}async function ie(t,e,n){await $h(t,e,n)}async function Js(t,e){let n=F.dirname(t),i=await qh(e.containedRoot,n);if(!i)return!1;let r,s;try{r=await I.lstat(t),s=await I.realpath(t)}catch(c){if(c.code==="ENOENT")return!1;throw c}if(!r.isFile()||r.isSymbolicLink()||!ht(i[0].realPath,s))throw new Error("Contained file removal target must be a regular file inside its managed root");await e.beforeRemove?.(),await Te(i);let[o,a]=await Promise.all([I.lstat(t),I.realpath(t)]);if(!o.isFile()||o.isSymbolicLink()||!Ri(r,o)||a!==s)throw new Error("Contained file removal target changed before removal");return await I.unlink(t),await Te(i),await gl(n),!0}var ze=W(()=>{"use strict";bi()});var jv,Us=W(()=>{"use strict";ze();on();ne();jv=16*1024});var Vs=W(()=>{"use strict";ze();me();on();ne();Us()});var $i=W(()=>{"use strict"});var Rl=W(()=>{"use strict"});var eo=W(()=>{"use strict";$i()});var Ol=W(()=>{"use strict";$i();eo()});var pg,Nl=W(()=>{"use strict";pg=Ct(pt(),1);ze();me();ne()});var Al=W(()=>{"use strict";$i();ze();Rl();Ol();me();Nl();ne();on();Vs();Us();eo()});import{TextDecoder as mg}from"util";function jl(t){return{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs}}function hg(t,e){try{return new mg("utf-8",{fatal:!0}).decode(t.bytes)}catch(n){throw new Error(`${e} is not valid UTF-8`,{cause:n})}}async function to(t,e,n,i,r={}){try{let s=await B(t,e,n,{label:i,hooks:r.hooks});return{result:s,text:hg(s,i)}}catch(s){let o=s.code;if(o==="ENOENT"||o==="ENOTDIR")return null;throw s}}async function we(t,e,n,i,r={}){return(await to(t,e,n,i,r))?.text??null}async function qe(t,e,n,i,r,s={}){if(Buffer.byteLength(n,"utf8")>i)throw new Error(`${r} exceeds ${i} bytes`);let o=await to(t,e,i,r),a=await A(t,e,{label:r,expected:"file"});await ie(a.target,n,{containedRoot:a.projectRoot,beforeCommit:async()=>{await s.beforeCommit?.();let c=await to(t,e,i,r);if(!(!o&&!c)){if(!o||!c)throw new Error(`${r} changed before commit`);if(o.result.realPath!==c.result.realPath||!he(jl(o.result.stat),jl(c.result.stat))||o.text!==c.text)throw new Error(`${r} changed before commit`)}}})}async function Il(t,e,n,i,r,s={}){let o=await we(t,e,i,r);await qe(t,e,`${o??""}${n}`,i,r,s)}async function Li(t,e,n,i={}){let r=await A(t,e,{label:n,expected:"file"});return r.exists?Js(r.target,{containedRoot:r.projectRoot,beforeRemove:i.beforeRemove}):!1}var no=W(()=>{"use strict";Al();bi()});var $l={};Mu($l,{RUN_STATE_FILE:()=>Fi,applyRunStateToDocument:()=>io,readRunState:()=>ro,removeRunState:()=>so,runStateFromDocument:()=>Di,writeRunState:()=>Mi});import gg from"path";function mn(t,e){let n=t[e];if(typeof n!="string"||n.length===0)throw new Error(`Invalid Run state: ${e} must be a non-empty string`);return n}function pn(t,e){let n=mn(t,e);if(gg.isAbsolute(n)||/^(?:[A-Za-z]:|[\\/]|~)/u.test(n)||n.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Run state: ${e} must stay inside the change directory`);return n}function wg(t){let e=t.run_retries??"{}",n;try{n=typeof e=="string"?JSON.parse(e):e}catch(i){throw new Error("Invalid Run state: run_retries must be a JSON object",{cause:i})}if(!n||typeof n!="object"||Array.isArray(n))throw new Error("Invalid Run state: run_retries must be a JSON object");for(let i of Object.values(n))if(!Number.isInteger(i)||Number(i)<0)throw new Error("Invalid Run state: retry counts must be non-negative integers");return n}function Di(t){if(!t.run_id)return null;let e=mn(t,"run_id"),n=mn(t,"skill"),i=mn(t,"skill_version"),r=mn(t,"skill_hash"),s=pn(t,"pending_ref"),o=pn(t,"trajectory_ref"),a=pn(t,"context_ref"),c=pn(t,"artifacts_ref"),l=pn(t,"checkpoint_ref"),u=Number(t.iteration);if(!Number.isInteger(u)||u<0)throw new Error("Invalid Run state: iteration must be a non-negative integer");if(t.orchestration!=="deterministic"&&t.orchestration!=="adaptive")throw new Error("Invalid Run state: orchestration must be deterministic or adaptive");if(t.run_status!=="running"&&t.run_status!=="waiting"&&t.run_status!=="completed"&&t.run_status!=="failed")throw new Error("Invalid Run state: run_status is invalid");return{runId:e,skill:n,skillVersion:i,skillHash:r,orchestration:t.orchestration,currentStep:Tl(t,"current_step"),iteration:u,pending:Tl(t,"pending"),pendingRef:s,trajectoryRef:o,contextRef:a,artifactsRef:c,checkpointRef:l,status:t.run_status,retries:wg(t)}}function io(t,e){e?t.run_id=e.runId:delete t.run_id}function yg(t){return{runId:t.runId,skill:t.skill,skillVersion:t.skillVersion,skillHash:t.skillHash,orchestration:t.orchestration,currentStep:t.currentStep,iteration:t.iteration,pending:t.pending,pendingRef:t.pendingRef,trajectoryRef:t.trajectoryRef,contextRef:t.contextRef,artifactsRef:t.artifactsRef,checkpointRef:t.checkpointRef,status:t.status,retries:t.retries}}function vg(t){let e={run_id:t.runId,skill:t.skill,skill_version:t.skillVersion,skill_hash:t.skillHash,orchestration:t.orchestration,current_step:t.currentStep,iteration:t.iteration,pending:t.pending,pending_ref:t.pendingRef,trajectory_ref:t.trajectoryRef,context_ref:t.contextRef,artifacts_ref:t.artifactsRef,checkpoint_ref:t.checkpointRef,run_status:t.status,run_retries:JSON.stringify(t.retries)};return Di(e)}async function ro(t,e={}){let n=await we(t,Fi,ql,"Run state",e);if(n===null)return null;let i=JSON.parse(n);return vg(i)}async function Mi(t,e,n={}){await qe(t,Fi,JSON.stringify(yg(e),null,2),ql,"Run state",n)}async function so(t,e={}){await Li(t,Fi,"Run state",e)}var Tl,Fi,ql,Wi=W(()=>{"use strict";no();Tl=(t,e)=>{let n=t[e];return n==null?null:String(n)};Fi=".comet/run-state.json",ql=256*1024});var Ru=Ct(pt(),1);import{createHash as xu}from"crypto";import{promises as _u}from"fs";import Pu from"path";import El from"path";import{promises as Wh}from"fs";import O from"path";import{promises as gh}from"fs";async function en(t){try{return await gh.access(t),!0}catch(e){if(wh(e))return!1;throw e}}function wh(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}me();on();Vs();ne();var an=class extends Error{code="classic-layout-unavailable";constructor(e="Classic artifact layout is unavailable from .comet/config.yaml"){super(e),this.name="ClassicLayoutUnavailableError"}},Gs=class extends Error{constructor(n,i,r){let s=L(r,n),o=L(r,i);super(`Classic layout conflict: both ${s}/ and ${o}/ exist; run comet doctor and resolve the conflict before writing`);this.configuredRoot=n;this.alternateRoot=i;this.name="ClassicLayoutConflictError"}configuredRoot;alternateRoot;code="classic-layout-conflict"},vl=".comet/config.yaml";function Bh(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function kl(t){await A(t,vl,{label:vl,expected:"file"})}function bl(t,e){let n=O.resolve(t),i=e==="docs"?O.join(n,"docs"):n,r=O.join(i,"openspec"),s=O.join(n,"docs","superpowers");return{projectRoot:n,artifactLayout:e,openSpecBase:i,openSpecRoot:r,changesDir:O.join(r,"changes"),archiveDir:O.join(r,"changes","archive"),specsDir:O.join(r,"specs"),superpowersRoot:s,superpowersSpecsDir:O.join(s,"specs"),superpowersPlansDir:O.join(s,"plans"),superpowersReportsDir:O.join(s,"reports")}}async function Kh(t){await kl(t);let e=await _i(t,{allowPartialProject:!0,allowMissingNativeFields:!0});if(!e?.config)throw new an;if(!(e.config.workflows??[e.config.default_workflow]).includes("classic"))throw new an("Classic artifact layout is unavailable because Classic is not enabled");return e.classic?.artifact_layout??"legacy"}async function Yh(t,e){return bl(t,e??await Kh(t))}async function Jh(t,e){let n=await Yh(t,e),i=n.artifactLayout==="legacy"?"docs":"legacy",r=bl(t,i).openSpecRoot,[s,o]=await Promise.all([A(n.projectRoot,L(n.projectRoot,n.openSpecRoot),{label:"Configured Classic OpenSpec root",expected:"directory"}),A(n.projectRoot,L(n.projectRoot,r),{label:"Alternate Classic OpenSpec root",expected:"directory"})]),a=s.exists,c=o.exists;return{paths:n,configuredRootExists:a,alternateRoot:r,alternateRootExists:c,dualRoots:a&&c}}async function Uh(t,e){let n=[t.openSpecRoot,t.changesDir,t.archiveDir,t.specsDir,e,t.superpowersRoot,t.superpowersSpecsDir,t.superpowersPlansDir,t.superpowersReportsDir];for(let i of n){let r=L(t.projectRoot,i);await A(t.projectRoot,r,{label:`Classic managed physical path ${r}`,expected:"directory"})}}async function Qe(t,e,n={}){let i=await Jh(t,e);if(await Uh(i.paths,i.alternateRoot),i.dualRoots&&!n.allowAlternateRoot)throw new Gs(i.paths.openSpecRoot,i.alternateRoot,i.paths.projectRoot);if(!i.configuredRootExists){let r=L(i.paths.projectRoot,i.paths.openSpecRoot),s=L(i.paths.projectRoot,i.alternateRoot);throw new an(`Configured Classic OpenSpec root is missing: ${r} (alternate ${s} is ${i.alternateRootExists?"present":"missing"})`)}return i.paths}async function zs(t,e,n={}){let i=O.join(O.resolve(t),".comet","classic-root-move.json");if(await en(i))throw new Error("Classic root move transaction is incomplete; inspect it with comet doctor and recover it explicitly before writing");let r=await Qe(t,e,n);if(!await en(r.openSpecRoot))throw new Error(`Configured Classic OpenSpec root is missing: ${L(r.projectRoot,r.openSpecRoot)}`);return r}async function Xe(t){let e=O.resolve(t),n=null;try{(await Wh.lstat(e)).isDirectory()||(e=O.dirname(e))}catch(i){if(!Bh(i))throw i}for(;;){O.basename(e)==="openspec"&&(n=O.dirname(e));let i=O.join(e,".comet","config.yaml"),r=!1;if(await en(i))try{await kl(e);let o=(await _i(e))?.value;r=!!o&&typeof o=="object"&&!Array.isArray(o)&&(o.schema==="comet.project.v1"||o.default_workflow!==void 0||o.native!==void 0)}catch{}if(r||await en(O.join(e,".git")))return e;let s=O.dirname(e);if(s===e)return n??O.resolve(t);e=s}}function L(t,e){return O.relative(O.resolve(t),e).replaceAll("\\","/")}ze();me();ne();import cn from"path";var Hh=2*1024*1024;function Ai(t,e,n){let i=cn.resolve(t),r=cn.isAbsolute(e)?cn.resolve(e):cn.resolve(i,e),s=cn.relative(i,r).replaceAll("\\","/");return{root:i,relative:Ne(s,n),target:r}}async function le(t,e,n){let i=Ai(t,e,n.label);return A(i.root,i.relative,n)}async function ji(t,e,n){return(await le(t,e,{label:n.label,expected:n.expected??"any"})).exists}async function Qs(t,e,n,i){return await ji(t,e,{label:n,expected:"file"})?(await Sl(t,e,{label:n,hooks:i})).byteLength>0:!1}async function gt(t,e,n){return(await Sl(t,e,n)).toString("utf8")}async function Sl(t,e,n){let i=Ai(t,e,n.label);return(await B(i.root,i.relative,n.maxBytes??Hh,{label:n.label,hooks:n.hooks})).bytes}async function Ii(t,e,n){let i=Ai(t,e,n);return Ks(i.root,i.relative,{label:n})}async function Cl(t,e,n,i){let r=Ai(t,e,i.label);await A(r.root,r.relative,{label:i.label,expected:"file"}),await ie(r.target,n,{containedRoot:r.root,beforeTemporaryOpen:i.beforeTemporaryOpen,beforeCommit:i.beforeCommit,exclusive:i.exclusive})}function Xs(t){return t?/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t)?t.includes("..")?"Change name cannot contain '..' (path traversal not allowed)":null:`Invalid change name: '${t}' -Valid format: lowercase kebab-case (a-z, 0-9, single hyphens)`:"Change name cannot be empty"}function Zs(t){let e=Xs(t);if(e)throw new Error(e)}function Vh(t,e){return{label:L(t,e),directory:e}}async function Gh(t,e,n){let i=Vh(t,e);if(!(await le(t,e,{label:n,expected:"directory"})).exists)return{change:i,exists:!1,stateExists:!1};let s=await le(t,El.join(e,".comet.yaml"),{label:`${n} state`,expected:"file"});return{change:i,exists:!0,stateExists:s.exists}}async function xl(t,e=process.cwd()){Zs(t);let n=await Qe(e),i=await Gh(n.projectRoot,El.join(n.changesDir,t),`Classic active change ${t}`);return{...i.change,exists:i.exists,stateExists:i.stateExists}}import{promises as hu}from"fs";import z from"path";import{fileURLToPath as gu}from"url";import{promises as Qh}from"fs";import ge from"path";ne();me();import ln from"path";function zh(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function _l(t,e,n,i){let r=Ne(n,"Classic handoff artifact pointer");if((await A(t,r,{label:"Classic handoff artifact",expected:"file"})).exists)return null;let o=await Qe(t),a=`${L(t,o.changesDir)}/`,l=(o.artifactLayout==="docs"?[a,"openspec/changes/"]:[a]).find(g=>r.startsWith(g));if(!l)return null;let u=r.slice(l.length).split("/");if(u.length<4||u[1]!==".comet"||u.slice(2).some(g=>g.length===0))return null;let f=u[0];Zs(f);let d=u.slice(2),h=ln.resolve(e);if(ln.dirname(h)!==ln.resolve(o.archiveDir))return null;let w=ln.basename(h),p=/^\d{4}-\d{2}-\d{2}-(.+)$/u.exec(w);if(w!==f&&p?.[1]!==f)return null;await A(t,L(t,h),{label:"Classic archived change directory",expected:"directory"});let m=ln.join(h,".comet",...d),y=L(t,m);try{return await B(t,y,i,{label:"Historical Classic archived handoff artifact"}),y}catch(g){if(zh(g))return null;throw g}}ne();var Pl=2*1024*1024;function un(t,e){return ge.relative(t,e).split(ge.sep).join("/")}async function fn(t,e,n){if(!n)return{code:e,satisfied:!1};let i=n.replaceAll("\\","/");try{let r=await xi(t,i,{label:`${e} artifact`});return{code:e,satisfied:r,source:i,...r?{resolvedSource:i}:{}}}catch(r){return{code:e,satisfied:!1,source:i,detail:`unsafe artifact pointer outside the project or through a special path: ${r instanceof Error?r.message:String(r)}`}}}async function Xh(t,e,n){try{await Qe(t)}catch(r){return{code:"design.handoff",satisfied:!1,...n?{source:n.replaceAll("\\","/")}:{},detail:`Classic layout is unsafe or unavailable for handoff evidence: ${r instanceof Error?r.message:String(r)}`}}let i=await fn(t,"design.handoff",n);if(!n||i.satisfied||i.detail)return i;try{let r=await _l(t,e,n,Pl);return r?{...i,satisfied:!0,resolvedSource:r,detail:`resolved historical legacy pointer from archived change: ${r}`}:i}catch(r){return{...i,satisfied:!1,detail:`unsafe archived handoff fallback: ${r instanceof Error?r.message:String(r)}`}}}async function Ti(t,e,n){return fn(t,e,un(t,n))}async function Zh(t,e){let n=ge.join(e,"specs"),i;try{let o=un(t,n);if(!(await A(t,o,{label:"OpenSpec delta-spec directory",expected:"directory"})).exists)return{code:"openspec.delta-spec",satisfied:!1};i=await Qh.readdir(n)}catch(o){return o.code==="ENOENT"?{code:"openspec.delta-spec",satisfied:!1}:{code:"openspec.delta-spec",satisfied:!1,detail:`unsafe delta-spec path: ${o instanceof Error?o.message:String(o)}`}}let r=i.map(o=>ge.join(n,o,"spec.md")),s=(await Promise.all(r.map(async o=>{try{return await xi(t,un(t,o),{label:"OpenSpec delta spec"})?o:null}catch{return null}}))).filter(o=>o!==null);return{code:"openspec.delta-spec",satisfied:s.length>0,source:s[0]?un(t,s[0]):void 0,detail:`${s.length} delta spec${s.length===1?"":"s"}`}}async function eg(t,e){let n,i=un(t,e);try{n=(await B(t,i,Pl,{label:"Classic tasks artifact"})).bytes.toString("utf8")}catch(o){return o.code==="ENOENT"?{code:"build.tasks-complete",satisfied:!1}:{code:"build.tasks-complete",satisfied:!1,source:i,detail:`unsafe tasks artifact: ${o instanceof Error?o.message:String(o)}`}}let r=[...n.matchAll(/^\s*[-*]\s+\[([ xX])\]\s+/gmu)],s=r.filter(o=>o[1].toLowerCase()==="x").length;return{code:"build.tasks-complete",satisfied:r.length>0&&s===r.length,source:i,detail:`${s} of ${r.length} tasks complete`}}function dn(t,e){return t.some(n=>n.code===e&&n.satisfied)}async function wt(t,e){let n=await Xe(t),i=e.classic,r=ge.join(t,"proposal.md"),s=ge.join(t,"design.md"),o=ge.join(t,"tasks.md"),a=e.run?ge.resolve(t,e.run.checkpointRef):ge.join(t,".comet","checkpoint.json"),c=await Promise.all([Ti(n,"openspec.proposal",r),Ti(n,"openspec.design",s),Ti(n,"openspec.tasks",o),Zh(n,t),fn(n,"design.document",i?.designDoc??null),fn(n,"build.plan",i?.plan??null),eg(n,o),fn(n,"verification.report",i?.verificationReport??null),Xh(n,t,i?.handoffContext??null),Ti(n,"run.checkpoint",a)]),l=c.find(u=>u.code==="design.handoff");return l&&!i?.handoffHash&&(l.satisfied=!1,l.detail="handoff hash is missing"),c.push({code:"archive.confirmed",satisfied:i?.archiveConfirmation==="confirmed"}),c}import{createHash as dw,randomUUID as pw}from"crypto";import{promises as ho}from"fs";import ye from"path";function tg(t){return t.classicProfile??t.workflow}function ng(t){return!t.buildMode||!t.tddMode||!t.isolation||!t.verifyMode?!1:t.buildMode==="subagent-driven-development"?t.subagentDispatch==="confirmed":t.buildMode==="direct"?t.directOverride===!0:!0}function ig(t){return t.buildMode==="direct"&&t.tddMode==="direct"&&t.isolation!==null&&t.verifyMode==="light"}function rg(t,e,n){if(e.verifyResult==="fail")return t==="full"?"full.build.fix":`${t}.build.execute`;if(t==="full"){if(!dn(n,"build.plan"))return"full.build.plan";if(e.buildPause==="plan-ready")return"full.build.plan-ready";if(!ng(e))return"full.build.configure"}else if(!ig(e))throw new Error(`${t} build configuration is incomplete`);return dn(n,"build.tasks-complete")?`${t}.build.complete`:`${t}.build.execute`}function sg(t,e,n){return e.verifyResult!=="pass"||!dn(n,"verification.report")?`${t}.verify.run`:`${t}.verify.branch`}function og(t,e){if(e.verifyResult!=="pass")throw new Error("archive requires verify_result=pass");return e.archiveConfirmation==="confirmed"?`${t}.archive.execute`:`${t}.archive.confirm`}function qi(t,e){let n=tg(t);if(t.archived&&t.phase!=="archive")throw new Error("archived=true requires phase=archive");if(t.archived)return"completed";if(n!=="full"&&t.phase==="design")throw new Error(`${n} workflow cannot enter design`);switch(t.phase){case"open":return`${n}.open`;case"design":return dn(e,"design.handoff")?"full.design.document":"full.design.handoff";case"build":return rg(n,t,e);case"verify":return sg(n,t,e);case"archive":return og(n,t)}}var Ji=Ct(pt(),1);ze();ne();import Yi from"path";Wi();var Ll=["full","hotfix","tweak"],Ze=1,kg=["open","design","build","verify","archive"],bg=["en","zh-CN"],Sg=["off","beta"],Cg=["subagent-driven-development","executing-plans","direct"],Eg=["plan-ready"],xg=["confirmed"],_g=["tdd","direct"],Pg=["off","standard","thorough"],Rg=["current","branch","worktree"],Og=["light","full"],Ng=["pending","pass","fail"],Ag=["pending","handled"],jg=["pending","confirmed"],Ki=["workflow","language","phase","context_compression","build_mode","build_pause","subagent_dispatch","tdd_mode","review_mode","isolation","bound_branch","verify_mode","auto_transition","base_ref","design_doc","plan","verify_result","verify_failures","verification_report","branch_status","created_at","verified_at","archive_confirmation","archived","direct_override","handoff_context","handoff_hash","classic_profile","classic_migration"],Ig=["run_id"],Tg=new Set([...Ki,...Ig]),qg=["workflow","phase","design_doc","plan","build_mode","isolation","verify_mode","verify_result","verified_at","archived"];function Dl(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function yt(t,e){let n=t[e];if(n==null||n==="")return null;if(typeof n!="string")throw new Error(`Invalid Classic state: ${e} must be a string or null`);return n}function K(t,e,n,i=!0){let r=t[e];if(r==null||r===""){if(i)return null;throw new Error(`Invalid Classic state: ${e} is required`)}if(typeof r!="string"||!n.includes(r))throw new Error(`Invalid Classic state: ${e} must be one of ${n.join(", ")}${i?" or null":""}`);return r}function oo(t,e,n=!0){let i=t[e];if(i==null||i===""){if(n)return null;throw new Error(`Invalid Classic state: ${e} is required`)}if(typeof i!="boolean")throw new Error(`Invalid Classic state: ${e} must be true or false`);return i}function $g(t,e,n=0){let i=t[e];if(i==null||i==="")return n;if(typeof i!="number"||!Number.isInteger(i)||i<0)throw new Error(`Invalid Classic state: ${e} must be a non-negative integer`);return i}function Bi(t,e){let n=yt(t,e);if(n===null)return null;if(/^(?:[A-Za-z]:|[\\/]|~)/u.test(n)||n.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Classic state: ${e} must be a relative repository path`);return n}function Lg(t,e){let n=yt(t,e);if(n!==null&&!/^[a-f0-9]{64}$/u.test(n))throw new Error(`Invalid Classic state: ${e} must be a sha256 hex digest`);return n}function Dg(t){let e=t.classic_migration;if(e==null||e==="")return null;if(e!==Ze)throw new Error(`Invalid Classic state: classic_migration must be ${Ze}`);return e}function Fg(t){if(!Ki.some(n=>Dl(t,n)))return null;for(let n of qg)if(!Dl(t,n))return null;return{workflow:K(t,"workflow",Ll,!1),language:K(t,"language",bg),phase:K(t,"phase",kg,!1),contextCompression:K(t,"context_compression",Sg),buildMode:K(t,"build_mode",Cg),buildPause:K(t,"build_pause",Eg),subagentDispatch:K(t,"subagent_dispatch",xg),tddMode:K(t,"tdd_mode",_g),reviewMode:K(t,"review_mode",Pg),isolation:K(t,"isolation",Rg),boundBranch:yt(t,"bound_branch"),verifyMode:K(t,"verify_mode",Og),autoTransition:oo(t,"auto_transition"),baseRef:yt(t,"base_ref"),designDoc:Bi(t,"design_doc"),plan:Bi(t,"plan"),verifyResult:K(t,"verify_result",Ng,!1),verifyFailures:$g(t,"verify_failures"),verificationReport:Bi(t,"verification_report"),branchStatus:K(t,"branch_status",Ag),createdAt:yt(t,"created_at"),verifiedAt:yt(t,"verified_at"),archiveConfirmation:K(t,"archive_confirmation",jg),archived:oo(t,"archived",!1),directOverride:oo(t,"direct_override"),handoffContext:Bi(t,"handoff_context"),handoffHash:Lg(t,"handoff_hash"),classicProfile:K(t,"classic_profile",Ll),classicMigration:Dg(t)}}function ao(t,e){let n=e??null;if(n===null&&e===void 0&&t.run_id&&t.skill)try{n=Di(t)}catch(i){let r=i instanceof Error?i.message:String(i);throw new Error(r.replace(/^Invalid Run state:/u,"Invalid Classic state:"),{cause:i})}return{classic:Fg(t),run:n,unknownKeys:Object.keys(t).filter(i=>!Tg.has(i))}}function Fl(t){return{workflow:t.workflow,language:t.language,phase:t.phase,context_compression:t.contextCompression,build_mode:t.buildMode,build_pause:t.buildPause,subagent_dispatch:t.subagentDispatch,tdd_mode:t.tddMode,review_mode:t.reviewMode,isolation:t.isolation,bound_branch:t.boundBranch,verify_mode:t.verifyMode,auto_transition:t.autoTransition,base_ref:t.baseRef,design_doc:t.designDoc,plan:t.plan,verify_result:t.verifyResult,verify_failures:t.verifyFailures,verification_report:t.verificationReport,branch_status:t.branchStatus,created_at:t.createdAt,verified_at:t.verifiedAt,archive_confirmation:t.archiveConfirmation,archived:t.archived,direct_override:t.directOverride,handoff_context:t.handoffContext,handoff_hash:t.handoffHash,classic_profile:t.classicProfile,classic_migration:t.classicMigration}}Wi();var Mg=2*1024*1024;function hn(t){let e=t.toJS();if(e===null)return{};if(typeof e!="object"||Array.isArray(e))throw new Error("Invalid Classic state document: root must be a mapping");return e}function Ml(t,e,n){t.get(e)!==n&&t.set(e,n)}function Wg(t,e){if(e.classic)for(let[n,i]of Object.entries(Fl(e.classic)))Ml(t,n,i);else for(let n of Ki)t.delete(n);io(t.toJS(),e.run),e.run?Ml(t,"run_id",e.run.runId):t.delete("run_id")}function Bg(t){let e=["skill","skill_version","skill_hash","orchestration","current_step","iteration","pending","pending_ref","trajectory_ref","context_ref","artifacts_ref","checkpoint_ref","run_status","run_retries"];for(let n of e)t.delete(n)}function Kg(t){let e=!1;for(let n of["build_command","verify_command"])t.has(n)&&(t.delete(n),e=!0);return e}async function Wl(t){let e;try{e=(await B(Yi.dirname(t),Yi.basename(t),Mg,{label:"Classic state document"})).bytes.toString("utf8")}catch(i){if(i.code!=="ENOENT")throw i;return new Ji.Document({})}let n=(0,Ji.parseDocument)(e);if(n.errors.length>0)throw new Error(`Invalid Classic state document: ${n.errors[0].message}`);return hn(n),n}async function $e(t,e={}){let n=e.migrate!==!1,i=Yi.join(t,".comet.yaml"),r=await Wl(i),s=hn(r),o=Kg(r);o&&(s=hn(r));let a=await ro(t);if(!a&&s.run_id&&s.skill){let{runStateFromDocument:c}=await Promise.resolve().then(()=>(Wi(),$l));a=c(s),a&&n&&(await Mi(t,a),Bg(r),o=!0)}return o&&n&&await ie(i,r.toString(),{containedRoot:t}),ao(hn(r),a)}async function et(t,e,n={}){let i=Yi.join(t,".comet.yaml"),r=await Wl(i);Wg(r,{...e,unknownKeys:e.unknownKeys??[]}),ao(hn(r),e.run??null),await ie(i,r.toString(),{containedRoot:t,beforeCommit:n.beforeCommit}),e.run?await Mi(t,e.run):await so(t)}function Bl(t,e,n){return{runId:e,skill:t.definition.metadata.name,skillVersion:t.definition.metadata.version,skillHash:n,orchestration:t.definition.orchestration.mode,currentStep:t.definition.orchestration.entry??null,iteration:0,pending:null,pendingRef:".comet/pending-action.json",trajectoryRef:".comet/trajectory.jsonl",contextRef:".comet/context.md",artifactsRef:".comet/artifacts.json",checkpointRef:".comet/checkpoint.json",status:"running",retries:{}}}no();import Ui from"path";var ue={trajectory:8*1024*1024,artifacts:1024*1024,context:1024*1024,pendingAction:256*1024,checkpoint:256*1024};function re(t,e){if(Ui.isAbsolute(e))throw new Error("Run path must stay inside the change directory");let n=Ui.resolve(t),i=Ui.resolve(n,e);if(i!==n&&!i.startsWith(n+Ui.sep))throw new Error("Run path must stay inside the change directory")}async function vt(t,e,n,i={}){re(t,e),await Il(t,e,`${JSON.stringify(n)} -`,ue.trajectory,"Run trajectory",i)}async function gn(t,e,n={}){re(t,e);let i=await we(t,e,ue.trajectory,"Run trajectory",n);return i===null?[]:i.split(/\r?\n/).map((r,s)=>({line:r,number:s+1})).filter(({line:r})=>r.length>0).map(({line:r,number:s})=>{try{return JSON.parse(r)}catch(o){throw new Error(`Invalid Trajectory event at line ${s}`,{cause:o})}})}async function co(t,e,n={}){re(t,e);let i=await we(t,e,ue.artifacts,"Run artifacts",n);return i===null?{}:JSON.parse(i)}async function Hi(t,e,n,i={}){re(t,e),await qe(t,e,JSON.stringify(n,null,2)+` -`,ue.artifacts,"Run artifacts",i)}async function Vi(t,e,n,i={}){re(t,e),await qe(t,e,n,ue.context,"Run context",i)}async function Kl(t,e,n={}){return re(t,e),we(t,e,ue.context,"Run context",n)}async function Yl(t,e,n,i={}){re(t,e),await qe(t,e,JSON.stringify(n,null,2)+` -`,ue.pendingAction,"Run pending action",i)}async function lo(t,e,n={}){re(t,e);let i=await we(t,e,ue.pendingAction,"Run pending action",n);return i===null?null:JSON.parse(i)}async function Jl(t,e,n={}){re(t,e),await Li(t,e,"Run pending action",n)}async function Gi(t,e,n,i={}){re(t,e),await qe(t,e,JSON.stringify(n,null,2)+` -`,ue.checkpoint,"Run checkpoint",i)}async function Ul(t,e,n={}){re(t,e);let i=await we(t,e,ue.checkpoint,"Run checkpoint",n);return i===null?null:JSON.parse(i)}import{createHash as ou,randomUUID as aw}from"crypto";import{promises as $}from"fs";import T from"path";var Gl=Ct(pt(),1);import{promises as uo}from"fs";import X from"path";var Yg=["invoke_skill","call_tool","handoff","ask_user","checkpoint"],Jg=["deterministic","adaptive"],Ug=["function","mcp","script","agent"],Hg=["none","read","write","external"],Vg=["progress","step","completion"],Gg=["artifact_exists","state_equals"];function tt(t,e,n){return new Error(`${t}: ${e} ${n}`)}function V(t,e,n="document"){if(t===null||typeof t!="object"||Array.isArray(t))throw tt(e,n,"must be an object")}function Le(t,e,n){if(!Array.isArray(t))throw tt(e,n,"must be an array")}function Y(t,e,n){if(typeof t!="string")throw tt(e,n,"must be a string")}function se(t,e,n,i){e in t&&Y(t[e],n,`${i}.${e}`)}function zl(t,e,n,i){if(e in t&&typeof t[e]!="boolean")throw tt(n,`${i}.${e}`,"must be a boolean")}function De(t,e,n,i){if(typeof t!="string"||!e.includes(t))throw tt(n,i,`must be one of ${e.join(", ")}`)}function zi(t,e,n){Le(t,e,n),t.forEach((i,r)=>{Y(i,e,`${n}[${r}]`)})}function Hl(t,e,n){V(t,e,n),Y(t.name,e,`${n}.name`),Y(t.description,e,`${n}.description`),zl(t,"required",e,n)}function zg(t,e,n){V(t,e,n),Y(t.id,e,`${n}.id`),se(t,"source",e,n),se(t,"version",e,n)}function Qg(t,e,n){V(t,e,n),Y(t.id,e,`${n}.id`),Y(t.role,e,`${n}.role`),se(t,"instructions",e,n)}function Xg(t,e,n){V(t,e,n),Y(t.id,e,`${n}.id`),De(t.kind,Ug,e,`${n}.kind`),Y(t.source,e,`${n}.source`),De(t.sideEffect,Hg,e,`${n}.sideEffect`),zl(t,"requiresConfirmation",e,n)}function Zg(t,e,n){V(t,e,n),De(t.type,Yg,e,`${n}.type`),se(t,"ref",e,n),se(t,"prompt",e,n),se(t,"question",e,n),"options"in t&&zi(t.options,e,`${n}.options`)}function ew(t,e,n){V(t,e,n),Y(t.id,e,`${n}.id`),Zg(t.action,e,`${n}.action`),se(t,"next",e,n),"completionEvals"in t&&zi(t.completionEvals,e,`${n}.completionEvals`)}function tw(t,e){let n="goal";V(t,e,n),Y(t.statement,e,`${n}.statement`),Le(t.inputs,e,`${n}.inputs`),t.inputs.forEach((i,r)=>{Hl(i,e,`${n}.inputs[${r}]`)}),Le(t.outputs,e,`${n}.outputs`),t.outputs.forEach((i,r)=>{Hl(i,e,`${n}.outputs[${r}]`)}),zi(t.success,e,`${n}.success`)}function nw(t,e){let n="orchestration";V(t,e,n),De(t.mode,Jg,e,`${n}.mode`),se(t,"entry",e,n),"steps"in t&&(Le(t.steps,e,`${n}.steps`),t.steps.forEach((i,r)=>{ew(i,e,`${n}.steps[${r}]`)}))}function Ql(t,e){return V(t,e),De(t.apiVersion,["comet/v1alpha1"],e,"apiVersion"),De(t.kind,["Skill"],e,"kind"),V(t.metadata,e,"metadata"),Y(t.metadata.name,e,"metadata.name"),Y(t.metadata.version,e,"metadata.version"),Y(t.metadata.description,e,"metadata.description"),tw(t.goal,e),nw(t.orchestration,e),Le(t.skills,e,"skills"),t.skills.forEach((n,i)=>{zg(n,e,`skills[${i}]`)}),Le(t.agents,e,"agents"),t.agents.forEach((n,i)=>{Qg(n,e,`agents[${i}]`)}),Le(t.tools,e,"tools"),t.tools.forEach((n,i)=>{Xg(n,e,`tools[${i}]`)}),t}function Xl(t,e){V(t,e);for(let n of["allowedSkills","allowedAgents","allowedTools","confirmationRequiredFor"])n in t&&zi(t[n],e,n);for(let n of["maxIterations","maxRetriesPerAction"])if(n in t&&(typeof t[n]!="number"||!Number.isFinite(t[n])))throw tt(e,n,"must be a finite number");return t}function iw(t,e){return V(t,e),"runtime"in t&&Zl(t.runtime,e,"runtime"),t}function Zl(t,e,n){return Le(t,e,n),t.forEach((i,r)=>{let s=`${n}[${r}]`;V(i,e,s),Y(i.id,e,`${s}.id`),De(i.scope,Vg,e,`${s}.scope`),De(i.type,Gg,e,`${s}.type`),se(i,"artifact",e,s),se(i,"field",e,s),se(i,"equals",e,s)}),t}async function fo(t){let e=await uo.readFile(t,"utf8");try{return(0,Gl.parse)(e)}catch(n){let i=n instanceof Error?n.message:String(n);throw tt(t,"document",i)}}async function rw(t){try{return await fo(t)}catch(e){if(e.code==="ENOENT")return null;throw e}}async function Vl(t){try{return await uo.access(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function sw(t){let e=X.join(t,"checks.yaml"),n=X.join(t,"evals.yaml"),[i,r]=await Promise.all([Vl(e),Vl(n)]);if(r)throw new Error(`${n}: evals.yaml is no longer supported; use checks.yaml`);return i?{document:iw(await fo(e),e)}:{document:null}}async function eu(t){let e=X.resolve(t.root),n=X.resolve(t.controlRoot);t.requireSkillMarkdown&&await uo.access(X.join(e,"SKILL.md"));let i=X.join(n,"skill.yaml"),r=X.join(n,"guardrails.yaml"),s=Ql(await fo(i),i),o=await rw(r),a=o===null?null:Xl(o,r),c=await sw(n),l={allowedSkills:s.skills.map(u=>u.id),allowedAgents:s.agents.map(u=>u.id),allowedTools:s.tools.map(u=>u.id),maxIterations:50,maxRetriesPerAction:3,confirmationRequiredFor:s.tools.filter(u=>u.requiresConfirmation).map(u=>u.id)};return{root:e,packageKind:t.packageKind==="runtime"?"runtime":void 0,definition:s,guardrails:{...l,...a},evals:c.document?.runtime??[]}}async function tu(t){let e=X.resolve(t);return eu({root:e,controlRoot:X.join(e,"comet"),packageKind:"skill",requireSkillMarkdown:!0})}async function nu(t){let e=X.resolve(t);return eu({root:e,controlRoot:e,packageKind:"runtime",requireSkillMarkdown:!1})}function iu(t,e,n=X.join(e,"package.json")){V(t,n);let i=t.packageKind==="runtime"?"runtime":void 0,r=Ql(t.definition,n),s=Xl(t.guardrails,n),o=Zl(t.evals,n,"evals"),a={allowedSkills:r.skills.map(c=>c.id),allowedAgents:r.agents.map(c=>c.id),allowedTools:r.tools.map(c=>c.id),maxIterations:50,maxRetriesPerAction:3,confirmationRequiredFor:r.tools.filter(c=>c.requiresConfirmation).map(c=>c.id)};return{root:X.resolve(e),packageKind:i,definition:r,guardrails:{...a,...s},evals:o}}import ru from"path";function ow(t,e,n,i){t.type==="invoke_skill"&&!e.definition.skills.some(r=>r.id===t.ref)&&n.push(`step ${i} references undeclared skill: ${t.ref??"(missing)"}`),t.type==="call_tool"&&!e.definition.tools.some(r=>r.id===t.ref)&&n.push(`step ${i} references undeclared tool: ${t.ref??"(missing)"}`),t.type==="handoff"&&!e.definition.agents.some(r=>r.id===t.ref)&&n.push(`step ${i} references undeclared agent: ${t.ref??"(missing)"}`),t.type==="ask_user"&&!t.question&&n.push(`step ${i} ask_user action requires question`)}function su(t){let e=[],{definition:n,guardrails:i,evals:r}=t;n.apiVersion!=="comet/v1alpha1"&&e.push("unsupported apiVersion"),n.kind!=="Skill"&&e.push("kind must be Skill"),n.metadata.name||e.push("metadata.name is required"),n.goal.statement||e.push("goal.statement is required"),i.maxIterations<1&&e.push("maxIterations must be at least 1"),i.maxRetriesPerAction<0&&e.push("maxRetriesPerAction must not be negative");let s=n.orchestration.steps??[];if(n.orchestration.mode==="adaptive")(n.orchestration.entry||s.length>0)&&e.push("adaptive orchestration must not define entry or steps");else{let o=new Set;for(let a of s)o.has(a.id)&&e.push(`duplicate step id: ${a.id}`),o.add(a.id),ow(a.action,t,e,a.id);(!n.orchestration.entry||!o.has(n.orchestration.entry))&&e.push(`orchestration.entry references unknown step: ${n.orchestration.entry??"(missing)"}`);for(let a of s){a.next&&!o.has(a.next)&&e.push(`step ${a.id} has unknown next step: ${a.next}`);for(let c of a.completionEvals??[])r.some(l=>l.id===c)||e.push(`step ${a.id} references unknown eval: ${c}`)}}for(let o of n.tools){if(o.kind!=="script")continue;let a=ru.posix.normalize(o.source.replaceAll("\\","/"));(ru.isAbsolute(o.source)||a===".."||a.startsWith("../"))&&e.push(`script tool ${o.id} must reference a relative path inside the Skill package`)}for(let o of i.allowedSkills)n.skills.some(a=>a.id===o)||e.push(`guardrails allow undeclared skill: ${o}`);for(let o of i.allowedAgents)n.agents.some(a=>a.id===o)||e.push(`guardrails allow undeclared agent: ${o}`);for(let o of i.allowedTools)n.tools.some(a=>a.id===o)||e.push(`guardrails allow undeclared tool: ${o}`);return e}function Qi(t){return Array.isArray(t)?t.map(Qi):t&&typeof t=="object"?Object.fromEntries(Object.entries(t).sort(([e],[n])=>e.localeCompare(n)).map(([e,n])=>[e,Qi(n)])):t}function cw(t){return Qi({...t.packageKind==="runtime"?{packageKind:"runtime"}:{},definition:t.definition,guardrails:t.guardrails,evals:t.evals})}function lw(t){return T.posix.normalize(t.replaceAll("\\","/"))}function kt(t,e,n){let i=T.relative(t,e);if(!(i===""||!T.isAbsolute(i)&&!i.startsWith(`..${T.sep}`)))throw new Error(`${n} resolves outside the Skill package`)}async function au(t,e,n){let i=lw(e);if(T.posix.isAbsolute(i)||i===".."||i.startsWith("../"))throw new Error(`${n} resolves outside the Skill package`);let r=T.resolve(t,...i.split("/"));kt(t,r,n);let s;try{s=await $.realpath(r)}catch(o){throw o.code==="ENOENT"?new Error(`${n} does not exist: ${e}`,{cause:o}):o}if(kt(t,s,n),!(await $.stat(s)).isFile())throw new Error(`${n} is not a file: ${e}`);return{path:i,content:await $.readFile(s)}}async function uw(t){let e=await $.realpath(t.root),n=t.packageKind==="runtime"?[]:[await au(e,"SKILL.md","SKILL.md")];for(let i of t.definition.tools)i.kind==="script"&&n.push(await au(e,i.source,`Script tool ${i.id}`));return n.sort((i,r)=>i.path.localeCompare(r.path))}function fw(t,e){let n=e.map(i=>({path:i.path,sha256:ou("sha256").update(i.content).digest("hex")}));return ou("sha256").update(JSON.stringify(Qi({package:t,files:n}))).digest("hex")}function uu(t){return JSON.stringify(t,null,2)+` -`}async function fu(t){let e=cw(t),n=await uw(t);return{document:e,files:n,hash:fw(e,n)}}async function Xi(t){return(await fu(t)).hash}async function cu(t){try{return await $.access(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function lu(t,e){try{if((await $.readFile(T.join(t,"sha256"),"utf8")).trim()!==e.hash)throw new Error("hash mismatch");if(await $.readFile(T.join(t,"package.json"),"utf8")!==uu(e.document))throw new Error("package mismatch");for(let r of e.files)if(!(await $.readFile(T.join(t,...r.path.split("/")))).equals(r.content))throw new Error(`file mismatch: ${r.path}`)}catch(n){throw new Error(`Existing Skill snapshot is invalid: ${e.hash}`,{cause:n})}}async function po(t,e){let n=await fu(t),i=T.resolve(e,".comet","skill-snapshots"),r=T.join(i,n.hash);if(await $.mkdir(i,{recursive:!0}),await cu(r))return await lu(r,n),{hash:n.hash,snapshotDir:r};let s=T.join(i,`.tmp-${aw()}`);kt(i,s,"Temporary snapshot"),kt(i,r,"Published snapshot");try{await $.mkdir(s);for(let o of n.files){let a=T.join(s,...o.path.split("/"));kt(s,a,`Snapshot file ${o.path}`),await $.mkdir(T.dirname(a),{recursive:!0}),await $.writeFile(a,o.content)}await $.writeFile(T.join(s,"package.json"),uu(n.document)),await $.writeFile(T.join(s,"sha256"),n.hash+` -`),await $.rename(s,r)}catch(o){if(await cu(r)){try{await lu(r,n)}finally{await $.rm(s,{recursive:!0,force:!0})}return{hash:n.hash,snapshotDir:r}}throw await $.rm(s,{recursive:!0,force:!0}),o}return{hash:n.hash,snapshotDir:r}}async function mo(t,e){if(!/^[a-f0-9]{64}$/u.test(e))throw new Error(`Invalid Skill snapshot hash: ${e}`);let n=T.resolve(t,".comet","skill-snapshots"),i=T.join(n,e);kt(n,i,"Skill snapshot");try{let r=(await $.readFile(T.join(i,"sha256"),"utf8")).trim();if(r!==e)throw new Error(`stored hash is ${r||"(empty)"}`);let s=T.join(i,"package.json"),o=JSON.parse(await $.readFile(s,"utf8")),a=iu(o,i,s),c=su(a);if(c.length>0)throw new Error(c.map(u=>` - ${u}`).join(` -`));let l=await Xi(a);if(l!==e)throw new Error(`calculated hash is ${l}`);return a}catch(r){throw new Error(`Skill snapshot is invalid or missing: ${e}`,{cause:r})}}async function du(t){try{return await ho.access(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}function pu(t){return dw("sha256").update(t).digest("hex")}function mw(t){return pu(JSON.stringify(Object.fromEntries(Object.entries(t).sort(([e],[n])=>e.localeCompare(n)))))}function hw(t){return t.replaceAll(".","_").replaceAll("-","_")}async function gw(t,e){let n=await Xe(t),i=Object.fromEntries(e.filter(o=>o.satisfied&&o.source).map(o=>[hw(o.code),o.source])),r=ye.join(t,"subagent-progress.md");await du(r)&&(i.subagent_progress=ye.relative(n,r).split(ye.sep).join("/"));let s=e.find(o=>o.code==="design.handoff"&&o.satisfied);return s?.source&&(i.handoff_context=s.source),i}function ww(t,e,n){return[{sequence:1,timestamp:n,type:"run_started",runId:t.runId,data:{skill:t.skill,skillVersion:t.skillVersion,skillHash:t.skillHash}},{sequence:2,timestamp:n,type:"state_migrated",runId:t.runId,data:{kind:"classic",migrationVersion:Ze,profile:e,source:"pre-migration"}}]}async function yw(t){await Promise.all(t.map(e=>ho.rm(e,{recursive:!0,force:!0})))}async function mu(t,e){let n=await $e(t);if(!n.classic)throw new Error("Classic migration requires a legacy state projection");let i=n.classic,r=i.classicProfile??i.workflow;if(n.run){if(i.classicMigration!==Ze)throw new Error("Classic Run exists without a supported classic_migration marker");if(n.run.skill!==e.skillPackage.definition.metadata.name)throw new Error(`Classic Run skill mismatch: expected ${e.skillPackage.definition.metadata.name}, got ${n.run.skill}`);if(await Xi(e.skillPackage)!==n.run.skillHash)return await mo(t,n.run.skillHash),{classic:i,run:n.run,evidence:await wt(t,n),migrated:!1,snapshotDir:ye.join(t,".comet","skill-snapshots",n.run.skillHash)};let d=await po(e.skillPackage,t);return{classic:i,run:n.run,evidence:await wt(t,n),migrated:!1,snapshotDir:d.snapshotDir}}let s=await wt(t,n),o=qi(i,s);if(!e.skillPackage.definition.orchestration.steps?.some(f=>f.id===o))throw new Error(`Classic Skill package does not define resolved step: ${o}`);let a=await Xi(e.skillPackage),c=ye.join(t,".comet","skill-snapshots",a),l=await du(c),u=[];try{let f=await po(e.skillPackage,t),d=Bl(e.skillPackage,e.runId?.()??pw(),f.hash);d.currentStep=o,o==="completed"&&(d.status="completed");let h={...i,classicProfile:r,classicMigration:Ze},w=await gw(t,s),p=await Xe(t),m=s.find(S=>S.code==="design.handoff"&&S.satisfied),y=null;m?.source&&(y=await gt(p,m.resolvedSource??m.source,{label:"Classic migration handoff context",hooks:e.handoffReadHooks}),await Vi(t,d.contextRef,y),u.push(ye.resolve(t,d.contextRef))),await Hi(t,d.artifactsRef,w),u.push(ye.resolve(t,d.artifactsRef));let g=(e.now?.()??new Date).toISOString(),b={runId:d.runId,stateVersion:1,trajectoryOffset:2,contextHash:y===null?null:pu(y),artifactsHash:mw(w),createdAt:g};await Gi(t,d.checkpointRef,b),u.push(ye.resolve(t,d.checkpointRef)),u.push(ye.resolve(t,d.trajectoryRef));for(let S of ww(d,r,g))await vt(t,d.trajectoryRef,S);return await et(t,{classic:h,run:d,unknownKeys:n.unknownKeys}),{classic:h,run:d,evidence:s,migrated:!0,snapshotDir:f.snapshotDir}}catch(f){throw await yw(u),l||await ho.rm(c,{recursive:!0,force:!0}),f}}async function vw(t){try{return(await hu.stat(t)).isDirectory()}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function Zi(t){try{return(await hu.stat(t)).isFile()}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function kw(t){return await vw(t)?await Zi(z.join(t,"skill.yaml"))?!0:await Zi(z.join(t,"SKILL.md"))&&await Zi(z.join(t,"comet","skill.yaml")):!1}function bw(t){return{root:t,packageKind:"runtime",definition:{apiVersion:"comet/v1alpha1",kind:"Skill",metadata:{name:"comet-classic",version:"1",description:"Internal compatibility orchestration for classic Comet full, hotfix, and tweak workflows"},goal:{statement:"Advance or restore a classic Comet Run without changing the user command surface",inputs:[{name:"classic-state",description:"Validated ClassicState consistent with the Run projection",required:!0},{name:"evidence",description:"Structured evidence produced by the Classic Evidence collector",required:!0}],outputs:[{name:"run-state",description:"Atomically synchronized Classic and Run state",required:!0}],success:["Legacy fields and Run fields remain consistent","Every step invokes only a declared public Comet Skill","The completed state passes its completion eval"]},orchestration:{mode:"deterministic",entry:"full.open",steps:[{id:"full.open",action:{type:"invoke_skill",ref:"comet-open"},next:"full.design.handoff"},{id:"full.design.handoff",action:{type:"invoke_skill",ref:"comet-design"},next:"full.design.document"},{id:"full.design.document",action:{type:"invoke_skill",ref:"comet-design"},next:"full.build.plan"},{id:"full.build.plan",action:{type:"invoke_skill",ref:"comet-build"},next:"full.build.plan-ready"},{id:"full.build.plan-ready",action:{type:"invoke_skill",ref:"comet-build"},next:"full.build.configure"},{id:"full.build.configure",action:{type:"invoke_skill",ref:"comet-build"},next:"full.build.execute"},{id:"full.build.execute",action:{type:"invoke_skill",ref:"comet-build"},next:"full.build.complete"},{id:"full.build.complete",action:{type:"invoke_skill",ref:"comet-build"},next:"full.verify.run"},{id:"full.build.fix",action:{type:"invoke_skill",ref:"comet-build"},next:"full.build.execute"},{id:"full.verify.run",action:{type:"invoke_skill",ref:"comet-verify"},next:"full.verify.branch"},{id:"full.verify.branch",action:{type:"invoke_skill",ref:"comet-verify"},next:"full.archive.confirm"},{id:"full.archive.confirm",action:{type:"invoke_skill",ref:"comet-archive"},next:"full.archive.execute"},{id:"full.archive.execute",action:{type:"invoke_skill",ref:"comet-archive"},next:"completed"},{id:"hotfix.open",action:{type:"invoke_skill",ref:"comet-hotfix"},next:"hotfix.build.execute"},{id:"hotfix.build.execute",action:{type:"invoke_skill",ref:"comet-build"},next:"hotfix.build.complete"},{id:"hotfix.build.complete",action:{type:"invoke_skill",ref:"comet-build"},next:"hotfix.verify.run"},{id:"hotfix.verify.run",action:{type:"invoke_skill",ref:"comet-verify"},next:"hotfix.verify.branch"},{id:"hotfix.verify.branch",action:{type:"invoke_skill",ref:"comet-verify"},next:"hotfix.archive.confirm"},{id:"hotfix.archive.confirm",action:{type:"invoke_skill",ref:"comet-archive"},next:"hotfix.archive.execute"},{id:"hotfix.archive.execute",action:{type:"invoke_skill",ref:"comet-archive"},next:"completed"},{id:"tweak.open",action:{type:"invoke_skill",ref:"comet-tweak"},next:"tweak.build.execute"},{id:"tweak.build.execute",action:{type:"invoke_skill",ref:"comet-build"},next:"tweak.build.complete"},{id:"tweak.build.complete",action:{type:"invoke_skill",ref:"comet-build"},next:"tweak.verify.run"},{id:"tweak.verify.run",action:{type:"invoke_skill",ref:"comet-verify"},next:"tweak.verify.branch"},{id:"tweak.verify.branch",action:{type:"invoke_skill",ref:"comet-verify"},next:"tweak.archive.confirm"},{id:"tweak.archive.confirm",action:{type:"invoke_skill",ref:"comet-archive"},next:"tweak.archive.execute"},{id:"tweak.archive.execute",action:{type:"invoke_skill",ref:"comet-archive"},next:"completed"},{id:"completed",action:{type:"checkpoint"},completionEvals:["classic-completed"]}]},skills:[{id:"comet-open"},{id:"comet-design"},{id:"comet-build"},{id:"comet-verify"},{id:"comet-archive"},{id:"comet-hotfix"},{id:"comet-tweak"}],agents:[],tools:[]},guardrails:{allowedSkills:["comet-open","comet-design","comet-build","comet-verify","comet-archive","comet-hotfix","comet-tweak"],allowedAgents:[],allowedTools:[],maxIterations:500,maxRetriesPerAction:3,confirmationRequiredFor:[]},evals:[{id:"classic-completed",scope:"completion",type:"state_equals",field:"status",equals:"completed"}]}}async function Sw(){let t=z.dirname(gu(import.meta.url)),e=[process.env.COMET_RUNTIME_CLASSIC_ROOT,z.resolve(t,"..","runtime","classic"),z.resolve(t,"..","..","comet","runtime","classic"),z.resolve(t,"..","..","assets","skills","comet","runtime","classic"),z.resolve("assets","skills","comet","runtime","classic"),process.env.COMET_CLASSIC_SKILL_ROOT,z.resolve(t,"..","..","comet-classic"),z.resolve(t,"..","..","assets","skills","comet-classic"),z.resolve("assets","skills","comet-classic")].filter(n=>!!n);for(let n of e)if(await kw(n))return n;return null}async function Cw(t){return await Zi(z.join(t,"skill.yaml"))?nu(t):tu(t)}async function wu(t){let e=await Sw();return mu(t,{skillPackage:e?await Cw(e):bw(z.dirname(gu(import.meta.url)))})}async function yu(t,e,n,i){let r=await $e(t);if(!r.classic||!r.run)throw new Error("Classic transition requires synchronized Classic and Run projections");let s=await wt(t,{classic:e,run:n,unknownKeys:r.unknownKeys}),o=qi(e,s),a={...n,currentStep:o,iteration:n.iteration+1,status:o==="completed"?"completed":"running"};await et(t,{classic:e,run:a,unknownKeys:r.unknownKeys});let c=await gn(t,a.trajectoryRef);return await vt(t,a.trajectoryRef,{sequence:c.length+1,timestamp:new Date().toISOString(),type:"state_transitioned",runId:a.runId,data:{kind:"classic",fromStep:n.currentStep,toStep:o,...i}}),a}import{AsyncLocalStorage as Ew}from"async_hooks";import{promises as vu}from"fs";import wn from"path";var go=new Ew;function xw(t,e){let n=wn.relative(t,e);return n===""||!wn.isAbsolute(n)&&n!==".."&&!n.startsWith(`..${wn.sep}`)}async function _w(t){let e=wn.resolve(t.invocationCwd??process.cwd()),n=wn.resolve(t.projectRoot??await Xe(e)),[i,r]=await Promise.all([vu.realpath(e),vu.realpath(n)]);if(!xw(r,i))throw new Error(`Classic command invocation cwd is outside the discovered project: ${e}`);return{invocationCwd:e,projectRoot:n}}async function ku(t,e){let n=go.getStore();if(n)return e(n);let i=await _w(t);return go.run(i,()=>e(i))}function bu(){let t=go.getStore();if(!t)throw new Error("Classic command project context is unavailable");return t.projectRoot}var Pw="\x1B[32m",Rw="\x1B[31m",Ow="\x1B[33m",yo="\x1B[0m";function Fe(t){return`${Pw}${t}${yo}`}function G(t){return`${Rw}${t}${yo}`}function Nw(t){return`${Ow}${t}${yo}`}var M=class extends Error{constructor(n,i=1){super(n);this.exitCode=i}exitCode},wo=class{stdout=[];stderr=[];toResult(e=0){return{exitCode:e,...this.stdout.length>0?{stdout:this.stdout.join(` +`,n)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let n=hi(e),i=dt(n);return i.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let n=hi(e),i=dt(n);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,n){return this.type!=="comment"||this.indent<=n?!1:e.every(i=>i.type==="newline"||i.type==="space")}*documentEnd(e){this.type!=="doc-mode"&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};tl.Parser=Ts});var ol=v(Zt=>{"use strict";var nl=bs(),Xm=Yt(),Xt=Ht(),Zm=vr(),eh=P(),th=Is(),il=qs();function rl(t){let e=t.prettyErrors!==!1;return{lineCounter:t.lineCounter||e&&new th.LineCounter||null,prettyErrors:e}}function nh(t,e={}){let{lineCounter:n,prettyErrors:i}=rl(e),r=new il.Parser(n?.addNewLine),s=new nl.Composer(e),o=Array.from(s.compose(r.parse(t)));if(i&&n)for(let a of o)a.errors.forEach(Xt.prettifyError(t,n)),a.warnings.forEach(Xt.prettifyError(t,n));return o.length>0?o:Object.assign([],{empty:!0},s.streamInfo())}function sl(t,e={}){let{lineCounter:n,prettyErrors:i}=rl(e),r=new il.Parser(n?.addNewLine),s=new nl.Composer(e),o=null;for(let a of s.compose(r.parse(t),!0,t.length))if(!o)o=a;else if(o.options.logLevel!=="silent"){o.errors.push(new Xt.YAMLParseError(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return i&&n&&(o.errors.forEach(Xt.prettifyError(t,n)),o.warnings.forEach(Xt.prettifyError(t,n))),o}function ih(t,e,n){let i;typeof e=="function"?i=e:n===void 0&&e&&typeof e=="object"&&(n=e);let r=sl(t,n);if(!r)return null;if(r.warnings.forEach(s=>Zm.warn(r.options.logLevel,s)),r.errors.length>0){if(r.options.logLevel!=="silent")throw r.errors[0];r.errors=[]}return r.toJS(Object.assign({reviver:i},n))}function rh(t,e,n){let i=null;if(typeof e=="function"||Array.isArray(e)?i=e:n===void 0&&e&&(n=e),typeof n=="string"&&(n=n.length),typeof n=="number"){let r=Math.round(n);n=r<1?void 0:r>8?{indent:8}:{indent:r}}if(t===void 0){let{keepUndefined:r}=n??e??{};if(!r)return}return eh.isDocument(t)&&!i?t.toString(n):new Xm.Document(t,i,n).toString(n)}Zt.parse=ih;Zt.parseAllDocuments=nh;Zt.parseDocument=sl;Zt.stringify=rh});var pt=v(_=>{"use strict";var sh=bs(),oh=Yt(),ah=ts(),$s=Ht(),ch=Rt(),Oe=P(),lh=Ee(),uh=j(),fh=Pe(),dh=_e(),ph=pi(),mh=As(),hh=Is(),gh=qs(),wi=ol(),al=Et();_.Composer=sh.Composer;_.Document=oh.Document;_.Schema=ah.Schema;_.YAMLError=$s.YAMLError;_.YAMLParseError=$s.YAMLParseError;_.YAMLWarning=$s.YAMLWarning;_.Alias=ch.Alias;_.isAlias=Oe.isAlias;_.isCollection=Oe.isCollection;_.isDocument=Oe.isDocument;_.isMap=Oe.isMap;_.isNode=Oe.isNode;_.isPair=Oe.isPair;_.isScalar=Oe.isScalar;_.isSeq=Oe.isSeq;_.Pair=lh.Pair;_.Scalar=uh.Scalar;_.YAMLMap=fh.YAMLMap;_.YAMLSeq=dh.YAMLSeq;_.CST=ph;_.Lexer=mh.Lexer;_.LineCounter=hh.LineCounter;_.Parser=gh.Parser;_.parse=wi.parse;_.parseAllDocuments=wi.parseAllDocuments;_.parseDocument=wi.parseDocument;_.stringify=wi.stringify;_.visit=al.visit;_.visitAsync=al.visitAsync});import yi from"path";function bh(t,e){if(typeof t!="string")throw new Error(`${e} must be a string`);let n=t.trim();if(n.length===0||yi.posix.isAbsolute(n)||yi.win32.isAbsolute(n)||/^(?:~|[\\/])/u.test(n))throw new Error(`${e} must be a project-relative path`);if(n===".")return[];let i=n.replaceAll("\\","/").split("/");if(i.some(r=>r===".."))throw new Error(`${e} must stay inside the project root`);if(i.some(r=>r===""||r==="."))throw new Error(`${e} must not contain empty or dot path segments`);return i}function vi(t){let e=bh(t,"native.artifact_root");return e.length===0?".":e.join("/")}function ll(t,e="docs"){let n=t??e;if(n!=="legacy"&&n!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return n}function Ne(t,e,n=!1){if(typeof t!="string")throw new Error(`${e} must be a string`);let i=t.trim().replaceAll("\\","/");if(i.length===0||yi.posix.isAbsolute(i)||yi.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${e} must be relative to its declared path base`);let r=i.split("/");if(r.some(s=>s===".."))throw new Error(`${e} must stay inside its declared path base`);if(r.some(s=>s===""||s==="."))throw new Error(`${e} must not contain empty or dot path segments`);if(!n&&/[*?]/u.test(i))throw new Error(`${e} cannot contain wildcards`);return r.join("/")}function tn(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function ul(t,e,n){let i=t??e;if(i!=="en"&&i!=="zh-CN")throw new Error(`${n} must be en or zh-CN`);return i}function fl(t,e){if(typeof t!="string"||t.length===0||t.includes("\\")||t.includes("\0")||t.startsWith("/")||t.split("/").includes(".."))throw new Error(`${e} contains an unsafe pattern`);if(t.length>Ds)throw new Error(`${e} exceeds ${Ds} characters`);let n=0;for(let i=0;iFs)throw new Error(`${e} contains more than ${Fs} wildcard tokens`);return t}function cl(t,e,n){if(t===void 0)return[...n];if(!Array.isArray(t))throw new Error(`${e} contains an unsafe pattern`);return[...new Set(t.map(i=>fl(i,e)))].sort((i,r)=>i.localeCompare(r,"en"))}function Ls(t,e,n){let i=t??e;if(!Number.isSafeInteger(i)||i<1)throw new Error(`${n} must be a positive integer`);return i}function Sh(t){if(t===void 0)return{...pe,include:[...pe.include],exclude:[...pe.exclude]};let e=tn(t,"native.snapshot");return{include:cl(e.include,"native.snapshot.include",pe.include),exclude:cl(e.exclude,"native.snapshot.exclude",pe.exclude),max_files:Ls(e.max_files,pe.max_files,"native.snapshot.max_files"),max_total_bytes:Ls(e.max_total_bytes,pe.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:Ls(e.max_duration_ms,pe.max_duration_ms,"native.snapshot.max_duration_ms")}}function Ch(t){if(t===void 0)return;let e=tn(t,"native.pending_root_move"),n=e.id,i=e.from_artifact_root,r=e.to_artifact_root,s=e.stage;if(typeof n!="string"||!/^[a-f0-9-]{8,}$/u.test(n))throw new Error("native.pending_root_move.id is invalid");if(typeof i!="string"||typeof r!="string")throw new Error("native.pending_root_move roots must be strings");if(s!=="copying"&&s!=="ready"&&s!=="switched")throw new Error("native.pending_root_move.stage is invalid");let o;if(e.cleanup!==void 0){let a=tn(e.cleanup,"native.pending_root_move.cleanup"),c=a.kind,l=a.state,u=a.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof u!="string"||!/^[a-f0-9]{64}$/u.test(u))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:u}}return{id:n,fromArtifactRoot:vi(i),toArtifactRoot:vi(r),stage:s,...o?{cleanup:o}:{}}}function Eh(t,e={}){let n=tn(t,"native"),i=n.artifact_root??(e.allowMissingArtifactRoot?"docs":void 0);if(typeof i!="string")throw new Error("native.artifact_root must be a string");let r=n.clarification_mode??"sequential";if(r!=="sequential"&&r!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let s=n.archive_confirmation??"automatic";if(s!=="automatic"&&s!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=n.max_verify_failures??vh;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let a=Ch(n.pending_root_move);return{artifact_root:vi(i),language:ul(n.language,"en","native.language"),clarification_mode:r,archive_confirmation:s,max_verify_failures:o,snapshot:Sh(n.snapshot),...a?{pending_root_move:a}:{}}}function xh(t){let e=tn(t,"classic"),n=e.context_compression??"off";if(n!=="off"&&n!=="beta")throw new Error("classic.context_compression must be off or beta");let i=e.review_mode??"standard";if(i!=="off"&&i!=="standard"&&i!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let r=e.auto_transition??!0;if(typeof r!="boolean")throw new Error("classic.auto_transition must be true or false");return{artifact_layout:ll(e.artifact_layout),language:ul(e.language,"zh-CN","classic.language"),context_compression:n,review_mode:i,auto_transition:r}}function Ph(t){let e=t??!0;if(typeof e!="boolean")throw new Error("ambient_resume must be true or false");return e}function _h(t,e,n,i,r){let s=t.schema!==void 0;if(!(s||t.default_workflow!==void 0||t.workflows!==void 0||!r.allowPartialProject&&t.native!==void 0)||r.allowPartialProject&&!s)return null;if(t.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(t.default_workflow!=="native"&&t.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let a=t.workflows??[t.default_workflow];if(!Array.isArray(a)||a.length===0||a.some(l=>l!=="native"&&l!=="classic"))throw new Error("workflows must contain native and/or classic");let c=[...new Set(a)];if(!c.includes(t.default_workflow))throw new Error("workflows must include default_workflow");if(c.includes("native")&&!e)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:t.default_workflow,workflows:c,ambient_resume:i,...e?{native:e}:{},...n?{classic:n}:{}}}function mt(t,e={}){let n=(0,Ms.parseDocument)(t,{uniqueKeys:!0});if(n.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${n.errors[0].message}`);let i=n.toJS();if(i==null)return{value:{},config:null,ambient_resume:!0};if(typeof i!="object"||Array.isArray(i))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let r=i,s=Ph(r.ambient_resume),o=r.native===void 0?void 0:Eh(r.native,{allowMissingArtifactRoot:e.allowMissingNativeFields}),a=r.classic===void 0?void 0:xh(r.classic),c=_h(r,o,a,s,{allowPartialProject:e.allowPartialProject??!1});return{value:r,config:c,ambient_resume:s,...o?{native:o}:{},...a?{classic:a}:{}}}var Ms,nn,Ds,Fs,vh,kh,pe,me=W(()=>{"use strict";Ms=Ct(pt(),1),nn=64*1024,Ds=1024,Fs=64,vh=5,kh=[".agents/skills/**",".amazonq/skills/**",".augment/skills/**",".bob/skills/**",".claude/skills/**",".cline/skills/**",".codebuddy/skills/**",".continue/skills/**",".cospec/skills/**",".crush/skills/**",".cursor/skills/**",".factory/skills/**",".forge/skills/**",".gemini/skills/**",".github/skills/**",".iflow/skills/**",".junie/skills/**",".kilocode/skills/**",".kimi-code/skills/**",".kiro/skills/**",".lingma/skills/**",".mimocode/skills/**",".opencode/skills/**",".pi/skills/**",".qoder/skills/**",".qwen/skills/**",".roo/skills/**",".trae-cn/skills/**",".trae/skills/**",".windsurf/skills/**",".zcode/skills/**"],pe={include:["**/*"],exclude:[...kh],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4}});function Ae(t){return t!==0&&t!==0n&&t!=="0"}function ki(t,e){return Ae(t.dev)&&Ae(e.dev)&&Ae(t.ino)&&Ae(e.ino)}function he(t,e){let n=Ae(t.dev)&&Ae(e.dev);if(n&&t.dev!==e.dev)return!1;let i=Ae(t.ino)&&Ae(e.ino);return i&&t.ino!==e.ino?!1:n&&i?!0:t.birthtime===e.birthtime}var bi=W(()=>{"use strict"});import{constants as Si,promises as ze}from"fs";function Ws(t){return"birthtimeNs"in t&&typeof t.birthtimeNs=="bigint"?t.birthtimeNs:t.birthtimeMs}function dl(t){return"ctimeNs"in t&&typeof t.ctimeNs=="bigint"?t.ctimeNs:t.ctimeMs}function rn(t){return{dev:t.dev,ino:t.ino,birthtime:Ws(t)}}function Ci(t,e){let n=rn(t),i=rn(e);return ki(n,i)?he(n,i):he(n,i)&&Ws(t)===Ws(e)&&dl(t)===dl(e)&&t.size===e.size}async function pl(t,e,n={}){if(!Number.isSafeInteger(e)||e<1)throw new Error("race-safe read byte limit must be a positive integer");let i=n.label??"file",r=n.bigint===!0,s=await ze.lstat(t,{bigint:r});if(!s.isFile()||s.isSymbolicLink())throw new je("not-regular-file",`${i} must be a regular file`);if(BigInt(s.size)>BigInt(e))throw new je("too-large",`${i} exceeds ${e} bytes`);let o=await ze.realpath(t);await n.verify?.("pre-open",{realPath:o,identity:rn(s)});let a=process.platform==="win32"?Si.O_RDONLY:Si.O_RDONLY|Si.O_NOFOLLOW|Si.O_NONBLOCK,c;try{c=await ze.open(t,a)}catch(l){throw l.code==="ELOOP"?new je("not-regular-file",`${i} must be a regular file`,{cause:l}):l}try{let[l,u,f]=await Promise.all([c.stat({bigint:r}),ze.lstat(t,{bigint:r}),ze.realpath(t)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||f!==o||!Ci(s,l)||!Ci(s,u))throw new je("changed",`${i} changed while opening`);await n.verify?.("post-open",{realPath:f,identity:rn(l)}),await n.hooks?.afterOpen?.();let d=[],h=0,w=Buffer.allocUnsafe(Math.min(64*1024,e+1));for(;;){let g=e+1-h,{bytesRead:b}=await c.read(w,0,Math.min(w.length,g),null);if(b===0)break;if(h+=b,h>e)throw new je("too-large",`${i} exceeds ${e} bytes`);d.push(Buffer.from(w.subarray(0,b)))}await n.hooks?.beforeFinalCheck?.();let[p,m,y]=await Promise.all([c.stat({bigint:r}),ze.lstat(t,{bigint:r}),ze.realpath(t)]);if(!m.isFile()||m.isSymbolicLink()||y!==o||!Ci(s,p)||!Ci(s,m))throw new je("changed",`${i} changed while reading`);return await n.verify?.("post-read",{realPath:y,identity:rn(p)}),{bytes:Buffer.concat(d,h),stat:p,realPath:y}}finally{await c.close()}}var je,ml=W(()=>{"use strict";bi();je=class extends Error{reason;constructor(e,n,i){super(n,i),this.name="RaceSafeReadError",this.reason=e}}});import{promises as Ie}from"fs";import te from"path";function hl(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}function Ei(t,e){let n=te.relative(t,e);return n===""||!te.isAbsolute(n)&&n!==".."&&!n.startsWith(`..${te.sep}`)}async function Bs(t,e){let n=te.resolve(t),i=await Ie.lstat(n);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${e} project root must be a real directory`);return Ie.realpath(n)}async function Ks(t,e,n,i){let r=t;for(let s=0;s{if(!Ei(s,a.realPath))throw new Error(`${i.label} resolves outside the project root`);await Ks(r.projectRoot,s,r.relative.split("/"),{label:i.label,expected:"file"})}})}var ne=W(()=>{"use strict";ml();me()});import{createHash as Rh}from"crypto";function Oh(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function Pi(t,e={}){return(await _i(t,e)).document}async function Nh(t){try{return(await B(t,sn,nn,{label:sn})).bytes}catch(e){if(Oh(e))return null;throw e}}function Ah(t){return t?{exists:!0,sha256:Rh("sha256").update(t).digest("hex")}:{exists:!1,sha256:null}}async function _i(t,e={}){let n=await Nh(t);return{document:n?mt(n.toString("utf8"),e):null,identity:Ah(n)}}var sn,on=W(()=>{"use strict";me();ne();sn=".comet/config.yaml"});import{randomUUID as jh}from"crypto";import{constants as Ih,promises as I}from"fs";import D from"path";async function Js(t,e){try{return await I.link(t,e),{linked:!0}}catch(n){let i=n.code;if(i!=="ENOTSUP"&&i!=="EOPNOTSUPP")throw n}return await I.copyFile(t,e,Ih.COPYFILE_EXCL),{linked:!1}}function ht(t,e){let n=D.relative(t,e);return n===""||!D.isAbsolute(n)&&n!==".."&&!n.startsWith(`..${D.sep}`)}function Oi(t){return{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs}}function Th(t,e){return he(t,Oi(e))}function Ri(t,e){let n=Oi(t),i=Oi(e);return ki(n,i)?he(n,i):he(n,i)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.size===e.size}async function Ni(t){let e=await I.lstat(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Contained atomic write parent must be a real directory: ${t}`);return{path:t,realPath:await I.realpath(t),...Oi(e)}}async function Te(t){for(let e of t){let n=await I.lstat(e.path);if(!n.isDirectory()||n.isSymbolicLink()||!Th(e,n)||await I.realpath(e.path)!==e.realPath)throw new Error(`Contained atomic write parent changed before commit: ${e.path}`)}}async function qh(t,e){let n=D.resolve(t),i=D.resolve(e);if(!ht(n,i))throw new Error(`Contained atomic write parent is outside its managed root: ${e}`);let r=[await Ni(n)],s=D.relative(n,i).split(D.sep).filter(Boolean),o=n;for(let a of s){await Te(r),o=D.join(o,a);try{await I.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await Ni(o);if(!ht(r[0].realPath,c.realPath))throw new Error(`Contained atomic write parent resolves outside its managed root: ${o}`);r.push(c)}return await Te(r),r}async function $h(t,e){let n=D.resolve(t),i=D.resolve(e);if(!ht(n,i))throw new Error(`Contained file parent is outside its managed root: ${e}`);let r=[await Ni(n)],s=D.relative(n,i).split(D.sep).filter(Boolean),o=n;for(let a of s){o=D.join(o,a);try{let c=await Ni(o);if(!ht(r[0].realPath,c.realPath))throw new Error(`Contained file parent resolves outside its managed root: ${o}`);r.push(c)}catch(c){if(c.code==="ENOENT")return null;throw c}}return await Te(r),r}async function gl(t){let e;try{e=await I.open(t,"r"),await e.sync()}catch(n){let i=n.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(i??""))throw n}finally{await e?.close()}}async function Lh(t,e,n){let i=D.dirname(t),r=await qh(n.containedRoot,i),s=D.join(i,`.${D.basename(t)}.${jh()}.tmp`),o,a;try{await n.beforeTemporaryOpen?.(),o=await I.open(s,"wx"),a=await o.stat();let[c,l]=await Promise.all([I.lstat(s),I.realpath(s)]);if(await Te(r),!c.isFile()||c.isSymbolicLink()||!Ri(a,c)||!ht(r[0].realPath,l))throw new Error("Contained atomic write temporary file opened outside its managed parent");if(typeof e=="string"?await o.writeFile(e,"utf8"):await o.writeFile(e),await o.sync(),!Ri(a,await o.stat()))throw new Error("Contained atomic write temporary file changed while writing");await o.close(),o=void 0,await n.beforeCommit?.(),await Te(r);let u=await I.lstat(s);if(!u.isFile()||u.isSymbolicLink()||!Ri(u,a))throw new Error("Contained atomic write temporary file changed before commit");n.exclusive?(await Js(s,t),await I.unlink(s)):await I.rename(s,t),await gl(i)}catch(c){await o?.close();try{await Te(r),await I.rm(s,{force:!0})}catch{}throw c}}async function ie(t,e,n){await Lh(t,e,n)}async function Us(t,e){let n=D.dirname(t),i=await $h(e.containedRoot,n);if(!i)return!1;let r,s;try{r=await I.lstat(t),s=await I.realpath(t)}catch(c){if(c.code==="ENOENT")return!1;throw c}if(!r.isFile()||r.isSymbolicLink()||!ht(i[0].realPath,s))throw new Error("Contained file removal target must be a regular file inside its managed root");await e.beforeRemove?.(),await Te(i);let[o,a]=await Promise.all([I.lstat(t),I.realpath(t)]);if(!o.isFile()||o.isSymbolicLink()||!Ri(r,o)||a!==s)throw new Error("Contained file removal target changed before removal");return await I.unlink(t),await Te(i),await gl(n),!0}var Qe=W(()=>{"use strict";bi()});var jv,Hs=W(()=>{"use strict";Qe();on();ne();jv=16*1024});var Gs=W(()=>{"use strict";Qe();me();on();ne();Hs()});var Li=W(()=>{"use strict"});var Ol=W(()=>{"use strict"});var eo=W(()=>{"use strict";Li()});var Nl=W(()=>{"use strict";Li();eo()});var pg,Al=W(()=>{"use strict";pg=Ct(pt(),1);Qe();me();ne()});var jl=W(()=>{"use strict";Li();Qe();Ol();Nl();me();Al();ne();on();Gs();Hs();eo()});import{TextDecoder as mg}from"util";function Il(t){return{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs}}function hg(t,e){try{return new mg("utf-8",{fatal:!0}).decode(t.bytes)}catch(n){throw new Error(`${e} is not valid UTF-8`,{cause:n})}}async function to(t,e,n,i,r={}){try{let s=await B(t,e,n,{label:i,hooks:r.hooks});return{result:s,text:hg(s,i)}}catch(s){let o=s.code;if(o==="ENOENT"||o==="ENOTDIR")return null;throw s}}async function we(t,e,n,i,r={}){return(await to(t,e,n,i,r))?.text??null}async function $e(t,e,n,i,r,s={}){if(Buffer.byteLength(n,"utf8")>i)throw new Error(`${r} exceeds ${i} bytes`);let o=await to(t,e,i,r),a=await A(t,e,{label:r,expected:"file"});await ie(a.target,n,{containedRoot:a.projectRoot,beforeCommit:async()=>{await s.beforeCommit?.();let c=await to(t,e,i,r);if(!(!o&&!c)){if(!o||!c)throw new Error(`${r} changed before commit`);if(o.result.realPath!==c.result.realPath||!he(Il(o.result.stat),Il(c.result.stat))||o.text!==c.text)throw new Error(`${r} changed before commit`)}}})}async function Tl(t,e,n,i,r,s={}){let o=await we(t,e,i,r);await $e(t,e,`${o??""}${n}`,i,r,s)}async function Di(t,e,n,i={}){let r=await A(t,e,{label:n,expected:"file"});return r.exists?Us(r.target,{containedRoot:r.projectRoot,beforeRemove:i.beforeRemove}):!1}var no=W(()=>{"use strict";jl();bi()});var Ll={};Wu(Ll,{RUN_STATE_FILE:()=>Mi,applyRunStateToDocument:()=>io,readRunState:()=>ro,removeRunState:()=>so,runStateFromDocument:()=>Fi,writeRunState:()=>Wi});import gg from"path";function mn(t,e){let n=t[e];if(typeof n!="string"||n.length===0)throw new Error(`Invalid Run state: ${e} must be a non-empty string`);return n}function pn(t,e){let n=mn(t,e);if(gg.isAbsolute(n)||/^(?:[A-Za-z]:|[\\/]|~)/u.test(n)||n.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Run state: ${e} must stay inside the change directory`);return n}function wg(t){let e=t.run_retries??"{}",n;try{n=typeof e=="string"?JSON.parse(e):e}catch(i){throw new Error("Invalid Run state: run_retries must be a JSON object",{cause:i})}if(!n||typeof n!="object"||Array.isArray(n))throw new Error("Invalid Run state: run_retries must be a JSON object");for(let i of Object.values(n))if(!Number.isInteger(i)||Number(i)<0)throw new Error("Invalid Run state: retry counts must be non-negative integers");return n}function Fi(t){if(!t.run_id)return null;let e=mn(t,"run_id"),n=mn(t,"skill"),i=mn(t,"skill_version"),r=mn(t,"skill_hash"),s=pn(t,"pending_ref"),o=pn(t,"trajectory_ref"),a=pn(t,"context_ref"),c=pn(t,"artifacts_ref"),l=pn(t,"checkpoint_ref"),u=Number(t.iteration);if(!Number.isInteger(u)||u<0)throw new Error("Invalid Run state: iteration must be a non-negative integer");if(t.orchestration!=="deterministic"&&t.orchestration!=="adaptive")throw new Error("Invalid Run state: orchestration must be deterministic or adaptive");if(t.run_status!=="running"&&t.run_status!=="waiting"&&t.run_status!=="completed"&&t.run_status!=="failed")throw new Error("Invalid Run state: run_status is invalid");return{runId:e,skill:n,skillVersion:i,skillHash:r,orchestration:t.orchestration,currentStep:ql(t,"current_step"),iteration:u,pending:ql(t,"pending"),pendingRef:s,trajectoryRef:o,contextRef:a,artifactsRef:c,checkpointRef:l,status:t.run_status,retries:wg(t)}}function io(t,e){e?t.run_id=e.runId:delete t.run_id}function yg(t){return{runId:t.runId,skill:t.skill,skillVersion:t.skillVersion,skillHash:t.skillHash,orchestration:t.orchestration,currentStep:t.currentStep,iteration:t.iteration,pending:t.pending,pendingRef:t.pendingRef,trajectoryRef:t.trajectoryRef,contextRef:t.contextRef,artifactsRef:t.artifactsRef,checkpointRef:t.checkpointRef,status:t.status,retries:t.retries}}function vg(t){let e={run_id:t.runId,skill:t.skill,skill_version:t.skillVersion,skill_hash:t.skillHash,orchestration:t.orchestration,current_step:t.currentStep,iteration:t.iteration,pending:t.pending,pending_ref:t.pendingRef,trajectory_ref:t.trajectoryRef,context_ref:t.contextRef,artifacts_ref:t.artifactsRef,checkpoint_ref:t.checkpointRef,run_status:t.status,run_retries:JSON.stringify(t.retries)};return Fi(e)}async function ro(t,e={}){let n=await we(t,Mi,$l,"Run state",e);if(n===null)return null;let i=JSON.parse(n);return vg(i)}async function Wi(t,e,n={}){await $e(t,Mi,JSON.stringify(yg(e),null,2),$l,"Run state",n)}async function so(t,e={}){await Di(t,Mi,"Run state",e)}var ql,Mi,$l,Bi=W(()=>{"use strict";no();ql=(t,e)=>{let n=t[e];return n==null?null:String(n)};Mi=".comet/run-state.json",$l=256*1024});var Ou=Ct(pt(),1);import{createHash as Pu}from"crypto";import{promises as _u}from"fs";import Ru from"path";import xl from"path";import{promises as kl}from"fs";import O from"path";import{promises as wh}from"fs";async function en(t){try{return await wh.access(t),!0}catch(e){if(yh(e))return!1;throw e}}function yh(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}me();on();Gs();ne();var an=class extends Error{code="classic-layout-unavailable";constructor(e="Classic artifact layout is unavailable from .comet/config.yaml"){super(e),this.name="ClassicLayoutUnavailableError"}},vl=".comet/config.yaml";function bl(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function Sl(t){await A(t,vl,{label:vl,expected:"file"})}function Ai(t,e){let n=O.resolve(t),i=e==="docs"?O.join(n,"docs"):n,r=O.join(i,"openspec"),s=O.join(n,"docs","superpowers");return{projectRoot:n,artifactLayout:e,openSpecBase:i,openSpecRoot:r,changesDir:O.join(r,"changes"),archiveDir:O.join(r,"changes","archive"),specsDir:O.join(r,"specs"),superpowersRoot:s,superpowersSpecsDir:O.join(s,"specs"),superpowersPlansDir:O.join(s,"plans"),superpowersReportsDir:O.join(s,"reports")}}async function Bh(t){await Sl(t);let e=await Pi(t,{allowPartialProject:!0,allowMissingNativeFields:!0});if(!e?.config)throw new an;if(!(e.config.workflows??[e.config.default_workflow]).includes("classic"))throw new an("Classic artifact layout is unavailable because Classic is not enabled");return e.classic?.artifact_layout??"legacy"}async function Kh(t,e){return Ai(t,e??await Bh(t))}async function Yh(t){try{return await kl.lstat(t),!0}catch(e){if(bl(e))return!1;throw e}}async function Jh(t,e){let n=await Kh(t,e),i=n.artifactLayout==="legacy"?"docs":"legacy",r=Ai(t,i).openSpecRoot,[s,o]=await Promise.all([A(n.projectRoot,F(n.projectRoot,n.openSpecRoot),{label:"Configured Classic OpenSpec root",expected:"directory"}),Yh(r)]),a=s.exists;return{paths:n,configuredRootExists:a,alternateRoot:r,alternateRootExists:o,dualRoots:a&&o}}async function Uh(t){let e=[t.openSpecRoot,t.changesDir,t.archiveDir,t.specsDir,t.superpowersRoot,t.superpowersSpecsDir,t.superpowersPlansDir,t.superpowersReportsDir];for(let n of e){let i=F(t.projectRoot,n);await A(t.projectRoot,i,{label:`Classic managed physical path ${i}`,expected:"directory"})}}async function qe(t,e){let n=await Jh(t,e);if(await Uh(n.paths),!n.configuredRootExists){let i=F(n.paths.projectRoot,n.paths.openSpecRoot),r=F(n.paths.projectRoot,n.alternateRoot);throw new an(`Configured Classic OpenSpec root is missing: ${i} (alternate ${r} is ${n.alternateRootExists?"present":"missing"})`)}return n.paths}async function zs(t,e){let n=O.join(O.resolve(t),".comet","classic-root-move.json");if(await en(n))throw new Error("Classic root move transaction is incomplete; inspect it with comet doctor and recover it explicitly before writing");let i=await qe(t,e);if(!await en(i.openSpecRoot))throw new Error(`Configured Classic OpenSpec root is missing: ${F(i.projectRoot,i.openSpecRoot)}`);return i}async function Xe(t){let e=O.resolve(t),n=null;try{(await kl.lstat(e)).isDirectory()||(e=O.dirname(e))}catch(i){if(!bl(i))throw i}for(;;){O.basename(e)==="openspec"&&(n=O.dirname(e));let i=O.join(e,".comet","config.yaml"),r=!1;if(await en(i))try{await Sl(e);let o=(await Pi(e))?.value;r=!!o&&typeof o=="object"&&!Array.isArray(o)&&(o.schema==="comet.project.v1"||o.default_workflow!==void 0||o.native!==void 0)}catch{}if(r||await en(O.join(e,".git")))return e;let s=O.dirname(e);if(s===e)return n??O.resolve(t);e=s}}function F(t,e){return O.relative(O.resolve(t),e).replaceAll("\\","/")}Qe();me();ne();import cn from"path";var Hh=2*1024*1024;function ji(t,e,n){let i=cn.resolve(t),r=cn.isAbsolute(e)?cn.resolve(e):cn.resolve(i,e),s=cn.relative(i,r).replaceAll("\\","/");return{root:i,relative:Ne(s,n),target:r}}async function le(t,e,n){let i=ji(t,e,n.label);return A(i.root,i.relative,n)}async function Ii(t,e,n){return(await le(t,e,{label:n.label,expected:n.expected??"any"})).exists}async function Qs(t,e,n,i){return await Ii(t,e,{label:n,expected:"file"})?(await Cl(t,e,{label:n,hooks:i})).byteLength>0:!1}async function gt(t,e,n){return(await Cl(t,e,n)).toString("utf8")}async function Cl(t,e,n){let i=ji(t,e,n.label);return(await B(i.root,i.relative,n.maxBytes??Hh,{label:n.label,hooks:n.hooks})).bytes}async function Ti(t,e,n){let i=ji(t,e,n);return Ys(i.root,i.relative,{label:n})}async function El(t,e,n,i){let r=ji(t,e,i.label);await A(r.root,r.relative,{label:i.label,expected:"file"}),await ie(r.target,n,{containedRoot:r.root,beforeTemporaryOpen:i.beforeTemporaryOpen,beforeCommit:i.beforeCommit,exclusive:i.exclusive})}function Xs(t){return t?/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t)?t.includes("..")?"Change name cannot contain '..' (path traversal not allowed)":null:`Invalid change name: '${t}' +Valid format: lowercase kebab-case (a-z, 0-9, single hyphens)`:"Change name cannot be empty"}function Zs(t){let e=Xs(t);if(e)throw new Error(e)}function Vh(t,e){return{label:F(t,e),directory:e}}async function Gh(t,e,n){let i=Vh(t,e);if(!(await le(t,e,{label:n,expected:"directory"})).exists)return{change:i,exists:!1,stateExists:!1};let s=await le(t,xl.join(e,".comet.yaml"),{label:`${n} state`,expected:"file"});return{change:i,exists:!0,stateExists:s.exists}}async function Pl(t,e=process.cwd()){Zs(t);let n=await qe(e),i=await Gh(n.projectRoot,xl.join(n.changesDir,t),`Classic active change ${t}`);return{...i.change,exists:i.exists,stateExists:i.stateExists}}import{promises as gu}from"fs";import z from"path";import{fileURLToPath as wu}from"url";import{promises as Qh}from"fs";import ge from"path";ne();me();import ln from"path";function zh(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function _l(t,e,n,i){let r=Ne(n,"Classic handoff artifact pointer");if((await A(t,r,{label:"Classic handoff artifact",expected:"file"})).exists)return null;let o=await qe(t),a=`${F(t,o.changesDir)}/`,l=(o.artifactLayout==="docs"?[a,"openspec/changes/"]:[a]).find(g=>r.startsWith(g));if(!l)return null;let u=r.slice(l.length).split("/");if(u.length<4||u[1]!==".comet"||u.slice(2).some(g=>g.length===0))return null;let f=u[0];Zs(f);let d=u.slice(2),h=ln.resolve(e);if(ln.dirname(h)!==ln.resolve(o.archiveDir))return null;let w=ln.basename(h),p=/^\d{4}-\d{2}-\d{2}-(.+)$/u.exec(w);if(w!==f&&p?.[1]!==f)return null;await A(t,F(t,h),{label:"Classic archived change directory",expected:"directory"});let m=ln.join(h,".comet",...d),y=F(t,m);try{return await B(t,y,i,{label:"Historical Classic archived handoff artifact"}),y}catch(g){if(zh(g))return null;throw g}}ne();var Rl=2*1024*1024;function un(t,e){return ge.relative(t,e).split(ge.sep).join("/")}async function fn(t,e,n,i,r){if(!n)return{code:e,satisfied:!1};let s=n.replaceAll("\\","/");if(r)return{code:e,satisfied:!1,source:s,detail:`Classic layout is unsafe or unavailable: ${r instanceof Error?r.message:String(r)}`};try{if(i){let a=i.artifactLayout==="legacy"?"docs":"legacy",c=F(t,Ai(t,a).openSpecRoot);if((s===c||s.startsWith(`${c}/`))&&(await A(t,s,{label:`${e} artifact`,expected:"file"})).exists)return{code:e,satisfied:!1,source:s,detail:"standalone OpenSpec root is not a Comet artifact root"}}let o=await xi(t,s,{label:`${e} artifact`});return{code:e,satisfied:o,source:s,...o?{resolvedSource:s}:{}}}catch(o){return{code:e,satisfied:!1,source:s,detail:`unsafe artifact pointer outside the project or through a special path: ${o instanceof Error?o.message:String(o)}`}}}async function Xh(t,e,n,i){try{i??=await qe(t)}catch(s){return{code:"design.handoff",satisfied:!1,...n?{source:n.replaceAll("\\","/")}:{},detail:`Classic layout is unsafe or unavailable for handoff evidence: ${s instanceof Error?s.message:String(s)}`}}let r=await fn(t,"design.handoff",n,i);if(!n||r.satisfied||r.detail)return r;try{let s=await _l(t,e,n,Rl);return s?{...r,satisfied:!0,resolvedSource:s,detail:`resolved historical legacy pointer from archived change: ${s}`}:r}catch(s){return{...r,satisfied:!1,detail:`unsafe archived handoff fallback: ${s instanceof Error?s.message:String(s)}`}}}async function qi(t,e,n){return fn(t,e,un(t,n))}async function Zh(t,e){let n=ge.join(e,"specs"),i;try{let o=un(t,n);if(!(await A(t,o,{label:"OpenSpec delta-spec directory",expected:"directory"})).exists)return{code:"openspec.delta-spec",satisfied:!1};i=await Qh.readdir(n)}catch(o){return o.code==="ENOENT"?{code:"openspec.delta-spec",satisfied:!1}:{code:"openspec.delta-spec",satisfied:!1,detail:`unsafe delta-spec path: ${o instanceof Error?o.message:String(o)}`}}let r=i.map(o=>ge.join(n,o,"spec.md")),s=(await Promise.all(r.map(async o=>{try{return await xi(t,un(t,o),{label:"OpenSpec delta spec"})?o:null}catch{return null}}))).filter(o=>o!==null);return{code:"openspec.delta-spec",satisfied:s.length>0,source:s[0]?un(t,s[0]):void 0,detail:`${s.length} delta spec${s.length===1?"":"s"}`}}async function eg(t,e){let n,i=un(t,e);try{n=(await B(t,i,Rl,{label:"Classic tasks artifact"})).bytes.toString("utf8")}catch(o){return o.code==="ENOENT"?{code:"build.tasks-complete",satisfied:!1}:{code:"build.tasks-complete",satisfied:!1,source:i,detail:`unsafe tasks artifact: ${o instanceof Error?o.message:String(o)}`}}let r=[...n.matchAll(/^\s*[-*]\s+\[([ xX])\]\s+/gmu)],s=r.filter(o=>o[1].toLowerCase()==="x").length;return{code:"build.tasks-complete",satisfied:r.length>0&&s===r.length,source:i,detail:`${s} of ${r.length} tasks complete`}}function dn(t,e){return t.some(n=>n.code===e&&n.satisfied)}async function wt(t,e){let n=await Xe(t),i=e.classic,r=ge.join(t,"proposal.md"),s=ge.join(t,"design.md"),o=ge.join(t,"tasks.md"),a=e.run?ge.resolve(t,e.run.checkpointRef):ge.join(t,".comet","checkpoint.json"),c,l;try{c=await qe(n)}catch(d){l=d}let u=await Promise.all([qi(n,"openspec.proposal",r),qi(n,"openspec.design",s),qi(n,"openspec.tasks",o),Zh(n,t),fn(n,"design.document",i?.designDoc??null,c,l),fn(n,"build.plan",i?.plan??null,c,l),eg(n,o),fn(n,"verification.report",i?.verificationReport??null,c,l),Xh(n,t,i?.handoffContext??null,c),qi(n,"run.checkpoint",a)]),f=u.find(d=>d.code==="design.handoff");return f&&!i?.handoffHash&&(f.satisfied=!1,f.detail="handoff hash is missing"),u.push({code:"archive.confirmed",satisfied:i?.archiveConfirmation==="confirmed"}),u}import{createHash as dw,randomUUID as pw}from"crypto";import{promises as ho}from"fs";import ye from"path";function tg(t){return t.classicProfile??t.workflow}function ng(t){return!t.buildMode||!t.tddMode||!t.isolation||!t.verifyMode?!1:t.buildMode==="subagent-driven-development"?t.subagentDispatch==="confirmed":t.buildMode==="direct"?t.directOverride===!0:!0}function ig(t){return t.buildMode==="direct"&&t.tddMode==="direct"&&t.isolation!==null&&t.verifyMode==="light"}function rg(t,e,n){if(e.verifyResult==="fail")return t==="full"?"full.build.fix":`${t}.build.execute`;if(t==="full"){if(!dn(n,"build.plan"))return"full.build.plan";if(e.buildPause==="plan-ready")return"full.build.plan-ready";if(!ng(e))return"full.build.configure"}else if(!ig(e))throw new Error(`${t} build configuration is incomplete`);return dn(n,"build.tasks-complete")?`${t}.build.complete`:`${t}.build.execute`}function sg(t,e,n){return e.verifyResult!=="pass"||!dn(n,"verification.report")?`${t}.verify.run`:`${t}.verify.branch`}function og(t,e){if(e.verifyResult!=="pass")throw new Error("archive requires verify_result=pass");return e.archiveConfirmation==="confirmed"?`${t}.archive.execute`:`${t}.archive.confirm`}function $i(t,e){let n=tg(t);if(t.archived&&t.phase!=="archive")throw new Error("archived=true requires phase=archive");if(t.archived)return"completed";if(n!=="full"&&t.phase==="design")throw new Error(`${n} workflow cannot enter design`);switch(t.phase){case"open":return`${n}.open`;case"design":return dn(e,"design.handoff")?"full.design.document":"full.design.handoff";case"build":return rg(n,t,e);case"verify":return sg(n,t,e);case"archive":return og(n,t)}}var Ui=Ct(pt(),1);Qe();ne();import Ji from"path";Bi();var Dl=["full","hotfix","tweak"],Ze=1,kg=["open","design","build","verify","archive"],bg=["en","zh-CN"],Sg=["off","beta"],Cg=["subagent-driven-development","executing-plans","direct"],Eg=["plan-ready"],xg=["confirmed"],Pg=["tdd","direct"],_g=["off","standard","thorough"],Rg=["current","branch","worktree"],Og=["light","full"],Ng=["pending","pass","fail"],Ag=["pending","handled"],jg=["pending","confirmed"],Yi=["workflow","language","phase","context_compression","build_mode","build_pause","subagent_dispatch","tdd_mode","review_mode","isolation","bound_branch","verify_mode","auto_transition","base_ref","design_doc","plan","verify_result","verify_failures","verification_report","branch_status","created_at","verified_at","archive_confirmation","archived","direct_override","handoff_context","handoff_hash","classic_profile","classic_migration"],Ig=["run_id"],Tg=new Set([...Yi,...Ig]),qg=["workflow","phase","design_doc","plan","build_mode","isolation","verify_mode","verify_result","verified_at","archived"];function Fl(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function yt(t,e){let n=t[e];if(n==null||n==="")return null;if(typeof n!="string")throw new Error(`Invalid Classic state: ${e} must be a string or null`);return n}function K(t,e,n,i=!0){let r=t[e];if(r==null||r===""){if(i)return null;throw new Error(`Invalid Classic state: ${e} is required`)}if(typeof r!="string"||!n.includes(r))throw new Error(`Invalid Classic state: ${e} must be one of ${n.join(", ")}${i?" or null":""}`);return r}function oo(t,e,n=!0){let i=t[e];if(i==null||i===""){if(n)return null;throw new Error(`Invalid Classic state: ${e} is required`)}if(typeof i!="boolean")throw new Error(`Invalid Classic state: ${e} must be true or false`);return i}function $g(t,e,n=0){let i=t[e];if(i==null||i==="")return n;if(typeof i!="number"||!Number.isInteger(i)||i<0)throw new Error(`Invalid Classic state: ${e} must be a non-negative integer`);return i}function Ki(t,e){let n=yt(t,e);if(n===null)return null;if(/^(?:[A-Za-z]:|[\\/]|~)/u.test(n)||n.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Classic state: ${e} must be a relative repository path`);return n}function Lg(t,e){let n=yt(t,e);if(n!==null&&!/^[a-f0-9]{64}$/u.test(n))throw new Error(`Invalid Classic state: ${e} must be a sha256 hex digest`);return n}function Dg(t){let e=t.classic_migration;if(e==null||e==="")return null;if(e!==Ze)throw new Error(`Invalid Classic state: classic_migration must be ${Ze}`);return e}function Fg(t){if(!Yi.some(n=>Fl(t,n)))return null;for(let n of qg)if(!Fl(t,n))return null;return{workflow:K(t,"workflow",Dl,!1),language:K(t,"language",bg),phase:K(t,"phase",kg,!1),contextCompression:K(t,"context_compression",Sg),buildMode:K(t,"build_mode",Cg),buildPause:K(t,"build_pause",Eg),subagentDispatch:K(t,"subagent_dispatch",xg),tddMode:K(t,"tdd_mode",Pg),reviewMode:K(t,"review_mode",_g),isolation:K(t,"isolation",Rg),boundBranch:yt(t,"bound_branch"),verifyMode:K(t,"verify_mode",Og),autoTransition:oo(t,"auto_transition"),baseRef:yt(t,"base_ref"),designDoc:Ki(t,"design_doc"),plan:Ki(t,"plan"),verifyResult:K(t,"verify_result",Ng,!1),verifyFailures:$g(t,"verify_failures"),verificationReport:Ki(t,"verification_report"),branchStatus:K(t,"branch_status",Ag),createdAt:yt(t,"created_at"),verifiedAt:yt(t,"verified_at"),archiveConfirmation:K(t,"archive_confirmation",jg),archived:oo(t,"archived",!1),directOverride:oo(t,"direct_override"),handoffContext:Ki(t,"handoff_context"),handoffHash:Lg(t,"handoff_hash"),classicProfile:K(t,"classic_profile",Dl),classicMigration:Dg(t)}}function ao(t,e){let n=e??null;if(n===null&&e===void 0&&t.run_id&&t.skill)try{n=Fi(t)}catch(i){let r=i instanceof Error?i.message:String(i);throw new Error(r.replace(/^Invalid Run state:/u,"Invalid Classic state:"),{cause:i})}return{classic:Fg(t),run:n,unknownKeys:Object.keys(t).filter(i=>!Tg.has(i))}}function Ml(t){return{workflow:t.workflow,language:t.language,phase:t.phase,context_compression:t.contextCompression,build_mode:t.buildMode,build_pause:t.buildPause,subagent_dispatch:t.subagentDispatch,tdd_mode:t.tddMode,review_mode:t.reviewMode,isolation:t.isolation,bound_branch:t.boundBranch,verify_mode:t.verifyMode,auto_transition:t.autoTransition,base_ref:t.baseRef,design_doc:t.designDoc,plan:t.plan,verify_result:t.verifyResult,verify_failures:t.verifyFailures,verification_report:t.verificationReport,branch_status:t.branchStatus,created_at:t.createdAt,verified_at:t.verifiedAt,archive_confirmation:t.archiveConfirmation,archived:t.archived,direct_override:t.directOverride,handoff_context:t.handoffContext,handoff_hash:t.handoffHash,classic_profile:t.classicProfile,classic_migration:t.classicMigration}}Bi();var Mg=2*1024*1024;function hn(t){let e=t.toJS();if(e===null)return{};if(typeof e!="object"||Array.isArray(e))throw new Error("Invalid Classic state document: root must be a mapping");return e}function Wl(t,e,n){t.get(e)!==n&&t.set(e,n)}function Wg(t,e){if(e.classic)for(let[n,i]of Object.entries(Ml(e.classic)))Wl(t,n,i);else for(let n of Yi)t.delete(n);io(t.toJS(),e.run),e.run?Wl(t,"run_id",e.run.runId):t.delete("run_id")}function Bg(t){let e=["skill","skill_version","skill_hash","orchestration","current_step","iteration","pending","pending_ref","trajectory_ref","context_ref","artifacts_ref","checkpoint_ref","run_status","run_retries"];for(let n of e)t.delete(n)}function Kg(t){let e=!1;for(let n of["build_command","verify_command"])t.has(n)&&(t.delete(n),e=!0);return e}async function Bl(t){let e;try{e=(await B(Ji.dirname(t),Ji.basename(t),Mg,{label:"Classic state document"})).bytes.toString("utf8")}catch(i){if(i.code!=="ENOENT")throw i;return new Ui.Document({})}let n=(0,Ui.parseDocument)(e);if(n.errors.length>0)throw new Error(`Invalid Classic state document: ${n.errors[0].message}`);return hn(n),n}async function Le(t,e={}){let n=e.migrate!==!1,i=Ji.join(t,".comet.yaml"),r=await Bl(i),s=hn(r),o=Kg(r);o&&(s=hn(r));let a=await ro(t);if(!a&&s.run_id&&s.skill){let{runStateFromDocument:c}=await Promise.resolve().then(()=>(Bi(),Ll));a=c(s),a&&n&&(await Wi(t,a),Bg(r),o=!0)}return o&&n&&await ie(i,r.toString(),{containedRoot:t}),ao(hn(r),a)}async function et(t,e,n={}){let i=Ji.join(t,".comet.yaml"),r=await Bl(i);Wg(r,{...e,unknownKeys:e.unknownKeys??[]}),ao(hn(r),e.run??null),await ie(i,r.toString(),{containedRoot:t,beforeCommit:n.beforeCommit}),e.run?await Wi(t,e.run):await so(t)}function Kl(t,e,n){return{runId:e,skill:t.definition.metadata.name,skillVersion:t.definition.metadata.version,skillHash:n,orchestration:t.definition.orchestration.mode,currentStep:t.definition.orchestration.entry??null,iteration:0,pending:null,pendingRef:".comet/pending-action.json",trajectoryRef:".comet/trajectory.jsonl",contextRef:".comet/context.md",artifactsRef:".comet/artifacts.json",checkpointRef:".comet/checkpoint.json",status:"running",retries:{}}}no();import Hi from"path";var ue={trajectory:8*1024*1024,artifacts:1024*1024,context:1024*1024,pendingAction:256*1024,checkpoint:256*1024};function re(t,e){if(Hi.isAbsolute(e))throw new Error("Run path must stay inside the change directory");let n=Hi.resolve(t),i=Hi.resolve(n,e);if(i!==n&&!i.startsWith(n+Hi.sep))throw new Error("Run path must stay inside the change directory")}async function vt(t,e,n,i={}){re(t,e),await Tl(t,e,`${JSON.stringify(n)} +`,ue.trajectory,"Run trajectory",i)}async function gn(t,e,n={}){re(t,e);let i=await we(t,e,ue.trajectory,"Run trajectory",n);return i===null?[]:i.split(/\r?\n/).map((r,s)=>({line:r,number:s+1})).filter(({line:r})=>r.length>0).map(({line:r,number:s})=>{try{return JSON.parse(r)}catch(o){throw new Error(`Invalid Trajectory event at line ${s}`,{cause:o})}})}async function co(t,e,n={}){re(t,e);let i=await we(t,e,ue.artifacts,"Run artifacts",n);return i===null?{}:JSON.parse(i)}async function Vi(t,e,n,i={}){re(t,e),await $e(t,e,JSON.stringify(n,null,2)+` +`,ue.artifacts,"Run artifacts",i)}async function Gi(t,e,n,i={}){re(t,e),await $e(t,e,n,ue.context,"Run context",i)}async function Yl(t,e,n={}){return re(t,e),we(t,e,ue.context,"Run context",n)}async function Jl(t,e,n,i={}){re(t,e),await $e(t,e,JSON.stringify(n,null,2)+` +`,ue.pendingAction,"Run pending action",i)}async function lo(t,e,n={}){re(t,e);let i=await we(t,e,ue.pendingAction,"Run pending action",n);return i===null?null:JSON.parse(i)}async function Ul(t,e,n={}){re(t,e),await Di(t,e,"Run pending action",n)}async function zi(t,e,n,i={}){re(t,e),await $e(t,e,JSON.stringify(n,null,2)+` +`,ue.checkpoint,"Run checkpoint",i)}async function Hl(t,e,n={}){re(t,e);let i=await we(t,e,ue.checkpoint,"Run checkpoint",n);return i===null?null:JSON.parse(i)}import{createHash as au,randomUUID as aw}from"crypto";import{promises as $}from"fs";import T from"path";var zl=Ct(pt(),1);import{promises as uo}from"fs";import X from"path";var Yg=["invoke_skill","call_tool","handoff","ask_user","checkpoint"],Jg=["deterministic","adaptive"],Ug=["function","mcp","script","agent"],Hg=["none","read","write","external"],Vg=["progress","step","completion"],Gg=["artifact_exists","state_equals"];function tt(t,e,n){return new Error(`${t}: ${e} ${n}`)}function V(t,e,n="document"){if(t===null||typeof t!="object"||Array.isArray(t))throw tt(e,n,"must be an object")}function De(t,e,n){if(!Array.isArray(t))throw tt(e,n,"must be an array")}function Y(t,e,n){if(typeof t!="string")throw tt(e,n,"must be a string")}function se(t,e,n,i){e in t&&Y(t[e],n,`${i}.${e}`)}function Ql(t,e,n,i){if(e in t&&typeof t[e]!="boolean")throw tt(n,`${i}.${e}`,"must be a boolean")}function Fe(t,e,n,i){if(typeof t!="string"||!e.includes(t))throw tt(n,i,`must be one of ${e.join(", ")}`)}function Qi(t,e,n){De(t,e,n),t.forEach((i,r)=>{Y(i,e,`${n}[${r}]`)})}function Vl(t,e,n){V(t,e,n),Y(t.name,e,`${n}.name`),Y(t.description,e,`${n}.description`),Ql(t,"required",e,n)}function zg(t,e,n){V(t,e,n),Y(t.id,e,`${n}.id`),se(t,"source",e,n),se(t,"version",e,n)}function Qg(t,e,n){V(t,e,n),Y(t.id,e,`${n}.id`),Y(t.role,e,`${n}.role`),se(t,"instructions",e,n)}function Xg(t,e,n){V(t,e,n),Y(t.id,e,`${n}.id`),Fe(t.kind,Ug,e,`${n}.kind`),Y(t.source,e,`${n}.source`),Fe(t.sideEffect,Hg,e,`${n}.sideEffect`),Ql(t,"requiresConfirmation",e,n)}function Zg(t,e,n){V(t,e,n),Fe(t.type,Yg,e,`${n}.type`),se(t,"ref",e,n),se(t,"prompt",e,n),se(t,"question",e,n),"options"in t&&Qi(t.options,e,`${n}.options`)}function ew(t,e,n){V(t,e,n),Y(t.id,e,`${n}.id`),Zg(t.action,e,`${n}.action`),se(t,"next",e,n),"completionEvals"in t&&Qi(t.completionEvals,e,`${n}.completionEvals`)}function tw(t,e){let n="goal";V(t,e,n),Y(t.statement,e,`${n}.statement`),De(t.inputs,e,`${n}.inputs`),t.inputs.forEach((i,r)=>{Vl(i,e,`${n}.inputs[${r}]`)}),De(t.outputs,e,`${n}.outputs`),t.outputs.forEach((i,r)=>{Vl(i,e,`${n}.outputs[${r}]`)}),Qi(t.success,e,`${n}.success`)}function nw(t,e){let n="orchestration";V(t,e,n),Fe(t.mode,Jg,e,`${n}.mode`),se(t,"entry",e,n),"steps"in t&&(De(t.steps,e,`${n}.steps`),t.steps.forEach((i,r)=>{ew(i,e,`${n}.steps[${r}]`)}))}function Xl(t,e){return V(t,e),Fe(t.apiVersion,["comet/v1alpha1"],e,"apiVersion"),Fe(t.kind,["Skill"],e,"kind"),V(t.metadata,e,"metadata"),Y(t.metadata.name,e,"metadata.name"),Y(t.metadata.version,e,"metadata.version"),Y(t.metadata.description,e,"metadata.description"),tw(t.goal,e),nw(t.orchestration,e),De(t.skills,e,"skills"),t.skills.forEach((n,i)=>{zg(n,e,`skills[${i}]`)}),De(t.agents,e,"agents"),t.agents.forEach((n,i)=>{Qg(n,e,`agents[${i}]`)}),De(t.tools,e,"tools"),t.tools.forEach((n,i)=>{Xg(n,e,`tools[${i}]`)}),t}function Zl(t,e){V(t,e);for(let n of["allowedSkills","allowedAgents","allowedTools","confirmationRequiredFor"])n in t&&Qi(t[n],e,n);for(let n of["maxIterations","maxRetriesPerAction"])if(n in t&&(typeof t[n]!="number"||!Number.isFinite(t[n])))throw tt(e,n,"must be a finite number");return t}function iw(t,e){return V(t,e),"runtime"in t&&eu(t.runtime,e,"runtime"),t}function eu(t,e,n){return De(t,e,n),t.forEach((i,r)=>{let s=`${n}[${r}]`;V(i,e,s),Y(i.id,e,`${s}.id`),Fe(i.scope,Vg,e,`${s}.scope`),Fe(i.type,Gg,e,`${s}.type`),se(i,"artifact",e,s),se(i,"field",e,s),se(i,"equals",e,s)}),t}async function fo(t){let e=await uo.readFile(t,"utf8");try{return(0,zl.parse)(e)}catch(n){let i=n instanceof Error?n.message:String(n);throw tt(t,"document",i)}}async function rw(t){try{return await fo(t)}catch(e){if(e.code==="ENOENT")return null;throw e}}async function Gl(t){try{return await uo.access(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function sw(t){let e=X.join(t,"checks.yaml"),n=X.join(t,"evals.yaml"),[i,r]=await Promise.all([Gl(e),Gl(n)]);if(r)throw new Error(`${n}: evals.yaml is no longer supported; use checks.yaml`);return i?{document:iw(await fo(e),e)}:{document:null}}async function tu(t){let e=X.resolve(t.root),n=X.resolve(t.controlRoot);t.requireSkillMarkdown&&await uo.access(X.join(e,"SKILL.md"));let i=X.join(n,"skill.yaml"),r=X.join(n,"guardrails.yaml"),s=Xl(await fo(i),i),o=await rw(r),a=o===null?null:Zl(o,r),c=await sw(n),l={allowedSkills:s.skills.map(u=>u.id),allowedAgents:s.agents.map(u=>u.id),allowedTools:s.tools.map(u=>u.id),maxIterations:50,maxRetriesPerAction:3,confirmationRequiredFor:s.tools.filter(u=>u.requiresConfirmation).map(u=>u.id)};return{root:e,packageKind:t.packageKind==="runtime"?"runtime":void 0,definition:s,guardrails:{...l,...a},evals:c.document?.runtime??[]}}async function nu(t){let e=X.resolve(t);return tu({root:e,controlRoot:X.join(e,"comet"),packageKind:"skill",requireSkillMarkdown:!0})}async function iu(t){let e=X.resolve(t);return tu({root:e,controlRoot:e,packageKind:"runtime",requireSkillMarkdown:!1})}function ru(t,e,n=X.join(e,"package.json")){V(t,n);let i=t.packageKind==="runtime"?"runtime":void 0,r=Xl(t.definition,n),s=Zl(t.guardrails,n),o=eu(t.evals,n,"evals"),a={allowedSkills:r.skills.map(c=>c.id),allowedAgents:r.agents.map(c=>c.id),allowedTools:r.tools.map(c=>c.id),maxIterations:50,maxRetriesPerAction:3,confirmationRequiredFor:r.tools.filter(c=>c.requiresConfirmation).map(c=>c.id)};return{root:X.resolve(e),packageKind:i,definition:r,guardrails:{...a,...s},evals:o}}import su from"path";function ow(t,e,n,i){t.type==="invoke_skill"&&!e.definition.skills.some(r=>r.id===t.ref)&&n.push(`step ${i} references undeclared skill: ${t.ref??"(missing)"}`),t.type==="call_tool"&&!e.definition.tools.some(r=>r.id===t.ref)&&n.push(`step ${i} references undeclared tool: ${t.ref??"(missing)"}`),t.type==="handoff"&&!e.definition.agents.some(r=>r.id===t.ref)&&n.push(`step ${i} references undeclared agent: ${t.ref??"(missing)"}`),t.type==="ask_user"&&!t.question&&n.push(`step ${i} ask_user action requires question`)}function ou(t){let e=[],{definition:n,guardrails:i,evals:r}=t;n.apiVersion!=="comet/v1alpha1"&&e.push("unsupported apiVersion"),n.kind!=="Skill"&&e.push("kind must be Skill"),n.metadata.name||e.push("metadata.name is required"),n.goal.statement||e.push("goal.statement is required"),i.maxIterations<1&&e.push("maxIterations must be at least 1"),i.maxRetriesPerAction<0&&e.push("maxRetriesPerAction must not be negative");let s=n.orchestration.steps??[];if(n.orchestration.mode==="adaptive")(n.orchestration.entry||s.length>0)&&e.push("adaptive orchestration must not define entry or steps");else{let o=new Set;for(let a of s)o.has(a.id)&&e.push(`duplicate step id: ${a.id}`),o.add(a.id),ow(a.action,t,e,a.id);(!n.orchestration.entry||!o.has(n.orchestration.entry))&&e.push(`orchestration.entry references unknown step: ${n.orchestration.entry??"(missing)"}`);for(let a of s){a.next&&!o.has(a.next)&&e.push(`step ${a.id} has unknown next step: ${a.next}`);for(let c of a.completionEvals??[])r.some(l=>l.id===c)||e.push(`step ${a.id} references unknown eval: ${c}`)}}for(let o of n.tools){if(o.kind!=="script")continue;let a=su.posix.normalize(o.source.replaceAll("\\","/"));(su.isAbsolute(o.source)||a===".."||a.startsWith("../"))&&e.push(`script tool ${o.id} must reference a relative path inside the Skill package`)}for(let o of i.allowedSkills)n.skills.some(a=>a.id===o)||e.push(`guardrails allow undeclared skill: ${o}`);for(let o of i.allowedAgents)n.agents.some(a=>a.id===o)||e.push(`guardrails allow undeclared agent: ${o}`);for(let o of i.allowedTools)n.tools.some(a=>a.id===o)||e.push(`guardrails allow undeclared tool: ${o}`);return e}function Xi(t){return Array.isArray(t)?t.map(Xi):t&&typeof t=="object"?Object.fromEntries(Object.entries(t).sort(([e],[n])=>e.localeCompare(n)).map(([e,n])=>[e,Xi(n)])):t}function cw(t){return Xi({...t.packageKind==="runtime"?{packageKind:"runtime"}:{},definition:t.definition,guardrails:t.guardrails,evals:t.evals})}function lw(t){return T.posix.normalize(t.replaceAll("\\","/"))}function kt(t,e,n){let i=T.relative(t,e);if(!(i===""||!T.isAbsolute(i)&&!i.startsWith(`..${T.sep}`)))throw new Error(`${n} resolves outside the Skill package`)}async function cu(t,e,n){let i=lw(e);if(T.posix.isAbsolute(i)||i===".."||i.startsWith("../"))throw new Error(`${n} resolves outside the Skill package`);let r=T.resolve(t,...i.split("/"));kt(t,r,n);let s;try{s=await $.realpath(r)}catch(o){throw o.code==="ENOENT"?new Error(`${n} does not exist: ${e}`,{cause:o}):o}if(kt(t,s,n),!(await $.stat(s)).isFile())throw new Error(`${n} is not a file: ${e}`);return{path:i,content:await $.readFile(s)}}async function uw(t){let e=await $.realpath(t.root),n=t.packageKind==="runtime"?[]:[await cu(e,"SKILL.md","SKILL.md")];for(let i of t.definition.tools)i.kind==="script"&&n.push(await cu(e,i.source,`Script tool ${i.id}`));return n.sort((i,r)=>i.path.localeCompare(r.path))}function fw(t,e){let n=e.map(i=>({path:i.path,sha256:au("sha256").update(i.content).digest("hex")}));return au("sha256").update(JSON.stringify(Xi({package:t,files:n}))).digest("hex")}function fu(t){return JSON.stringify(t,null,2)+` +`}async function du(t){let e=cw(t),n=await uw(t);return{document:e,files:n,hash:fw(e,n)}}async function Zi(t){return(await du(t)).hash}async function lu(t){try{return await $.access(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function uu(t,e){try{if((await $.readFile(T.join(t,"sha256"),"utf8")).trim()!==e.hash)throw new Error("hash mismatch");if(await $.readFile(T.join(t,"package.json"),"utf8")!==fu(e.document))throw new Error("package mismatch");for(let r of e.files)if(!(await $.readFile(T.join(t,...r.path.split("/")))).equals(r.content))throw new Error(`file mismatch: ${r.path}`)}catch(n){throw new Error(`Existing Skill snapshot is invalid: ${e.hash}`,{cause:n})}}async function po(t,e){let n=await du(t),i=T.resolve(e,".comet","skill-snapshots"),r=T.join(i,n.hash);if(await $.mkdir(i,{recursive:!0}),await lu(r))return await uu(r,n),{hash:n.hash,snapshotDir:r};let s=T.join(i,`.tmp-${aw()}`);kt(i,s,"Temporary snapshot"),kt(i,r,"Published snapshot");try{await $.mkdir(s);for(let o of n.files){let a=T.join(s,...o.path.split("/"));kt(s,a,`Snapshot file ${o.path}`),await $.mkdir(T.dirname(a),{recursive:!0}),await $.writeFile(a,o.content)}await $.writeFile(T.join(s,"package.json"),fu(n.document)),await $.writeFile(T.join(s,"sha256"),n.hash+` +`),await $.rename(s,r)}catch(o){if(await lu(r)){try{await uu(r,n)}finally{await $.rm(s,{recursive:!0,force:!0})}return{hash:n.hash,snapshotDir:r}}throw await $.rm(s,{recursive:!0,force:!0}),o}return{hash:n.hash,snapshotDir:r}}async function mo(t,e){if(!/^[a-f0-9]{64}$/u.test(e))throw new Error(`Invalid Skill snapshot hash: ${e}`);let n=T.resolve(t,".comet","skill-snapshots"),i=T.join(n,e);kt(n,i,"Skill snapshot");try{let r=(await $.readFile(T.join(i,"sha256"),"utf8")).trim();if(r!==e)throw new Error(`stored hash is ${r||"(empty)"}`);let s=T.join(i,"package.json"),o=JSON.parse(await $.readFile(s,"utf8")),a=ru(o,i,s),c=ou(a);if(c.length>0)throw new Error(c.map(u=>` - ${u}`).join(` +`));let l=await Zi(a);if(l!==e)throw new Error(`calculated hash is ${l}`);return a}catch(r){throw new Error(`Skill snapshot is invalid or missing: ${e}`,{cause:r})}}async function pu(t){try{return await ho.access(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}function mu(t){return dw("sha256").update(t).digest("hex")}function mw(t){return mu(JSON.stringify(Object.fromEntries(Object.entries(t).sort(([e],[n])=>e.localeCompare(n)))))}function hw(t){return t.replaceAll(".","_").replaceAll("-","_")}async function gw(t,e){let n=await Xe(t),i=Object.fromEntries(e.filter(o=>o.satisfied&&o.source).map(o=>[hw(o.code),o.source])),r=ye.join(t,"subagent-progress.md");await pu(r)&&(i.subagent_progress=ye.relative(n,r).split(ye.sep).join("/"));let s=e.find(o=>o.code==="design.handoff"&&o.satisfied);return s?.source&&(i.handoff_context=s.source),i}function ww(t,e,n){return[{sequence:1,timestamp:n,type:"run_started",runId:t.runId,data:{skill:t.skill,skillVersion:t.skillVersion,skillHash:t.skillHash}},{sequence:2,timestamp:n,type:"state_migrated",runId:t.runId,data:{kind:"classic",migrationVersion:Ze,profile:e,source:"pre-migration"}}]}async function yw(t){await Promise.all(t.map(e=>ho.rm(e,{recursive:!0,force:!0})))}async function hu(t,e){let n=await Le(t);if(!n.classic)throw new Error("Classic migration requires a legacy state projection");let i=n.classic,r=i.classicProfile??i.workflow;if(n.run){if(i.classicMigration!==Ze)throw new Error("Classic Run exists without a supported classic_migration marker");if(n.run.skill!==e.skillPackage.definition.metadata.name)throw new Error(`Classic Run skill mismatch: expected ${e.skillPackage.definition.metadata.name}, got ${n.run.skill}`);if(await Zi(e.skillPackage)!==n.run.skillHash)return await mo(t,n.run.skillHash),{classic:i,run:n.run,evidence:await wt(t,n),migrated:!1,snapshotDir:ye.join(t,".comet","skill-snapshots",n.run.skillHash)};let d=await po(e.skillPackage,t);return{classic:i,run:n.run,evidence:await wt(t,n),migrated:!1,snapshotDir:d.snapshotDir}}let s=await wt(t,n),o=$i(i,s);if(!e.skillPackage.definition.orchestration.steps?.some(f=>f.id===o))throw new Error(`Classic Skill package does not define resolved step: ${o}`);let a=await Zi(e.skillPackage),c=ye.join(t,".comet","skill-snapshots",a),l=await pu(c),u=[];try{let f=await po(e.skillPackage,t),d=Kl(e.skillPackage,e.runId?.()??pw(),f.hash);d.currentStep=o,o==="completed"&&(d.status="completed");let h={...i,classicProfile:r,classicMigration:Ze},w=await gw(t,s),p=await Xe(t),m=s.find(S=>S.code==="design.handoff"&&S.satisfied),y=null;m?.source&&(y=await gt(p,m.resolvedSource??m.source,{label:"Classic migration handoff context",hooks:e.handoffReadHooks}),await Gi(t,d.contextRef,y),u.push(ye.resolve(t,d.contextRef))),await Vi(t,d.artifactsRef,w),u.push(ye.resolve(t,d.artifactsRef));let g=(e.now?.()??new Date).toISOString(),b={runId:d.runId,stateVersion:1,trajectoryOffset:2,contextHash:y===null?null:mu(y),artifactsHash:mw(w),createdAt:g};await zi(t,d.checkpointRef,b),u.push(ye.resolve(t,d.checkpointRef)),u.push(ye.resolve(t,d.trajectoryRef));for(let S of ww(d,r,g))await vt(t,d.trajectoryRef,S);return await et(t,{classic:h,run:d,unknownKeys:n.unknownKeys}),{classic:h,run:d,evidence:s,migrated:!0,snapshotDir:f.snapshotDir}}catch(f){throw await yw(u),l||await ho.rm(c,{recursive:!0,force:!0}),f}}async function vw(t){try{return(await gu.stat(t)).isDirectory()}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function er(t){try{return(await gu.stat(t)).isFile()}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function kw(t){return await vw(t)?await er(z.join(t,"skill.yaml"))?!0:await er(z.join(t,"SKILL.md"))&&await er(z.join(t,"comet","skill.yaml")):!1}function bw(t){return{root:t,packageKind:"runtime",definition:{apiVersion:"comet/v1alpha1",kind:"Skill",metadata:{name:"comet-classic",version:"1",description:"Internal compatibility orchestration for classic Comet full, hotfix, and tweak workflows"},goal:{statement:"Advance or restore a classic Comet Run without changing the user command surface",inputs:[{name:"classic-state",description:"Validated ClassicState consistent with the Run projection",required:!0},{name:"evidence",description:"Structured evidence produced by the Classic Evidence collector",required:!0}],outputs:[{name:"run-state",description:"Atomically synchronized Classic and Run state",required:!0}],success:["Legacy fields and Run fields remain consistent","Every step invokes only a declared public Comet Skill","The completed state passes its completion eval"]},orchestration:{mode:"deterministic",entry:"full.open",steps:[{id:"full.open",action:{type:"invoke_skill",ref:"comet-open"},next:"full.design.handoff"},{id:"full.design.handoff",action:{type:"invoke_skill",ref:"comet-design"},next:"full.design.document"},{id:"full.design.document",action:{type:"invoke_skill",ref:"comet-design"},next:"full.build.plan"},{id:"full.build.plan",action:{type:"invoke_skill",ref:"comet-build"},next:"full.build.plan-ready"},{id:"full.build.plan-ready",action:{type:"invoke_skill",ref:"comet-build"},next:"full.build.configure"},{id:"full.build.configure",action:{type:"invoke_skill",ref:"comet-build"},next:"full.build.execute"},{id:"full.build.execute",action:{type:"invoke_skill",ref:"comet-build"},next:"full.build.complete"},{id:"full.build.complete",action:{type:"invoke_skill",ref:"comet-build"},next:"full.verify.run"},{id:"full.build.fix",action:{type:"invoke_skill",ref:"comet-build"},next:"full.build.execute"},{id:"full.verify.run",action:{type:"invoke_skill",ref:"comet-verify"},next:"full.verify.branch"},{id:"full.verify.branch",action:{type:"invoke_skill",ref:"comet-verify"},next:"full.archive.confirm"},{id:"full.archive.confirm",action:{type:"invoke_skill",ref:"comet-archive"},next:"full.archive.execute"},{id:"full.archive.execute",action:{type:"invoke_skill",ref:"comet-archive"},next:"completed"},{id:"hotfix.open",action:{type:"invoke_skill",ref:"comet-hotfix"},next:"hotfix.build.execute"},{id:"hotfix.build.execute",action:{type:"invoke_skill",ref:"comet-build"},next:"hotfix.build.complete"},{id:"hotfix.build.complete",action:{type:"invoke_skill",ref:"comet-build"},next:"hotfix.verify.run"},{id:"hotfix.verify.run",action:{type:"invoke_skill",ref:"comet-verify"},next:"hotfix.verify.branch"},{id:"hotfix.verify.branch",action:{type:"invoke_skill",ref:"comet-verify"},next:"hotfix.archive.confirm"},{id:"hotfix.archive.confirm",action:{type:"invoke_skill",ref:"comet-archive"},next:"hotfix.archive.execute"},{id:"hotfix.archive.execute",action:{type:"invoke_skill",ref:"comet-archive"},next:"completed"},{id:"tweak.open",action:{type:"invoke_skill",ref:"comet-tweak"},next:"tweak.build.execute"},{id:"tweak.build.execute",action:{type:"invoke_skill",ref:"comet-build"},next:"tweak.build.complete"},{id:"tweak.build.complete",action:{type:"invoke_skill",ref:"comet-build"},next:"tweak.verify.run"},{id:"tweak.verify.run",action:{type:"invoke_skill",ref:"comet-verify"},next:"tweak.verify.branch"},{id:"tweak.verify.branch",action:{type:"invoke_skill",ref:"comet-verify"},next:"tweak.archive.confirm"},{id:"tweak.archive.confirm",action:{type:"invoke_skill",ref:"comet-archive"},next:"tweak.archive.execute"},{id:"tweak.archive.execute",action:{type:"invoke_skill",ref:"comet-archive"},next:"completed"},{id:"completed",action:{type:"checkpoint"},completionEvals:["classic-completed"]}]},skills:[{id:"comet-open"},{id:"comet-design"},{id:"comet-build"},{id:"comet-verify"},{id:"comet-archive"},{id:"comet-hotfix"},{id:"comet-tweak"}],agents:[],tools:[]},guardrails:{allowedSkills:["comet-open","comet-design","comet-build","comet-verify","comet-archive","comet-hotfix","comet-tweak"],allowedAgents:[],allowedTools:[],maxIterations:500,maxRetriesPerAction:3,confirmationRequiredFor:[]},evals:[{id:"classic-completed",scope:"completion",type:"state_equals",field:"status",equals:"completed"}]}}async function Sw(){let t=z.dirname(wu(import.meta.url)),e=[process.env.COMET_RUNTIME_CLASSIC_ROOT,z.resolve(t,"..","runtime","classic"),z.resolve(t,"..","..","comet","runtime","classic"),z.resolve(t,"..","..","assets","skills","comet","runtime","classic"),z.resolve("assets","skills","comet","runtime","classic"),process.env.COMET_CLASSIC_SKILL_ROOT,z.resolve(t,"..","..","comet-classic"),z.resolve(t,"..","..","assets","skills","comet-classic"),z.resolve("assets","skills","comet-classic")].filter(n=>!!n);for(let n of e)if(await kw(n))return n;return null}async function Cw(t){return await er(z.join(t,"skill.yaml"))?iu(t):nu(t)}async function yu(t){let e=await Sw();return hu(t,{skillPackage:e?await Cw(e):bw(z.dirname(wu(import.meta.url)))})}async function vu(t,e,n,i){let r=await Le(t);if(!r.classic||!r.run)throw new Error("Classic transition requires synchronized Classic and Run projections");let s=await wt(t,{classic:e,run:n,unknownKeys:r.unknownKeys}),o=$i(e,s),a={...n,currentStep:o,iteration:n.iteration+1,status:o==="completed"?"completed":"running"};await et(t,{classic:e,run:a,unknownKeys:r.unknownKeys});let c=await gn(t,a.trajectoryRef);return await vt(t,a.trajectoryRef,{sequence:c.length+1,timestamp:new Date().toISOString(),type:"state_transitioned",runId:a.runId,data:{kind:"classic",fromStep:n.currentStep,toStep:o,...i}}),a}import{AsyncLocalStorage as Ew}from"async_hooks";import{promises as ku}from"fs";import wn from"path";var go=new Ew;function xw(t,e){let n=wn.relative(t,e);return n===""||!wn.isAbsolute(n)&&n!==".."&&!n.startsWith(`..${wn.sep}`)}async function Pw(t){let e=wn.resolve(t.invocationCwd??process.cwd()),n=wn.resolve(t.projectRoot??await Xe(e)),[i,r]=await Promise.all([ku.realpath(e),ku.realpath(n)]);if(!xw(r,i))throw new Error(`Classic command invocation cwd is outside the discovered project: ${e}`);return{invocationCwd:e,projectRoot:n}}async function bu(t,e){let n=go.getStore();if(n)return e(n);let i=await Pw(t);return go.run(i,()=>e(i))}function Su(){let t=go.getStore();if(!t)throw new Error("Classic command project context is unavailable");return t.projectRoot}var _w="\x1B[32m",Rw="\x1B[31m",Ow="\x1B[33m",yo="\x1B[0m";function Me(t){return`${_w}${t}${yo}`}function G(t){return`${Rw}${t}${yo}`}function Nw(t){return`${Ow}${t}${yo}`}var M=class extends Error{constructor(n,i=1){super(n);this.exitCode=i}exitCode},wo=class{stdout=[];stderr=[];toResult(e=0){return{exitCode:e,...this.stdout.length>0?{stdout:this.stdout.join(` `)+` `}:{},...this.stderr.length>0?{stderr:this.stderr.join(` `)+` -`}:{}}}};async function Me(t,e,n){return await ji(t,e,{label:n,expected:"file"})?gt(t,e,{label:n}):null}async function er(t,e,n,i){await Cl(t,e,n,{label:i})}function Aw(t){let e=Xs(t);if(e)throw new M(G(`ERROR: ${e}`))}function ve(t){return xu("sha256").update(t).digest("hex")}function Ou(t){return ve(JSON.stringify(Object.fromEntries(Object.entries(t).sort(([e],[n])=>e.localeCompare(n)))))}async function yn(t,e){let n=[`${e}/proposal.md`,`${e}/design.md`,`${e}/tasks.md`],i=`${e}/specs`;if((await le(t,i,{label:"Classic handoff specs directory",expected:"directory"})).exists){let s=(await _u.readdir(i,{withFileTypes:!0})).sort((o,a)=>o.name.localeCompare(a.name));for(let o of s){if(!o.isDirectory()&&!o.isSymbolicLink())continue;let a=`${i}/${o.name}/spec.md`;(await le(t,`${i}/${o.name}`,{label:`Classic handoff spec directory ${o.name}`,expected:"directory"})).exists&&await ji(t,a,{label:`Classic handoff spec ${o.name}`,expected:"file"})&&n.push(a)}}return n}function bt(t,e,n){let i=Pu.relative(t,n).replaceAll("\\","/");return`${e}/${i}`}async function Su(t,e,n){let i=[];for(let r of await yn(t,e)){let s=bt(e,n,r),o=await Me(t,r,`Classic handoff source ${s}`);o!==null&&i.push(`path:${s}`,`sha256:${ve(o)}`)}return xu("sha256").update(i.join(` -`)).digest("hex")}function Cu(t){return t.replace(/\\/gu,"\\\\").replace(/"/gu,'\\"')}function Nu(t){return(t.match(/\n/gu)??[]).length}function jw(t,e){let n=0;for(let i=0;if.name.localeCompare(d.name));for(let f of u){if(!f.isDirectory()&&!f.isSymbolicLink())continue;let d=`${a}/${f.name}/spec.md`,h=await Me(t,d,`Classic handoff spec ${f.name}`);h!==null&&(c=!0,o.push(...await qw(bt(e,n,d),h)))}}c||o.push("No delta spec files found.",""),o.push("Full source files remain canonical. If a required heading or scenario is missing here, regenerate the handoff or read the source spec directly. Supporting files (proposal, design, tasks) are referenced by hash only."),await er(t,s,o.join(` -`),"Classic handoff spec markdown output")}async function Lw(t,e,n,i,r,s){let o=[];for(let a of await yn(t,e)){let c=bt(e,n,a),l=await Me(t,a,`Classic handoff source ${c}`);if(l===null)continue;let u=/\/specs\/[^/]+\/spec\.md$/u.test(c)?"spec":"supporting";o.push({path:c,sha256:ve(l),role:u})}await er(t,s,`${JSON.stringify({change:i,phase:"design",mode:"beta",canonical_spec:"openspec",generated_by:"comet-handoff.sh",context_hash:r,files:o},null,2)} -`,"Classic handoff spec JSON output")}async function Eu(t,e,n){let i=Pu.join(e,".comet.yaml"),r=(0,Ru.parseDocument)(await gt(t,i,{label:"Classic change state"}),{uniqueKeys:!1});if(r.errors.length>0)throw new M(`ERROR: Invalid .comet.yaml: ${r.errors[0].message}`);let o=r.toJS()[n];return o==null?"":typeof o=="object"?JSON.stringify(o):String(o)}async function Dw(t,e,n){let i=await gn(t,e.trajectoryRef);i.some(s=>s.type==="recovery_reconciled"&&s.data.kind==="classic-handoff"&&s.data.actionId===n)||await vt(t,e.trajectoryRef,{sequence:i.length+1,timestamp:new Date().toISOString(),type:"recovery_reconciled",runId:e.runId,data:{kind:"classic-handoff",actionId:n}})}async function Fw(t,e,n,i,r,s,o,a){let[c,l,u]=await Promise.all([Kl(e,n.contextRef),co(e,n.artifactsRef),Ul(e,n.checkpointRef)]),[f,d]=await Promise.all([Me(t,r,"Classic handoff JSON output"),Me(t,s,"Classic handoff markdown output")]);return f===null||d===null||c!==d||l.handoff_context!==o||l.handoff_markdown!==a?!1:u?.runId===n.runId&&u.contextHash===(c===null?null:ve(c))&&u.artifactsHash===Ou(l)&&i.length===64}var Au=async(t,e)=>ku(e,async()=>{let n=new wo,[i,r,s,o]=t;try{Aw(i);let a=await zs(bu()),c=await xl(i,a.projectRoot),l=c.directory,u=L(a.projectRoot,l);if(r==="--hash-only"){if(!c.exists)throw new M(G(`ERROR: change directory not found: ${u}`));for(let Be of["proposal.md","design.md","tasks.md"])if(!await Qs(a.projectRoot,`${l}/${Be}`,`Classic handoff source ${Be}`))throw new M(G(`ERROR: required file missing or empty: ${u}/${Be}`));return n.stdout.push(await Su(a.projectRoot,l,u)),n.toResult(0)}if(r!=="design"||s!=="--write")throw new M(G("Usage: comet-handoff.mjs design --write [--full]"));let f;if(o===void 0||o==="")f="compact";else if(o==="--full")f="full";else throw new M(G("Usage: comet-handoff.mjs design --write [--full]"));if(!c.exists)throw new M(G(`ERROR: change directory not found: ${u}`));if(!c.stateExists)throw new M(G(`ERROR: .comet.yaml not found at ${u}/.comet.yaml`));if(await Eu(a.projectRoot,l,"phase")!=="design")throw new M(G("ERROR: design handoff requires phase: design"));for(let Be of["proposal.md","design.md","tasks.md"])if(!await Qs(a.projectRoot,`${l}/${Be}`,`Classic handoff source ${Be}`))throw new M(G(`ERROR: required OpenSpec artifact missing or empty: ${u}/${Be}`));let d=`${l}/.comet/handoff`;await le(a.projectRoot,`${l}/.comet`,{label:"Classic change runtime directory",expected:"directory"}),await le(a.projectRoot,d,{label:"Classic handoff directory",expected:"directory"});let h=await Eu(a.projectRoot,l,"context_compression")||"off",w,p;if(h==="off")w=`${d}/design-context.json`,p=`${d}/design-context.md`;else if(h==="beta")f==="full"&&n.stderr.push(Nw("[HANDOFF] --full is ignored in beta mode; spec files are projected verbatim")),f="beta",w=`${d}/spec-context.json`,p=`${d}/spec-context.md`;else throw new M([G(`ERROR: invalid context_compression: ${h}`),G("Valid values: off, beta")].join(` -`));let m=L(a.projectRoot,w),y=L(a.projectRoot,p),g=await Su(a.projectRoot,l,u),b=`classic-handoff:${g}`,S=await $e(l);if(!S.classic)throw new M(G("ERROR: design handoff requires Classic state"));let C=S.run?await lo(l,S.run.pendingRef):null,E=C?.id===b&&C.type==="handoff"&&C.ref===g;if(S.classic.handoffHash&&S.classic.handoffHash!==g&&!E)throw new M(G(`ERROR: stale handoff detected: source hash ${g} does not match completed hash ${S.classic.handoffHash}`));await Ii(a.projectRoot,`${l}/.comet`,"Classic change runtime directory"),await Ii(a.projectRoot,d,"Classic handoff directory");let x=await wu(l),k=await lo(l,x.run.pendingRef),N=k?.id===b&&k.type==="handoff"&&k.ref===g;if(x.run.pending&&x.run.pending!==b)throw new M(G(`ERROR: another action is pending: ${x.run.pending}`));if(x.classic.handoffHash===g&&x.classic.handoffContext===m&&!x.run.pending&&!k&&await Fw(a.projectRoot,l,x.run,g,w,p,m,y))return n.stderr.push(Fe(`[HANDOFF] wrote ${m}`)),n.stderr.push(Fe(`[HANDOFF] wrote ${y}`)),n.stderr.push(Fe(`[HANDOFF] handoff_hash=${g}`)),n.toResult(0);let oe={id:b,stepId:x.run.currentStep,type:"handoff",ref:g};await Yl(l,x.run.pendingRef,oe);let J={...x.run,pending:b,status:"waiting"};await et(l,{classic:x.classic,run:J,unknownKeys:(await $e(l)).unknownKeys}),f==="beta"?(await $w(a.projectRoot,l,u,i,g,p),await Lw(a.projectRoot,l,u,i,g,w)):(await Iw(a.projectRoot,l,u,i,f,g,p),await Tw(a.projectRoot,l,u,i,f,g,w));let R=await gt(a.projectRoot,p,{label:"Classic handoff markdown output"});await Vi(l,J.contextRef,R);let St={...await co(l,J.artifactsRef),handoff_context:m,handoff_markdown:y};await Hi(l,J.artifactsRef,St);let vo={...x.classic,handoffContext:m,handoffHash:g},We={...J.currentStep==="full.design.handoff"?await yu(l,vo,J,{actionId:b,kind:"classic-handoff"}):J,pending:null,status:"running"};(E||N)&&await Dw(l,We,b);let Iu=await gn(l,We.trajectoryRef),Tu={runId:We.runId,stateVersion:We.iteration,trajectoryOffset:Iu.length,contextHash:ve(R),artifactsHash:Ou(St),createdAt:new Date().toISOString()};return await Gi(l,We.checkpointRef,Tu),await et(l,{classic:vo,run:We,unknownKeys:(await $e(l)).unknownKeys}),await Jl(l,We.pendingRef),n.stderr.push(Fe(`[SET] handoff_context=${w}`)),n.stderr.push(Fe(`[SET] handoff_hash=${g}`)),n.stderr.push(Fe(`[HANDOFF] wrote ${m}`)),n.stderr.push(Fe(`[HANDOFF] wrote ${y}`)),n.stderr.push(Fe(`[HANDOFF] handoff_hash=${g}`)),n.toResult(0)}catch(a){if(a instanceof M){for(let c of a.message.split(` +`}:{}}}};async function We(t,e,n){return await Ii(t,e,{label:n,expected:"file"})?gt(t,e,{label:n}):null}async function tr(t,e,n,i){await El(t,e,n,{label:i})}function Aw(t){let e=Xs(t);if(e)throw new M(G(`ERROR: ${e}`))}function ve(t){return Pu("sha256").update(t).digest("hex")}function Nu(t){return ve(JSON.stringify(Object.fromEntries(Object.entries(t).sort(([e],[n])=>e.localeCompare(n)))))}async function yn(t,e){let n=[`${e}/proposal.md`,`${e}/design.md`,`${e}/tasks.md`],i=`${e}/specs`;if((await le(t,i,{label:"Classic handoff specs directory",expected:"directory"})).exists){let s=(await _u.readdir(i,{withFileTypes:!0})).sort((o,a)=>o.name.localeCompare(a.name));for(let o of s){if(!o.isDirectory()&&!o.isSymbolicLink())continue;let a=`${i}/${o.name}/spec.md`;(await le(t,`${i}/${o.name}`,{label:`Classic handoff spec directory ${o.name}`,expected:"directory"})).exists&&await Ii(t,a,{label:`Classic handoff spec ${o.name}`,expected:"file"})&&n.push(a)}}return n}function bt(t,e,n){let i=Ru.relative(t,n).replaceAll("\\","/");return`${e}/${i}`}async function Cu(t,e,n){let i=[];for(let r of await yn(t,e)){let s=bt(e,n,r),o=await We(t,r,`Classic handoff source ${s}`);o!==null&&i.push(`path:${s}`,`sha256:${ve(o)}`)}return Pu("sha256").update(i.join(` +`)).digest("hex")}function Eu(t){return t.replace(/\\/gu,"\\\\").replace(/"/gu,'\\"')}function Au(t){return(t.match(/\n/gu)??[]).length}function jw(t,e){let n=0;for(let i=0;if.name.localeCompare(d.name));for(let f of u){if(!f.isDirectory()&&!f.isSymbolicLink())continue;let d=`${a}/${f.name}/spec.md`,h=await We(t,d,`Classic handoff spec ${f.name}`);h!==null&&(c=!0,o.push(...await qw(bt(e,n,d),h)))}}c||o.push("No delta spec files found.",""),o.push("Full source files remain canonical. If a required heading or scenario is missing here, regenerate the handoff or read the source spec directly. Supporting files (proposal, design, tasks) are referenced by hash only."),await tr(t,s,o.join(` +`),"Classic handoff spec markdown output")}async function Lw(t,e,n,i,r,s){let o=[];for(let a of await yn(t,e)){let c=bt(e,n,a),l=await We(t,a,`Classic handoff source ${c}`);if(l===null)continue;let u=/\/specs\/[^/]+\/spec\.md$/u.test(c)?"spec":"supporting";o.push({path:c,sha256:ve(l),role:u})}await tr(t,s,`${JSON.stringify({change:i,phase:"design",mode:"beta",canonical_spec:"openspec",generated_by:"comet-handoff.sh",context_hash:r,files:o},null,2)} +`,"Classic handoff spec JSON output")}async function xu(t,e,n){let i=Ru.join(e,".comet.yaml"),r=(0,Ou.parseDocument)(await gt(t,i,{label:"Classic change state"}),{uniqueKeys:!1});if(r.errors.length>0)throw new M(`ERROR: Invalid .comet.yaml: ${r.errors[0].message}`);let o=r.toJS()[n];return o==null?"":typeof o=="object"?JSON.stringify(o):String(o)}async function Dw(t,e,n){let i=await gn(t,e.trajectoryRef);i.some(s=>s.type==="recovery_reconciled"&&s.data.kind==="classic-handoff"&&s.data.actionId===n)||await vt(t,e.trajectoryRef,{sequence:i.length+1,timestamp:new Date().toISOString(),type:"recovery_reconciled",runId:e.runId,data:{kind:"classic-handoff",actionId:n}})}async function Fw(t,e,n,i,r,s,o,a){let[c,l,u]=await Promise.all([Yl(e,n.contextRef),co(e,n.artifactsRef),Hl(e,n.checkpointRef)]),[f,d]=await Promise.all([We(t,r,"Classic handoff JSON output"),We(t,s,"Classic handoff markdown output")]);return f===null||d===null||c!==d||l.handoff_context!==o||l.handoff_markdown!==a?!1:u?.runId===n.runId&&u.contextHash===(c===null?null:ve(c))&&u.artifactsHash===Nu(l)&&i.length===64}var ju=async(t,e)=>bu(e,async()=>{let n=new wo,[i,r,s,o]=t;try{Aw(i);let a=await zs(Su()),c=await Pl(i,a.projectRoot),l=c.directory,u=F(a.projectRoot,l);if(r==="--hash-only"){if(!c.exists)throw new M(G(`ERROR: change directory not found: ${u}`));for(let Ke of["proposal.md","design.md","tasks.md"])if(!await Qs(a.projectRoot,`${l}/${Ke}`,`Classic handoff source ${Ke}`))throw new M(G(`ERROR: required file missing or empty: ${u}/${Ke}`));return n.stdout.push(await Cu(a.projectRoot,l,u)),n.toResult(0)}if(r!=="design"||s!=="--write")throw new M(G("Usage: comet-handoff.mjs design --write [--full]"));let f;if(o===void 0||o==="")f="compact";else if(o==="--full")f="full";else throw new M(G("Usage: comet-handoff.mjs design --write [--full]"));if(!c.exists)throw new M(G(`ERROR: change directory not found: ${u}`));if(!c.stateExists)throw new M(G(`ERROR: .comet.yaml not found at ${u}/.comet.yaml`));if(await xu(a.projectRoot,l,"phase")!=="design")throw new M(G("ERROR: design handoff requires phase: design"));for(let Ke of["proposal.md","design.md","tasks.md"])if(!await Qs(a.projectRoot,`${l}/${Ke}`,`Classic handoff source ${Ke}`))throw new M(G(`ERROR: required OpenSpec artifact missing or empty: ${u}/${Ke}`));let d=`${l}/.comet/handoff`;await le(a.projectRoot,`${l}/.comet`,{label:"Classic change runtime directory",expected:"directory"}),await le(a.projectRoot,d,{label:"Classic handoff directory",expected:"directory"});let h=await xu(a.projectRoot,l,"context_compression")||"off",w,p;if(h==="off")w=`${d}/design-context.json`,p=`${d}/design-context.md`;else if(h==="beta")f==="full"&&n.stderr.push(Nw("[HANDOFF] --full is ignored in beta mode; spec files are projected verbatim")),f="beta",w=`${d}/spec-context.json`,p=`${d}/spec-context.md`;else throw new M([G(`ERROR: invalid context_compression: ${h}`),G("Valid values: off, beta")].join(` +`));let m=F(a.projectRoot,w),y=F(a.projectRoot,p),g=await Cu(a.projectRoot,l,u),b=`classic-handoff:${g}`,S=await Le(l);if(!S.classic)throw new M(G("ERROR: design handoff requires Classic state"));let C=S.run?await lo(l,S.run.pendingRef):null,E=C?.id===b&&C.type==="handoff"&&C.ref===g;if(S.classic.handoffHash&&S.classic.handoffHash!==g&&!E)throw new M(G(`ERROR: stale handoff detected: source hash ${g} does not match completed hash ${S.classic.handoffHash}`));await Ti(a.projectRoot,`${l}/.comet`,"Classic change runtime directory"),await Ti(a.projectRoot,d,"Classic handoff directory");let x=await yu(l),k=await lo(l,x.run.pendingRef),N=k?.id===b&&k.type==="handoff"&&k.ref===g;if(x.run.pending&&x.run.pending!==b)throw new M(G(`ERROR: another action is pending: ${x.run.pending}`));if(x.classic.handoffHash===g&&x.classic.handoffContext===m&&!x.run.pending&&!k&&await Fw(a.projectRoot,l,x.run,g,w,p,m,y))return n.stderr.push(Me(`[HANDOFF] wrote ${m}`)),n.stderr.push(Me(`[HANDOFF] wrote ${y}`)),n.stderr.push(Me(`[HANDOFF] handoff_hash=${g}`)),n.toResult(0);let oe={id:b,stepId:x.run.currentStep,type:"handoff",ref:g};await Jl(l,x.run.pendingRef,oe);let J={...x.run,pending:b,status:"waiting"};await et(l,{classic:x.classic,run:J,unknownKeys:(await Le(l)).unknownKeys}),f==="beta"?(await $w(a.projectRoot,l,u,i,g,p),await Lw(a.projectRoot,l,u,i,g,w)):(await Iw(a.projectRoot,l,u,i,f,g,p),await Tw(a.projectRoot,l,u,i,f,g,w));let R=await gt(a.projectRoot,p,{label:"Classic handoff markdown output"});await Gi(l,J.contextRef,R);let St={...await co(l,J.artifactsRef),handoff_context:m,handoff_markdown:y};await Vi(l,J.artifactsRef,St);let vo={...x.classic,handoffContext:m,handoffHash:g},Be={...J.currentStep==="full.design.handoff"?await vu(l,vo,J,{actionId:b,kind:"classic-handoff"}):J,pending:null,status:"running"};(E||N)&&await Dw(l,Be,b);let Tu=await gn(l,Be.trajectoryRef),qu={runId:Be.runId,stateVersion:Be.iteration,trajectoryOffset:Tu.length,contextHash:ve(R),artifactsHash:Nu(St),createdAt:new Date().toISOString()};return await zi(l,Be.checkpointRef,qu),await et(l,{classic:vo,run:Be,unknownKeys:(await Le(l)).unknownKeys}),await Ul(l,Be.pendingRef),n.stderr.push(Me(`[SET] handoff_context=${w}`)),n.stderr.push(Me(`[SET] handoff_hash=${g}`)),n.stderr.push(Me(`[HANDOFF] wrote ${m}`)),n.stderr.push(Me(`[HANDOFF] wrote ${y}`)),n.stderr.push(Me(`[HANDOFF] handoff_hash=${g}`)),n.toResult(0)}catch(a){if(a instanceof M){for(let c of a.message.split(` `))n.stderr.push(c);return n.toResult(a.exitCode)}throw a}});function Mw(t,e){return{exitCode:e.exitCode,stdout:JSON.stringify({command:t,exitCode:e.exitCode,...e.stdout===void 0?{}:{stdout:e.stdout},...e.stderr===void 0?{}:{stderr:e.stderr}})+` -`}}async function ju(t,e,n=process.argv.slice(2)){let i=n.includes("--json"),r=n.filter(a=>a!=="--json"),s;try{s=await e(r,{json:i})}catch(a){s={exitCode:70,stderr:a instanceof Error?a.message:String(a)}}let o=i?Mw(t,s):s;return o.stdout&&process.stdout.write(o.stdout),o.stderr&&process.stderr.write(o.stderr+(o.stderr.endsWith(` +`}}async function Iu(t,e,n=process.argv.slice(2)){let i=n.includes("--json"),r=n.filter(a=>a!=="--json"),s;try{s=await e(r,{json:i})}catch(a){s={exitCode:70,stderr:a instanceof Error?a.message:String(a)}}let o=i?Mw(t,s):s;return o.stdout&&process.stdout.write(o.stdout),o.stderr&&process.stderr.write(o.stderr+(o.stderr.endsWith(` `)?"":` -`)),o.exitCode}process.exitCode=await ju("handoff",Au); +`)),o.exitCode}process.exitCode=await Iu("handoff",ju); diff --git a/assets/skills/comet/scripts/comet-hook-guard.mjs b/assets/skills/comet/scripts/comet-hook-guard.mjs index c19147e88..435d0c4bb 100644 --- a/assets/skills/comet/scripts/comet-hook-guard.mjs +++ b/assets/skills/comet/scripts/comet-hook-guard.mjs @@ -1,17 +1,17 @@ #!/usr/bin/env node import { createRequire as __cometCreateRequire } from 'module'; const require = __cometCreateRequire(import.meta.url); -var bl=Object.create;var dr=Object.defineProperty;var vl=Object.getOwnPropertyDescriptor;var kl=Object.getOwnPropertyNames;var Sl=Object.getPrototypeOf,Cl=Object.prototype.hasOwnProperty;var Ft=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var q=(t,e,n)=>()=>{if(n)throw n[0];try{return t&&(e=t(t=0)),e}catch(r){throw n=[r],r}};var g=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(n){throw e=0,n}},El=(t,e)=>{for(var n in e)dr(t,n,{get:e[n],enumerable:!0})},_l=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of kl(e))!Cl.call(t,i)&&i!==n&&dr(t,i,{get:()=>e[i],enumerable:!(r=vl(e,i))||r.enumerable});return t};var Bt=(t,e,n)=>(n=t!=null?bl(Sl(t)):{},_l(e||!t||!t.__esModule?dr(n,"default",{value:t,enumerable:!0}):n,t));var _=g(j=>{"use strict";var mr=Symbol.for("yaml.alias"),Ps=Symbol.for("yaml.document"),Kt=Symbol.for("yaml.map"),Os=Symbol.for("yaml.pair"),gr=Symbol.for("yaml.scalar"),Yt=Symbol.for("yaml.seq"),Q=Symbol.for("yaml.node.type"),Nl=t=>!!t&&typeof t=="object"&&t[Q]===mr,Al=t=>!!t&&typeof t=="object"&&t[Q]===Ps,xl=t=>!!t&&typeof t=="object"&&t[Q]===Kt,Tl=t=>!!t&&typeof t=="object"&&t[Q]===Os,Ns=t=>!!t&&typeof t=="object"&&t[Q]===gr,Rl=t=>!!t&&typeof t=="object"&&t[Q]===Yt;function As(t){if(t&&typeof t=="object")switch(t[Q]){case Kt:case Yt:return!0}return!1}function Il(t){if(t&&typeof t=="object")switch(t[Q]){case mr:case Kt:case gr:case Yt:return!0}return!1}var jl=t=>(Ns(t)||As(t))&&!!t.anchor;j.ALIAS=mr;j.DOC=Ps;j.MAP=Kt;j.NODE_TYPE=Q;j.PAIR=Os;j.SCALAR=gr;j.SEQ=Yt;j.hasAnchor=jl;j.isAlias=Nl;j.isCollection=As;j.isDocument=Al;j.isMap=xl;j.isNode=Il;j.isPair=Tl;j.isScalar=Ns;j.isSeq=Rl});var Ge=g(wr=>{"use strict";var R=_(),$=Symbol("break visit"),xs=Symbol("skip children"),G=Symbol("remove node");function Ut(t,e){let n=Ts(e);R.isDocument(t)?Ie(null,t.contents,n,Object.freeze([t]))===G&&(t.contents=null):Ie(null,t,n,Object.freeze([]))}Ut.BREAK=$;Ut.SKIP=xs;Ut.REMOVE=G;function Ie(t,e,n,r){let i=Rs(t,e,n,r);if(R.isNode(i)||R.isPair(i))return Is(t,r,i),Ie(t,i,n,r);if(typeof i!="symbol"){if(R.isCollection(e)){r=Object.freeze(r.concat(e));for(let s=0;s{"use strict";var js=_(),Ll=Ge(),ql={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Dl=t=>t.replace(/[!,[\]{}]/g,e=>ql[e]),ze=class t{constructor(e,n){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},t.defaultYaml,e),this.tags=Object.assign({},t.defaultTags,n)}clone(){let e=new t(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){let e=new t(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:t.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},t.defaultTags);break}return e}add(e,n){this.atNextDocument&&(this.yaml={explicit:t.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},t.defaultTags),this.atNextDocument=!1);let r=e.trim().split(/[ \t]+/),i=r.shift();switch(i){case"%TAG":{if(r.length!==2&&(n(0,"%TAG directive should contain exactly two parts"),r.length<2))return!1;let[s,o]=r;return this.tags[s]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,r.length!==1)return n(0,"%YAML directive should contain exactly one part"),!1;let[s]=r;if(s==="1.1"||s==="1.2")return this.yaml.version=s,!0;{let o=/^\d+\.\d+$/.test(s);return n(6,`Unsupported YAML version ${s}`,o),!1}}default:return n(0,`Unknown directive ${i}`,!0),!1}}tagName(e,n){if(e==="!")return"!";if(e[0]!=="!")return n(`Not a valid tag: ${e}`),null;if(e[1]==="<"){let o=e.slice(2,-1);return o==="!"||o==="!!"?(n(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&n("Verbatim tags must end with a >"),o)}let[,r,i]=e.match(/^(.*!)([^!]*)$/s);i||n(`The ${e} tag has no suffix`);let s=this.tags[r];if(s)try{return s+decodeURIComponent(i)}catch(o){return n(String(o)),null}return r==="!"?e:(n(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[n,r]of Object.entries(this.tags))if(e.startsWith(r))return n+Dl(e.substring(r.length));return e[0]==="!"?e:`!<${e}>`}toString(e){let n=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],r=Object.entries(this.tags),i;if(e&&r.length>0&&js.isNode(e.contents)){let s={};Ll.visit(e.contents,(o,a)=>{js.isNode(a)&&a.tag&&(s[a.tag]=!0)}),i=Object.keys(s)}else i=[];for(let[s,o]of r)s==="!!"&&o==="tag:yaml.org,2002:"||(!e||i.some(a=>a.startsWith(o)))&&n.push(`%TAG ${s} ${o}`);return n.join(` -`)}};ze.defaultYaml={explicit:!1,version:"1.2"};ze.defaultTags={"!!":"tag:yaml.org,2002:"};Ls.Directives=ze});var Jt=g(Xe=>{"use strict";var qs=_(),$l=Ge();function Wl(t){if(/[\x00-\x19\s,[\]{}]/.test(t)){let n=`Anchor must not contain whitespace or control characters: ${JSON.stringify(t)}`;throw new Error(n)}return!0}function Ds(t){let e=new Set;return $l.visit(t,{Value(n,r){r.anchor&&e.add(r.anchor)}}),e}function $s(t,e){for(let n=1;;++n){let r=`${t}${n}`;if(!e.has(r))return r}}function Ml(t,e){let n=[],r=new Map,i=null;return{onAnchor:s=>{n.push(s),i??(i=Ds(t));let o=$s(e,i);return i.add(o),o},setAnchors:()=>{for(let s of n){let o=r.get(s);if(typeof o=="object"&&o.anchor&&(qs.isScalar(o.node)||qs.isCollection(o.node)))o.node.anchor=o.anchor;else{let a=new Error("Failed to resolve repeated object (this should not happen)");throw a.source=s,a}}},sourceObjects:r}}Xe.anchorIsValid=Wl;Xe.anchorNames=Ds;Xe.createNodeAnchors=Ml;Xe.findNewAnchor=$s});var br=g(Ws=>{"use strict";function Qe(t,e,n,r){if(r&&typeof r=="object")if(Array.isArray(r))for(let i=0,s=r.length;i{"use strict";var Fl=_();function Ms(t,e,n){if(Array.isArray(t))return t.map((r,i)=>Ms(r,String(i),n));if(t&&typeof t.toJSON=="function"){if(!n||!Fl.hasAnchor(t))return t.toJSON(e,n);let r={aliasCount:0,count:1,res:void 0};n.anchors.set(t,r),n.onCreate=s=>{r.res=s,delete n.onCreate};let i=t.toJSON(e,n);return n.onCreate&&n.onCreate(i),i}return typeof t=="bigint"&&!n?.keep?Number(t):t}Fs.toJS=Ms});var Vt=g(Ks=>{"use strict";var Bl=br(),Bs=_(),Kl=oe(),vr=class{constructor(e){Object.defineProperty(this,Bs.NODE_TYPE,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:n,maxAliasCount:r,onAnchor:i,reviver:s}={}){if(!Bs.isDocument(e))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:e,keep:!0,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},a=Kl.toJS(this,"",o);if(typeof i=="function")for(let{count:c,res:l}of o.anchors.values())i(l,c);return typeof s=="function"?Bl.applyReviver(s,{"":a},"",a):a}};Ks.NodeBase=vr});var Ze=g(Ys=>{"use strict";var Yl=Jt(),Ul=Ge(),Le=_(),Hl=Vt(),Jl=oe(),kr=class extends Hl.NodeBase{constructor(e){super(Le.ALIAS),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,n){if(n?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let r;n?.aliasResolveCache?r=n.aliasResolveCache:(r=[],Ul.visit(e,{Node:(s,o)=>{(Le.isAlias(o)||Le.hasAnchor(o))&&r.push(o)}}),n&&(n.aliasResolveCache=r));let i;for(let s of r){if(s===this)break;s.anchor===this.source&&(i=s)}return i}toJSON(e,n){if(!n)return{source:this.source};let{anchors:r,doc:i,maxAliasCount:s}=n,o=this.resolve(i,n);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let a=r.get(o);if(a||(Jl.toJS(o,null,n),a=r.get(o)),a?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(s>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=Gt(i,o,r)),a.count*a.aliasCount>s)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return a.res}toString(e,n,r){let i=`*${this.source}`;if(e){if(Yl.anchorIsValid(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let s=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(s)}if(e.implicitKey)return`${i} `}return i}};function Gt(t,e,n){if(Le.isAlias(e)){let r=e.resolve(t),i=n&&r&&n.get(r);return i?i.count*i.aliasCount:0}else if(Le.isCollection(e)){let r=0;for(let i of e.items){let s=Gt(t,i,n);s>r&&(r=s)}return r}else if(Le.isPair(e)){let r=Gt(t,e.key,n),i=Gt(t,e.value,n);return Math.max(r,i)}return 1}Ys.Alias=kr});var N=g(Sr=>{"use strict";var Vl=_(),Gl=Vt(),zl=oe(),Xl=t=>!t||typeof t!="function"&&typeof t!="object",ae=class extends Gl.NodeBase{constructor(e){super(Vl.SCALAR),this.value=e}toJSON(e,n){return n?.keep?this.value:zl.toJS(this.value,e,n)}toString(){return String(this.value)}};ae.BLOCK_FOLDED="BLOCK_FOLDED";ae.BLOCK_LITERAL="BLOCK_LITERAL";ae.PLAIN="PLAIN";ae.QUOTE_DOUBLE="QUOTE_DOUBLE";ae.QUOTE_SINGLE="QUOTE_SINGLE";Sr.Scalar=ae;Sr.isScalarValue=Xl});var et=g(Hs=>{"use strict";var Ql=Ze(),ke=_(),Us=N(),Zl="tag:yaml.org,2002:";function eu(t,e,n){if(e){let r=n.filter(s=>s.tag===e),i=r.find(s=>!s.format)??r[0];if(!i)throw new Error(`Tag ${e} not found`);return i}return n.find(r=>r.identify?.(t)&&!r.format)}function tu(t,e,n){if(ke.isDocument(t)&&(t=t.contents),ke.isNode(t))return t;if(ke.isPair(t)){let u=n.schema[ke.MAP].createNode?.(n.schema,null,n);return u.items.push(t),u}(t instanceof String||t instanceof Number||t instanceof Boolean||typeof BigInt<"u"&&t instanceof BigInt)&&(t=t.valueOf());let{aliasDuplicateObjects:r,onAnchor:i,onTagObj:s,schema:o,sourceObjects:a}=n,c;if(r&&t&&typeof t=="object"){if(c=a.get(t),c)return c.anchor??(c.anchor=i(t)),new Ql.Alias(c.anchor);c={anchor:null,node:null},a.set(t,c)}e?.startsWith("!!")&&(e=Zl+e.slice(2));let l=eu(t,e,o.tags);if(!l){if(t&&typeof t.toJSON=="function"&&(t=t.toJSON()),!t||typeof t!="object"){let u=new Us.Scalar(t);return c&&(c.node=u),u}l=t instanceof Map?o[ke.MAP]:Symbol.iterator in Object(t)?o[ke.SEQ]:o[ke.MAP]}s&&(s(l),delete n.onTagObj);let d=l?.createNode?l.createNode(n.schema,t,n):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(n.schema,t,n):new Us.Scalar(t);return e?d.tag=e:l.default||(d.tag=l.tag),c&&(c.node=d),d}Hs.createNode=tu});var Xt=g(zt=>{"use strict";var nu=et(),z=_(),ru=Vt();function Cr(t,e,n){let r=n;for(let i=e.length-1;i>=0;--i){let s=e[i];if(typeof s=="number"&&Number.isInteger(s)&&s>=0){let o=[];o[s]=r,r=o}else r=new Map([[s,r]])}return nu.createNode(r,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:t,sourceObjects:new Map})}var Js=t=>t==null||typeof t=="object"&&!!t[Symbol.iterator]().next().done,Er=class extends ru.NodeBase{constructor(e,n){super(e),Object.defineProperty(this,"schema",{value:n,configurable:!0,enumerable:!1,writable:!0})}clone(e){let n=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(n.schema=e),n.items=n.items.map(r=>z.isNode(r)||z.isPair(r)?r.clone(e):r),this.range&&(n.range=this.range.slice()),n}addIn(e,n){if(Js(e))this.add(n);else{let[r,...i]=e,s=this.get(r,!0);if(z.isCollection(s))s.addIn(i,n);else if(s===void 0&&this.schema)this.set(r,Cr(this.schema,i,n));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${i}`)}}deleteIn(e){let[n,...r]=e;if(r.length===0)return this.delete(n);let i=this.get(n,!0);if(z.isCollection(i))return i.deleteIn(r);throw new Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}getIn(e,n){let[r,...i]=e,s=this.get(r,!0);return i.length===0?!n&&z.isScalar(s)?s.value:s:z.isCollection(s)?s.getIn(i,n):void 0}hasAllNullValues(e){return this.items.every(n=>{if(!z.isPair(n))return!1;let r=n.value;return r==null||e&&z.isScalar(r)&&r.value==null&&!r.commentBefore&&!r.comment&&!r.tag})}hasIn(e){let[n,...r]=e;if(r.length===0)return this.has(n);let i=this.get(n,!0);return z.isCollection(i)?i.hasIn(r):!1}setIn(e,n){let[r,...i]=e;if(i.length===0)this.set(r,n);else{let s=this.get(r,!0);if(z.isCollection(s))s.setIn(i,n);else if(s===void 0&&this.schema)this.set(r,Cr(this.schema,i,n));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${i}`)}}};zt.Collection=Er;zt.collectionFromPath=Cr;zt.isEmptyPath=Js});var tt=g(Qt=>{"use strict";var iu=t=>t.replace(/^(?!$)(?: $)?/gm,"#");function _r(t,e){return/^\n+$/.test(t)?t.substring(1):e?t.replace(/^(?! *$)/gm,e):t}var su=(t,e,n)=>t.endsWith(` +var yl=Object.create;var dr=Object.defineProperty;var bl=Object.getOwnPropertyDescriptor;var vl=Object.getOwnPropertyNames;var kl=Object.getPrototypeOf,Sl=Object.prototype.hasOwnProperty;var Ft=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var L=(t,e,n)=>()=>{if(n)throw n[0];try{return t&&(e=t(t=0)),e}catch(r){throw n=[r],r}};var g=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(n){throw e=0,n}},Cl=(t,e)=>{for(var n in e)dr(t,n,{get:e[n],enumerable:!0})},El=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of vl(e))!Sl.call(t,i)&&i!==n&&dr(t,i,{get:()=>e[i],enumerable:!(r=bl(e,i))||r.enumerable});return t};var Bt=(t,e,n)=>(n=t!=null?yl(kl(t)):{},El(e||!t||!t.__esModule?dr(n,"default",{value:t,enumerable:!0}):n,t));var _=g(I=>{"use strict";var mr=Symbol.for("yaml.alias"),_s=Symbol.for("yaml.document"),Kt=Symbol.for("yaml.map"),Ps=Symbol.for("yaml.pair"),gr=Symbol.for("yaml.scalar"),Yt=Symbol.for("yaml.seq"),Q=Symbol.for("yaml.node.type"),Ol=t=>!!t&&typeof t=="object"&&t[Q]===mr,Nl=t=>!!t&&typeof t=="object"&&t[Q]===_s,Al=t=>!!t&&typeof t=="object"&&t[Q]===Kt,xl=t=>!!t&&typeof t=="object"&&t[Q]===Ps,Os=t=>!!t&&typeof t=="object"&&t[Q]===gr,Tl=t=>!!t&&typeof t=="object"&&t[Q]===Yt;function Ns(t){if(t&&typeof t=="object")switch(t[Q]){case Kt:case Yt:return!0}return!1}function Rl(t){if(t&&typeof t=="object")switch(t[Q]){case mr:case Kt:case gr:case Yt:return!0}return!1}var Il=t=>(Os(t)||Ns(t))&&!!t.anchor;I.ALIAS=mr;I.DOC=_s;I.MAP=Kt;I.NODE_TYPE=Q;I.PAIR=Ps;I.SCALAR=gr;I.SEQ=Yt;I.hasAnchor=Il;I.isAlias=Ol;I.isCollection=Ns;I.isDocument=Nl;I.isMap=Al;I.isNode=Rl;I.isPair=xl;I.isScalar=Os;I.isSeq=Tl});var Ge=g(wr=>{"use strict";var R=_(),$=Symbol("break visit"),As=Symbol("skip children"),G=Symbol("remove node");function Ut(t,e){let n=xs(e);R.isDocument(t)?Ie(null,t.contents,n,Object.freeze([t]))===G&&(t.contents=null):Ie(null,t,n,Object.freeze([]))}Ut.BREAK=$;Ut.SKIP=As;Ut.REMOVE=G;function Ie(t,e,n,r){let i=Ts(t,e,n,r);if(R.isNode(i)||R.isPair(i))return Rs(t,r,i),Ie(t,i,n,r);if(typeof i!="symbol"){if(R.isCollection(e)){r=Object.freeze(r.concat(e));for(let s=0;s{"use strict";var Is=_(),jl=Ge(),Ll={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},ql=t=>t.replace(/[!,[\]{}]/g,e=>Ll[e]),ze=class t{constructor(e,n){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},t.defaultYaml,e),this.tags=Object.assign({},t.defaultTags,n)}clone(){let e=new t(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){let e=new t(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:t.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},t.defaultTags);break}return e}add(e,n){this.atNextDocument&&(this.yaml={explicit:t.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},t.defaultTags),this.atNextDocument=!1);let r=e.trim().split(/[ \t]+/),i=r.shift();switch(i){case"%TAG":{if(r.length!==2&&(n(0,"%TAG directive should contain exactly two parts"),r.length<2))return!1;let[s,o]=r;return this.tags[s]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,r.length!==1)return n(0,"%YAML directive should contain exactly one part"),!1;let[s]=r;if(s==="1.1"||s==="1.2")return this.yaml.version=s,!0;{let o=/^\d+\.\d+$/.test(s);return n(6,`Unsupported YAML version ${s}`,o),!1}}default:return n(0,`Unknown directive ${i}`,!0),!1}}tagName(e,n){if(e==="!")return"!";if(e[0]!=="!")return n(`Not a valid tag: ${e}`),null;if(e[1]==="<"){let o=e.slice(2,-1);return o==="!"||o==="!!"?(n(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&n("Verbatim tags must end with a >"),o)}let[,r,i]=e.match(/^(.*!)([^!]*)$/s);i||n(`The ${e} tag has no suffix`);let s=this.tags[r];if(s)try{return s+decodeURIComponent(i)}catch(o){return n(String(o)),null}return r==="!"?e:(n(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[n,r]of Object.entries(this.tags))if(e.startsWith(r))return n+ql(e.substring(r.length));return e[0]==="!"?e:`!<${e}>`}toString(e){let n=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],r=Object.entries(this.tags),i;if(e&&r.length>0&&Is.isNode(e.contents)){let s={};jl.visit(e.contents,(o,a)=>{Is.isNode(a)&&a.tag&&(s[a.tag]=!0)}),i=Object.keys(s)}else i=[];for(let[s,o]of r)s==="!!"&&o==="tag:yaml.org,2002:"||(!e||i.some(a=>a.startsWith(o)))&&n.push(`%TAG ${s} ${o}`);return n.join(` +`)}};ze.defaultYaml={explicit:!1,version:"1.2"};ze.defaultTags={"!!":"tag:yaml.org,2002:"};js.Directives=ze});var Jt=g(Xe=>{"use strict";var Ls=_(),Dl=Ge();function $l(t){if(/[\x00-\x19\s,[\]{}]/.test(t)){let n=`Anchor must not contain whitespace or control characters: ${JSON.stringify(t)}`;throw new Error(n)}return!0}function qs(t){let e=new Set;return Dl.visit(t,{Value(n,r){r.anchor&&e.add(r.anchor)}}),e}function Ds(t,e){for(let n=1;;++n){let r=`${t}${n}`;if(!e.has(r))return r}}function Wl(t,e){let n=[],r=new Map,i=null;return{onAnchor:s=>{n.push(s),i??(i=qs(t));let o=Ds(e,i);return i.add(o),o},setAnchors:()=>{for(let s of n){let o=r.get(s);if(typeof o=="object"&&o.anchor&&(Ls.isScalar(o.node)||Ls.isCollection(o.node)))o.node.anchor=o.anchor;else{let a=new Error("Failed to resolve repeated object (this should not happen)");throw a.source=s,a}}},sourceObjects:r}}Xe.anchorIsValid=$l;Xe.anchorNames=qs;Xe.createNodeAnchors=Wl;Xe.findNewAnchor=Ds});var br=g($s=>{"use strict";function Qe(t,e,n,r){if(r&&typeof r=="object")if(Array.isArray(r))for(let i=0,s=r.length;i{"use strict";var Ml=_();function Ws(t,e,n){if(Array.isArray(t))return t.map((r,i)=>Ws(r,String(i),n));if(t&&typeof t.toJSON=="function"){if(!n||!Ml.hasAnchor(t))return t.toJSON(e,n);let r={aliasCount:0,count:1,res:void 0};n.anchors.set(t,r),n.onCreate=s=>{r.res=s,delete n.onCreate};let i=t.toJSON(e,n);return n.onCreate&&n.onCreate(i),i}return typeof t=="bigint"&&!n?.keep?Number(t):t}Ms.toJS=Ws});var Vt=g(Bs=>{"use strict";var Fl=br(),Fs=_(),Bl=oe(),vr=class{constructor(e){Object.defineProperty(this,Fs.NODE_TYPE,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:n,maxAliasCount:r,onAnchor:i,reviver:s}={}){if(!Fs.isDocument(e))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:e,keep:!0,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},a=Bl.toJS(this,"",o);if(typeof i=="function")for(let{count:c,res:l}of o.anchors.values())i(l,c);return typeof s=="function"?Fl.applyReviver(s,{"":a},"",a):a}};Bs.NodeBase=vr});var Ze=g(Ks=>{"use strict";var Kl=Jt(),Yl=Ge(),Le=_(),Ul=Vt(),Hl=oe(),kr=class extends Ul.NodeBase{constructor(e){super(Le.ALIAS),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,n){if(n?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let r;n?.aliasResolveCache?r=n.aliasResolveCache:(r=[],Yl.visit(e,{Node:(s,o)=>{(Le.isAlias(o)||Le.hasAnchor(o))&&r.push(o)}}),n&&(n.aliasResolveCache=r));let i;for(let s of r){if(s===this)break;s.anchor===this.source&&(i=s)}return i}toJSON(e,n){if(!n)return{source:this.source};let{anchors:r,doc:i,maxAliasCount:s}=n,o=this.resolve(i,n);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let a=r.get(o);if(a||(Hl.toJS(o,null,n),a=r.get(o)),a?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(s>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=Gt(i,o,r)),a.count*a.aliasCount>s)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return a.res}toString(e,n,r){let i=`*${this.source}`;if(e){if(Kl.anchorIsValid(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let s=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(s)}if(e.implicitKey)return`${i} `}return i}};function Gt(t,e,n){if(Le.isAlias(e)){let r=e.resolve(t),i=n&&r&&n.get(r);return i?i.count*i.aliasCount:0}else if(Le.isCollection(e)){let r=0;for(let i of e.items){let s=Gt(t,i,n);s>r&&(r=s)}return r}else if(Le.isPair(e)){let r=Gt(t,e.key,n),i=Gt(t,e.value,n);return Math.max(r,i)}return 1}Ks.Alias=kr});var N=g(Sr=>{"use strict";var Jl=_(),Vl=Vt(),Gl=oe(),zl=t=>!t||typeof t!="function"&&typeof t!="object",ae=class extends Vl.NodeBase{constructor(e){super(Jl.SCALAR),this.value=e}toJSON(e,n){return n?.keep?this.value:Gl.toJS(this.value,e,n)}toString(){return String(this.value)}};ae.BLOCK_FOLDED="BLOCK_FOLDED";ae.BLOCK_LITERAL="BLOCK_LITERAL";ae.PLAIN="PLAIN";ae.QUOTE_DOUBLE="QUOTE_DOUBLE";ae.QUOTE_SINGLE="QUOTE_SINGLE";Sr.Scalar=ae;Sr.isScalarValue=zl});var et=g(Us=>{"use strict";var Xl=Ze(),ke=_(),Ys=N(),Ql="tag:yaml.org,2002:";function Zl(t,e,n){if(e){let r=n.filter(s=>s.tag===e),i=r.find(s=>!s.format)??r[0];if(!i)throw new Error(`Tag ${e} not found`);return i}return n.find(r=>r.identify?.(t)&&!r.format)}function eu(t,e,n){if(ke.isDocument(t)&&(t=t.contents),ke.isNode(t))return t;if(ke.isPair(t)){let u=n.schema[ke.MAP].createNode?.(n.schema,null,n);return u.items.push(t),u}(t instanceof String||t instanceof Number||t instanceof Boolean||typeof BigInt<"u"&&t instanceof BigInt)&&(t=t.valueOf());let{aliasDuplicateObjects:r,onAnchor:i,onTagObj:s,schema:o,sourceObjects:a}=n,c;if(r&&t&&typeof t=="object"){if(c=a.get(t),c)return c.anchor??(c.anchor=i(t)),new Xl.Alias(c.anchor);c={anchor:null,node:null},a.set(t,c)}e?.startsWith("!!")&&(e=Ql+e.slice(2));let l=Zl(t,e,o.tags);if(!l){if(t&&typeof t.toJSON=="function"&&(t=t.toJSON()),!t||typeof t!="object"){let u=new Ys.Scalar(t);return c&&(c.node=u),u}l=t instanceof Map?o[ke.MAP]:Symbol.iterator in Object(t)?o[ke.SEQ]:o[ke.MAP]}s&&(s(l),delete n.onTagObj);let d=l?.createNode?l.createNode(n.schema,t,n):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(n.schema,t,n):new Ys.Scalar(t);return e?d.tag=e:l.default||(d.tag=l.tag),c&&(c.node=d),d}Us.createNode=eu});var Xt=g(zt=>{"use strict";var tu=et(),z=_(),nu=Vt();function Cr(t,e,n){let r=n;for(let i=e.length-1;i>=0;--i){let s=e[i];if(typeof s=="number"&&Number.isInteger(s)&&s>=0){let o=[];o[s]=r,r=o}else r=new Map([[s,r]])}return tu.createNode(r,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:t,sourceObjects:new Map})}var Hs=t=>t==null||typeof t=="object"&&!!t[Symbol.iterator]().next().done,Er=class extends nu.NodeBase{constructor(e,n){super(e),Object.defineProperty(this,"schema",{value:n,configurable:!0,enumerable:!1,writable:!0})}clone(e){let n=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(n.schema=e),n.items=n.items.map(r=>z.isNode(r)||z.isPair(r)?r.clone(e):r),this.range&&(n.range=this.range.slice()),n}addIn(e,n){if(Hs(e))this.add(n);else{let[r,...i]=e,s=this.get(r,!0);if(z.isCollection(s))s.addIn(i,n);else if(s===void 0&&this.schema)this.set(r,Cr(this.schema,i,n));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${i}`)}}deleteIn(e){let[n,...r]=e;if(r.length===0)return this.delete(n);let i=this.get(n,!0);if(z.isCollection(i))return i.deleteIn(r);throw new Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}getIn(e,n){let[r,...i]=e,s=this.get(r,!0);return i.length===0?!n&&z.isScalar(s)?s.value:s:z.isCollection(s)?s.getIn(i,n):void 0}hasAllNullValues(e){return this.items.every(n=>{if(!z.isPair(n))return!1;let r=n.value;return r==null||e&&z.isScalar(r)&&r.value==null&&!r.commentBefore&&!r.comment&&!r.tag})}hasIn(e){let[n,...r]=e;if(r.length===0)return this.has(n);let i=this.get(n,!0);return z.isCollection(i)?i.hasIn(r):!1}setIn(e,n){let[r,...i]=e;if(i.length===0)this.set(r,n);else{let s=this.get(r,!0);if(z.isCollection(s))s.setIn(i,n);else if(s===void 0&&this.schema)this.set(r,Cr(this.schema,i,n));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${i}`)}}};zt.Collection=Er;zt.collectionFromPath=Cr;zt.isEmptyPath=Hs});var tt=g(Qt=>{"use strict";var ru=t=>t.replace(/^(?!$)(?: $)?/gm,"#");function _r(t,e){return/^\n+$/.test(t)?t.substring(1):e?t.replace(/^(?! *$)/gm,e):t}var iu=(t,e,n)=>t.endsWith(` `)?_r(n,e):n.includes(` `)?` -`+_r(n,e):(t.endsWith(" ")?"":" ")+n;Qt.indentComment=_r;Qt.lineComment=su;Qt.stringifyComment=iu});var Gs=g(nt=>{"use strict";var ou="flow",Pr="block",Zt="quoted";function au(t,e,n="flow",{indentAtStart:r,lineWidth:i=80,minContentWidth:s=20,onFold:o,onOverflow:a}={}){if(!i||i<0)return t;ii-Math.max(2,s)?l.push(0):u=i-r);let f,m,w=!1,p=-1,h=-1,y=-1;n===Pr&&(p=Vs(t,p,e.length),p!==-1&&(u=p+c));for(let k;k=t[p+=1];){if(n===Zt&&k==="\\"){switch(h=p,t[p+1]){case"x":p+=3;break;case"u":p+=5;break;case"U":p+=9;break;default:p+=1}y=p}if(k===` -`)n===Pr&&(p=Vs(t,p,e.length)),u=p+e.length+c,f=void 0;else{if(k===" "&&m&&m!==" "&&m!==` +`+_r(n,e):(t.endsWith(" ")?"":" ")+n;Qt.indentComment=_r;Qt.lineComment=iu;Qt.stringifyComment=ru});var Vs=g(nt=>{"use strict";var su="flow",Pr="block",Zt="quoted";function ou(t,e,n="flow",{indentAtStart:r,lineWidth:i=80,minContentWidth:s=20,onFold:o,onOverflow:a}={}){if(!i||i<0)return t;ii-Math.max(2,s)?l.push(0):u=i-r);let f,m,w=!1,p=-1,h=-1,y=-1;n===Pr&&(p=Js(t,p,e.length),p!==-1&&(u=p+c));for(let k;k=t[p+=1];){if(n===Zt&&k==="\\"){switch(h=p,t[p+1]){case"x":p+=3;break;case"u":p+=5;break;case"U":p+=9;break;default:p+=1}y=p}if(k===` +`)n===Pr&&(p=Js(t,p,e.length)),u=p+e.length+c,f=void 0;else{if(k===" "&&m&&m!==" "&&m!==` `&&m!==" "){let S=t[p+1];S&&S!==" "&&S!==` `&&S!==" "&&(f=p)}if(p>=u)if(f)l.push(f),u=f+c,f=void 0;else if(n===Zt){for(;m===" "||m===" ";)m=k,k=t[p+=1],w=!0;let S=p>y+1?p-2:h-1;if(d[S])return t;l.push(S),d[S]=!0,u=S+c,f=void 0}else w=!0}m=k}if(w&&a&&a(),l.length===0)return t;o&&o();let v=t.slice(0,l[0]);for(let k=0;k{"use strict";var U=N(),ce=Gs(),tn=(t,e)=>({indentAtStart:e?t.indent.length:t.indentAtStart,lineWidth:t.options.lineWidth,minContentWidth:t.options.minContentWidth}),nn=t=>/^(%|---|\.\.\.)/m.test(t);function cu(t,e,n){if(!e||e<0)return!1;let r=e-n,i=t.length;if(i<=r)return!1;for(let s=0,o=0;s{"use strict";var U=N(),ce=Vs(),tn=(t,e)=>({indentAtStart:e?t.indent.length:t.indentAtStart,lineWidth:t.options.lineWidth,minContentWidth:t.options.minContentWidth}),nn=t=>/^(%|---|\.\.\.)/m.test(t);function au(t,e,n){if(!e||e<0)return!1;let r=e-n,i=t.length;if(i<=r)return!1;for(let s=0,o=0;sr)return!0;if(o=s+1,i-o<=r)return!1}return!0}function rt(t,e){let n=JSON.stringify(t);if(e.options.doubleQuotedAsJSON)return n;let{implicitKey:r}=e,i=e.options.doubleQuotedMinMultiLineLength,s=e.indent||(nn(t)?" ":""),o="",a=0;for(let c=0,l=n[c];l;l=n[++c])if(l===" "&&n[c+1]==="\\"&&n[c+2]==="n"&&(o+=n.slice(a,c)+"\\ ",c+=1,a=c,l="\\"),l==="\\")switch(n[c+1]){case"u":{o+=n.slice(a,c);let d=n.substr(c+2,4);switch(d){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:d.substr(0,2)==="00"?o+="\\x"+d.substr(2):o+=n.substr(c,6)}c+=5,a=c+1}break;case"n":if(r||n[c+2]==='"'||n.length `;let u,f;for(f=n.length;f>0;--f){let C=n[f-1];if(C!==` `&&C!==" "&&C!==" ")break}let m=n.substring(f),w=m.indexOf(` @@ -29,13 +29,13 @@ ${n}`)+"'";return e.implicitKey?r:ce.foldFlowLines(r,n,ce.FOLD_FLOW,tn(e,!1))}fu `)y=h;else break}let v=n.substring(0,y{E=!0});let b=ce.foldFlowLines(`${v}${C}${m}`,l,ce.FOLD_BLOCK,O);if(!E)return`>${S} ${l}${b}`}return n=n.replace(/\n+/g,`$&${l}`),`|${S} -${l}${v}${n}${m}`}function lu(t,e,n,r){let{type:i,value:s}=t,{actualString:o,implicitKey:a,indent:c,indentStep:l,inFlow:d}=e;if(a&&s.includes(` +${l}${v}${n}${m}`}function cu(t,e,n,r){let{type:i,value:s}=t,{actualString:o,implicitKey:a,indent:c,indentStep:l,inFlow:d}=e;if(a&&s.includes(` `)||d&&/[[\]{},]/.test(s))return qe(s,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(s))return a||d||!s.includes(` `)?qe(s,e):en(t,e,n,r);if(!a&&!d&&i!==U.Scalar.PLAIN&&s.includes(` `))return en(t,e,n,r);if(nn(s)){if(c==="")return e.forceBlockIndent=!0,en(t,e,n,r);if(a&&c===l)return qe(s,e)}let u=s.replace(/\n+/g,`$& -${c}`);if(o){let f=p=>p.default&&p.tag!=="tag:yaml.org,2002:str"&&p.test?.test(u),{compat:m,tags:w}=e.doc.schema;if(w.some(f)||m?.some(f))return qe(s,e)}return a?u:ce.foldFlowLines(u,c,ce.FOLD_FLOW,tn(e,!1))}function uu(t,e,n,r){let{implicitKey:i,inFlow:s}=e,o=typeof t.value=="string"?t:Object.assign({},t,{value:String(t.value)}),{type:a}=t;a!==U.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=U.Scalar.QUOTE_DOUBLE);let c=d=>{switch(d){case U.Scalar.BLOCK_FOLDED:case U.Scalar.BLOCK_LITERAL:return i||s?qe(o.value,e):en(o,e,n,r);case U.Scalar.QUOTE_DOUBLE:return rt(o.value,e);case U.Scalar.QUOTE_SINGLE:return Or(o.value,e);case U.Scalar.PLAIN:return lu(o,e,n,r);default:return null}},l=c(a);if(l===null){let{defaultKeyType:d,defaultStringType:u}=e.options,f=i&&d||u;if(l=c(f),l===null)throw new Error(`Unsupported default string type ${f}`)}return l}zs.stringifyString=uu});var st=g(Ar=>{"use strict";var fu=Jt(),le=_(),du=tt(),pu=it();function hu(t,e){let n=Object.assign({blockQuote:!0,commentString:du.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},t.schema.toStringOptions,e),r;switch(n.collectionStyle){case"block":r=!1;break;case"flow":r=!0;break;default:r=null}return{anchors:new Set,doc:t,flowCollectionPadding:n.flowCollectionPadding?" ":"",indent:"",indentStep:typeof n.indent=="number"?" ".repeat(n.indent):" ",inFlow:r,options:n}}function mu(t,e){if(e.tag){let i=t.filter(s=>s.tag===e.tag);if(i.length>0)return i.find(s=>s.format===e.format)??i[0]}let n,r;if(le.isScalar(e)){r=e.value;let i=t.filter(s=>s.identify?.(r));if(i.length>1){let s=i.filter(o=>o.test);s.length>0&&(i=s)}n=i.find(s=>s.format===e.format)??i.find(s=>!s.format)}else r=e,n=t.find(i=>i.nodeClass&&r instanceof i.nodeClass);if(!n){let i=r?.constructor?.name??(r===null?"null":typeof r);throw new Error(`Tag not resolved for ${i} value`)}return n}function gu(t,e,{anchors:n,doc:r}){if(!r.directives)return"";let i=[],s=(le.isScalar(t)||le.isCollection(t))&&t.anchor;s&&fu.anchorIsValid(s)&&(n.add(s),i.push(`&${s}`));let o=t.tag??(e.default?null:e.tag);return o&&i.push(r.directives.tagString(o)),i.join(" ")}function wu(t,e,n,r){if(le.isPair(t))return t.toString(e,n,r);if(le.isAlias(t)){if(e.doc.directives)return t.toString(e);if(e.resolvedAliases?.has(t))throw new TypeError("Cannot stringify circular structure without alias nodes");e.resolvedAliases?e.resolvedAliases.add(t):e.resolvedAliases=new Set([t]),t=t.resolve(e.doc)}let i,s=le.isNode(t)?t:e.doc.createNode(t,{onTagObj:c=>i=c});i??(i=mu(e.doc.schema.tags,s));let o=gu(s,i,e);o.length>0&&(e.indentAtStart=(e.indentAtStart??0)+o.length+1);let a=typeof i.stringify=="function"?i.stringify(s,e,n,r):le.isScalar(s)?pu.stringifyString(s,e,n,r):s.toString(e,n,r);return o?le.isScalar(s)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o} -${e.indent}${a}`:a}Ar.createStringifyContext=hu;Ar.stringify=wu});var eo=g(Zs=>{"use strict";var Z=_(),Xs=N(),Qs=st(),ot=tt();function yu({key:t,value:e},n,r,i){let{allNullValues:s,doc:o,indent:a,indentStep:c,options:{commentString:l,indentSeq:d,simpleKeys:u}}=n,f=Z.isNode(t)&&t.comment||null;if(u){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(Z.isCollection(t)||!Z.isNode(t)&&typeof t=="object"){let O="With simple keys, collection cannot be used as a key value";throw new Error(O)}}let m=!u&&(!t||f&&e==null&&!n.inFlow||Z.isCollection(t)||(Z.isScalar(t)?t.type===Xs.Scalar.BLOCK_FOLDED||t.type===Xs.Scalar.BLOCK_LITERAL:typeof t=="object"));n=Object.assign({},n,{allNullValues:!1,implicitKey:!m&&(u||!s),indent:a+c});let w=!1,p=!1,h=Qs.stringify(t,n,()=>w=!0,()=>p=!0);if(!m&&!n.inFlow&&h.length>1024){if(u)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");m=!0}if(n.inFlow){if(s||e==null)return w&&r&&r(),h===""?"?":m?`? ${h}`:h}else if(s&&!u||e==null&&m)return h=`? ${h}`,f&&!w?h+=ot.lineComment(h,n.indent,l(f)):p&&i&&i(),h;w&&(f=null),m?(f&&(h+=ot.lineComment(h,n.indent,l(f))),h=`? ${h} -${a}:`):(h=`${h}:`,f&&(h+=ot.lineComment(h,n.indent,l(f))));let y,v,k;Z.isNode(e)?(y=!!e.spaceBefore,v=e.commentBefore,k=e.comment):(y=!1,v=null,k=null,e&&typeof e=="object"&&(e=o.createNode(e))),n.implicitKey=!1,!m&&!f&&Z.isScalar(e)&&(n.indentAtStart=h.length+1),p=!1,!d&&c.length>=2&&!n.inFlow&&!m&&Z.isSeq(e)&&!e.flow&&!e.tag&&!e.anchor&&(n.indent=n.indent.substring(2));let S=!1,C=Qs.stringify(e,n,()=>S=!0,()=>p=!0),E=" ";if(f||y||v){if(E=y?` +${c}`);if(o){let f=p=>p.default&&p.tag!=="tag:yaml.org,2002:str"&&p.test?.test(u),{compat:m,tags:w}=e.doc.schema;if(w.some(f)||m?.some(f))return qe(s,e)}return a?u:ce.foldFlowLines(u,c,ce.FOLD_FLOW,tn(e,!1))}function lu(t,e,n,r){let{implicitKey:i,inFlow:s}=e,o=typeof t.value=="string"?t:Object.assign({},t,{value:String(t.value)}),{type:a}=t;a!==U.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=U.Scalar.QUOTE_DOUBLE);let c=d=>{switch(d){case U.Scalar.BLOCK_FOLDED:case U.Scalar.BLOCK_LITERAL:return i||s?qe(o.value,e):en(o,e,n,r);case U.Scalar.QUOTE_DOUBLE:return rt(o.value,e);case U.Scalar.QUOTE_SINGLE:return Or(o.value,e);case U.Scalar.PLAIN:return cu(o,e,n,r);default:return null}},l=c(a);if(l===null){let{defaultKeyType:d,defaultStringType:u}=e.options,f=i&&d||u;if(l=c(f),l===null)throw new Error(`Unsupported default string type ${f}`)}return l}Gs.stringifyString=lu});var st=g(Ar=>{"use strict";var uu=Jt(),le=_(),fu=tt(),du=it();function pu(t,e){let n=Object.assign({blockQuote:!0,commentString:fu.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},t.schema.toStringOptions,e),r;switch(n.collectionStyle){case"block":r=!1;break;case"flow":r=!0;break;default:r=null}return{anchors:new Set,doc:t,flowCollectionPadding:n.flowCollectionPadding?" ":"",indent:"",indentStep:typeof n.indent=="number"?" ".repeat(n.indent):" ",inFlow:r,options:n}}function hu(t,e){if(e.tag){let i=t.filter(s=>s.tag===e.tag);if(i.length>0)return i.find(s=>s.format===e.format)??i[0]}let n,r;if(le.isScalar(e)){r=e.value;let i=t.filter(s=>s.identify?.(r));if(i.length>1){let s=i.filter(o=>o.test);s.length>0&&(i=s)}n=i.find(s=>s.format===e.format)??i.find(s=>!s.format)}else r=e,n=t.find(i=>i.nodeClass&&r instanceof i.nodeClass);if(!n){let i=r?.constructor?.name??(r===null?"null":typeof r);throw new Error(`Tag not resolved for ${i} value`)}return n}function mu(t,e,{anchors:n,doc:r}){if(!r.directives)return"";let i=[],s=(le.isScalar(t)||le.isCollection(t))&&t.anchor;s&&uu.anchorIsValid(s)&&(n.add(s),i.push(`&${s}`));let o=t.tag??(e.default?null:e.tag);return o&&i.push(r.directives.tagString(o)),i.join(" ")}function gu(t,e,n,r){if(le.isPair(t))return t.toString(e,n,r);if(le.isAlias(t)){if(e.doc.directives)return t.toString(e);if(e.resolvedAliases?.has(t))throw new TypeError("Cannot stringify circular structure without alias nodes");e.resolvedAliases?e.resolvedAliases.add(t):e.resolvedAliases=new Set([t]),t=t.resolve(e.doc)}let i,s=le.isNode(t)?t:e.doc.createNode(t,{onTagObj:c=>i=c});i??(i=hu(e.doc.schema.tags,s));let o=mu(s,i,e);o.length>0&&(e.indentAtStart=(e.indentAtStart??0)+o.length+1);let a=typeof i.stringify=="function"?i.stringify(s,e,n,r):le.isScalar(s)?du.stringifyString(s,e,n,r):s.toString(e,n,r);return o?le.isScalar(s)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o} +${e.indent}${a}`:a}Ar.createStringifyContext=pu;Ar.stringify=gu});var Zs=g(Qs=>{"use strict";var Z=_(),zs=N(),Xs=st(),ot=tt();function wu({key:t,value:e},n,r,i){let{allNullValues:s,doc:o,indent:a,indentStep:c,options:{commentString:l,indentSeq:d,simpleKeys:u}}=n,f=Z.isNode(t)&&t.comment||null;if(u){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(Z.isCollection(t)||!Z.isNode(t)&&typeof t=="object"){let O="With simple keys, collection cannot be used as a key value";throw new Error(O)}}let m=!u&&(!t||f&&e==null&&!n.inFlow||Z.isCollection(t)||(Z.isScalar(t)?t.type===zs.Scalar.BLOCK_FOLDED||t.type===zs.Scalar.BLOCK_LITERAL:typeof t=="object"));n=Object.assign({},n,{allNullValues:!1,implicitKey:!m&&(u||!s),indent:a+c});let w=!1,p=!1,h=Xs.stringify(t,n,()=>w=!0,()=>p=!0);if(!m&&!n.inFlow&&h.length>1024){if(u)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");m=!0}if(n.inFlow){if(s||e==null)return w&&r&&r(),h===""?"?":m?`? ${h}`:h}else if(s&&!u||e==null&&m)return h=`? ${h}`,f&&!w?h+=ot.lineComment(h,n.indent,l(f)):p&&i&&i(),h;w&&(f=null),m?(f&&(h+=ot.lineComment(h,n.indent,l(f))),h=`? ${h} +${a}:`):(h=`${h}:`,f&&(h+=ot.lineComment(h,n.indent,l(f))));let y,v,k;Z.isNode(e)?(y=!!e.spaceBefore,v=e.commentBefore,k=e.comment):(y=!1,v=null,k=null,e&&typeof e=="object"&&(e=o.createNode(e))),n.implicitKey=!1,!m&&!f&&Z.isScalar(e)&&(n.indentAtStart=h.length+1),p=!1,!d&&c.length>=2&&!n.inFlow&&!m&&Z.isSeq(e)&&!e.flow&&!e.tag&&!e.anchor&&(n.indent=n.indent.substring(2));let S=!1,C=Xs.stringify(e,n,()=>S=!0,()=>p=!0),E=" ";if(f||y||v){if(E=y?` `:"",v){let O=l(v);E+=` ${ot.indentComment(O,n.indent)}`}C===""&&!n.inFlow?E===` `&&k&&(E=` @@ -44,32 +44,32 @@ ${ot.indentComment(O,n.indent)}`}C===""&&!n.inFlow?E===` ${n.indent}`}else if(!m&&Z.isCollection(e)){let O=C[0],b=C.indexOf(` `),x=b!==-1,se=n.inFlow??e.flow??e.items.length===0;if(x||!se){let Re=!1;if(x&&(O==="&"||O==="!")){let T=C.indexOf(" ");O==="&"&&T!==-1&&T{"use strict";var to=Ft("process");function bu(t,...e){t==="debug"&&console.log(...e)}function vu(t,e){(t==="debug"||t==="warn")&&(typeof to.emitWarning=="function"?to.emitWarning(e):console.warn(e))}xr.debug=bu;xr.warn=vu});var cn=g(an=>{"use strict";var on=_(),no=N(),rn="<<",sn={identify:t=>t===rn||typeof t=="symbol"&&t.description===rn,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new no.Scalar(Symbol(rn)),{addToJSMap:ro}),stringify:()=>rn},ku=(t,e)=>(sn.identify(e)||on.isScalar(e)&&(!e.type||e.type===no.Scalar.PLAIN)&&sn.identify(e.value))&&t?.doc.schema.tags.some(n=>n.tag===sn.tag&&n.default);function ro(t,e,n){let r=io(t,n);if(on.isSeq(r))for(let i of r.items)Rr(t,e,i);else if(Array.isArray(r))for(let i of r)Rr(t,e,i);else Rr(t,e,r)}function Rr(t,e,n){let r=io(t,n);if(!on.isMap(r))throw new Error("Merge sources must be maps or map aliases");let i=r.toJSON(null,t,Map);for(let[s,o]of i)e instanceof Map?e.has(s)||e.set(s,o):e instanceof Set?e.add(s):Object.prototype.hasOwnProperty.call(e,s)||Object.defineProperty(e,s,{value:o,writable:!0,enumerable:!0,configurable:!0});return e}function io(t,e){return t&&on.isAlias(e)?e.resolve(t.doc,t):e}an.addMergeToJSMap=ro;an.isMergeKey=ku;an.merge=sn});var jr=g(ao=>{"use strict";var Su=Tr(),so=cn(),Cu=st(),oo=_(),Ir=oe();function Eu(t,e,{key:n,value:r}){if(oo.isNode(n)&&n.addToJSMap)n.addToJSMap(t,e,r);else if(so.isMergeKey(t,n))so.addMergeToJSMap(t,e,r);else{let i=Ir.toJS(n,"",t);if(e instanceof Map)e.set(i,Ir.toJS(r,i,t));else if(e instanceof Set)e.add(i);else{let s=_u(n,i,t),o=Ir.toJS(r,s,t);s in e?Object.defineProperty(e,s,{value:o,writable:!0,enumerable:!0,configurable:!0}):e[s]=o}}return e}function _u(t,e,n){if(e===null)return"";if(typeof e!="object")return String(e);if(oo.isNode(t)&&n?.doc){let r=Cu.createStringifyContext(n.doc,{});r.anchors=new Set;for(let s of n.anchors.keys())r.anchors.add(s.anchor);r.inFlow=!0,r.inStringifyKey=!0;let i=t.toString(r);if(!n.mapKeyWarned){let s=JSON.stringify(i);s.length>40&&(s=s.substring(0,36)+'..."'),Su.warn(n.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${s}. Set mapAsMap: true to use object keys.`),n.mapKeyWarned=!0}return i}return JSON.stringify(e)}ao.addPairToJSMap=Eu});var ue=g(Lr=>{"use strict";var co=et(),Pu=eo(),Ou=jr(),ln=_();function Nu(t,e,n){let r=co.createNode(t,void 0,n),i=co.createNode(e,void 0,n);return new un(r,i)}var un=class t{constructor(e,n=null){Object.defineProperty(this,ln.NODE_TYPE,{value:ln.PAIR}),this.key=e,this.value=n}clone(e){let{key:n,value:r}=this;return ln.isNode(n)&&(n=n.clone(e)),ln.isNode(r)&&(r=r.clone(e)),new t(n,r)}toJSON(e,n){let r=n?.mapAsMap?new Map:{};return Ou.addPairToJSMap(n,r,this)}toString(e,n,r){return e?.doc?Pu.stringifyPair(this,e,n,r):JSON.stringify(this)}};Lr.Pair=un;Lr.createPair=Nu});var qr=g(uo=>{"use strict";var Se=_(),lo=st(),fn=tt();function Au(t,e,n){return(e.inFlow??t.flow?Tu:xu)(t,e,n)}function xu({comment:t,items:e},n,{blockItemPrefix:r,flowChars:i,itemIndent:s,onChompKeep:o,onComment:a}){let{indent:c,options:{commentString:l}}=n,d=Object.assign({},n,{indent:s,type:null}),u=!1,f=[];for(let w=0;wh=null,()=>u=!0);h&&(y+=fn.lineComment(y,s,l(h))),u&&h&&(u=!1),f.push(r+y)}let m;if(f.length===0)m=i.start+i.end;else{m=f[0];for(let w=1;w{"use strict";var eo=Ft("process");function yu(t,...e){t==="debug"&&console.log(...e)}function bu(t,e){(t==="debug"||t==="warn")&&(typeof eo.emitWarning=="function"?eo.emitWarning(e):console.warn(e))}xr.debug=yu;xr.warn=bu});var cn=g(an=>{"use strict";var on=_(),to=N(),rn="<<",sn={identify:t=>t===rn||typeof t=="symbol"&&t.description===rn,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new to.Scalar(Symbol(rn)),{addToJSMap:no}),stringify:()=>rn},vu=(t,e)=>(sn.identify(e)||on.isScalar(e)&&(!e.type||e.type===to.Scalar.PLAIN)&&sn.identify(e.value))&&t?.doc.schema.tags.some(n=>n.tag===sn.tag&&n.default);function no(t,e,n){let r=ro(t,n);if(on.isSeq(r))for(let i of r.items)Rr(t,e,i);else if(Array.isArray(r))for(let i of r)Rr(t,e,i);else Rr(t,e,r)}function Rr(t,e,n){let r=ro(t,n);if(!on.isMap(r))throw new Error("Merge sources must be maps or map aliases");let i=r.toJSON(null,t,Map);for(let[s,o]of i)e instanceof Map?e.has(s)||e.set(s,o):e instanceof Set?e.add(s):Object.prototype.hasOwnProperty.call(e,s)||Object.defineProperty(e,s,{value:o,writable:!0,enumerable:!0,configurable:!0});return e}function ro(t,e){return t&&on.isAlias(e)?e.resolve(t.doc,t):e}an.addMergeToJSMap=no;an.isMergeKey=vu;an.merge=sn});var jr=g(oo=>{"use strict";var ku=Tr(),io=cn(),Su=st(),so=_(),Ir=oe();function Cu(t,e,{key:n,value:r}){if(so.isNode(n)&&n.addToJSMap)n.addToJSMap(t,e,r);else if(io.isMergeKey(t,n))io.addMergeToJSMap(t,e,r);else{let i=Ir.toJS(n,"",t);if(e instanceof Map)e.set(i,Ir.toJS(r,i,t));else if(e instanceof Set)e.add(i);else{let s=Eu(n,i,t),o=Ir.toJS(r,s,t);s in e?Object.defineProperty(e,s,{value:o,writable:!0,enumerable:!0,configurable:!0}):e[s]=o}}return e}function Eu(t,e,n){if(e===null)return"";if(typeof e!="object")return String(e);if(so.isNode(t)&&n?.doc){let r=Su.createStringifyContext(n.doc,{});r.anchors=new Set;for(let s of n.anchors.keys())r.anchors.add(s.anchor);r.inFlow=!0,r.inStringifyKey=!0;let i=t.toString(r);if(!n.mapKeyWarned){let s=JSON.stringify(i);s.length>40&&(s=s.substring(0,36)+'..."'),ku.warn(n.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${s}. Set mapAsMap: true to use object keys.`),n.mapKeyWarned=!0}return i}return JSON.stringify(e)}oo.addPairToJSMap=Cu});var ue=g(Lr=>{"use strict";var ao=et(),_u=Zs(),Pu=jr(),ln=_();function Ou(t,e,n){let r=ao.createNode(t,void 0,n),i=ao.createNode(e,void 0,n);return new un(r,i)}var un=class t{constructor(e,n=null){Object.defineProperty(this,ln.NODE_TYPE,{value:ln.PAIR}),this.key=e,this.value=n}clone(e){let{key:n,value:r}=this;return ln.isNode(n)&&(n=n.clone(e)),ln.isNode(r)&&(r=r.clone(e)),new t(n,r)}toJSON(e,n){let r=n?.mapAsMap?new Map:{};return Pu.addPairToJSMap(n,r,this)}toString(e,n,r){return e?.doc?_u.stringifyPair(this,e,n,r):JSON.stringify(this)}};Lr.Pair=un;Lr.createPair=Ou});var qr=g(lo=>{"use strict";var Se=_(),co=st(),fn=tt();function Nu(t,e,n){return(e.inFlow??t.flow?xu:Au)(t,e,n)}function Au({comment:t,items:e},n,{blockItemPrefix:r,flowChars:i,itemIndent:s,onChompKeep:o,onComment:a}){let{indent:c,options:{commentString:l}}=n,d=Object.assign({},n,{indent:s,type:null}),u=!1,f=[];for(let w=0;wh=null,()=>u=!0);h&&(y+=fn.lineComment(y,s,l(h))),u&&h&&(u=!1),f.push(r+y)}let m;if(f.length===0)m=i.start+i.end;else{m=f[0];for(let w=1;wh=null);l||(l=u.length>d||y.includes(` +`+fn.indentComment(l(t),c),a&&a()):u&&o&&o(),m}function xu({items:t},e,{flowChars:n,itemIndent:r}){let{indent:i,indentStep:s,flowCollectionPadding:o,options:{commentString:a}}=e;r+=s;let c=Object.assign({},e,{indent:r,inFlow:!0,type:null}),l=!1,d=0,u=[];for(let w=0;wh=null);l||(l=u.length>d||y.includes(` `)),w0&&(l||(l=u.reduce((v,k)=>v+k.length+2,2)+(y.length+2)>e.options.lineWidth)),l&&(y+=",")),h&&(y+=fn.lineComment(y,r,a(h))),u.push(y),d=u.length}let{start:f,end:m}=n;if(u.length===0)return f+m;if(!l){let w=u.reduce((p,h)=>p+h.length+2,2);l=e.options.lineWidth>0&&w>e.options.lineWidth}if(l){let w=f;for(let p of u)w+=p?` ${s}${i}${p}`:` `;return`${w} -${i}${m}`}else return`${f}${o}${u.join(" ")}${o}${m}`}function dn({indent:t,options:{commentString:e}},n,r,i){if(r&&i&&(r=r.replace(/^\n+/,"")),r){let s=fn.indentComment(e(r),t);n.push(s.trimStart())}}uo.stringifyCollection=Au});var de=g($r=>{"use strict";var Ru=qr(),Iu=jr(),ju=Xt(),fe=_(),pn=ue(),Lu=N();function at(t,e){let n=fe.isScalar(e)?e.value:e;for(let r of t)if(fe.isPair(r)&&(r.key===e||r.key===n||fe.isScalar(r.key)&&r.key.value===n))return r}var Dr=class extends ju.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(fe.MAP,e),this.items=[]}static from(e,n,r){let{keepUndefined:i,replacer:s}=r,o=new this(e),a=(c,l)=>{if(typeof s=="function")l=s.call(n,c,l);else if(Array.isArray(s)&&!s.includes(c))return;(l!==void 0||i)&&o.items.push(pn.createPair(c,l,r))};if(n instanceof Map)for(let[c,l]of n)a(c,l);else if(n&&typeof n=="object")for(let c of Object.keys(n))a(c,n[c]);return typeof e.sortMapEntries=="function"&&o.items.sort(e.sortMapEntries),o}add(e,n){let r;fe.isPair(e)?r=e:!e||typeof e!="object"||!("key"in e)?r=new pn.Pair(e,e?.value):r=new pn.Pair(e.key,e.value);let i=at(this.items,r.key),s=this.schema?.sortMapEntries;if(i){if(!n)throw new Error(`Key ${r.key} already set`);fe.isScalar(i.value)&&Lu.isScalarValue(r.value)?i.value.value=r.value:i.value=r.value}else if(s){let o=this.items.findIndex(a=>s(r,a)<0);o===-1?this.items.push(r):this.items.splice(o,0,r)}else this.items.push(r)}delete(e){let n=at(this.items,e);return n?this.items.splice(this.items.indexOf(n),1).length>0:!1}get(e,n){let i=at(this.items,e)?.value;return(!n&&fe.isScalar(i)?i.value:i)??void 0}has(e){return!!at(this.items,e)}set(e,n){this.add(new pn.Pair(e,n),!0)}toJSON(e,n,r){let i=r?new r:n?.mapAsMap?new Map:{};n?.onCreate&&n.onCreate(i);for(let s of this.items)Iu.addPairToJSMap(n,i,s);return i}toString(e,n,r){if(!e)return JSON.stringify(this);for(let i of this.items)if(!fe.isPair(i))throw new Error(`Map items must all be pairs; found ${JSON.stringify(i)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),Ru.stringifyCollection(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:r,onComment:n})}};$r.YAMLMap=Dr;$r.findPair=at});var De=g(po=>{"use strict";var qu=_(),fo=de(),Du={collection:"map",default:!0,nodeClass:fo.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(t,e){return qu.isMap(t)||e("Expected a mapping for this tag"),t},createNode:(t,e,n)=>fo.YAMLMap.from(t,e,n)};po.map=Du});var pe=g(ho=>{"use strict";var $u=et(),Wu=qr(),Mu=Xt(),mn=_(),Fu=N(),Bu=oe(),Wr=class extends Mu.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(mn.SEQ,e),this.items=[]}add(e){this.items.push(e)}delete(e){let n=hn(e);return typeof n!="number"?!1:this.items.splice(n,1).length>0}get(e,n){let r=hn(e);if(typeof r!="number")return;let i=this.items[r];return!n&&mn.isScalar(i)?i.value:i}has(e){let n=hn(e);return typeof n=="number"&&n=0?e:null}ho.YAMLSeq=Wr});var $e=g(go=>{"use strict";var Ku=_(),mo=pe(),Yu={collection:"seq",default:!0,nodeClass:mo.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(t,e){return Ku.isSeq(t)||e("Expected a sequence for this tag"),t},createNode:(t,e,n)=>mo.YAMLSeq.from(t,e,n)};go.seq=Yu});var ct=g(wo=>{"use strict";var Uu=it(),Hu={identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify(t,e,n,r){return e=Object.assign({actualString:!0},e),Uu.stringifyString(t,e,n,r)}};wo.string=Hu});var gn=g(vo=>{"use strict";var yo=N(),bo={identify:t=>t==null,createNode:()=>new yo.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new yo.Scalar(null),stringify:({source:t},e)=>typeof t=="string"&&bo.test.test(t)?t:e.options.nullStr};vo.nullTag=bo});var Mr=g(So=>{"use strict";var Ju=N(),ko={identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:t=>new Ju.Scalar(t[0]==="t"||t[0]==="T"),stringify({source:t,value:e},n){if(t&&ko.test.test(t)){let r=t[0]==="t"||t[0]==="T";if(e===r)return t}return e?n.options.trueStr:n.options.falseStr}};So.boolTag=ko});var We=g(Co=>{"use strict";function Vu({format:t,minFractionDigits:e,tag:n,value:r}){if(typeof r=="bigint")return String(r);let i=typeof r=="number"?r:Number(r);if(!isFinite(i))return isNaN(i)?".nan":i<0?"-.inf":".inf";let s=Object.is(r,-0)?"-0":JSON.stringify(r);if(!t&&e&&(!n||n==="tag:yaml.org,2002:float")&&/^-?\d/.test(s)&&!s.includes("e")){let o=s.indexOf(".");o<0&&(o=s.length,s+=".");let a=e-(s.length-o-1);for(;a-- >0;)s+="0"}return s}Co.stringifyNumber=Vu});var Br=g(wn=>{"use strict";var Gu=N(),Fr=We(),zu={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:t=>t.slice(-3).toLowerCase()==="nan"?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Fr.stringifyNumber},Xu={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t),stringify(t){let e=Number(t.value);return isFinite(e)?e.toExponential():Fr.stringifyNumber(t)}},Qu={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(t){let e=new Gu.Scalar(parseFloat(t)),n=t.indexOf(".");return n!==-1&&t[t.length-1]==="0"&&(e.minFractionDigits=t.length-n-1),e},stringify:Fr.stringifyNumber};wn.float=Qu;wn.floatExp=Xu;wn.floatNaN=zu});var Yr=g(bn=>{"use strict";var Eo=We(),yn=t=>typeof t=="bigint"||Number.isInteger(t),Kr=(t,e,n,{intAsBigInt:r})=>r?BigInt(t):parseInt(t.substring(e),n);function _o(t,e,n){let{value:r}=t;return yn(r)&&r>=0?n+r.toString(e):Eo.stringifyNumber(t)}var Zu={identify:t=>yn(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(t,e,n)=>Kr(t,2,8,n),stringify:t=>_o(t,8,"0o")},ef={identify:yn,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(t,e,n)=>Kr(t,0,10,n),stringify:Eo.stringifyNumber},tf={identify:t=>yn(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(t,e,n)=>Kr(t,2,16,n),stringify:t=>_o(t,16,"0x")};bn.int=ef;bn.intHex=tf;bn.intOct=Zu});var Oo=g(Po=>{"use strict";var nf=De(),rf=gn(),sf=$e(),of=ct(),af=Mr(),Ur=Br(),Hr=Yr(),cf=[nf.map,sf.seq,of.string,rf.nullTag,af.boolTag,Hr.intOct,Hr.int,Hr.intHex,Ur.floatNaN,Ur.floatExp,Ur.float];Po.schema=cf});var xo=g(Ao=>{"use strict";var lf=N(),uf=De(),ff=$e();function No(t){return typeof t=="bigint"||Number.isInteger(t)}var vn=({value:t})=>JSON.stringify(t),df=[{identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify:vn},{identify:t=>t==null,createNode:()=>new lf.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:vn},{identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:t=>t==="true",stringify:vn},{identify:No,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(t,e,{intAsBigInt:n})=>n?BigInt(t):parseInt(t,10),stringify:({value:t})=>No(t)?t.toString():JSON.stringify(t)},{identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:t=>parseFloat(t),stringify:vn}],pf={default:!0,tag:"",test:/^/,resolve(t,e){return e(`Unresolved plain scalar ${JSON.stringify(t)}`),t}},hf=[uf.map,ff.seq].concat(df,pf);Ao.schema=hf});var Vr=g(To=>{"use strict";var lt=Ft("buffer"),Jr=N(),mf=it(),gf={identify:t=>t instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(t,e){if(typeof lt.Buffer=="function")return lt.Buffer.from(t,"base64");if(typeof atob=="function"){let n=atob(t.replace(/[\n\r]/g,"")),r=new Uint8Array(n.length);for(let i=0;i{"use strict";var kn=_(),Gr=ue(),wf=N(),yf=pe();function Ro(t,e){if(kn.isSeq(t))for(let n=0;n1&&e("Each pair must have its own sequence indicator");let i=r.items[0]||new Gr.Pair(new wf.Scalar(null));if(r.commentBefore&&(i.key.commentBefore=i.key.commentBefore?`${r.commentBefore} +${i}${m}`}else return`${f}${o}${u.join(" ")}${o}${m}`}function dn({indent:t,options:{commentString:e}},n,r,i){if(r&&i&&(r=r.replace(/^\n+/,"")),r){let s=fn.indentComment(e(r),t);n.push(s.trimStart())}}lo.stringifyCollection=Nu});var de=g($r=>{"use strict";var Tu=qr(),Ru=jr(),Iu=Xt(),fe=_(),pn=ue(),ju=N();function at(t,e){let n=fe.isScalar(e)?e.value:e;for(let r of t)if(fe.isPair(r)&&(r.key===e||r.key===n||fe.isScalar(r.key)&&r.key.value===n))return r}var Dr=class extends Iu.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(fe.MAP,e),this.items=[]}static from(e,n,r){let{keepUndefined:i,replacer:s}=r,o=new this(e),a=(c,l)=>{if(typeof s=="function")l=s.call(n,c,l);else if(Array.isArray(s)&&!s.includes(c))return;(l!==void 0||i)&&o.items.push(pn.createPair(c,l,r))};if(n instanceof Map)for(let[c,l]of n)a(c,l);else if(n&&typeof n=="object")for(let c of Object.keys(n))a(c,n[c]);return typeof e.sortMapEntries=="function"&&o.items.sort(e.sortMapEntries),o}add(e,n){let r;fe.isPair(e)?r=e:!e||typeof e!="object"||!("key"in e)?r=new pn.Pair(e,e?.value):r=new pn.Pair(e.key,e.value);let i=at(this.items,r.key),s=this.schema?.sortMapEntries;if(i){if(!n)throw new Error(`Key ${r.key} already set`);fe.isScalar(i.value)&&ju.isScalarValue(r.value)?i.value.value=r.value:i.value=r.value}else if(s){let o=this.items.findIndex(a=>s(r,a)<0);o===-1?this.items.push(r):this.items.splice(o,0,r)}else this.items.push(r)}delete(e){let n=at(this.items,e);return n?this.items.splice(this.items.indexOf(n),1).length>0:!1}get(e,n){let i=at(this.items,e)?.value;return(!n&&fe.isScalar(i)?i.value:i)??void 0}has(e){return!!at(this.items,e)}set(e,n){this.add(new pn.Pair(e,n),!0)}toJSON(e,n,r){let i=r?new r:n?.mapAsMap?new Map:{};n?.onCreate&&n.onCreate(i);for(let s of this.items)Ru.addPairToJSMap(n,i,s);return i}toString(e,n,r){if(!e)return JSON.stringify(this);for(let i of this.items)if(!fe.isPair(i))throw new Error(`Map items must all be pairs; found ${JSON.stringify(i)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),Tu.stringifyCollection(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:r,onComment:n})}};$r.YAMLMap=Dr;$r.findPair=at});var De=g(fo=>{"use strict";var Lu=_(),uo=de(),qu={collection:"map",default:!0,nodeClass:uo.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(t,e){return Lu.isMap(t)||e("Expected a mapping for this tag"),t},createNode:(t,e,n)=>uo.YAMLMap.from(t,e,n)};fo.map=qu});var pe=g(po=>{"use strict";var Du=et(),$u=qr(),Wu=Xt(),mn=_(),Mu=N(),Fu=oe(),Wr=class extends Wu.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(mn.SEQ,e),this.items=[]}add(e){this.items.push(e)}delete(e){let n=hn(e);return typeof n!="number"?!1:this.items.splice(n,1).length>0}get(e,n){let r=hn(e);if(typeof r!="number")return;let i=this.items[r];return!n&&mn.isScalar(i)?i.value:i}has(e){let n=hn(e);return typeof n=="number"&&n=0?e:null}po.YAMLSeq=Wr});var $e=g(mo=>{"use strict";var Bu=_(),ho=pe(),Ku={collection:"seq",default:!0,nodeClass:ho.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(t,e){return Bu.isSeq(t)||e("Expected a sequence for this tag"),t},createNode:(t,e,n)=>ho.YAMLSeq.from(t,e,n)};mo.seq=Ku});var ct=g(go=>{"use strict";var Yu=it(),Uu={identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify(t,e,n,r){return e=Object.assign({actualString:!0},e),Yu.stringifyString(t,e,n,r)}};go.string=Uu});var gn=g(bo=>{"use strict";var wo=N(),yo={identify:t=>t==null,createNode:()=>new wo.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new wo.Scalar(null),stringify:({source:t},e)=>typeof t=="string"&&yo.test.test(t)?t:e.options.nullStr};bo.nullTag=yo});var Mr=g(ko=>{"use strict";var Hu=N(),vo={identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:t=>new Hu.Scalar(t[0]==="t"||t[0]==="T"),stringify({source:t,value:e},n){if(t&&vo.test.test(t)){let r=t[0]==="t"||t[0]==="T";if(e===r)return t}return e?n.options.trueStr:n.options.falseStr}};ko.boolTag=vo});var We=g(So=>{"use strict";function Ju({format:t,minFractionDigits:e,tag:n,value:r}){if(typeof r=="bigint")return String(r);let i=typeof r=="number"?r:Number(r);if(!isFinite(i))return isNaN(i)?".nan":i<0?"-.inf":".inf";let s=Object.is(r,-0)?"-0":JSON.stringify(r);if(!t&&e&&(!n||n==="tag:yaml.org,2002:float")&&/^-?\d/.test(s)&&!s.includes("e")){let o=s.indexOf(".");o<0&&(o=s.length,s+=".");let a=e-(s.length-o-1);for(;a-- >0;)s+="0"}return s}So.stringifyNumber=Ju});var Br=g(wn=>{"use strict";var Vu=N(),Fr=We(),Gu={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:t=>t.slice(-3).toLowerCase()==="nan"?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Fr.stringifyNumber},zu={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t),stringify(t){let e=Number(t.value);return isFinite(e)?e.toExponential():Fr.stringifyNumber(t)}},Xu={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(t){let e=new Vu.Scalar(parseFloat(t)),n=t.indexOf(".");return n!==-1&&t[t.length-1]==="0"&&(e.minFractionDigits=t.length-n-1),e},stringify:Fr.stringifyNumber};wn.float=Xu;wn.floatExp=zu;wn.floatNaN=Gu});var Yr=g(bn=>{"use strict";var Co=We(),yn=t=>typeof t=="bigint"||Number.isInteger(t),Kr=(t,e,n,{intAsBigInt:r})=>r?BigInt(t):parseInt(t.substring(e),n);function Eo(t,e,n){let{value:r}=t;return yn(r)&&r>=0?n+r.toString(e):Co.stringifyNumber(t)}var Qu={identify:t=>yn(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(t,e,n)=>Kr(t,2,8,n),stringify:t=>Eo(t,8,"0o")},Zu={identify:yn,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(t,e,n)=>Kr(t,0,10,n),stringify:Co.stringifyNumber},ef={identify:t=>yn(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(t,e,n)=>Kr(t,2,16,n),stringify:t=>Eo(t,16,"0x")};bn.int=Zu;bn.intHex=ef;bn.intOct=Qu});var Po=g(_o=>{"use strict";var tf=De(),nf=gn(),rf=$e(),sf=ct(),of=Mr(),Ur=Br(),Hr=Yr(),af=[tf.map,rf.seq,sf.string,nf.nullTag,of.boolTag,Hr.intOct,Hr.int,Hr.intHex,Ur.floatNaN,Ur.floatExp,Ur.float];_o.schema=af});var Ao=g(No=>{"use strict";var cf=N(),lf=De(),uf=$e();function Oo(t){return typeof t=="bigint"||Number.isInteger(t)}var vn=({value:t})=>JSON.stringify(t),ff=[{identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify:vn},{identify:t=>t==null,createNode:()=>new cf.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:vn},{identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:t=>t==="true",stringify:vn},{identify:Oo,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(t,e,{intAsBigInt:n})=>n?BigInt(t):parseInt(t,10),stringify:({value:t})=>Oo(t)?t.toString():JSON.stringify(t)},{identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:t=>parseFloat(t),stringify:vn}],df={default:!0,tag:"",test:/^/,resolve(t,e){return e(`Unresolved plain scalar ${JSON.stringify(t)}`),t}},pf=[lf.map,uf.seq].concat(ff,df);No.schema=pf});var Vr=g(xo=>{"use strict";var lt=Ft("buffer"),Jr=N(),hf=it(),mf={identify:t=>t instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(t,e){if(typeof lt.Buffer=="function")return lt.Buffer.from(t,"base64");if(typeof atob=="function"){let n=atob(t.replace(/[\n\r]/g,"")),r=new Uint8Array(n.length);for(let i=0;i{"use strict";var kn=_(),Gr=ue(),gf=N(),wf=pe();function To(t,e){if(kn.isSeq(t))for(let n=0;n1&&e("Each pair must have its own sequence indicator");let i=r.items[0]||new Gr.Pair(new gf.Scalar(null));if(r.commentBefore&&(i.key.commentBefore=i.key.commentBefore?`${r.commentBefore} ${i.key.commentBefore}`:r.commentBefore),r.comment){let s=i.value??i.key;s.comment=s.comment?`${r.comment} -${s.comment}`:r.comment}r=i}t.items[n]=kn.isPair(r)?r:new Gr.Pair(r)}}else e("Expected a sequence for this tag");return t}function Io(t,e,n){let{replacer:r}=n,i=new yf.YAMLSeq(t);i.tag="tag:yaml.org,2002:pairs";let s=0;if(e&&Symbol.iterator in Object(e))for(let o of e){typeof r=="function"&&(o=r.call(e,String(s++),o));let a,c;if(Array.isArray(o))if(o.length===2)a=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)a=l[0],c=o[a];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else a=o;i.items.push(Gr.createPair(a,c,n))}return i}var bf={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Ro,createNode:Io};Sn.createPairs=Io;Sn.pairs=bf;Sn.resolvePairs=Ro});var Qr=g(Xr=>{"use strict";var jo=_(),zr=oe(),ut=de(),vf=pe(),Lo=Cn(),Ce=class t extends vf.YAMLSeq{constructor(){super(),this.add=ut.YAMLMap.prototype.add.bind(this),this.delete=ut.YAMLMap.prototype.delete.bind(this),this.get=ut.YAMLMap.prototype.get.bind(this),this.has=ut.YAMLMap.prototype.has.bind(this),this.set=ut.YAMLMap.prototype.set.bind(this),this.tag=t.tag}toJSON(e,n){if(!n)return super.toJSON(e);let r=new Map;n?.onCreate&&n.onCreate(r);for(let i of this.items){let s,o;if(jo.isPair(i)?(s=zr.toJS(i.key,"",n),o=zr.toJS(i.value,s,n)):s=zr.toJS(i,"",n),r.has(s))throw new Error("Ordered maps must not include duplicate keys");r.set(s,o)}return r}static from(e,n,r){let i=Lo.createPairs(e,n,r),s=new this;return s.items=i.items,s}};Ce.tag="tag:yaml.org,2002:omap";var kf={collection:"seq",identify:t=>t instanceof Map,nodeClass:Ce,default:!1,tag:"tag:yaml.org,2002:omap",resolve(t,e){let n=Lo.resolvePairs(t,e),r=[];for(let{key:i}of n.items)jo.isScalar(i)&&(r.includes(i.value)?e(`Ordered maps must not include duplicate keys: ${i.value}`):r.push(i.value));return Object.assign(new Ce,n)},createNode:(t,e,n)=>Ce.from(t,e,n)};Xr.YAMLOMap=Ce;Xr.omap=kf});var Mo=g(Zr=>{"use strict";var qo=N();function Do({value:t,source:e},n){return e&&(t?$o:Wo).test.test(e)?e:t?n.options.trueStr:n.options.falseStr}var $o={identify:t=>t===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new qo.Scalar(!0),stringify:Do},Wo={identify:t=>t===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new qo.Scalar(!1),stringify:Do};Zr.falseTag=Wo;Zr.trueTag=$o});var Fo=g(En=>{"use strict";var Sf=N(),ei=We(),Cf={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:t=>t.slice(-3).toLowerCase()==="nan"?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:ei.stringifyNumber},Ef={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t.replace(/_/g,"")),stringify(t){let e=Number(t.value);return isFinite(e)?e.toExponential():ei.stringifyNumber(t)}},_f={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(t){let e=new Sf.Scalar(parseFloat(t.replace(/_/g,""))),n=t.indexOf(".");if(n!==-1){let r=t.substring(n+1).replace(/_/g,"");r[r.length-1]==="0"&&(e.minFractionDigits=r.length)}return e},stringify:ei.stringifyNumber};En.float=_f;En.floatExp=Ef;En.floatNaN=Cf});var Ko=g(dt=>{"use strict";var Bo=We(),ft=t=>typeof t=="bigint"||Number.isInteger(t);function _n(t,e,n,{intAsBigInt:r}){let i=t[0];if((i==="-"||i==="+")&&(e+=1),t=t.substring(e).replace(/_/g,""),r){switch(n){case 2:t=`0b${t}`;break;case 8:t=`0o${t}`;break;case 16:t=`0x${t}`;break}let o=BigInt(t);return i==="-"?BigInt(-1)*o:o}let s=parseInt(t,n);return i==="-"?-1*s:s}function ti(t,e,n){let{value:r}=t;if(ft(r)){let i=r.toString(e);return r<0?"-"+n+i.substr(1):n+i}return Bo.stringifyNumber(t)}var Pf={identify:ft,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(t,e,n)=>_n(t,2,2,n),stringify:t=>ti(t,2,"0b")},Of={identify:ft,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(t,e,n)=>_n(t,1,8,n),stringify:t=>ti(t,8,"0")},Nf={identify:ft,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(t,e,n)=>_n(t,0,10,n),stringify:Bo.stringifyNumber},Af={identify:ft,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(t,e,n)=>_n(t,2,16,n),stringify:t=>ti(t,16,"0x")};dt.int=Nf;dt.intBin=Pf;dt.intHex=Af;dt.intOct=Of});var ri=g(ni=>{"use strict";var Nn=_(),Pn=ue(),On=de(),Ee=class t extends On.YAMLMap{constructor(e){super(e),this.tag=t.tag}add(e){let n;Nn.isPair(e)?n=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?n=new Pn.Pair(e.key,null):n=new Pn.Pair(e,null),On.findPair(this.items,n.key)||this.items.push(n)}get(e,n){let r=On.findPair(this.items,e);return!n&&Nn.isPair(r)?Nn.isScalar(r.key)?r.key.value:r.key:r}set(e,n){if(typeof n!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof n}`);let r=On.findPair(this.items,e);r&&!n?this.items.splice(this.items.indexOf(r),1):!r&&n&&this.items.push(new Pn.Pair(e))}toJSON(e,n){return super.toJSON(e,n,Set)}toString(e,n,r){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),n,r);throw new Error("Set items must all have null values")}static from(e,n,r){let{replacer:i}=r,s=new this(e);if(n&&Symbol.iterator in Object(n))for(let o of n)typeof i=="function"&&(o=i.call(n,o,o)),s.items.push(Pn.createPair(o,null,r));return s}};Ee.tag="tag:yaml.org,2002:set";var xf={collection:"map",identify:t=>t instanceof Set,nodeClass:Ee,default:!1,tag:"tag:yaml.org,2002:set",createNode:(t,e,n)=>Ee.from(t,e,n),resolve(t,e){if(Nn.isMap(t)){if(t.hasAllNullValues(!0))return Object.assign(new Ee,t);e("Set items must all have null values")}else e("Expected a mapping for this tag");return t}};ni.YAMLSet=Ee;ni.set=xf});var si=g(An=>{"use strict";var Tf=We();function ii(t,e){let n=t[0],r=n==="-"||n==="+"?t.substring(1):t,i=o=>e?BigInt(o):Number(o),s=r.replace(/_/g,"").split(":").reduce((o,a)=>o*i(60)+i(a),i(0));return n==="-"?i(-1)*s:s}function Yo(t){let{value:e}=t,n=o=>o;if(typeof e=="bigint")n=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return Tf.stringifyNumber(t);let r="";e<0&&(r="-",e*=n(-1));let i=n(60),s=[e%i];return e<60?s.unshift(0):(e=(e-s[0])/i,s.unshift(e%i),e>=60&&(e=(e-s[0])/i,s.unshift(e))),r+s.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var Rf={identify:t=>typeof t=="bigint"||Number.isInteger(t),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(t,e,{intAsBigInt:n})=>ii(t,n),stringify:Yo},If={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:t=>ii(t,!1),stringify:Yo},Uo={identify:t=>t instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(t){let e=t.match(Uo.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,n,r,i,s,o,a]=e.map(Number),c=e[7]?Number((e[7]+"00").substr(1,3)):0,l=Date.UTC(n,r-1,i,s||0,o||0,a||0,c),d=e[8];if(d&&d!=="Z"){let u=ii(d,!1);Math.abs(u)<30&&(u*=60),l-=6e4*u}return new Date(l)},stringify:({value:t})=>t?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};An.floatTime=If;An.intTime=Rf;An.timestamp=Uo});var Vo=g(Jo=>{"use strict";var jf=De(),Lf=gn(),qf=$e(),Df=ct(),$f=Vr(),Ho=Mo(),oi=Fo(),xn=Ko(),Wf=cn(),Mf=Qr(),Ff=Cn(),Bf=ri(),ai=si(),Kf=[jf.map,qf.seq,Df.string,Lf.nullTag,Ho.trueTag,Ho.falseTag,xn.intBin,xn.intOct,xn.int,xn.intHex,oi.floatNaN,oi.floatExp,oi.float,$f.binary,Wf.merge,Mf.omap,Ff.pairs,Bf.set,ai.intTime,ai.floatTime,ai.timestamp];Jo.schema=Kf});var ia=g(ui=>{"use strict";var Qo=De(),Yf=gn(),Zo=$e(),Uf=ct(),Hf=Mr(),ci=Br(),li=Yr(),Jf=Oo(),Vf=xo(),ea=Vr(),pt=cn(),ta=Qr(),na=Cn(),Go=Vo(),ra=ri(),Tn=si(),zo=new Map([["core",Jf.schema],["failsafe",[Qo.map,Zo.seq,Uf.string]],["json",Vf.schema],["yaml11",Go.schema],["yaml-1.1",Go.schema]]),Xo={binary:ea.binary,bool:Hf.boolTag,float:ci.float,floatExp:ci.floatExp,floatNaN:ci.floatNaN,floatTime:Tn.floatTime,int:li.int,intHex:li.intHex,intOct:li.intOct,intTime:Tn.intTime,map:Qo.map,merge:pt.merge,null:Yf.nullTag,omap:ta.omap,pairs:na.pairs,seq:Zo.seq,set:ra.set,timestamp:Tn.timestamp},Gf={"tag:yaml.org,2002:binary":ea.binary,"tag:yaml.org,2002:merge":pt.merge,"tag:yaml.org,2002:omap":ta.omap,"tag:yaml.org,2002:pairs":na.pairs,"tag:yaml.org,2002:set":ra.set,"tag:yaml.org,2002:timestamp":Tn.timestamp};function zf(t,e,n){let r=zo.get(e);if(r&&!t)return n&&!r.includes(pt.merge)?r.concat(pt.merge):r.slice();let i=r;if(!i)if(Array.isArray(t))i=[];else{let s=Array.from(zo.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${e}"; use one of ${s} or define customTags array`)}if(Array.isArray(t))for(let s of t)i=i.concat(s);else typeof t=="function"&&(i=t(i.slice()));return n&&(i=i.concat(pt.merge)),i.reduce((s,o)=>{let a=typeof o=="string"?Xo[o]:o;if(!a){let c=JSON.stringify(o),l=Object.keys(Xo).map(d=>JSON.stringify(d)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return s.includes(a)||s.push(a),s},[])}ui.coreKnownTags=Gf;ui.getTags=zf});var pi=g(sa=>{"use strict";var fi=_(),Xf=De(),Qf=$e(),Zf=ct(),Rn=ia(),ed=(t,e)=>t.keye.key?1:0,di=class t{constructor({compat:e,customTags:n,merge:r,resolveKnownTags:i,schema:s,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?Rn.getTags(e,"compat"):e?Rn.getTags(null,e):null,this.name=typeof s=="string"&&s||"core",this.knownTags=i?Rn.coreKnownTags:{},this.tags=Rn.getTags(n,this.name,r),this.toStringOptions=a??null,Object.defineProperty(this,fi.MAP,{value:Xf.map}),Object.defineProperty(this,fi.SCALAR,{value:Zf.string}),Object.defineProperty(this,fi.SEQ,{value:Qf.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?ed:null}clone(){let e=Object.create(t.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};sa.Schema=di});var aa=g(oa=>{"use strict";var td=_(),hi=st(),ht=tt();function nd(t,e){let n=[],r=e.directives===!0;if(e.directives!==!1&&t.directives){let c=t.directives.toString(t);c?(n.push(c),r=!0):t.directives.docStart&&(r=!0)}r&&n.push("---");let i=hi.createStringifyContext(t,e),{commentString:s}=i.options;if(t.commentBefore){n.length!==1&&n.unshift("");let c=s(t.commentBefore);n.unshift(ht.indentComment(c,""))}let o=!1,a=null;if(t.contents){if(td.isNode(t.contents)){if(t.contents.spaceBefore&&r&&n.push(""),t.contents.commentBefore){let d=s(t.contents.commentBefore);n.push(ht.indentComment(d,""))}i.forceBlockIndent=!!t.comment,a=t.contents.comment}let c=a?void 0:()=>o=!0,l=hi.stringify(t.contents,i,()=>a=null,c);a&&(l+=ht.lineComment(l,"",s(a))),(l[0]==="|"||l[0]===">")&&n[n.length-1]==="---"?n[n.length-1]=`--- ${l}`:n.push(l)}else n.push(hi.stringify(t.contents,i));if(t.directives?.docEnd)if(t.comment){let c=s(t.comment);c.includes(` +${s.comment}`:r.comment}r=i}t.items[n]=kn.isPair(r)?r:new Gr.Pair(r)}}else e("Expected a sequence for this tag");return t}function Ro(t,e,n){let{replacer:r}=n,i=new wf.YAMLSeq(t);i.tag="tag:yaml.org,2002:pairs";let s=0;if(e&&Symbol.iterator in Object(e))for(let o of e){typeof r=="function"&&(o=r.call(e,String(s++),o));let a,c;if(Array.isArray(o))if(o.length===2)a=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)a=l[0],c=o[a];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else a=o;i.items.push(Gr.createPair(a,c,n))}return i}var yf={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:To,createNode:Ro};Sn.createPairs=Ro;Sn.pairs=yf;Sn.resolvePairs=To});var Qr=g(Xr=>{"use strict";var Io=_(),zr=oe(),ut=de(),bf=pe(),jo=Cn(),Ce=class t extends bf.YAMLSeq{constructor(){super(),this.add=ut.YAMLMap.prototype.add.bind(this),this.delete=ut.YAMLMap.prototype.delete.bind(this),this.get=ut.YAMLMap.prototype.get.bind(this),this.has=ut.YAMLMap.prototype.has.bind(this),this.set=ut.YAMLMap.prototype.set.bind(this),this.tag=t.tag}toJSON(e,n){if(!n)return super.toJSON(e);let r=new Map;n?.onCreate&&n.onCreate(r);for(let i of this.items){let s,o;if(Io.isPair(i)?(s=zr.toJS(i.key,"",n),o=zr.toJS(i.value,s,n)):s=zr.toJS(i,"",n),r.has(s))throw new Error("Ordered maps must not include duplicate keys");r.set(s,o)}return r}static from(e,n,r){let i=jo.createPairs(e,n,r),s=new this;return s.items=i.items,s}};Ce.tag="tag:yaml.org,2002:omap";var vf={collection:"seq",identify:t=>t instanceof Map,nodeClass:Ce,default:!1,tag:"tag:yaml.org,2002:omap",resolve(t,e){let n=jo.resolvePairs(t,e),r=[];for(let{key:i}of n.items)Io.isScalar(i)&&(r.includes(i.value)?e(`Ordered maps must not include duplicate keys: ${i.value}`):r.push(i.value));return Object.assign(new Ce,n)},createNode:(t,e,n)=>Ce.from(t,e,n)};Xr.YAMLOMap=Ce;Xr.omap=vf});var Wo=g(Zr=>{"use strict";var Lo=N();function qo({value:t,source:e},n){return e&&(t?Do:$o).test.test(e)?e:t?n.options.trueStr:n.options.falseStr}var Do={identify:t=>t===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new Lo.Scalar(!0),stringify:qo},$o={identify:t=>t===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new Lo.Scalar(!1),stringify:qo};Zr.falseTag=$o;Zr.trueTag=Do});var Mo=g(En=>{"use strict";var kf=N(),ei=We(),Sf={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:t=>t.slice(-3).toLowerCase()==="nan"?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:ei.stringifyNumber},Cf={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t.replace(/_/g,"")),stringify(t){let e=Number(t.value);return isFinite(e)?e.toExponential():ei.stringifyNumber(t)}},Ef={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(t){let e=new kf.Scalar(parseFloat(t.replace(/_/g,""))),n=t.indexOf(".");if(n!==-1){let r=t.substring(n+1).replace(/_/g,"");r[r.length-1]==="0"&&(e.minFractionDigits=r.length)}return e},stringify:ei.stringifyNumber};En.float=Ef;En.floatExp=Cf;En.floatNaN=Sf});var Bo=g(dt=>{"use strict";var Fo=We(),ft=t=>typeof t=="bigint"||Number.isInteger(t);function _n(t,e,n,{intAsBigInt:r}){let i=t[0];if((i==="-"||i==="+")&&(e+=1),t=t.substring(e).replace(/_/g,""),r){switch(n){case 2:t=`0b${t}`;break;case 8:t=`0o${t}`;break;case 16:t=`0x${t}`;break}let o=BigInt(t);return i==="-"?BigInt(-1)*o:o}let s=parseInt(t,n);return i==="-"?-1*s:s}function ti(t,e,n){let{value:r}=t;if(ft(r)){let i=r.toString(e);return r<0?"-"+n+i.substr(1):n+i}return Fo.stringifyNumber(t)}var _f={identify:ft,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(t,e,n)=>_n(t,2,2,n),stringify:t=>ti(t,2,"0b")},Pf={identify:ft,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(t,e,n)=>_n(t,1,8,n),stringify:t=>ti(t,8,"0")},Of={identify:ft,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(t,e,n)=>_n(t,0,10,n),stringify:Fo.stringifyNumber},Nf={identify:ft,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(t,e,n)=>_n(t,2,16,n),stringify:t=>ti(t,16,"0x")};dt.int=Of;dt.intBin=_f;dt.intHex=Nf;dt.intOct=Pf});var ri=g(ni=>{"use strict";var Nn=_(),Pn=ue(),On=de(),Ee=class t extends On.YAMLMap{constructor(e){super(e),this.tag=t.tag}add(e){let n;Nn.isPair(e)?n=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?n=new Pn.Pair(e.key,null):n=new Pn.Pair(e,null),On.findPair(this.items,n.key)||this.items.push(n)}get(e,n){let r=On.findPair(this.items,e);return!n&&Nn.isPair(r)?Nn.isScalar(r.key)?r.key.value:r.key:r}set(e,n){if(typeof n!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof n}`);let r=On.findPair(this.items,e);r&&!n?this.items.splice(this.items.indexOf(r),1):!r&&n&&this.items.push(new Pn.Pair(e))}toJSON(e,n){return super.toJSON(e,n,Set)}toString(e,n,r){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),n,r);throw new Error("Set items must all have null values")}static from(e,n,r){let{replacer:i}=r,s=new this(e);if(n&&Symbol.iterator in Object(n))for(let o of n)typeof i=="function"&&(o=i.call(n,o,o)),s.items.push(Pn.createPair(o,null,r));return s}};Ee.tag="tag:yaml.org,2002:set";var Af={collection:"map",identify:t=>t instanceof Set,nodeClass:Ee,default:!1,tag:"tag:yaml.org,2002:set",createNode:(t,e,n)=>Ee.from(t,e,n),resolve(t,e){if(Nn.isMap(t)){if(t.hasAllNullValues(!0))return Object.assign(new Ee,t);e("Set items must all have null values")}else e("Expected a mapping for this tag");return t}};ni.YAMLSet=Ee;ni.set=Af});var si=g(An=>{"use strict";var xf=We();function ii(t,e){let n=t[0],r=n==="-"||n==="+"?t.substring(1):t,i=o=>e?BigInt(o):Number(o),s=r.replace(/_/g,"").split(":").reduce((o,a)=>o*i(60)+i(a),i(0));return n==="-"?i(-1)*s:s}function Ko(t){let{value:e}=t,n=o=>o;if(typeof e=="bigint")n=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return xf.stringifyNumber(t);let r="";e<0&&(r="-",e*=n(-1));let i=n(60),s=[e%i];return e<60?s.unshift(0):(e=(e-s[0])/i,s.unshift(e%i),e>=60&&(e=(e-s[0])/i,s.unshift(e))),r+s.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var Tf={identify:t=>typeof t=="bigint"||Number.isInteger(t),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(t,e,{intAsBigInt:n})=>ii(t,n),stringify:Ko},Rf={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:t=>ii(t,!1),stringify:Ko},Yo={identify:t=>t instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(t){let e=t.match(Yo.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,n,r,i,s,o,a]=e.map(Number),c=e[7]?Number((e[7]+"00").substr(1,3)):0,l=Date.UTC(n,r-1,i,s||0,o||0,a||0,c),d=e[8];if(d&&d!=="Z"){let u=ii(d,!1);Math.abs(u)<30&&(u*=60),l-=6e4*u}return new Date(l)},stringify:({value:t})=>t?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};An.floatTime=Rf;An.intTime=Tf;An.timestamp=Yo});var Jo=g(Ho=>{"use strict";var If=De(),jf=gn(),Lf=$e(),qf=ct(),Df=Vr(),Uo=Wo(),oi=Mo(),xn=Bo(),$f=cn(),Wf=Qr(),Mf=Cn(),Ff=ri(),ai=si(),Bf=[If.map,Lf.seq,qf.string,jf.nullTag,Uo.trueTag,Uo.falseTag,xn.intBin,xn.intOct,xn.int,xn.intHex,oi.floatNaN,oi.floatExp,oi.float,Df.binary,$f.merge,Wf.omap,Mf.pairs,Ff.set,ai.intTime,ai.floatTime,ai.timestamp];Ho.schema=Bf});var ra=g(ui=>{"use strict";var Xo=De(),Kf=gn(),Qo=$e(),Yf=ct(),Uf=Mr(),ci=Br(),li=Yr(),Hf=Po(),Jf=Ao(),Zo=Vr(),pt=cn(),ea=Qr(),ta=Cn(),Vo=Jo(),na=ri(),Tn=si(),Go=new Map([["core",Hf.schema],["failsafe",[Xo.map,Qo.seq,Yf.string]],["json",Jf.schema],["yaml11",Vo.schema],["yaml-1.1",Vo.schema]]),zo={binary:Zo.binary,bool:Uf.boolTag,float:ci.float,floatExp:ci.floatExp,floatNaN:ci.floatNaN,floatTime:Tn.floatTime,int:li.int,intHex:li.intHex,intOct:li.intOct,intTime:Tn.intTime,map:Xo.map,merge:pt.merge,null:Kf.nullTag,omap:ea.omap,pairs:ta.pairs,seq:Qo.seq,set:na.set,timestamp:Tn.timestamp},Vf={"tag:yaml.org,2002:binary":Zo.binary,"tag:yaml.org,2002:merge":pt.merge,"tag:yaml.org,2002:omap":ea.omap,"tag:yaml.org,2002:pairs":ta.pairs,"tag:yaml.org,2002:set":na.set,"tag:yaml.org,2002:timestamp":Tn.timestamp};function Gf(t,e,n){let r=Go.get(e);if(r&&!t)return n&&!r.includes(pt.merge)?r.concat(pt.merge):r.slice();let i=r;if(!i)if(Array.isArray(t))i=[];else{let s=Array.from(Go.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${e}"; use one of ${s} or define customTags array`)}if(Array.isArray(t))for(let s of t)i=i.concat(s);else typeof t=="function"&&(i=t(i.slice()));return n&&(i=i.concat(pt.merge)),i.reduce((s,o)=>{let a=typeof o=="string"?zo[o]:o;if(!a){let c=JSON.stringify(o),l=Object.keys(zo).map(d=>JSON.stringify(d)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return s.includes(a)||s.push(a),s},[])}ui.coreKnownTags=Vf;ui.getTags=Gf});var pi=g(ia=>{"use strict";var fi=_(),zf=De(),Xf=$e(),Qf=ct(),Rn=ra(),Zf=(t,e)=>t.keye.key?1:0,di=class t{constructor({compat:e,customTags:n,merge:r,resolveKnownTags:i,schema:s,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?Rn.getTags(e,"compat"):e?Rn.getTags(null,e):null,this.name=typeof s=="string"&&s||"core",this.knownTags=i?Rn.coreKnownTags:{},this.tags=Rn.getTags(n,this.name,r),this.toStringOptions=a??null,Object.defineProperty(this,fi.MAP,{value:zf.map}),Object.defineProperty(this,fi.SCALAR,{value:Qf.string}),Object.defineProperty(this,fi.SEQ,{value:Xf.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?Zf:null}clone(){let e=Object.create(t.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};ia.Schema=di});var oa=g(sa=>{"use strict";var ed=_(),hi=st(),ht=tt();function td(t,e){let n=[],r=e.directives===!0;if(e.directives!==!1&&t.directives){let c=t.directives.toString(t);c?(n.push(c),r=!0):t.directives.docStart&&(r=!0)}r&&n.push("---");let i=hi.createStringifyContext(t,e),{commentString:s}=i.options;if(t.commentBefore){n.length!==1&&n.unshift("");let c=s(t.commentBefore);n.unshift(ht.indentComment(c,""))}let o=!1,a=null;if(t.contents){if(ed.isNode(t.contents)){if(t.contents.spaceBefore&&r&&n.push(""),t.contents.commentBefore){let d=s(t.contents.commentBefore);n.push(ht.indentComment(d,""))}i.forceBlockIndent=!!t.comment,a=t.contents.comment}let c=a?void 0:()=>o=!0,l=hi.stringify(t.contents,i,()=>a=null,c);a&&(l+=ht.lineComment(l,"",s(a))),(l[0]==="|"||l[0]===">")&&n[n.length-1]==="---"?n[n.length-1]=`--- ${l}`:n.push(l)}else n.push(hi.stringify(t.contents,i));if(t.directives?.docEnd)if(t.comment){let c=s(t.comment);c.includes(` `)?(n.push("..."),n.push(ht.indentComment(c,""))):n.push(`... ${c}`)}else n.push("...");else{let c=t.comment;c&&o&&(c=c.replace(/^\n+/,"")),c&&((!o||a)&&n[n.length-1]!==""&&n.push(""),n.push(ht.indentComment(s(c),"")))}return n.join(` `)+` -`}oa.stringifyDocument=nd});var mt=g(ca=>{"use strict";var rd=Ze(),Me=Xt(),Y=_(),id=ue(),sd=oe(),od=pi(),ad=aa(),mi=Jt(),cd=br(),ld=et(),gi=yr(),wi=class t{constructor(e,n,r){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,Y.NODE_TYPE,{value:Y.DOC});let i=null;typeof n=="function"||Array.isArray(n)?i=n:r===void 0&&n&&(r=n,n=void 0);let s=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},r);this.options=s;let{version:o}=s;r?._directives?(this.directives=r._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new gi.Directives({version:o}),this.setSchema(o,r),this.contents=e===void 0?null:this.createNode(e,i,r)}clone(){let e=Object.create(t.prototype,{[Y.NODE_TYPE]:{value:Y.DOC}});return e.commentBefore=this.commentBefore,e.comment=this.comment,e.errors=this.errors.slice(),e.warnings=this.warnings.slice(),e.options=Object.assign({},this.options),this.directives&&(e.directives=this.directives.clone()),e.schema=this.schema.clone(),e.contents=Y.isNode(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){Fe(this.contents)&&this.contents.add(e)}addIn(e,n){Fe(this.contents)&&this.contents.addIn(e,n)}createAlias(e,n){if(!e.anchor){let r=mi.anchorNames(this);e.anchor=!n||r.has(n)?mi.findNewAnchor(n||"a",r):n}return new rd.Alias(e.anchor)}createNode(e,n,r){let i;if(typeof n=="function")e=n.call({"":e},"",e),i=n;else if(Array.isArray(n)){let h=v=>typeof v=="number"||v instanceof String||v instanceof Number,y=n.filter(h).map(String);y.length>0&&(n=n.concat(y)),i=n}else r===void 0&&n&&(r=n,n=void 0);let{aliasDuplicateObjects:s,anchorPrefix:o,flow:a,keepUndefined:c,onTagObj:l,tag:d}=r??{},{onAnchor:u,setAnchors:f,sourceObjects:m}=mi.createNodeAnchors(this,o||"a"),w={aliasDuplicateObjects:s??!0,keepUndefined:c??!1,onAnchor:u,onTagObj:l,replacer:i,schema:this.schema,sourceObjects:m},p=ld.createNode(e,d,w);return a&&Y.isCollection(p)&&(p.flow=!0),f(),p}createPair(e,n,r={}){let i=this.createNode(e,null,r),s=this.createNode(n,null,r);return new id.Pair(i,s)}delete(e){return Fe(this.contents)?this.contents.delete(e):!1}deleteIn(e){return Me.isEmptyPath(e)?this.contents==null?!1:(this.contents=null,!0):Fe(this.contents)?this.contents.deleteIn(e):!1}get(e,n){return Y.isCollection(this.contents)?this.contents.get(e,n):void 0}getIn(e,n){return Me.isEmptyPath(e)?!n&&Y.isScalar(this.contents)?this.contents.value:this.contents:Y.isCollection(this.contents)?this.contents.getIn(e,n):void 0}has(e){return Y.isCollection(this.contents)?this.contents.has(e):!1}hasIn(e){return Me.isEmptyPath(e)?this.contents!==void 0:Y.isCollection(this.contents)?this.contents.hasIn(e):!1}set(e,n){this.contents==null?this.contents=Me.collectionFromPath(this.schema,[e],n):Fe(this.contents)&&this.contents.set(e,n)}setIn(e,n){Me.isEmptyPath(e)?this.contents=n:this.contents==null?this.contents=Me.collectionFromPath(this.schema,Array.from(e),n):Fe(this.contents)&&this.contents.setIn(e,n)}setSchema(e,n={}){typeof e=="number"&&(e=String(e));let r;switch(e){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new gi.Directives({version:"1.1"}),r={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=e:this.directives=new gi.Directives({version:e}),r={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,r=null;break;default:{let i=JSON.stringify(e);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${i}`)}}if(n.schema instanceof Object)this.schema=n.schema;else if(r)this.schema=new od.Schema(Object.assign(r,n));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:e,jsonArg:n,mapAsMap:r,maxAliasCount:i,onAnchor:s,reviver:o}={}){let a={anchors:new Map,doc:this,keep:!e,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},c=sd.toJS(this.contents,n??"",a);if(typeof s=="function")for(let{count:l,res:d}of a.anchors.values())s(d,l);return typeof o=="function"?cd.applyReviver(o,{"":c},"",c):c}toJSON(e,n){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:n})}toString(e={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let n=JSON.stringify(e.indent);throw new Error(`"indent" option must be a positive integer, not ${n}`)}return ad.stringifyDocument(this,e)}};function Fe(t){if(Y.isCollection(t))return!0;throw new Error("Expected a YAML collection as document contents")}ca.Document=wi});var yt=g(wt=>{"use strict";var gt=class extends Error{constructor(e,n,r,i){super(),this.name=e,this.code=r,this.message=i,this.pos=n}},yi=class extends gt{constructor(e,n,r){super("YAMLParseError",e,n,r)}},bi=class extends gt{constructor(e,n,r){super("YAMLWarning",e,n,r)}},ud=(t,e)=>n=>{if(n.pos[0]===-1)return;n.linePos=n.pos.map(a=>e.linePos(a));let{line:r,col:i}=n.linePos[0];n.message+=` at line ${r}, column ${i}`;let s=i-1,o=t.substring(e.lineStarts[r-1],e.lineStarts[r]).replace(/[\n\r]+$/,"");if(s>=60&&o.length>80){let a=Math.min(s-39,o.length-79);o="…"+o.substring(a),s-=a-1}if(o.length>80&&(o=o.substring(0,79)+"…"),r>1&&/^ *$/.test(o.substring(0,s))){let a=t.substring(e.lineStarts[r-2],e.lineStarts[r-1]);a.length>80&&(a=a.substring(0,79)+`… +`}sa.stringifyDocument=td});var mt=g(aa=>{"use strict";var nd=Ze(),Me=Xt(),Y=_(),rd=ue(),id=oe(),sd=pi(),od=oa(),mi=Jt(),ad=br(),cd=et(),gi=yr(),wi=class t{constructor(e,n,r){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,Y.NODE_TYPE,{value:Y.DOC});let i=null;typeof n=="function"||Array.isArray(n)?i=n:r===void 0&&n&&(r=n,n=void 0);let s=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},r);this.options=s;let{version:o}=s;r?._directives?(this.directives=r._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new gi.Directives({version:o}),this.setSchema(o,r),this.contents=e===void 0?null:this.createNode(e,i,r)}clone(){let e=Object.create(t.prototype,{[Y.NODE_TYPE]:{value:Y.DOC}});return e.commentBefore=this.commentBefore,e.comment=this.comment,e.errors=this.errors.slice(),e.warnings=this.warnings.slice(),e.options=Object.assign({},this.options),this.directives&&(e.directives=this.directives.clone()),e.schema=this.schema.clone(),e.contents=Y.isNode(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){Fe(this.contents)&&this.contents.add(e)}addIn(e,n){Fe(this.contents)&&this.contents.addIn(e,n)}createAlias(e,n){if(!e.anchor){let r=mi.anchorNames(this);e.anchor=!n||r.has(n)?mi.findNewAnchor(n||"a",r):n}return new nd.Alias(e.anchor)}createNode(e,n,r){let i;if(typeof n=="function")e=n.call({"":e},"",e),i=n;else if(Array.isArray(n)){let h=v=>typeof v=="number"||v instanceof String||v instanceof Number,y=n.filter(h).map(String);y.length>0&&(n=n.concat(y)),i=n}else r===void 0&&n&&(r=n,n=void 0);let{aliasDuplicateObjects:s,anchorPrefix:o,flow:a,keepUndefined:c,onTagObj:l,tag:d}=r??{},{onAnchor:u,setAnchors:f,sourceObjects:m}=mi.createNodeAnchors(this,o||"a"),w={aliasDuplicateObjects:s??!0,keepUndefined:c??!1,onAnchor:u,onTagObj:l,replacer:i,schema:this.schema,sourceObjects:m},p=cd.createNode(e,d,w);return a&&Y.isCollection(p)&&(p.flow=!0),f(),p}createPair(e,n,r={}){let i=this.createNode(e,null,r),s=this.createNode(n,null,r);return new rd.Pair(i,s)}delete(e){return Fe(this.contents)?this.contents.delete(e):!1}deleteIn(e){return Me.isEmptyPath(e)?this.contents==null?!1:(this.contents=null,!0):Fe(this.contents)?this.contents.deleteIn(e):!1}get(e,n){return Y.isCollection(this.contents)?this.contents.get(e,n):void 0}getIn(e,n){return Me.isEmptyPath(e)?!n&&Y.isScalar(this.contents)?this.contents.value:this.contents:Y.isCollection(this.contents)?this.contents.getIn(e,n):void 0}has(e){return Y.isCollection(this.contents)?this.contents.has(e):!1}hasIn(e){return Me.isEmptyPath(e)?this.contents!==void 0:Y.isCollection(this.contents)?this.contents.hasIn(e):!1}set(e,n){this.contents==null?this.contents=Me.collectionFromPath(this.schema,[e],n):Fe(this.contents)&&this.contents.set(e,n)}setIn(e,n){Me.isEmptyPath(e)?this.contents=n:this.contents==null?this.contents=Me.collectionFromPath(this.schema,Array.from(e),n):Fe(this.contents)&&this.contents.setIn(e,n)}setSchema(e,n={}){typeof e=="number"&&(e=String(e));let r;switch(e){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new gi.Directives({version:"1.1"}),r={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=e:this.directives=new gi.Directives({version:e}),r={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,r=null;break;default:{let i=JSON.stringify(e);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${i}`)}}if(n.schema instanceof Object)this.schema=n.schema;else if(r)this.schema=new sd.Schema(Object.assign(r,n));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:e,jsonArg:n,mapAsMap:r,maxAliasCount:i,onAnchor:s,reviver:o}={}){let a={anchors:new Map,doc:this,keep:!e,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},c=id.toJS(this.contents,n??"",a);if(typeof s=="function")for(let{count:l,res:d}of a.anchors.values())s(d,l);return typeof o=="function"?ad.applyReviver(o,{"":c},"",c):c}toJSON(e,n){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:n})}toString(e={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let n=JSON.stringify(e.indent);throw new Error(`"indent" option must be a positive integer, not ${n}`)}return od.stringifyDocument(this,e)}};function Fe(t){if(Y.isCollection(t))return!0;throw new Error("Expected a YAML collection as document contents")}aa.Document=wi});var yt=g(wt=>{"use strict";var gt=class extends Error{constructor(e,n,r,i){super(),this.name=e,this.code=r,this.message=i,this.pos=n}},yi=class extends gt{constructor(e,n,r){super("YAMLParseError",e,n,r)}},bi=class extends gt{constructor(e,n,r){super("YAMLWarning",e,n,r)}},ld=(t,e)=>n=>{if(n.pos[0]===-1)return;n.linePos=n.pos.map(a=>e.linePos(a));let{line:r,col:i}=n.linePos[0];n.message+=` at line ${r}, column ${i}`;let s=i-1,o=t.substring(e.lineStarts[r-1],e.lineStarts[r]).replace(/[\n\r]+$/,"");if(s>=60&&o.length>80){let a=Math.min(s-39,o.length-79);o="…"+o.substring(a),s-=a-1}if(o.length>80&&(o=o.substring(0,79)+"…"),r>1&&/^ *$/.test(o.substring(0,s))){let a=t.substring(e.lineStarts[r-2],e.lineStarts[r-1]);a.length>80&&(a=a.substring(0,79)+`… `),o=a+o}if(/[^ ]/.test(o)){let a=1,c=n.linePos[1];c?.line===r&&c.col>i&&(a=Math.max(1,Math.min(c.col-i,80-s)));let l=" ".repeat(s)+"^".repeat(a);n.message+=`: ${o} ${l} -`}};wt.YAMLError=gt;wt.YAMLParseError=yi;wt.YAMLWarning=bi;wt.prettifyError=ud});var bt=g(la=>{"use strict";function fd(t,{flow:e,indicator:n,next:r,offset:i,onError:s,parentIndent:o,startOnNewline:a}){let c=!1,l=a,d=a,u="",f="",m=!1,w=!1,p=null,h=null,y=null,v=null,k=null,S=null,C=null;for(let b of t)switch(w&&(b.type!=="space"&&b.type!=="newline"&&b.type!=="comma"&&s(b.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),w=!1),p&&(l&&b.type!=="comment"&&b.type!=="newline"&&s(p,"TAB_AS_INDENT","Tabs are not allowed as indentation"),p=null),b.type){case"space":!e&&(n!=="doc-start"||r?.type!=="flow-collection")&&b.source.includes(" ")&&(p=b),d=!0;break;case"comment":{d||s(b,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let x=b.source.substring(1)||" ";u?u+=f+x:u=x,f="",l=!1;break}case"newline":l?u?u+=b.source:(!S||n!=="seq-item-ind")&&(c=!0):f+=b.source,l=!0,m=!0,(h||y)&&(v=b),d=!0;break;case"anchor":h&&s(b,"MULTIPLE_ANCHORS","A node can have at most one anchor"),b.source.endsWith(":")&&s(b.offset+b.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),h=b,C??(C=b.offset),l=!1,d=!1,w=!0;break;case"tag":{y&&s(b,"MULTIPLE_TAGS","A node can have at most one tag"),y=b,C??(C=b.offset),l=!1,d=!1,w=!0;break}case n:(h||y)&&s(b,"BAD_PROP_ORDER",`Anchors and tags must be after the ${b.source} indicator`),S&&s(b,"UNEXPECTED_TOKEN",`Unexpected ${b.source} in ${e??"collection"}`),S=b,l=n==="seq-item-ind"||n==="explicit-key-ind",d=!1;break;case"comma":if(e){k&&s(b,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),k=b,l=!1,d=!1;break}default:s(b,"UNEXPECTED_TOKEN",`Unexpected ${b.type} token`),l=!1,d=!1}let E=t[t.length-1],O=E?E.offset+E.source.length:i;return w&&r&&r.type!=="space"&&r.type!=="newline"&&r.type!=="comma"&&(r.type!=="scalar"||r.source!=="")&&s(r.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),p&&(l&&p.indent<=o||r?.type==="block-map"||r?.type==="block-seq")&&s(p,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:k,found:S,spaceBefore:c,comment:u,hasNewline:m,anchor:h,tag:y,newlineAfterProp:v,end:O,start:C??O}}la.resolveProps=fd});var In=g(ua=>{"use strict";function vi(t){if(!t)return null;switch(t.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(t.source.includes(` -`))return!0;if(t.end){for(let e of t.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(let e of t.items){for(let n of e.start)if(n.type==="newline")return!0;if(e.sep){for(let n of e.sep)if(n.type==="newline")return!0}if(vi(e.key)||vi(e.value))return!0}return!1;default:return!0}}ua.containsNewline=vi});var ki=g(fa=>{"use strict";var dd=In();function pd(t,e,n){if(e?.type==="flow-collection"){let r=e.end[0];r.indent===t&&(r.source==="]"||r.source==="}")&&dd.containsNewline(e)&&n(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}fa.flowIndentCheck=pd});var Si=g(pa=>{"use strict";var da=_();function hd(t,e,n){let{uniqueKeys:r}=t.options;if(r===!1)return!1;let i=typeof r=="function"?r:(s,o)=>s===o||da.isScalar(s)&&da.isScalar(o)&&s.value===o.value;return e.some(s=>i(s.key,n))}pa.mapIncludes=hd});var ba=g(ya=>{"use strict";var ha=ue(),md=de(),ma=bt(),gd=In(),ga=ki(),wd=Si(),wa="All mapping items must start at the same column";function yd({composeNode:t,composeEmptyNode:e},n,r,i,s){let o=s?.nodeClass??md.YAMLMap,a=new o(n.schema);n.atRoot&&(n.atRoot=!1);let c=r.offset,l=null;for(let d of r.items){let{start:u,key:f,sep:m,value:w}=d,p=ma.resolveProps(u,{indicator:"explicit-key-ind",next:f??m?.[0],offset:c,onError:i,parentIndent:r.indent,startOnNewline:!0}),h=!p.found;if(h){if(f&&(f.type==="block-seq"?i(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in f&&f.indent!==r.indent&&i(c,"BAD_INDENT",wa)),!p.anchor&&!p.tag&&!m){l=p.end,p.comment&&(a.comment?a.comment+=` -`+p.comment:a.comment=p.comment);continue}(p.newlineAfterProp||gd.containsNewline(f))&&i(f??u[u.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else p.found?.indent!==r.indent&&i(c,"BAD_INDENT",wa);n.atKey=!0;let y=p.end,v=f?t(n,f,p,i):e(n,y,u,null,p,i);n.schema.compat&&ga.flowIndentCheck(r.indent,f,i),n.atKey=!1,wd.mapIncludes(n,a.items,v)&&i(y,"DUPLICATE_KEY","Map keys must be unique");let k=ma.resolveProps(m??[],{indicator:"map-value-ind",next:w,offset:v.range[2],onError:i,parentIndent:r.indent,startOnNewline:!f||f.type==="block-scalar"});if(c=k.end,k.found){h&&(w?.type==="block-map"&&!k.hasNewline&&i(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),n.options.strict&&p.start{"use strict";var bd=pe(),vd=bt(),kd=ki();function Sd({composeNode:t,composeEmptyNode:e},n,r,i,s){let o=s?.nodeClass??bd.YAMLSeq,a=new o(n.schema);n.atRoot&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let c=r.offset,l=null;for(let{start:d,value:u}of r.items){let f=vd.resolveProps(d,{indicator:"seq-item-ind",next:u,offset:c,onError:i,parentIndent:r.indent,startOnNewline:!0});if(!f.found)if(f.anchor||f.tag||u)u?.type==="block-seq"?i(f.end,"BAD_INDENT","All sequence items must start at the same column"):i(c,"MISSING_CHAR","Sequence item without - indicator");else{l=f.end,f.comment&&(a.comment=f.comment);continue}let m=u?t(n,u,f,i):e(n,f.end,d,null,f,i);n.schema.compat&&kd.flowIndentCheck(r.indent,u,i),c=m.range[2],a.items.push(m)}return a.range=[r.offset,c,l??c],a}va.resolveBlockSeq=Sd});var Be=g(Sa=>{"use strict";function Cd(t,e,n,r){let i="";if(t){let s=!1,o="";for(let a of t){let{source:c,type:l}=a;switch(l){case"space":s=!0;break;case"comment":{n&&!s&&r(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let d=c.substring(1)||" ";i?i+=o+d:i=d,o="";break}case"newline":i&&(o+=c),s=!0;break;default:r(a,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}e+=c.length}}return{comment:i,offset:e}}Sa.resolveEnd=Cd});var Pa=g(_a=>{"use strict";var Ed=_(),_d=ue(),Ca=de(),Pd=pe(),Od=Be(),Ea=bt(),Nd=In(),Ad=Si(),Ci="Block collections are not allowed within flow collections",Ei=t=>t&&(t.type==="block-map"||t.type==="block-seq");function xd({composeNode:t,composeEmptyNode:e},n,r,i,s){let o=r.start.source==="{",a=o?"flow map":"flow sequence",c=s?.nodeClass??(o?Ca.YAMLMap:Pd.YAMLSeq),l=new c(n.schema);l.flow=!0;let d=n.atRoot;d&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let u=r.offset+r.start.source.length;for(let h=0;h0){let h=Od.resolveEnd(w,p,n.options.strict,i);h.comment&&(l.comment?l.comment+=` -`+h.comment:l.comment=h.comment),l.range=[r.offset,p,h.offset]}else l.range=[r.offset,p,p];return l}_a.resolveFlowCollection=xd});var Na=g(Oa=>{"use strict";var Td=_(),Rd=N(),Id=de(),jd=pe(),Ld=ba(),qd=ka(),Dd=Pa();function _i(t,e,n,r,i,s){let o=n.type==="block-map"?Ld.resolveBlockMap(t,e,n,r,s):n.type==="block-seq"?qd.resolveBlockSeq(t,e,n,r,s):Dd.resolveFlowCollection(t,e,n,r,s),a=o.constructor;return i==="!"||i===a.tagName?(o.tag=a.tagName,o):(i&&(o.tag=i),o)}function $d(t,e,n,r,i){let s=r.tag,o=s?e.directives.tagName(s.source,f=>i(s,"TAG_RESOLVE_FAILED",f)):null;if(n.type==="block-seq"){let{anchor:f,newlineAfterProp:m}=r,w=f&&s?f.offset>s.offset?f:s:f??s;w&&(!m||m.offsetf.tag===o&&f.collection===a);if(!c){let f=e.schema.knownTags[o];if(f?.collection===a)e.schema.tags.push(Object.assign({},f,{default:!1})),c=f;else return f?i(s,"BAD_COLLECTION_TYPE",`${f.tag} used for ${a} collection, but expects ${f.collection??"scalar"}`,!0):i(s,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),_i(t,e,n,i,o)}let l=_i(t,e,n,i,o,c),d=c.resolve?.(l,f=>i(s,"TAG_RESOLVE_FAILED",f),e.options)??l,u=Td.isNode(d)?d:new Rd.Scalar(d);return u.range=l.range,u.tag=o,c?.format&&(u.format=c.format),u}Oa.composeCollection=$d});var Oi=g(Aa=>{"use strict";var Pi=N();function Wd(t,e,n){let r=e.offset,i=Md(e,t.options.strict,n);if(!i)return{value:"",type:null,comment:"",range:[r,r,r]};let s=i.mode===">"?Pi.Scalar.BLOCK_FOLDED:Pi.Scalar.BLOCK_LITERAL,o=e.source?Fd(e.source):[],a=o.length;for(let p=o.length-1;p>=0;--p){let h=o[p][1];if(h===""||h==="\r")a=p;else break}if(a===0){let p=i.chomp==="+"&&o.length>0?` +`}};wt.YAMLError=gt;wt.YAMLParseError=yi;wt.YAMLWarning=bi;wt.prettifyError=ld});var bt=g(ca=>{"use strict";function ud(t,{flow:e,indicator:n,next:r,offset:i,onError:s,parentIndent:o,startOnNewline:a}){let c=!1,l=a,d=a,u="",f="",m=!1,w=!1,p=null,h=null,y=null,v=null,k=null,S=null,C=null;for(let b of t)switch(w&&(b.type!=="space"&&b.type!=="newline"&&b.type!=="comma"&&s(b.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),w=!1),p&&(l&&b.type!=="comment"&&b.type!=="newline"&&s(p,"TAB_AS_INDENT","Tabs are not allowed as indentation"),p=null),b.type){case"space":!e&&(n!=="doc-start"||r?.type!=="flow-collection")&&b.source.includes(" ")&&(p=b),d=!0;break;case"comment":{d||s(b,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let x=b.source.substring(1)||" ";u?u+=f+x:u=x,f="",l=!1;break}case"newline":l?u?u+=b.source:(!S||n!=="seq-item-ind")&&(c=!0):f+=b.source,l=!0,m=!0,(h||y)&&(v=b),d=!0;break;case"anchor":h&&s(b,"MULTIPLE_ANCHORS","A node can have at most one anchor"),b.source.endsWith(":")&&s(b.offset+b.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),h=b,C??(C=b.offset),l=!1,d=!1,w=!0;break;case"tag":{y&&s(b,"MULTIPLE_TAGS","A node can have at most one tag"),y=b,C??(C=b.offset),l=!1,d=!1,w=!0;break}case n:(h||y)&&s(b,"BAD_PROP_ORDER",`Anchors and tags must be after the ${b.source} indicator`),S&&s(b,"UNEXPECTED_TOKEN",`Unexpected ${b.source} in ${e??"collection"}`),S=b,l=n==="seq-item-ind"||n==="explicit-key-ind",d=!1;break;case"comma":if(e){k&&s(b,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),k=b,l=!1,d=!1;break}default:s(b,"UNEXPECTED_TOKEN",`Unexpected ${b.type} token`),l=!1,d=!1}let E=t[t.length-1],O=E?E.offset+E.source.length:i;return w&&r&&r.type!=="space"&&r.type!=="newline"&&r.type!=="comma"&&(r.type!=="scalar"||r.source!=="")&&s(r.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),p&&(l&&p.indent<=o||r?.type==="block-map"||r?.type==="block-seq")&&s(p,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:k,found:S,spaceBefore:c,comment:u,hasNewline:m,anchor:h,tag:y,newlineAfterProp:v,end:O,start:C??O}}ca.resolveProps=ud});var In=g(la=>{"use strict";function vi(t){if(!t)return null;switch(t.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(t.source.includes(` +`))return!0;if(t.end){for(let e of t.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(let e of t.items){for(let n of e.start)if(n.type==="newline")return!0;if(e.sep){for(let n of e.sep)if(n.type==="newline")return!0}if(vi(e.key)||vi(e.value))return!0}return!1;default:return!0}}la.containsNewline=vi});var ki=g(ua=>{"use strict";var fd=In();function dd(t,e,n){if(e?.type==="flow-collection"){let r=e.end[0];r.indent===t&&(r.source==="]"||r.source==="}")&&fd.containsNewline(e)&&n(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}ua.flowIndentCheck=dd});var Si=g(da=>{"use strict";var fa=_();function pd(t,e,n){let{uniqueKeys:r}=t.options;if(r===!1)return!1;let i=typeof r=="function"?r:(s,o)=>s===o||fa.isScalar(s)&&fa.isScalar(o)&&s.value===o.value;return e.some(s=>i(s.key,n))}da.mapIncludes=pd});var ya=g(wa=>{"use strict";var pa=ue(),hd=de(),ha=bt(),md=In(),ma=ki(),gd=Si(),ga="All mapping items must start at the same column";function wd({composeNode:t,composeEmptyNode:e},n,r,i,s){let o=s?.nodeClass??hd.YAMLMap,a=new o(n.schema);n.atRoot&&(n.atRoot=!1);let c=r.offset,l=null;for(let d of r.items){let{start:u,key:f,sep:m,value:w}=d,p=ha.resolveProps(u,{indicator:"explicit-key-ind",next:f??m?.[0],offset:c,onError:i,parentIndent:r.indent,startOnNewline:!0}),h=!p.found;if(h){if(f&&(f.type==="block-seq"?i(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in f&&f.indent!==r.indent&&i(c,"BAD_INDENT",ga)),!p.anchor&&!p.tag&&!m){l=p.end,p.comment&&(a.comment?a.comment+=` +`+p.comment:a.comment=p.comment);continue}(p.newlineAfterProp||md.containsNewline(f))&&i(f??u[u.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else p.found?.indent!==r.indent&&i(c,"BAD_INDENT",ga);n.atKey=!0;let y=p.end,v=f?t(n,f,p,i):e(n,y,u,null,p,i);n.schema.compat&&ma.flowIndentCheck(r.indent,f,i),n.atKey=!1,gd.mapIncludes(n,a.items,v)&&i(y,"DUPLICATE_KEY","Map keys must be unique");let k=ha.resolveProps(m??[],{indicator:"map-value-ind",next:w,offset:v.range[2],onError:i,parentIndent:r.indent,startOnNewline:!f||f.type==="block-scalar"});if(c=k.end,k.found){h&&(w?.type==="block-map"&&!k.hasNewline&&i(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),n.options.strict&&p.start{"use strict";var yd=pe(),bd=bt(),vd=ki();function kd({composeNode:t,composeEmptyNode:e},n,r,i,s){let o=s?.nodeClass??yd.YAMLSeq,a=new o(n.schema);n.atRoot&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let c=r.offset,l=null;for(let{start:d,value:u}of r.items){let f=bd.resolveProps(d,{indicator:"seq-item-ind",next:u,offset:c,onError:i,parentIndent:r.indent,startOnNewline:!0});if(!f.found)if(f.anchor||f.tag||u)u?.type==="block-seq"?i(f.end,"BAD_INDENT","All sequence items must start at the same column"):i(c,"MISSING_CHAR","Sequence item without - indicator");else{l=f.end,f.comment&&(a.comment=f.comment);continue}let m=u?t(n,u,f,i):e(n,f.end,d,null,f,i);n.schema.compat&&vd.flowIndentCheck(r.indent,u,i),c=m.range[2],a.items.push(m)}return a.range=[r.offset,c,l??c],a}ba.resolveBlockSeq=kd});var Be=g(ka=>{"use strict";function Sd(t,e,n,r){let i="";if(t){let s=!1,o="";for(let a of t){let{source:c,type:l}=a;switch(l){case"space":s=!0;break;case"comment":{n&&!s&&r(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let d=c.substring(1)||" ";i?i+=o+d:i=d,o="";break}case"newline":i&&(o+=c),s=!0;break;default:r(a,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}e+=c.length}}return{comment:i,offset:e}}ka.resolveEnd=Sd});var _a=g(Ea=>{"use strict";var Cd=_(),Ed=ue(),Sa=de(),_d=pe(),Pd=Be(),Ca=bt(),Od=In(),Nd=Si(),Ci="Block collections are not allowed within flow collections",Ei=t=>t&&(t.type==="block-map"||t.type==="block-seq");function Ad({composeNode:t,composeEmptyNode:e},n,r,i,s){let o=r.start.source==="{",a=o?"flow map":"flow sequence",c=s?.nodeClass??(o?Sa.YAMLMap:_d.YAMLSeq),l=new c(n.schema);l.flow=!0;let d=n.atRoot;d&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let u=r.offset+r.start.source.length;for(let h=0;h0){let h=Pd.resolveEnd(w,p,n.options.strict,i);h.comment&&(l.comment?l.comment+=` +`+h.comment:l.comment=h.comment),l.range=[r.offset,p,h.offset]}else l.range=[r.offset,p,p];return l}Ea.resolveFlowCollection=Ad});var Oa=g(Pa=>{"use strict";var xd=_(),Td=N(),Rd=de(),Id=pe(),jd=ya(),Ld=va(),qd=_a();function _i(t,e,n,r,i,s){let o=n.type==="block-map"?jd.resolveBlockMap(t,e,n,r,s):n.type==="block-seq"?Ld.resolveBlockSeq(t,e,n,r,s):qd.resolveFlowCollection(t,e,n,r,s),a=o.constructor;return i==="!"||i===a.tagName?(o.tag=a.tagName,o):(i&&(o.tag=i),o)}function Dd(t,e,n,r,i){let s=r.tag,o=s?e.directives.tagName(s.source,f=>i(s,"TAG_RESOLVE_FAILED",f)):null;if(n.type==="block-seq"){let{anchor:f,newlineAfterProp:m}=r,w=f&&s?f.offset>s.offset?f:s:f??s;w&&(!m||m.offsetf.tag===o&&f.collection===a);if(!c){let f=e.schema.knownTags[o];if(f?.collection===a)e.schema.tags.push(Object.assign({},f,{default:!1})),c=f;else return f?i(s,"BAD_COLLECTION_TYPE",`${f.tag} used for ${a} collection, but expects ${f.collection??"scalar"}`,!0):i(s,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),_i(t,e,n,i,o)}let l=_i(t,e,n,i,o,c),d=c.resolve?.(l,f=>i(s,"TAG_RESOLVE_FAILED",f),e.options)??l,u=xd.isNode(d)?d:new Td.Scalar(d);return u.range=l.range,u.tag=o,c?.format&&(u.format=c.format),u}Pa.composeCollection=Dd});var Oi=g(Na=>{"use strict";var Pi=N();function $d(t,e,n){let r=e.offset,i=Wd(e,t.options.strict,n);if(!i)return{value:"",type:null,comment:"",range:[r,r,r]};let s=i.mode===">"?Pi.Scalar.BLOCK_FOLDED:Pi.Scalar.BLOCK_LITERAL,o=e.source?Md(e.source):[],a=o.length;for(let p=o.length-1;p>=0;--p){let h=o[p][1];if(h===""||h==="\r")a=p;else break}if(a===0){let p=i.chomp==="+"&&o.length>0?` `.repeat(Math.max(1,o.length-1)):"",h=r+i.length;return e.source&&(h+=e.source.length),{value:p,type:s,comment:i.comment,range:[r,h,h]}}let c=e.indent+i.indent,l=e.offset+i.length,d=0;for(let p=0;pc&&(c=h.length);else{h.length=a;--p)o[p][0].length>c&&(a=p+1);let u="",f="",m=!1;for(let p=0;pc||y[0]===" "?(f===" "?f=` @@ -84,41 +84,41 @@ ${l} `+o[p][0].slice(c);u[u.length-1]!==` `&&(u+=` `);break;default:u+=` -`}let w=r+i.length+e.source.length;return{value:u,type:s,comment:i.comment,range:[r,w,w]}}function Md({offset:t,props:e},n,r){if(e[0].type!=="block-scalar-header")return r(e[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:i}=e[0],s=i[0],o=0,a="",c=-1;for(let f=1;f{"use strict";var Ni=N(),Bd=Be();function Kd(t,e,n){let{offset:r,type:i,source:s,end:o}=t,a,c,l=(f,m,w)=>n(r+f,m,w);switch(i){case"scalar":a=Ni.Scalar.PLAIN,c=Yd(s,l);break;case"single-quoted-scalar":a=Ni.Scalar.QUOTE_SINGLE,c=Ud(s,l);break;case"double-quoted-scalar":a=Ni.Scalar.QUOTE_DOUBLE,c=Hd(s,l);break;default:return n(t,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${i}`),{value:"",type:null,comment:"",range:[r,r+s.length,r+s.length]}}let d=r+s.length,u=Bd.resolveEnd(o,d,e,n);return{value:c,type:a,comment:u.comment,range:[r,d,u.offset]}}function Yd(t,e){let n="";switch(t[0]){case" ":n="a tab character";break;case",":n="flow indicator character ,";break;case"%":n="directive indicator character %";break;case"|":case">":{n=`block scalar indicator ${t[0]}`;break}case"@":case"`":{n=`reserved character ${t[0]}`;break}}return n&&e(0,"BAD_SCALAR_START",`Plain value cannot start with ${n}`),xa(t)}function Ud(t,e){return(t[t.length-1]!=="'"||t.length===1)&&e(t.length,"MISSING_CHAR","Missing closing 'quote"),xa(t.slice(1,-1)).replace(/''/g,"'")}function xa(t){let e,n;try{e=new RegExp(`(.*?)(?{"use strict";var Ni=N(),Fd=Be();function Bd(t,e,n){let{offset:r,type:i,source:s,end:o}=t,a,c,l=(f,m,w)=>n(r+f,m,w);switch(i){case"scalar":a=Ni.Scalar.PLAIN,c=Kd(s,l);break;case"single-quoted-scalar":a=Ni.Scalar.QUOTE_SINGLE,c=Yd(s,l);break;case"double-quoted-scalar":a=Ni.Scalar.QUOTE_DOUBLE,c=Ud(s,l);break;default:return n(t,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${i}`),{value:"",type:null,comment:"",range:[r,r+s.length,r+s.length]}}let d=r+s.length,u=Fd.resolveEnd(o,d,e,n);return{value:c,type:a,comment:u.comment,range:[r,d,u.offset]}}function Kd(t,e){let n="";switch(t[0]){case" ":n="a tab character";break;case",":n="flow indicator character ,";break;case"%":n="directive indicator character %";break;case"|":case">":{n=`block scalar indicator ${t[0]}`;break}case"@":case"`":{n=`reserved character ${t[0]}`;break}}return n&&e(0,"BAD_SCALAR_START",`Plain value cannot start with ${n}`),Aa(t)}function Yd(t,e){return(t[t.length-1]!=="'"||t.length===1)&&e(t.length,"MISSING_CHAR","Missing closing 'quote"),Aa(t.slice(1,-1)).replace(/''/g,"'")}function Aa(t){let e,n;try{e=new RegExp(`(.*?)(?s?t.slice(s,r+1):i)}else n+=i}return(t[t.length-1]!=='"'||t.length===1)&&e(t.length,"MISSING_CHAR",'Missing closing "quote'),n}function Jd(t,e){let n="",r=t[e+1];for(;(r===" "||r===" "||r===` +`)&&(n+=r>s?t.slice(s,r+1):i)}else n+=i}return(t[t.length-1]!=='"'||t.length===1)&&e(t.length,"MISSING_CHAR",'Missing closing "quote'),n}function Hd(t,e){let n="",r=t[e+1];for(;(r===" "||r===" "||r===` `||r==="\r")&&!(r==="\r"&&t[e+2]!==` `);)r===` `&&(n+=` -`),e+=1,r=t[e+1];return n||(n=" "),{fold:n,offset:e}}var Vd={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:` -`,r:"\r",t:" ",v:"\v",N:"…",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function Gd(t,e,n,r){let i=t.substr(e,n),o=i.length===n&&/^[0-9a-fA-F]+$/.test(i)?parseInt(i,16):NaN;try{return String.fromCodePoint(o)}catch{let a=t.substr(e-2,n+2);return r(e-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),a}}Ta.resolveFlowScalar=Kd});var ja=g(Ia=>{"use strict";var _e=_(),Ra=N(),zd=Oi(),Xd=Ai();function Qd(t,e,n,r){let{value:i,type:s,comment:o,range:a}=e.type==="block-scalar"?zd.resolveBlockScalar(t,e,r):Xd.resolveFlowScalar(e,t.options.strict,r),c=n?t.directives.tagName(n.source,u=>r(n,"TAG_RESOLVE_FAILED",u)):null,l;t.options.stringKeys&&t.atKey?l=t.schema[_e.SCALAR]:c?l=Zd(t.schema,i,c,n,r):e.type==="scalar"?l=ep(t,i,e,r):l=t.schema[_e.SCALAR];let d;try{let u=l.resolve(i,f=>r(n??e,"TAG_RESOLVE_FAILED",f),t.options);d=_e.isScalar(u)?u:new Ra.Scalar(u)}catch(u){let f=u instanceof Error?u.message:String(u);r(n??e,"TAG_RESOLVE_FAILED",f),d=new Ra.Scalar(i)}return d.range=a,d.source=i,s&&(d.type=s),c&&(d.tag=c),l.format&&(d.format=l.format),o&&(d.comment=o),d}function Zd(t,e,n,r,i){if(n==="!")return t[_e.SCALAR];let s=[];for(let a of t.tags)if(!a.collection&&a.tag===n)if(a.default&&a.test)s.push(a);else return a;for(let a of s)if(a.test?.test(e))return a;let o=t.knownTags[n];return o&&!o.collection?(t.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(i(r,"TAG_RESOLVE_FAILED",`Unresolved tag: ${n}`,n!=="tag:yaml.org,2002:str"),t[_e.SCALAR])}function ep({atKey:t,directives:e,schema:n},r,i,s){let o=n.tags.find(a=>(a.default===!0||t&&a.default==="key")&&a.test?.test(r))||n[_e.SCALAR];if(n.compat){let a=n.compat.find(c=>c.default&&c.test?.test(r))??n[_e.SCALAR];if(o.tag!==a.tag){let c=e.tagString(o.tag),l=e.tagString(a.tag),d=`Value may be parsed as either ${c} or ${l}`;s(i,"TAG_RESOLVE_FAILED",d,!0)}}return o}Ia.composeScalar=Qd});var qa=g(La=>{"use strict";function tp(t,e,n){if(e){n??(n=e.length);for(let r=n-1;r>=0;--r){let i=e[r];switch(i.type){case"space":case"comment":case"newline":t-=i.source.length;continue}for(i=e[++r];i?.type==="space";)t+=i.source.length,i=e[++r];break}}return t}La.emptyScalarPosition=tp});var Wa=g(Ti=>{"use strict";var np=Ze(),rp=_(),ip=Na(),Da=ja(),sp=Be(),op=qa(),ap={composeNode:$a,composeEmptyNode:xi};function $a(t,e,n,r){let i=t.atKey,{spaceBefore:s,comment:o,anchor:a,tag:c}=n,l,d=!0;switch(e.type){case"alias":l=cp(t,e,r),(a||c)&&r(e,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=Da.composeScalar(t,e,c,r),a&&(l.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=ip.composeCollection(ap,t,e,n,r),a&&(l.anchor=a.source.substring(1))}catch(u){let f=u instanceof Error?u.message:String(u);r(e,"RESOURCE_EXHAUSTION",f)}break;default:{let u=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;r(e,"UNEXPECTED_TOKEN",u),d=!1}}return l??(l=xi(t,e.offset,void 0,null,n,r)),a&&l.anchor===""&&r(a,"BAD_ALIAS","Anchor cannot be an empty string"),i&&t.options.stringKeys&&(!rp.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&r(c??e,"NON_STRING_KEY","With stringKeys, all keys must be strings"),s&&(l.spaceBefore=!0),o&&(e.type==="scalar"&&e.source===""?l.comment=o:l.commentBefore=o),t.options.keepSourceTokens&&d&&(l.srcToken=e),l}function xi(t,e,n,r,{spaceBefore:i,comment:s,anchor:o,tag:a,end:c},l){let d={type:"scalar",offset:op.emptyScalarPosition(e,n,r),indent:-1,source:""},u=Da.composeScalar(t,d,a,l);return o&&(u.anchor=o.source.substring(1),u.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),i&&(u.spaceBefore=!0),s&&(u.comment=s,u.range[2]=c),u}function cp({options:t},{offset:e,source:n,end:r},i){let s=new np.Alias(n.substring(1));s.source===""&&i(e,"BAD_ALIAS","Alias cannot be an empty string"),s.source.endsWith(":")&&i(e+n.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=e+n.length,a=sp.resolveEnd(r,o,t.strict,i);return s.range=[e,o,a.offset],a.comment&&(s.comment=a.comment),s}Ti.composeEmptyNode=xi;Ti.composeNode=$a});var Ba=g(Fa=>{"use strict";var lp=mt(),Ma=Wa(),up=Be(),fp=bt();function dp(t,e,{offset:n,start:r,value:i,end:s},o){let a=Object.assign({_directives:e},t),c=new lp.Document(void 0,a),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},d=fp.resolveProps(r,{indicator:"doc-start",next:i??s?.[0],offset:n,onError:o,parentIndent:0,startOnNewline:!0});d.found&&(c.directives.docStart=!0,i&&(i.type==="block-map"||i.type==="block-seq")&&!d.hasNewline&&o(d.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=i?Ma.composeNode(l,i,d,o):Ma.composeEmptyNode(l,d.end,r,null,d,o);let u=c.contents.range[2],f=up.resolveEnd(s,u,!1,o);return f.comment&&(c.comment=f.comment),c.range=[n,u,f.offset],c}Fa.composeDoc=dp});var Ii=g(Ua=>{"use strict";var pp=Ft("process"),hp=yr(),mp=mt(),vt=yt(),Ka=_(),gp=Ba(),wp=Be();function kt(t){if(typeof t=="number")return[t,t+1];if(Array.isArray(t))return t.length===2?t:[t[0],t[1]];let{offset:e,source:n}=t;return[e,e+(typeof n=="string"?n.length:1)]}function Ya(t){let e="",n=!1,r=!1;for(let i=0;i{"use strict";var _e=_(),Ta=N(),Gd=Oi(),zd=Ai();function Xd(t,e,n,r){let{value:i,type:s,comment:o,range:a}=e.type==="block-scalar"?Gd.resolveBlockScalar(t,e,r):zd.resolveFlowScalar(e,t.options.strict,r),c=n?t.directives.tagName(n.source,u=>r(n,"TAG_RESOLVE_FAILED",u)):null,l;t.options.stringKeys&&t.atKey?l=t.schema[_e.SCALAR]:c?l=Qd(t.schema,i,c,n,r):e.type==="scalar"?l=Zd(t,i,e,r):l=t.schema[_e.SCALAR];let d;try{let u=l.resolve(i,f=>r(n??e,"TAG_RESOLVE_FAILED",f),t.options);d=_e.isScalar(u)?u:new Ta.Scalar(u)}catch(u){let f=u instanceof Error?u.message:String(u);r(n??e,"TAG_RESOLVE_FAILED",f),d=new Ta.Scalar(i)}return d.range=a,d.source=i,s&&(d.type=s),c&&(d.tag=c),l.format&&(d.format=l.format),o&&(d.comment=o),d}function Qd(t,e,n,r,i){if(n==="!")return t[_e.SCALAR];let s=[];for(let a of t.tags)if(!a.collection&&a.tag===n)if(a.default&&a.test)s.push(a);else return a;for(let a of s)if(a.test?.test(e))return a;let o=t.knownTags[n];return o&&!o.collection?(t.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(i(r,"TAG_RESOLVE_FAILED",`Unresolved tag: ${n}`,n!=="tag:yaml.org,2002:str"),t[_e.SCALAR])}function Zd({atKey:t,directives:e,schema:n},r,i,s){let o=n.tags.find(a=>(a.default===!0||t&&a.default==="key")&&a.test?.test(r))||n[_e.SCALAR];if(n.compat){let a=n.compat.find(c=>c.default&&c.test?.test(r))??n[_e.SCALAR];if(o.tag!==a.tag){let c=e.tagString(o.tag),l=e.tagString(a.tag),d=`Value may be parsed as either ${c} or ${l}`;s(i,"TAG_RESOLVE_FAILED",d,!0)}}return o}Ra.composeScalar=Xd});var La=g(ja=>{"use strict";function ep(t,e,n){if(e){n??(n=e.length);for(let r=n-1;r>=0;--r){let i=e[r];switch(i.type){case"space":case"comment":case"newline":t-=i.source.length;continue}for(i=e[++r];i?.type==="space";)t+=i.source.length,i=e[++r];break}}return t}ja.emptyScalarPosition=ep});var $a=g(Ti=>{"use strict";var tp=Ze(),np=_(),rp=Oa(),qa=Ia(),ip=Be(),sp=La(),op={composeNode:Da,composeEmptyNode:xi};function Da(t,e,n,r){let i=t.atKey,{spaceBefore:s,comment:o,anchor:a,tag:c}=n,l,d=!0;switch(e.type){case"alias":l=ap(t,e,r),(a||c)&&r(e,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=qa.composeScalar(t,e,c,r),a&&(l.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=rp.composeCollection(op,t,e,n,r),a&&(l.anchor=a.source.substring(1))}catch(u){let f=u instanceof Error?u.message:String(u);r(e,"RESOURCE_EXHAUSTION",f)}break;default:{let u=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;r(e,"UNEXPECTED_TOKEN",u),d=!1}}return l??(l=xi(t,e.offset,void 0,null,n,r)),a&&l.anchor===""&&r(a,"BAD_ALIAS","Anchor cannot be an empty string"),i&&t.options.stringKeys&&(!np.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&r(c??e,"NON_STRING_KEY","With stringKeys, all keys must be strings"),s&&(l.spaceBefore=!0),o&&(e.type==="scalar"&&e.source===""?l.comment=o:l.commentBefore=o),t.options.keepSourceTokens&&d&&(l.srcToken=e),l}function xi(t,e,n,r,{spaceBefore:i,comment:s,anchor:o,tag:a,end:c},l){let d={type:"scalar",offset:sp.emptyScalarPosition(e,n,r),indent:-1,source:""},u=qa.composeScalar(t,d,a,l);return o&&(u.anchor=o.source.substring(1),u.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),i&&(u.spaceBefore=!0),s&&(u.comment=s,u.range[2]=c),u}function ap({options:t},{offset:e,source:n,end:r},i){let s=new tp.Alias(n.substring(1));s.source===""&&i(e,"BAD_ALIAS","Alias cannot be an empty string"),s.source.endsWith(":")&&i(e+n.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=e+n.length,a=ip.resolveEnd(r,o,t.strict,i);return s.range=[e,o,a.offset],a.comment&&(s.comment=a.comment),s}Ti.composeEmptyNode=xi;Ti.composeNode=Da});var Fa=g(Ma=>{"use strict";var cp=mt(),Wa=$a(),lp=Be(),up=bt();function fp(t,e,{offset:n,start:r,value:i,end:s},o){let a=Object.assign({_directives:e},t),c=new cp.Document(void 0,a),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},d=up.resolveProps(r,{indicator:"doc-start",next:i??s?.[0],offset:n,onError:o,parentIndent:0,startOnNewline:!0});d.found&&(c.directives.docStart=!0,i&&(i.type==="block-map"||i.type==="block-seq")&&!d.hasNewline&&o(d.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=i?Wa.composeNode(l,i,d,o):Wa.composeEmptyNode(l,d.end,r,null,d,o);let u=c.contents.range[2],f=lp.resolveEnd(s,u,!1,o);return f.comment&&(c.comment=f.comment),c.range=[n,u,f.offset],c}Ma.composeDoc=fp});var Ii=g(Ya=>{"use strict";var dp=Ft("process"),pp=yr(),hp=mt(),vt=yt(),Ba=_(),mp=Fa(),gp=Be();function kt(t){if(typeof t=="number")return[t,t+1];if(Array.isArray(t))return t.length===2?t:[t[0],t[1]];let{offset:e,source:n}=t;return[e,e+(typeof n=="string"?n.length:1)]}function Ka(t){let e="",n=!1,r=!1;for(let i=0;i{let o=kt(n);s?this.warnings.push(new vt.YAMLWarning(o,r,i)):this.errors.push(new vt.YAMLParseError(o,r,i))},this.directives=new hp.Directives({version:e.version||"1.2"}),this.options=e}decorate(e,n){let{comment:r,afterEmptyLine:i}=Ya(this.prelude);if(r){let s=e.contents;if(n)e.comment=e.comment?`${e.comment} -${r}`:r;else if(i||e.directives.docStart||!s)e.commentBefore=r;else if(Ka.isCollection(s)&&!s.flow&&s.items.length>0){let o=s.items[0];Ka.isPair(o)&&(o=o.key);let a=o.commentBefore;o.commentBefore=a?`${r} +`)+(s.substring(1)||" "),n=!0,r=!1;break;case"%":t[i+1]?.[0]!=="#"&&(i+=1),n=!1;break;default:n||(r=!0),n=!1}}return{comment:e,afterEmptyLine:r}}var Ri=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(n,r,i,s)=>{let o=kt(n);s?this.warnings.push(new vt.YAMLWarning(o,r,i)):this.errors.push(new vt.YAMLParseError(o,r,i))},this.directives=new pp.Directives({version:e.version||"1.2"}),this.options=e}decorate(e,n){let{comment:r,afterEmptyLine:i}=Ka(this.prelude);if(r){let s=e.contents;if(n)e.comment=e.comment?`${e.comment} +${r}`:r;else if(i||e.directives.docStart||!s)e.commentBefore=r;else if(Ba.isCollection(s)&&!s.flow&&s.items.length>0){let o=s.items[0];Ba.isPair(o)&&(o=o.key);let a=o.commentBefore;o.commentBefore=a?`${r} ${a}`:r}else{let o=s.commentBefore;s.commentBefore=o?`${r} -${o}`:r}}if(n){for(let s=0;s{let s=kt(e);s[0]+=n,this.onError(s,"BAD_DIRECTIVE",r,i)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let n=gp.composeDoc(this.options,this.directives,e,this.onError);this.atDirectives&&!n.directives.docStart&&this.onError(e,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(n,!1),this.doc&&(yield this.doc),this.doc=n,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(e.source);break;case"error":{let n=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,r=new vt.YAMLParseError(kt(e),"UNEXPECTED_TOKEN",n);this.atDirectives||!this.doc?this.errors.push(r):this.doc.errors.push(r);break}case"doc-end":{if(!this.doc){let r="Unexpected doc-end without preceding document";this.errors.push(new vt.YAMLParseError(kt(e),"UNEXPECTED_TOKEN",r));break}this.doc.directives.docEnd=!0;let n=wp.resolveEnd(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),n.comment){let r=this.doc.comment;this.doc.comment=r?`${r} -${n.comment}`:n.comment}this.doc.range[2]=n.offset;break}default:this.errors.push(new vt.YAMLParseError(kt(e),"UNEXPECTED_TOKEN",`Unsupported token ${e.type}`))}}*end(e=!1,n=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let r=Object.assign({_directives:this.directives},this.options),i=new mp.Document(void 0,r);this.atDirectives&&this.onError(n,"MISSING_CHAR","Missing directives-end indicator line"),i.range=[0,n,n],this.decorate(i,!1),yield i}}};Ua.Composer=Ri});var Va=g(jn=>{"use strict";var yp=Oi(),bp=Ai(),vp=yt(),Ha=it();function kp(t,e=!0,n){if(t){let r=(i,s,o)=>{let a=typeof i=="number"?i:Array.isArray(i)?i[0]:i.offset;if(n)n(a,s,o);else throw new vp.YAMLParseError([a,a+1],s,o)};switch(t.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return bp.resolveFlowScalar(t,e,r);case"block-scalar":return yp.resolveBlockScalar({options:{strict:e}},t,r)}}return null}function Sp(t,e){let{implicitKey:n=!1,indent:r,inFlow:i=!1,offset:s=-1,type:o="PLAIN"}=e,a=Ha.stringifyString({type:o,value:t},{implicitKey:n,indent:r>0?" ".repeat(r):"",inFlow:i,options:{blockQuote:!0,lineWidth:-1}}),c=e.end??[{type:"newline",offset:-1,indent:r,source:` +${o}`:r}}if(n){for(let s=0;s{let s=kt(e);s[0]+=n,this.onError(s,"BAD_DIRECTIVE",r,i)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let n=mp.composeDoc(this.options,this.directives,e,this.onError);this.atDirectives&&!n.directives.docStart&&this.onError(e,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(n,!1),this.doc&&(yield this.doc),this.doc=n,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(e.source);break;case"error":{let n=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,r=new vt.YAMLParseError(kt(e),"UNEXPECTED_TOKEN",n);this.atDirectives||!this.doc?this.errors.push(r):this.doc.errors.push(r);break}case"doc-end":{if(!this.doc){let r="Unexpected doc-end without preceding document";this.errors.push(new vt.YAMLParseError(kt(e),"UNEXPECTED_TOKEN",r));break}this.doc.directives.docEnd=!0;let n=gp.resolveEnd(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),n.comment){let r=this.doc.comment;this.doc.comment=r?`${r} +${n.comment}`:n.comment}this.doc.range[2]=n.offset;break}default:this.errors.push(new vt.YAMLParseError(kt(e),"UNEXPECTED_TOKEN",`Unsupported token ${e.type}`))}}*end(e=!1,n=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let r=Object.assign({_directives:this.directives},this.options),i=new hp.Document(void 0,r);this.atDirectives&&this.onError(n,"MISSING_CHAR","Missing directives-end indicator line"),i.range=[0,n,n],this.decorate(i,!1),yield i}}};Ya.Composer=Ri});var Ja=g(jn=>{"use strict";var wp=Oi(),yp=Ai(),bp=yt(),Ua=it();function vp(t,e=!0,n){if(t){let r=(i,s,o)=>{let a=typeof i=="number"?i:Array.isArray(i)?i[0]:i.offset;if(n)n(a,s,o);else throw new bp.YAMLParseError([a,a+1],s,o)};switch(t.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yp.resolveFlowScalar(t,e,r);case"block-scalar":return wp.resolveBlockScalar({options:{strict:e}},t,r)}}return null}function kp(t,e){let{implicitKey:n=!1,indent:r,inFlow:i=!1,offset:s=-1,type:o="PLAIN"}=e,a=Ua.stringifyString({type:o,value:t},{implicitKey:n,indent:r>0?" ".repeat(r):"",inFlow:i,options:{blockQuote:!0,lineWidth:-1}}),c=e.end??[{type:"newline",offset:-1,indent:r,source:` `}];switch(a[0]){case"|":case">":{let l=a.indexOf(` `),d=a.substring(0,l),u=a.substring(l+1)+` -`,f=[{type:"block-scalar-header",offset:s,indent:r,source:d}];return Ja(f,c)||f.push({type:"newline",offset:-1,indent:r,source:` -`}),{type:"block-scalar",offset:s,indent:r,props:f,source:u}}case'"':return{type:"double-quoted-scalar",offset:s,indent:r,source:a,end:c};case"'":return{type:"single-quoted-scalar",offset:s,indent:r,source:a,end:c};default:return{type:"scalar",offset:s,indent:r,source:a,end:c}}}function Cp(t,e,n={}){let{afterKey:r=!1,implicitKey:i=!1,inFlow:s=!1,type:o}=n,a="indent"in t?t.indent:null;if(r&&typeof a=="number"&&(a+=2),!o)switch(t.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let l=t.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let c=Ha.stringifyString({type:o,value:e},{implicitKey:i||a===null,indent:a!==null&&a>0?" ".repeat(a):"",inFlow:s,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":Ep(t,c);break;case'"':ji(t,c,"double-quoted-scalar");break;case"'":ji(t,c,"single-quoted-scalar");break;default:ji(t,c,"scalar")}}function Ep(t,e){let n=e.indexOf(` +`,f=[{type:"block-scalar-header",offset:s,indent:r,source:d}];return Ha(f,c)||f.push({type:"newline",offset:-1,indent:r,source:` +`}),{type:"block-scalar",offset:s,indent:r,props:f,source:u}}case'"':return{type:"double-quoted-scalar",offset:s,indent:r,source:a,end:c};case"'":return{type:"single-quoted-scalar",offset:s,indent:r,source:a,end:c};default:return{type:"scalar",offset:s,indent:r,source:a,end:c}}}function Sp(t,e,n={}){let{afterKey:r=!1,implicitKey:i=!1,inFlow:s=!1,type:o}=n,a="indent"in t?t.indent:null;if(r&&typeof a=="number"&&(a+=2),!o)switch(t.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let l=t.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let c=Ua.stringifyString({type:o,value:e},{implicitKey:i||a===null,indent:a!==null&&a>0?" ".repeat(a):"",inFlow:s,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":Cp(t,c);break;case'"':ji(t,c,"double-quoted-scalar");break;case"'":ji(t,c,"single-quoted-scalar");break;default:ji(t,c,"scalar")}}function Cp(t,e){let n=e.indexOf(` `),r=e.substring(0,n),i=e.substring(n+1)+` -`;if(t.type==="block-scalar"){let s=t.props[0];if(s.type!=="block-scalar-header")throw new Error("Invalid block scalar header");s.source=r,t.source=i}else{let{offset:s}=t,o="indent"in t?t.indent:-1,a=[{type:"block-scalar-header",offset:s,indent:o,source:r}];Ja(a,"end"in t?t.end:void 0)||a.push({type:"newline",offset:-1,indent:o,source:` -`});for(let c of Object.keys(t))c!=="type"&&c!=="offset"&&delete t[c];Object.assign(t,{type:"block-scalar",indent:o,props:a,source:i})}}function Ja(t,e){if(e)for(let n of e)switch(n.type){case"space":case"comment":t.push(n);break;case"newline":return t.push(n),!0}return!1}function ji(t,e,n){switch(t.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":t.type=n,t.source=e;break;case"block-scalar":{let r=t.props.slice(1),i=e.length;t.props[0].type==="block-scalar-header"&&(i-=t.props[0].source.length);for(let s of r)s.offset+=i;delete t.props,Object.assign(t,{type:n,source:e,end:r});break}case"block-map":case"block-seq":{let i={type:"newline",offset:t.offset+e.length,indent:t.indent,source:` -`};delete t.items,Object.assign(t,{type:n,source:e,end:[i]});break}default:{let r="indent"in t?t.indent:-1,i="end"in t&&Array.isArray(t.end)?t.end.filter(s=>s.type==="space"||s.type==="comment"||s.type==="newline"):[];for(let s of Object.keys(t))s!=="type"&&s!=="offset"&&delete t[s];Object.assign(t,{type:n,indent:r,source:e,end:i})}}}jn.createScalarToken=Sp;jn.resolveAsScalar=kp;jn.setScalarValue=Cp});var za=g(Ga=>{"use strict";var _p=t=>"type"in t?qn(t):Ln(t);function qn(t){switch(t.type){case"block-scalar":{let e="";for(let n of t.props)e+=qn(n);return e+t.source}case"block-map":case"block-seq":{let e="";for(let n of t.items)e+=Ln(n);return e}case"flow-collection":{let e=t.start.source;for(let n of t.items)e+=Ln(n);for(let n of t.end)e+=n.source;return e}case"document":{let e=Ln(t);if(t.end)for(let n of t.end)e+=n.source;return e}default:{let e=t.source;if("end"in t&&t.end)for(let n of t.end)e+=n.source;return e}}}function Ln({start:t,key:e,sep:n,value:r}){let i="";for(let s of t)i+=s.source;if(e&&(i+=qn(e)),n)for(let s of n)i+=s.source;return r&&(i+=qn(r)),i}Ga.stringify=_p});var ec=g(Za=>{"use strict";var Li=Symbol("break visit"),Pp=Symbol("skip children"),Xa=Symbol("remove item");function Pe(t,e){"type"in t&&t.type==="document"&&(t={start:t.start,value:t.value}),Qa(Object.freeze([]),t,e)}Pe.BREAK=Li;Pe.SKIP=Pp;Pe.REMOVE=Xa;Pe.itemAtPath=(t,e)=>{let n=t;for(let[r,i]of e){let s=n?.[r];if(s&&"items"in s)n=s.items[i];else return}return n};Pe.parentCollection=(t,e)=>{let n=Pe.itemAtPath(t,e.slice(0,-1)),r=e[e.length-1][0],i=n?.[r];if(i&&"items"in i)return i;throw new Error("Parent collection not found")};function Qa(t,e,n){let r=n(e,t);if(typeof r=="symbol")return r;for(let i of["key","value"]){let s=e[i];if(s&&"items"in s){for(let o=0;o{"use strict";var qi=Va(),Op=za(),Np=ec(),Di="\uFEFF",$i="",Wi="",Mi="",Ap=t=>!!t&&"items"in t,xp=t=>!!t&&(t.type==="scalar"||t.type==="single-quoted-scalar"||t.type==="double-quoted-scalar"||t.type==="block-scalar");function Tp(t){switch(t){case Di:return"";case $i:return"";case Wi:return"";case Mi:return"";default:return JSON.stringify(t)}}function Rp(t){switch(t){case Di:return"byte-order-mark";case $i:return"doc-mode";case Wi:return"flow-error-end";case Mi:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case` +`;if(t.type==="block-scalar"){let s=t.props[0];if(s.type!=="block-scalar-header")throw new Error("Invalid block scalar header");s.source=r,t.source=i}else{let{offset:s}=t,o="indent"in t?t.indent:-1,a=[{type:"block-scalar-header",offset:s,indent:o,source:r}];Ha(a,"end"in t?t.end:void 0)||a.push({type:"newline",offset:-1,indent:o,source:` +`});for(let c of Object.keys(t))c!=="type"&&c!=="offset"&&delete t[c];Object.assign(t,{type:"block-scalar",indent:o,props:a,source:i})}}function Ha(t,e){if(e)for(let n of e)switch(n.type){case"space":case"comment":t.push(n);break;case"newline":return t.push(n),!0}return!1}function ji(t,e,n){switch(t.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":t.type=n,t.source=e;break;case"block-scalar":{let r=t.props.slice(1),i=e.length;t.props[0].type==="block-scalar-header"&&(i-=t.props[0].source.length);for(let s of r)s.offset+=i;delete t.props,Object.assign(t,{type:n,source:e,end:r});break}case"block-map":case"block-seq":{let i={type:"newline",offset:t.offset+e.length,indent:t.indent,source:` +`};delete t.items,Object.assign(t,{type:n,source:e,end:[i]});break}default:{let r="indent"in t?t.indent:-1,i="end"in t&&Array.isArray(t.end)?t.end.filter(s=>s.type==="space"||s.type==="comment"||s.type==="newline"):[];for(let s of Object.keys(t))s!=="type"&&s!=="offset"&&delete t[s];Object.assign(t,{type:n,indent:r,source:e,end:i})}}}jn.createScalarToken=kp;jn.resolveAsScalar=vp;jn.setScalarValue=Sp});var Ga=g(Va=>{"use strict";var Ep=t=>"type"in t?qn(t):Ln(t);function qn(t){switch(t.type){case"block-scalar":{let e="";for(let n of t.props)e+=qn(n);return e+t.source}case"block-map":case"block-seq":{let e="";for(let n of t.items)e+=Ln(n);return e}case"flow-collection":{let e=t.start.source;for(let n of t.items)e+=Ln(n);for(let n of t.end)e+=n.source;return e}case"document":{let e=Ln(t);if(t.end)for(let n of t.end)e+=n.source;return e}default:{let e=t.source;if("end"in t&&t.end)for(let n of t.end)e+=n.source;return e}}}function Ln({start:t,key:e,sep:n,value:r}){let i="";for(let s of t)i+=s.source;if(e&&(i+=qn(e)),n)for(let s of n)i+=s.source;return r&&(i+=qn(r)),i}Va.stringify=Ep});var Za=g(Qa=>{"use strict";var Li=Symbol("break visit"),_p=Symbol("skip children"),za=Symbol("remove item");function Pe(t,e){"type"in t&&t.type==="document"&&(t={start:t.start,value:t.value}),Xa(Object.freeze([]),t,e)}Pe.BREAK=Li;Pe.SKIP=_p;Pe.REMOVE=za;Pe.itemAtPath=(t,e)=>{let n=t;for(let[r,i]of e){let s=n?.[r];if(s&&"items"in s)n=s.items[i];else return}return n};Pe.parentCollection=(t,e)=>{let n=Pe.itemAtPath(t,e.slice(0,-1)),r=e[e.length-1][0],i=n?.[r];if(i&&"items"in i)return i;throw new Error("Parent collection not found")};function Xa(t,e,n){let r=n(e,t);if(typeof r=="symbol")return r;for(let i of["key","value"]){let s=e[i];if(s&&"items"in s){for(let o=0;o{"use strict";var qi=Ja(),Pp=Ga(),Op=Za(),Di="\uFEFF",$i="",Wi="",Mi="",Np=t=>!!t&&"items"in t,Ap=t=>!!t&&(t.type==="scalar"||t.type==="single-quoted-scalar"||t.type==="double-quoted-scalar"||t.type==="block-scalar");function xp(t){switch(t){case Di:return"";case $i:return"";case Wi:return"";case Mi:return"";default:return JSON.stringify(t)}}function Tp(t){switch(t){case Di:return"byte-order-mark";case $i:return"doc-mode";case Wi:return"flow-error-end";case Mi:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case` `:case`\r -`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(t[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}W.createScalarToken=qi.createScalarToken;W.resolveAsScalar=qi.resolveAsScalar;W.setScalarValue=qi.setScalarValue;W.stringify=Op.stringify;W.visit=Np.visit;W.BOM=Di;W.DOCUMENT=$i;W.FLOW_END=Wi;W.SCALAR=Mi;W.isCollection=Ap;W.isScalar=xp;W.prettyToken=Tp;W.tokenType=Rp});var Ki=g(nc=>{"use strict";var St=Dn();function H(t){switch(t){case void 0:case" ":case` -`:case"\r":case" ":return!0;default:return!1}}var tc=new Set("0123456789ABCDEFabcdef"),Ip=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),$n=new Set(",[]{}"),jp=new Set(` ,[]{} -\r `),Fi=t=>!t||jp.has(t),Bi=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,n=!1){if(e){if(typeof e!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!n;let r=this.next??"stream";for(;r&&(n||this.hasChars(1));)r=yield*this.parseNext(r)}atLineEnd(){let e=this.pos,n=this.buffer[e];for(;n===" "||n===" ";)n=this.buffer[++e];return!n||n==="#"||n===` +`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(t[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}W.createScalarToken=qi.createScalarToken;W.resolveAsScalar=qi.resolveAsScalar;W.setScalarValue=qi.setScalarValue;W.stringify=Pp.stringify;W.visit=Op.visit;W.BOM=Di;W.DOCUMENT=$i;W.FLOW_END=Wi;W.SCALAR=Mi;W.isCollection=Np;W.isScalar=Ap;W.prettyToken=xp;W.tokenType=Tp});var Ki=g(tc=>{"use strict";var St=Dn();function H(t){switch(t){case void 0:case" ":case` +`:case"\r":case" ":return!0;default:return!1}}var ec=new Set("0123456789ABCDEFabcdef"),Rp=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),$n=new Set(",[]{}"),Ip=new Set(` ,[]{} +\r `),Fi=t=>!t||Ip.has(t),Bi=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,n=!1){if(e){if(typeof e!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!n;let r=this.next??"stream";for(;r&&(n||this.hasChars(1));)r=yield*this.parseNext(r)}atLineEnd(){let e=this.pos,n=this.buffer[e];for(;n===" "||n===" ";)n=this.buffer[++e];return!n||n==="#"||n===` `?!0:n==="\r"?this.buffer[e+1]===` `:!1}charAt(e){return this.buffer[this.pos+e]}continueScalar(e){let n=this.buffer[e];if(this.indentNext>0){let r=0;for(;n===" ";)n=this.buffer[++r+e];if(n==="\r"){let i=this.buffer[r+e+1];if(i===` `||!i&&!this.atEnd)return e+r+1}return n===` @@ -133,22 +133,22 @@ ${n.comment}`:n.comment}this.doc.range[2]=n.offset;break}default:this.errors.pus `&&s>=this.pos&&s+1+n>a)e=s;else break}while(!0);return yield St.SCALAR,yield*this.pushToIndex(e+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let e=this.flowLevel>0,n=this.pos-1,r=this.pos-1,i;for(;i=this.buffer[++r];)if(i===":"){let s=this.buffer[r+1];if(H(s)||e&&$n.has(s))break;n=r}else if(H(i)){let s=this.buffer[r+1];if(i==="\r"&&(s===` `?(r+=1,i=` `,s=this.buffer[r+1]):n=r),s==="#"||e&&$n.has(s))break;if(i===` -`){let o=this.continueScalar(r+1);if(o===-1)break;r=Math.max(r,o-2)}}else{if(e&&$n.has(i))break;n=r}return!i&&!this.atEnd?this.setNext("plain-scalar"):(yield St.SCALAR,yield*this.pushToIndex(n+1,!0),e?"flow":"doc")}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,n){let r=this.buffer.slice(this.pos,e);return r?(yield r,this.pos+=r.length,r.length):(n&&(yield""),0)}*pushIndicators(){let e=0;e:for(;;){switch(this.charAt(0)){case"!":e+=yield*this.pushTag(),e+=yield*this.pushSpaces(!0);continue e;case"&":e+=yield*this.pushUntil(Fi),e+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let n=this.flowLevel>0,r=this.charAt(1);if(H(r)||n&&$n.has(r)){n?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,e+=yield*this.pushCount(1),e+=yield*this.pushSpaces(!0);continue e}}}break e}return e}*pushTag(){if(this.charAt(1)==="<"){let e=this.pos+2,n=this.buffer[e];for(;!H(n)&&n!==">";)n=this.buffer[++e];return yield*this.pushToIndex(n===">"?e+1:e,!1)}else{let e=this.pos+1,n=this.buffer[e];for(;n;)if(Ip.has(n))n=this.buffer[++e];else if(n==="%"&&tc.has(this.buffer[e+1])&&tc.has(this.buffer[e+2]))n=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];return e===` +`){let o=this.continueScalar(r+1);if(o===-1)break;r=Math.max(r,o-2)}}else{if(e&&$n.has(i))break;n=r}return!i&&!this.atEnd?this.setNext("plain-scalar"):(yield St.SCALAR,yield*this.pushToIndex(n+1,!0),e?"flow":"doc")}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,n){let r=this.buffer.slice(this.pos,e);return r?(yield r,this.pos+=r.length,r.length):(n&&(yield""),0)}*pushIndicators(){let e=0;e:for(;;){switch(this.charAt(0)){case"!":e+=yield*this.pushTag(),e+=yield*this.pushSpaces(!0);continue e;case"&":e+=yield*this.pushUntil(Fi),e+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let n=this.flowLevel>0,r=this.charAt(1);if(H(r)||n&&$n.has(r)){n?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,e+=yield*this.pushCount(1),e+=yield*this.pushSpaces(!0);continue e}}}break e}return e}*pushTag(){if(this.charAt(1)==="<"){let e=this.pos+2,n=this.buffer[e];for(;!H(n)&&n!==">";)n=this.buffer[++e];return yield*this.pushToIndex(n===">"?e+1:e,!1)}else{let e=this.pos+1,n=this.buffer[e];for(;n;)if(Rp.has(n))n=this.buffer[++e];else if(n==="%"&&ec.has(this.buffer[e+1])&&ec.has(this.buffer[e+2]))n=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];return e===` `?yield*this.pushCount(1):e==="\r"&&this.charAt(1)===` -`?yield*this.pushCount(2):0}*pushSpaces(e){let n=this.pos-1,r;do r=this.buffer[++n];while(r===" "||e&&r===" ");let i=n-this.pos;return i>0&&(yield this.buffer.substr(this.pos,i),this.pos=n),i}*pushUntil(e){let n=this.pos,r=this.buffer[n];for(;!e(r);)r=this.buffer[++n];return yield*this.pushToIndex(n,!1)}};nc.Lexer=Bi});var Ui=g(rc=>{"use strict";var Yi=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let n=0,r=this.lineStarts.length;for(;n>1;this.lineStarts[s]{"use strict";var Lp=Ft("process"),ic=Dn(),qp=Ki();function he(t,e){for(let n=0;n=0;)switch(t[e].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;t[++e]?.type==="space";);return t.splice(e,t.length)}function Mn(t,e){if(e.length<1e5)Array.prototype.push.apply(t,e);else for(let n=0;n0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let e=this.peek(1);if(this.type==="doc-end"&&e?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!e)return yield*this.stream();switch(e.type){case"document":return yield*this.document(e);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(e);case"block-scalar":return yield*this.blockScalar(e);case"block-map":return yield*this.blockMap(e);case"block-seq":return yield*this.blockSequence(e);case"flow-collection":return yield*this.flowCollection(e);case"doc-end":return yield*this.documentEnd(e)}yield*this.pop()}peek(e){return this.stack[this.stack.length-e]}*pop(e){let n=e??this.stack.pop();if(!n)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield n;else{let r=this.peek(1);switch(n.type==="block-scalar"?n.indent="indent"in r?r.indent:0:n.type==="flow-collection"&&r.type==="document"&&(n.indent=0),n.type==="flow-collection"&&oc(n),r.type){case"document":r.value=n;break;case"block-scalar":r.props.push(n);break;case"block-map":{let i=r.items[r.items.length-1];if(i.value){r.items.push({start:[],key:n,sep:[]}),this.onKeyLine=!0;return}else if(i.sep)i.value=n;else{Object.assign(i,{key:n,sep:[]}),this.onKeyLine=!i.explicitKey;return}break}case"block-seq":{let i=r.items[r.items.length-1];i.value?r.items.push({start:[],value:n}):i.value=n;break}case"flow-collection":{let i=r.items[r.items.length-1];!i||i.value?r.items.push({start:[],key:n,sep:[]}):i.sep?i.value=n:Object.assign(i,{key:n,sep:[]});return}default:yield*this.pop(),yield*this.pop(n)}if((r.type==="document"||r.type==="block-map"||r.type==="block-seq")&&(n.type==="block-map"||n.type==="block-seq")){let i=n.items[n.items.length-1];i&&!i.sep&&!i.value&&i.start.length>0&&sc(i.start)===-1&&(n.indent===0||i.start.every(s=>s.type!=="comment"||s.indent0&&(yield this.buffer.substr(this.pos,i),this.pos=n),i}*pushUntil(e){let n=this.pos,r=this.buffer[n];for(;!e(r);)r=this.buffer[++n];return yield*this.pushToIndex(n,!1)}};tc.Lexer=Bi});var Ui=g(nc=>{"use strict";var Yi=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let n=0,r=this.lineStarts.length;for(;n>1;this.lineStarts[s]{"use strict";var jp=Ft("process"),rc=Dn(),Lp=Ki();function he(t,e){for(let n=0;n=0;)switch(t[e].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;t[++e]?.type==="space";);return t.splice(e,t.length)}function Mn(t,e){if(e.length<1e5)Array.prototype.push.apply(t,e);else for(let n=0;n0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let e=this.peek(1);if(this.type==="doc-end"&&e?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!e)return yield*this.stream();switch(e.type){case"document":return yield*this.document(e);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(e);case"block-scalar":return yield*this.blockScalar(e);case"block-map":return yield*this.blockMap(e);case"block-seq":return yield*this.blockSequence(e);case"flow-collection":return yield*this.flowCollection(e);case"doc-end":return yield*this.documentEnd(e)}yield*this.pop()}peek(e){return this.stack[this.stack.length-e]}*pop(e){let n=e??this.stack.pop();if(!n)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield n;else{let r=this.peek(1);switch(n.type==="block-scalar"?n.indent="indent"in r?r.indent:0:n.type==="flow-collection"&&r.type==="document"&&(n.indent=0),n.type==="flow-collection"&&sc(n),r.type){case"document":r.value=n;break;case"block-scalar":r.props.push(n);break;case"block-map":{let i=r.items[r.items.length-1];if(i.value){r.items.push({start:[],key:n,sep:[]}),this.onKeyLine=!0;return}else if(i.sep)i.value=n;else{Object.assign(i,{key:n,sep:[]}),this.onKeyLine=!i.explicitKey;return}break}case"block-seq":{let i=r.items[r.items.length-1];i.value?r.items.push({start:[],value:n}):i.value=n;break}case"flow-collection":{let i=r.items[r.items.length-1];!i||i.value?r.items.push({start:[],key:n,sep:[]}):i.sep?i.value=n:Object.assign(i,{key:n,sep:[]});return}default:yield*this.pop(),yield*this.pop(n)}if((r.type==="document"||r.type==="block-map"||r.type==="block-seq")&&(n.type==="block-map"||n.type==="block-seq")){let i=n.items[n.items.length-1];i&&!i.sep&&!i.value&&i.start.length>0&&ic(i.start)===-1&&(n.indent===0||i.start.every(s=>s.type!=="comment"||s.indent=e.indent){let r=!this.onKeyLine&&this.indent===e.indent,i=r&&(n.sep||n.explicitKey)&&this.type!=="seq-item-ind",s=[];if(i&&n.sep&&!n.value){let o=[];for(let a=0;ae.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(s=n.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":i||n.value?(s.push(this.sourceToken),e.items.push({start:s}),this.onKeyLine=!0):n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"explicit-key-ind":!n.sep&&!n.explicitKey?(n.start.push(this.sourceToken),n.explicitKey=!0):i||n.value?(s.push(this.sourceToken),e.items.push({start:s,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(n.explicitKey)if(n.sep)if(n.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(he(n.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:s,key:null,sep:[this.sourceToken]}]});else if(ac(n.key)&&!he(n.sep,"newline")){let o=Ke(n.start),a=n.key,c=n.sep;c.push(this.sourceToken),delete n.key,delete n.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:a,sep:c}]})}else s.length>0?n.sep=n.sep.concat(s,this.sourceToken):n.sep.push(this.sourceToken);else if(he(n.start,"newline"))Object.assign(n,{key:null,sep:[this.sourceToken]});else{let o=Ke(n.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else n.sep?n.value||i?e.items.push({start:s,key:null,sep:[this.sourceToken]}):he(n.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):n.sep.push(this.sourceToken):Object.assign(n,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);i||n.value?(e.items.push({start:s,key:o,sep:[]}),this.onKeyLine=!0):n.sep?this.stack.push(o):(Object.assign(n,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(e);if(o){if(o.type==="block-seq"){if(!n.explicitKey&&n.sep&&!he(n.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else r&&e.items.push({start:s});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let n=e.items[e.items.length-1];switch(this.type){case"newline":if(n.value){let r="end"in n.value?n.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else n.start.push(this.sourceToken);return;case"space":case"comment":if(n.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(n.start,e.indent)){let i=e.items[e.items.length-2]?.value?.end;if(Array.isArray(i)){Mn(i,n.start),i.push(this.sourceToken),e.items.pop();return}}n.start.push(this.sourceToken)}return;case"anchor":case"tag":if(n.value||this.indent<=e.indent)break;n.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;n.value||he(n.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):n.start.push(this.sourceToken);return}if(this.indent>e.indent){let r=this.startBlockValue(e);if(r){this.stack.push(r);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let n=e.items[e.items.length-1];if(this.type==="flow-error-end"){let r;do yield*this.pop(),r=this.peek(1);while(r?.type==="flow-collection")}else if(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!n||n.sep?e.items.push({start:[this.sourceToken]}):n.start.push(this.sourceToken);return;case"map-value-ind":!n||n.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):n.sep?n.sep.push(this.sourceToken):Object.assign(n,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!n||n.value?e.items.push({start:[this.sourceToken]}):n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let i=this.flowScalar(this.type);!n||n.value?e.items.push({start:[],key:i,sep:[]}):n.sep?this.stack.push(i):Object.assign(n,{key:i,sep:[]});return}case"flow-map-end":case"flow-seq-end":e.end.push(this.sourceToken);return}let r=this.startBlockValue(e);r?this.stack.push(r):(yield*this.pop(),yield*this.step())}else{let r=this.peek(2);if(r.type==="block-map"&&(this.type==="map-value-ind"&&r.indent===e.indent||this.type==="newline"&&!r.items[r.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&r.type!=="flow-collection"){let i=Wn(r),s=Ke(i);oc(e);let o=e.end.splice(1,e.end.length);o.push(this.sourceToken);let a={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:s,key:e,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let n=this.source.indexOf(` +`,n)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let n=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,n.value){let r="end"in n.value?n.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"space":case"comment":if(n.value)e.items.push({start:[this.sourceToken]});else if(n.sep)n.sep.push(this.sourceToken);else{if(this.atIndentedComment(n.start,e.indent)){let i=e.items[e.items.length-2]?.value?.end;if(Array.isArray(i)){Mn(i,n.start),i.push(this.sourceToken),e.items.pop();return}}n.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let r=!this.onKeyLine&&this.indent===e.indent,i=r&&(n.sep||n.explicitKey)&&this.type!=="seq-item-ind",s=[];if(i&&n.sep&&!n.value){let o=[];for(let a=0;ae.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(s=n.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":i||n.value?(s.push(this.sourceToken),e.items.push({start:s}),this.onKeyLine=!0):n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"explicit-key-ind":!n.sep&&!n.explicitKey?(n.start.push(this.sourceToken),n.explicitKey=!0):i||n.value?(s.push(this.sourceToken),e.items.push({start:s,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(n.explicitKey)if(n.sep)if(n.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(he(n.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:s,key:null,sep:[this.sourceToken]}]});else if(oc(n.key)&&!he(n.sep,"newline")){let o=Ke(n.start),a=n.key,c=n.sep;c.push(this.sourceToken),delete n.key,delete n.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:a,sep:c}]})}else s.length>0?n.sep=n.sep.concat(s,this.sourceToken):n.sep.push(this.sourceToken);else if(he(n.start,"newline"))Object.assign(n,{key:null,sep:[this.sourceToken]});else{let o=Ke(n.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else n.sep?n.value||i?e.items.push({start:s,key:null,sep:[this.sourceToken]}):he(n.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):n.sep.push(this.sourceToken):Object.assign(n,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);i||n.value?(e.items.push({start:s,key:o,sep:[]}),this.onKeyLine=!0):n.sep?this.stack.push(o):(Object.assign(n,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(e);if(o){if(o.type==="block-seq"){if(!n.explicitKey&&n.sep&&!he(n.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else r&&e.items.push({start:s});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let n=e.items[e.items.length-1];switch(this.type){case"newline":if(n.value){let r="end"in n.value?n.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else n.start.push(this.sourceToken);return;case"space":case"comment":if(n.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(n.start,e.indent)){let i=e.items[e.items.length-2]?.value?.end;if(Array.isArray(i)){Mn(i,n.start),i.push(this.sourceToken),e.items.pop();return}}n.start.push(this.sourceToken)}return;case"anchor":case"tag":if(n.value||this.indent<=e.indent)break;n.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;n.value||he(n.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):n.start.push(this.sourceToken);return}if(this.indent>e.indent){let r=this.startBlockValue(e);if(r){this.stack.push(r);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let n=e.items[e.items.length-1];if(this.type==="flow-error-end"){let r;do yield*this.pop(),r=this.peek(1);while(r?.type==="flow-collection")}else if(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!n||n.sep?e.items.push({start:[this.sourceToken]}):n.start.push(this.sourceToken);return;case"map-value-ind":!n||n.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):n.sep?n.sep.push(this.sourceToken):Object.assign(n,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!n||n.value?e.items.push({start:[this.sourceToken]}):n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let i=this.flowScalar(this.type);!n||n.value?e.items.push({start:[],key:i,sep:[]}):n.sep?this.stack.push(i):Object.assign(n,{key:i,sep:[]});return}case"flow-map-end":case"flow-seq-end":e.end.push(this.sourceToken);return}let r=this.startBlockValue(e);r?this.stack.push(r):(yield*this.pop(),yield*this.step())}else{let r=this.peek(2);if(r.type==="block-map"&&(this.type==="map-value-ind"&&r.indent===e.indent||this.type==="newline"&&!r.items[r.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&r.type!=="flow-collection"){let i=Wn(r),s=Ke(i);sc(e);let o=e.end.splice(1,e.end.length);o.push(this.sourceToken);let a={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:s,key:e,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let n=this.source.indexOf(` `)+1;for(;n!==0;)this.onNewLine(this.offset+n),n=this.source.indexOf(` -`,n)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let n=Wn(e),r=Ke(n);return r.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let n=Wn(e),r=Ke(n);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,n){return this.type!=="comment"||this.indent<=n?!1:e.every(r=>r.type==="newline"||r.type==="space")}*documentEnd(e){this.type!=="doc-mode"&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};cc.Parser=Hi});var pc=g(Et=>{"use strict";var lc=Ii(),Dp=mt(),Ct=yt(),$p=Tr(),Wp=_(),Mp=Ui(),uc=Ji();function fc(t){let e=t.prettyErrors!==!1;return{lineCounter:t.lineCounter||e&&new Mp.LineCounter||null,prettyErrors:e}}function Fp(t,e={}){let{lineCounter:n,prettyErrors:r}=fc(e),i=new uc.Parser(n?.addNewLine),s=new lc.Composer(e),o=Array.from(s.compose(i.parse(t)));if(r&&n)for(let a of o)a.errors.forEach(Ct.prettifyError(t,n)),a.warnings.forEach(Ct.prettifyError(t,n));return o.length>0?o:Object.assign([],{empty:!0},s.streamInfo())}function dc(t,e={}){let{lineCounter:n,prettyErrors:r}=fc(e),i=new uc.Parser(n?.addNewLine),s=new lc.Composer(e),o=null;for(let a of s.compose(i.parse(t),!0,t.length))if(!o)o=a;else if(o.options.logLevel!=="silent"){o.errors.push(new Ct.YAMLParseError(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return r&&n&&(o.errors.forEach(Ct.prettifyError(t,n)),o.warnings.forEach(Ct.prettifyError(t,n))),o}function Bp(t,e,n){let r;typeof e=="function"?r=e:n===void 0&&e&&typeof e=="object"&&(n=e);let i=dc(t,n);if(!i)return null;if(i.warnings.forEach(s=>$p.warn(i.options.logLevel,s)),i.errors.length>0){if(i.options.logLevel!=="silent")throw i.errors[0];i.errors=[]}return i.toJS(Object.assign({reviver:r},n))}function Kp(t,e,n){let r=null;if(typeof e=="function"||Array.isArray(e)?r=e:n===void 0&&e&&(n=e),typeof n=="string"&&(n=n.length),typeof n=="number"){let i=Math.round(n);n=i<1?void 0:i>8?{indent:8}:{indent:i}}if(t===void 0){let{keepUndefined:i}=n??e??{};if(!i)return}return Wp.isDocument(t)&&!r?t.toString(n):new Dp.Document(t,r,n).toString(n)}Et.parse=Bp;Et.parseAllDocuments=Fp;Et.parseDocument=dc;Et.stringify=Kp});var _t=g(P=>{"use strict";var Yp=Ii(),Up=mt(),Hp=pi(),Vi=yt(),Jp=Ze(),me=_(),Vp=ue(),Gp=N(),zp=de(),Xp=pe(),Qp=Dn(),Zp=Ki(),eh=Ui(),th=Ji(),Fn=pc(),hc=Ge();P.Composer=Yp.Composer;P.Document=Up.Document;P.Schema=Hp.Schema;P.YAMLError=Vi.YAMLError;P.YAMLParseError=Vi.YAMLParseError;P.YAMLWarning=Vi.YAMLWarning;P.Alias=Jp.Alias;P.isAlias=me.isAlias;P.isCollection=me.isCollection;P.isDocument=me.isDocument;P.isMap=me.isMap;P.isNode=me.isNode;P.isPair=me.isPair;P.isScalar=me.isScalar;P.isSeq=me.isSeq;P.Pair=Vp.Pair;P.Scalar=Gp.Scalar;P.YAMLMap=zp.YAMLMap;P.YAMLSeq=Xp.YAMLSeq;P.CST=Qp;P.Lexer=Zp.Lexer;P.LineCounter=eh.LineCounter;P.Parser=th.Parser;P.parse=Fn.parse;P.parseAllDocuments=Fn.parseAllDocuments;P.parseDocument=Fn.parseDocument;P.stringify=Fn.stringify;P.visit=hc.visit;P.visitAsync=hc.visitAsync});import Bn from"path";function ih(t,e){if(typeof t!="string")throw new Error(`${e} must be a string`);let n=t.trim();if(n.length===0||Bn.posix.isAbsolute(n)||Bn.win32.isAbsolute(n)||/^(?:~|[\\/])/u.test(n))throw new Error(`${e} must be a project-relative path`);if(n===".")return[];let r=n.replaceAll("\\","/").split("/");if(r.some(i=>i===".."))throw new Error(`${e} must stay inside the project root`);if(r.some(i=>i===""||i==="."))throw new Error(`${e} must not contain empty or dot path segments`);return r}function Kn(t){let e=ih(t,"native.artifact_root");return e.length===0?".":e.join("/")}function gc(t,e="docs"){let n=t??e;if(n!=="legacy"&&n!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return n}function Nt(t,e,n=!1){if(typeof t!="string")throw new Error(`${e} must be a string`);let r=t.trim().replaceAll("\\","/");if(r.length===0||Bn.posix.isAbsolute(r)||Bn.win32.isAbsolute(r)||/^(?:~|[\\/])/u.test(r))throw new Error(`${e} must be relative to its declared path base`);let i=r.split("/");if(i.some(s=>s===".."))throw new Error(`${e} must stay inside its declared path base`);if(i.some(s=>s===""||s==="."))throw new Error(`${e} must not contain empty or dot path segments`);if(!n&&/[*?]/u.test(r))throw new Error(`${e} cannot contain wildcards`);return i.join("/")}function Pt(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function wc(t,e,n){let r=t??e;if(r!=="en"&&r!=="zh-CN")throw new Error(`${n} must be en or zh-CN`);return r}function yc(t,e){if(typeof t!="string"||t.length===0||t.includes("\\")||t.includes("\0")||t.startsWith("/")||t.split("/").includes(".."))throw new Error(`${e} contains an unsafe pattern`);if(t.length>zi)throw new Error(`${e} exceeds ${zi} characters`);let n=0;for(let r=0;rXi)throw new Error(`${e} contains more than ${Xi} wildcard tokens`);return t}function mc(t,e,n){if(t===void 0)return[...n];if(!Array.isArray(t))throw new Error(`${e} contains an unsafe pattern`);return[...new Set(t.map(r=>yc(r,e)))].sort((r,i)=>r.localeCompare(i,"en"))}function Gi(t,e,n){let r=t??e;if(!Number.isSafeInteger(r)||r<1)throw new Error(`${n} must be a positive integer`);return r}function sh(t){if(t===void 0)return{...ee,include:[...ee.include],exclude:[...ee.exclude]};let e=Pt(t,"native.snapshot");return{include:mc(e.include,"native.snapshot.include",ee.include),exclude:mc(e.exclude,"native.snapshot.exclude",ee.exclude),max_files:Gi(e.max_files,ee.max_files,"native.snapshot.max_files"),max_total_bytes:Gi(e.max_total_bytes,ee.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:Gi(e.max_duration_ms,ee.max_duration_ms,"native.snapshot.max_duration_ms")}}function oh(t){if(t===void 0)return;let e=Pt(t,"native.pending_root_move"),n=e.id,r=e.from_artifact_root,i=e.to_artifact_root,s=e.stage;if(typeof n!="string"||!/^[a-f0-9-]{8,}$/u.test(n))throw new Error("native.pending_root_move.id is invalid");if(typeof r!="string"||typeof i!="string")throw new Error("native.pending_root_move roots must be strings");if(s!=="copying"&&s!=="ready"&&s!=="switched")throw new Error("native.pending_root_move.stage is invalid");let o;if(e.cleanup!==void 0){let a=Pt(e.cleanup,"native.pending_root_move.cleanup"),c=a.kind,l=a.state,d=a.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof d!="string"||!/^[a-f0-9]{64}$/u.test(d))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:d}}return{id:n,fromArtifactRoot:Kn(r),toArtifactRoot:Kn(i),stage:s,...o?{cleanup:o}:{}}}function ah(t,e={}){let n=Pt(t,"native"),r=n.artifact_root??(e.allowMissingArtifactRoot?"docs":void 0);if(typeof r!="string")throw new Error("native.artifact_root must be a string");let i=n.clarification_mode??"sequential";if(i!=="sequential"&&i!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let s=n.archive_confirmation??"automatic";if(s!=="automatic"&&s!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=n.max_verify_failures??nh;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let a=oh(n.pending_root_move);return{artifact_root:Kn(r),language:wc(n.language,"en","native.language"),clarification_mode:i,archive_confirmation:s,max_verify_failures:o,snapshot:sh(n.snapshot),...a?{pending_root_move:a}:{}}}function ch(t){let e=Pt(t,"classic"),n=e.context_compression??"off";if(n!=="off"&&n!=="beta")throw new Error("classic.context_compression must be off or beta");let r=e.review_mode??"standard";if(r!=="off"&&r!=="standard"&&r!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let i=e.auto_transition??!0;if(typeof i!="boolean")throw new Error("classic.auto_transition must be true or false");return{artifact_layout:gc(e.artifact_layout),language:wc(e.language,"zh-CN","classic.language"),context_compression:n,review_mode:r,auto_transition:i}}function lh(t){let e=t??!0;if(typeof e!="boolean")throw new Error("ambient_resume must be true or false");return e}function uh(t,e,n,r,i){let s=t.schema!==void 0;if(!(s||t.default_workflow!==void 0||t.workflows!==void 0||!i.allowPartialProject&&t.native!==void 0)||i.allowPartialProject&&!s)return null;if(t.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(t.default_workflow!=="native"&&t.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let a=t.workflows??[t.default_workflow];if(!Array.isArray(a)||a.length===0||a.some(l=>l!=="native"&&l!=="classic"))throw new Error("workflows must contain native and/or classic");let c=[...new Set(a)];if(!c.includes(t.default_workflow))throw new Error("workflows must include default_workflow");if(c.includes("native")&&!e)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:t.default_workflow,workflows:c,ambient_resume:r,...e?{native:e}:{},...n?{classic:n}:{}}}function Ye(t,e={}){let n=(0,Qi.parseDocument)(t,{uniqueKeys:!0});if(n.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${n.errors[0].message}`);let r=n.toJS();if(r==null)return{value:{},config:null,ambient_resume:!0};if(typeof r!="object"||Array.isArray(r))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let i=r,s=lh(i.ambient_resume),o=i.native===void 0?void 0:ah(i.native,{allowMissingArtifactRoot:e.allowMissingNativeFields}),a=i.classic===void 0?void 0:ch(i.classic),c=uh(i,o,a,s,{allowPartialProject:e.allowPartialProject??!1});return{value:i,config:c,ambient_resume:s,...o?{native:o}:{},...a?{classic:a}:{}}}var Qi,Ot,zi,Xi,nh,rh,ee,ge=q(()=>{"use strict";Qi=Bt(_t(),1),Ot=64*1024,zi=1024,Xi=64,nh=5,rh=[".agents/skills/**",".amazonq/skills/**",".augment/skills/**",".bob/skills/**",".claude/skills/**",".cline/skills/**",".codebuddy/skills/**",".continue/skills/**",".cospec/skills/**",".crush/skills/**",".cursor/skills/**",".factory/skills/**",".forge/skills/**",".gemini/skills/**",".github/skills/**",".iflow/skills/**",".junie/skills/**",".kilocode/skills/**",".kimi-code/skills/**",".kiro/skills/**",".lingma/skills/**",".mimocode/skills/**",".opencode/skills/**",".pi/skills/**",".qoder/skills/**",".qwen/skills/**",".roo/skills/**",".trae-cn/skills/**",".trae/skills/**",".windsurf/skills/**",".zcode/skills/**"],ee={include:["**/*"],exclude:[...rh],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4}});function we(t){return t!==0&&t!==0n&&t!=="0"}function Yn(t,e){return we(t.dev)&&we(e.dev)&&we(t.ino)&&we(e.ino)}function te(t,e){let n=we(t.dev)&&we(e.dev);if(n&&t.dev!==e.dev)return!1;let r=we(t.ino)&&we(e.ino);return r&&t.ino!==e.ino?!1:n&&r?!0:t.birthtime===e.birthtime}var Un=q(()=>{"use strict"});import{constants as Hn,promises as Oe}from"fs";function Zi(t){return"birthtimeNs"in t&&typeof t.birthtimeNs=="bigint"?t.birthtimeNs:t.birthtimeMs}function bc(t){return"ctimeNs"in t&&typeof t.ctimeNs=="bigint"?t.ctimeNs:t.ctimeMs}function At(t){return{dev:t.dev,ino:t.ino,birthtime:Zi(t)}}function Jn(t,e){let n=At(t),r=At(e);return Yn(n,r)?te(n,r):te(n,r)&&Zi(t)===Zi(e)&&bc(t)===bc(e)&&t.size===e.size}async function Vn(t,e,n={}){if(!Number.isSafeInteger(e)||e<1)throw new Error("race-safe read byte limit must be a positive integer");let r=n.label??"file",i=n.bigint===!0,s=await Oe.lstat(t,{bigint:i});if(!s.isFile()||s.isSymbolicLink())throw new ye("not-regular-file",`${r} must be a regular file`);if(BigInt(s.size)>BigInt(e))throw new ye("too-large",`${r} exceeds ${e} bytes`);let o=await Oe.realpath(t);await n.verify?.("pre-open",{realPath:o,identity:At(s)});let a=process.platform==="win32"?Hn.O_RDONLY:Hn.O_RDONLY|Hn.O_NOFOLLOW|Hn.O_NONBLOCK,c;try{c=await Oe.open(t,a)}catch(l){throw l.code==="ELOOP"?new ye("not-regular-file",`${r} must be a regular file`,{cause:l}):l}try{let[l,d,u]=await Promise.all([c.stat({bigint:i}),Oe.lstat(t,{bigint:i}),Oe.realpath(t)]);if(!l.isFile()||!d.isFile()||d.isSymbolicLink()||u!==o||!Jn(s,l)||!Jn(s,d))throw new ye("changed",`${r} changed while opening`);await n.verify?.("post-open",{realPath:u,identity:At(l)}),await n.hooks?.afterOpen?.();let f=[],m=0,w=Buffer.allocUnsafe(Math.min(64*1024,e+1));for(;;){let v=e+1-m,{bytesRead:k}=await c.read(w,0,Math.min(w.length,v),null);if(k===0)break;if(m+=k,m>e)throw new ye("too-large",`${r} exceeds ${e} bytes`);f.push(Buffer.from(w.subarray(0,k)))}await n.hooks?.beforeFinalCheck?.();let[p,h,y]=await Promise.all([c.stat({bigint:i}),Oe.lstat(t,{bigint:i}),Oe.realpath(t)]);if(!h.isFile()||h.isSymbolicLink()||y!==o||!Jn(s,p)||!Jn(s,h))throw new ye("changed",`${r} changed while reading`);return await n.verify?.("post-read",{realPath:y,identity:At(p)}),{bytes:Buffer.concat(f,m),stat:p,realPath:y}}finally{await c.close()}}var ye,es=q(()=>{"use strict";Un();ye=class extends Error{reason;constructor(e,n,r){super(n,r),this.name="RaceSafeReadError",this.reason=e}}});import{promises as Gn}from"fs";import be from"path";function fh(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}function ts(t,e){let n=be.relative(t,e);return n===""||!be.isAbsolute(n)&&n!==".."&&!n.startsWith(`..${be.sep}`)}async function vc(t,e){let n=be.resolve(t),r=await Gn.lstat(n);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${e} project root must be a real directory`);return Gn.realpath(n)}async function kc(t,e,n,r){let i=t;for(let s=0;s{if(!ts(s,a.realPath))throw new Error(`${r.label} resolves outside the project root`);await kc(i.projectRoot,s,i.relative.split("/"),{label:r.label,expected:"file"})}})}var ne=q(()=>{"use strict";es();ge()});import{createHash as dh}from"crypto";function ph(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function ns(t,e={}){return(await zn(t,e)).document}async function hh(t){try{return(await J(t,xt,Ot,{label:xt})).bytes}catch(e){if(ph(e))return null;throw e}}function mh(t){return t?{exists:!0,sha256:dh("sha256").update(t).digest("hex")}:{exists:!1,sha256:null}}async function zn(t,e={}){let n=await hh(t);return{document:n?Ye(n.toString("utf8"),e):null,identity:mh(n)}}var xt,Tt=q(()=>{"use strict";ge();ne();xt=".comet/config.yaml"});import{randomUUID as gh}from"crypto";import{constants as wh,promises as A}from"fs";import L from"path";async function rs(t,e){try{return await A.link(t,e),{linked:!0}}catch(n){let r=n.code;if(r!=="ENOTSUP"&&r!=="EOPNOTSUPP")throw n}return await A.copyFile(t,e,wh.COPYFILE_EXCL),{linked:!1}}function Ue(t,e){let n=L.relative(t,e);return n===""||!L.isAbsolute(n)&&n!==".."&&!n.startsWith(`..${L.sep}`)}function Qn(t){return{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs}}function yh(t,e){return te(t,Qn(e))}function Xn(t,e){let n=Qn(t),r=Qn(e);return Yn(n,r)?te(n,r):te(n,r)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.size===e.size}async function Zn(t){let e=await A.lstat(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Contained atomic write parent must be a real directory: ${t}`);return{path:t,realPath:await A.realpath(t),...Qn(e)}}async function ve(t){for(let e of t){let n=await A.lstat(e.path);if(!n.isDirectory()||n.isSymbolicLink()||!yh(e,n)||await A.realpath(e.path)!==e.realPath)throw new Error(`Contained atomic write parent changed before commit: ${e.path}`)}}async function bh(t,e){let n=L.resolve(t),r=L.resolve(e);if(!Ue(n,r))throw new Error(`Contained atomic write parent is outside its managed root: ${e}`);let i=[await Zn(n)],s=L.relative(n,r).split(L.sep).filter(Boolean),o=n;for(let a of s){await ve(i),o=L.join(o,a);try{await A.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await Zn(o);if(!Ue(i[0].realPath,c.realPath))throw new Error(`Contained atomic write parent resolves outside its managed root: ${o}`);i.push(c)}return await ve(i),i}async function vh(t,e){let n=L.resolve(t),r=L.resolve(e);if(!Ue(n,r))throw new Error(`Contained file parent is outside its managed root: ${e}`);let i=[await Zn(n)],s=L.relative(n,r).split(L.sep).filter(Boolean),o=n;for(let a of s){o=L.join(o,a);try{let c=await Zn(o);if(!Ue(i[0].realPath,c.realPath))throw new Error(`Contained file parent resolves outside its managed root: ${o}`);i.push(c)}catch(c){if(c.code==="ENOENT")return null;throw c}}return await ve(i),i}async function Sc(t){let e;try{e=await A.open(t,"r"),await e.sync()}catch(n){let r=n.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(r??""))throw n}finally{await e?.close()}}async function kh(t,e,n){let r=L.dirname(t),i=await bh(n.containedRoot,r),s=L.join(r,`.${L.basename(t)}.${gh()}.tmp`),o,a;try{await n.beforeTemporaryOpen?.(),o=await A.open(s,"wx"),a=await o.stat();let[c,l]=await Promise.all([A.lstat(s),A.realpath(s)]);if(await ve(i),!c.isFile()||c.isSymbolicLink()||!Xn(a,c)||!Ue(i[0].realPath,l))throw new Error("Contained atomic write temporary file opened outside its managed parent");if(typeof e=="string"?await o.writeFile(e,"utf8"):await o.writeFile(e),await o.sync(),!Xn(a,await o.stat()))throw new Error("Contained atomic write temporary file changed while writing");await o.close(),o=void 0,await n.beforeCommit?.(),await ve(i);let d=await A.lstat(s);if(!d.isFile()||d.isSymbolicLink()||!Xn(d,a))throw new Error("Contained atomic write temporary file changed before commit");n.exclusive?(await rs(s,t),await A.unlink(s)):await A.rename(s,t),await Sc(r)}catch(c){await o?.close();try{await ve(i),await A.rm(s,{force:!0})}catch{}throw c}}async function re(t,e,n){await kh(t,e,n)}async function is(t,e){let n=L.dirname(t),r=await vh(e.containedRoot,n);if(!r)return!1;let i,s;try{i=await A.lstat(t),s=await A.realpath(t)}catch(c){if(c.code==="ENOENT")return!1;throw c}if(!i.isFile()||i.isSymbolicLink()||!Ue(r[0].realPath,s))throw new Error("Contained file removal target must be a regular file inside its managed root");await e.beforeRemove?.(),await ve(r);let[o,a]=await Promise.all([A.lstat(t),A.realpath(t)]);if(!o.isFile()||o.isSymbolicLink()||!Xn(i,o)||a!==s)throw new Error("Contained file removal target changed before removal");return await A.unlink(t),await ve(r),await Sc(n),!0}var Ne=q(()=>{"use strict";Un()});var Jw,ss=q(()=>{"use strict";Ne();Tt();ne();Jw=16*1024});var as=q(()=>{"use strict";Ne();ge();Tt();ne();ss()});var rr=q(()=>{"use strict"});var Dc=q(()=>{"use strict"});var ms=q(()=>{"use strict";rr()});var $c=q(()=>{"use strict";rr();ms()});var tm,Wc=q(()=>{"use strict";tm=Bt(_t(),1);Ne();ge();ne()});var Mc=q(()=>{"use strict";rr();Ne();Dc();$c();ge();Wc();ne();Tt();as();ss();ms()});import{TextDecoder as nm}from"util";function Fc(t){return{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs}}function rm(t,e){try{return new nm("utf-8",{fatal:!0}).decode(t.bytes)}catch(n){throw new Error(`${e} is not valid UTF-8`,{cause:n})}}async function gs(t,e,n,r,i={}){try{let s=await J(t,e,n,{label:r,hooks:i.hooks});return{result:s,text:rm(s,r)}}catch(s){let o=s.code;if(o==="ENOENT"||o==="ENOTDIR")return null;throw s}}async function Bc(t,e,n,r,i={}){return(await gs(t,e,n,r,i))?.text??null}async function Kc(t,e,n,r,i,s={}){if(Buffer.byteLength(n,"utf8")>r)throw new Error(`${i} exceeds ${r} bytes`);let o=await gs(t,e,r,i),a=await M(t,e,{label:i,expected:"file"});await re(a.target,n,{containedRoot:a.projectRoot,beforeCommit:async()=>{await s.beforeCommit?.();let c=await gs(t,e,r,i);if(!(!o&&!c)){if(!o||!c)throw new Error(`${i} changed before commit`);if(o.result.realPath!==c.result.realPath||!te(Fc(o.result.stat),Fc(c.result.stat))||o.text!==c.text)throw new Error(`${i} changed before commit`)}}})}async function Yc(t,e,n,r={}){let i=await M(t,e,{label:n,expected:"file"});return i.exists?is(i.target,{containedRoot:i.projectRoot,beforeRemove:r.beforeRemove}):!1}var Uc=q(()=>{"use strict";Mc();Un()});var zc={};El(zc,{RUN_STATE_FILE:()=>sr,applyRunStateToDocument:()=>Jc,readRunState:()=>ws,removeRunState:()=>Gc,runStateFromDocument:()=>ir,writeRunState:()=>ys});import im from"path";function Dt(t,e){let n=t[e];if(typeof n!="string"||n.length===0)throw new Error(`Invalid Run state: ${e} must be a non-empty string`);return n}function qt(t,e){let n=Dt(t,e);if(im.isAbsolute(n)||/^(?:[A-Za-z]:|[\\/]|~)/u.test(n)||n.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Run state: ${e} must stay inside the change directory`);return n}function sm(t){let e=t.run_retries??"{}",n;try{n=typeof e=="string"?JSON.parse(e):e}catch(r){throw new Error("Invalid Run state: run_retries must be a JSON object",{cause:r})}if(!n||typeof n!="object"||Array.isArray(n))throw new Error("Invalid Run state: run_retries must be a JSON object");for(let r of Object.values(n))if(!Number.isInteger(r)||Number(r)<0)throw new Error("Invalid Run state: retry counts must be non-negative integers");return n}function ir(t){if(!t.run_id)return null;let e=Dt(t,"run_id"),n=Dt(t,"skill"),r=Dt(t,"skill_version"),i=Dt(t,"skill_hash"),s=qt(t,"pending_ref"),o=qt(t,"trajectory_ref"),a=qt(t,"context_ref"),c=qt(t,"artifacts_ref"),l=qt(t,"checkpoint_ref"),d=Number(t.iteration);if(!Number.isInteger(d)||d<0)throw new Error("Invalid Run state: iteration must be a non-negative integer");if(t.orchestration!=="deterministic"&&t.orchestration!=="adaptive")throw new Error("Invalid Run state: orchestration must be deterministic or adaptive");if(t.run_status!=="running"&&t.run_status!=="waiting"&&t.run_status!=="completed"&&t.run_status!=="failed")throw new Error("Invalid Run state: run_status is invalid");return{runId:e,skill:n,skillVersion:r,skillHash:i,orchestration:t.orchestration,currentStep:Hc(t,"current_step"),iteration:d,pending:Hc(t,"pending"),pendingRef:s,trajectoryRef:o,contextRef:a,artifactsRef:c,checkpointRef:l,status:t.run_status,retries:sm(t)}}function Jc(t,e){e?t.run_id=e.runId:delete t.run_id}function om(t){return{runId:t.runId,skill:t.skill,skillVersion:t.skillVersion,skillHash:t.skillHash,orchestration:t.orchestration,currentStep:t.currentStep,iteration:t.iteration,pending:t.pending,pendingRef:t.pendingRef,trajectoryRef:t.trajectoryRef,contextRef:t.contextRef,artifactsRef:t.artifactsRef,checkpointRef:t.checkpointRef,status:t.status,retries:t.retries}}function am(t){let e={run_id:t.runId,skill:t.skill,skill_version:t.skillVersion,skill_hash:t.skillHash,orchestration:t.orchestration,current_step:t.currentStep,iteration:t.iteration,pending:t.pending,pending_ref:t.pendingRef,trajectory_ref:t.trajectoryRef,context_ref:t.contextRef,artifacts_ref:t.artifactsRef,checkpoint_ref:t.checkpointRef,run_status:t.status,run_retries:JSON.stringify(t.retries)};return ir(e)}async function ws(t,e={}){let n=await Bc(t,sr,Vc,"Run state",e);if(n===null)return null;let r=JSON.parse(n);return am(r)}async function ys(t,e,n={}){await Kc(t,sr,JSON.stringify(om(e),null,2),Vc,"Run state",n)}async function Gc(t,e={}){await Yc(t,sr,"Run state",e)}var Hc,sr,Vc,or=q(()=>{"use strict";Uc();Hc=(t,e)=>{let n=t[e];return n==null?null:String(n)};sr=".comet/run-state.json",Vc=256*1024});import{promises as fr,readFileSync as Tm}from"fs";import K from"path";var Es=null;function _s(t,e){let n=t;for(let r of e)n+="\0"+(typeof r=="string"?r:JSON.stringify(r));return n}function Ve(t,e){return(...n)=>{let r=Es;if(r===null)return e(...n);let i=_s(`async:${t}`,n),s=r.entries.get(i);if(s)return s.value;let o=e(...n).catch(a=>{throw r.entries.delete(i),a});return r.entries.set(i,{value:o}),o}}function pr(t,e){return(...n)=>{let r=Es;if(r===null)return e(...n);let i=_s(`sync:${t}`,n),s=r.entries.get(i);if(s)return s.value;let o=e(...n);return r.entries.set(i,{value:o}),o}}import F from"path";import{promises as Pl}from"fs";async function hr(t){try{return await Pl.access(t),!0}catch(e){if(Ol(e))return!1;throw e}}function Ol(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}ge();Tt();as();ne();var Rt=class extends Error{code="classic-layout-unavailable";constructor(e="Classic artifact layout is unavailable from .comet/config.yaml"){super(e),this.name="ClassicLayoutUnavailableError"}},cs=class extends Error{constructor(n,r,i){let s=I(i,n),o=I(i,r);super(`Classic layout conflict: both ${s}/ and ${o}/ exist; run comet doctor and resolve the conflict before writing`);this.configuredRoot=n;this.alternateRoot=r;this.name="ClassicLayoutConflictError"}configuredRoot;alternateRoot;code="classic-layout-conflict"},_c=".comet/config.yaml";async function Ph(t){await M(t,_c,{label:_c,expected:"file"})}function Pc(t,e){let n=F.resolve(t),r=e==="docs"?F.join(n,"docs"):n,i=F.join(r,"openspec"),s=F.join(n,"docs","superpowers");return{projectRoot:n,artifactLayout:e,openSpecBase:r,openSpecRoot:i,changesDir:F.join(i,"changes"),archiveDir:F.join(i,"changes","archive"),specsDir:F.join(i,"specs"),superpowersRoot:s,superpowersSpecsDir:F.join(s,"specs"),superpowersPlansDir:F.join(s,"plans"),superpowersReportsDir:F.join(s,"reports")}}async function Oh(t){await Ph(t);let e=await ns(t,{allowPartialProject:!0,allowMissingNativeFields:!0});if(!e?.config)throw new Rt;if(!(e.config.workflows??[e.config.default_workflow]).includes("classic"))throw new Rt("Classic artifact layout is unavailable because Classic is not enabled");return e.classic?.artifact_layout??"legacy"}async function Nh(t,e){return Pc(t,e??await Oh(t))}async function Ah(t,e){let n=await Nh(t,e),r=n.artifactLayout==="legacy"?"docs":"legacy",i=Pc(t,r).openSpecRoot,[s,o]=await Promise.all([M(n.projectRoot,I(n.projectRoot,n.openSpecRoot),{label:"Configured Classic OpenSpec root",expected:"directory"}),M(n.projectRoot,I(n.projectRoot,i),{label:"Alternate Classic OpenSpec root",expected:"directory"})]),a=s.exists,c=o.exists;return{paths:n,configuredRootExists:a,alternateRoot:i,alternateRootExists:c,dualRoots:a&&c}}async function xh(t,e){let n=[t.openSpecRoot,t.changesDir,t.archiveDir,t.specsDir,e,t.superpowersRoot,t.superpowersSpecsDir,t.superpowersPlansDir,t.superpowersReportsDir];for(let r of n){let i=I(t.projectRoot,r);await M(t.projectRoot,i,{label:`Classic managed physical path ${i}`,expected:"directory"})}}async function Ae(t,e,n={}){let r=await Ah(t,e);if(await xh(r.paths,r.alternateRoot),r.dualRoots&&!n.allowAlternateRoot)throw new cs(r.paths.openSpecRoot,r.alternateRoot,r.paths.projectRoot);if(!r.configuredRootExists){let i=I(r.paths.projectRoot,r.paths.openSpecRoot),s=I(r.paths.projectRoot,r.alternateRoot);throw new Rt(`Configured Classic OpenSpec root is missing: ${i} (alternate ${s} is ${r.alternateRootExists?"present":"missing"})`)}return r.paths}async function ls(t,e,n={}){let r=F.join(F.resolve(t),".comet","classic-root-move.json");if(await hr(r))throw new Error("Classic root move transaction is incomplete; inspect it with comet doctor and recover it explicitly before writing");let i=await Ae(t,e,n);if(!await hr(i.openSpecRoot))throw new Error(`Configured Classic OpenSpec root is missing: ${I(i.projectRoot,i.openSpecRoot)}`);return i}function I(t,e){return F.relative(F.resolve(t),e).replaceAll("\\","/")}import Nc from"path";Ne();ge();ne();import It from"path";var py=2*1024*1024;function Rh(t,e,n){let r=It.resolve(t),i=It.isAbsolute(e)?It.resolve(e):It.resolve(r,e),s=It.relative(r,i).replaceAll("\\","/");return{root:r,relative:Nt(s,n),target:i}}async function He(t,e,n){let r=Rh(t,e,n.label);return M(r.root,r.relative,n)}async function Oc(t,e,n){return(await He(t,e,{label:n.label,expected:n.expected??"any"})).exists}function us(t){return t?/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t)?t.includes("..")?"Change name cannot contain '..' (path traversal not allowed)":null:`Invalid change name: '${t}' -Valid format: lowercase kebab-case (a-z, 0-9, single hyphens)`:"Change name cannot be empty"}function fs(t){let e=us(t);if(e)throw new Error(e)}function Ih(t,e){return{label:I(t,e),directory:e}}async function jh(t,e,n){let r=Ih(t,e);if(!(await He(t,e,{label:n,expected:"directory"})).exists)return{change:r,exists:!1,stateExists:!1};let s=await He(t,Nc.join(e,".comet.yaml"),{label:`${n} state`,expected:"file"});return{change:r,exists:!0,stateExists:s.exists}}async function jt(t,e=process.cwd()){fs(t);let n=await Ae(e),r=await jh(n.projectRoot,Nc.join(n.changesDir,t),`Classic active change ${t}`);return{...r.change,exists:r.exists,stateExists:r.stateExists}}import{promises as ds}from"fs";import B from"path";function Ac(t,e){let n=B.relative(t,e);return n===""||n!==".."&&!n.startsWith(`..${B.sep}`)&&!B.isAbsolute(n)}async function Lh(t){let e=B.resolve(t),n=B.parse(e).root,r=[],i=e;for(;i&&i!==n;)try{let s=await ds.realpath(i);return B.join(s,...r.reverse())}catch(s){let o=s.code;if(o!=="ENOENT"&&o!=="ENOTDIR")throw s;r.push(B.basename(i)),i=B.dirname(i)}try{let s=await ds.realpath(n);return B.join(s,...r.reverse())}catch{return null}}async function xc(t,e){let n=B.resolve(t),r=await ds.realpath(n),i=[],s=[];for(let o of e){let a=B.isAbsolute(o)?B.resolve(o):B.resolve(n,o),c=await Lh(a);((c?Ac(r,c):Ac(n,a))?i:s).push(o)}return{projectTargets:i,externalTargets:s}}var ps=Bt(_t(),1);import{execFileSync as Tc}from"child_process";import{randomUUID as qh}from"crypto";import{promises as Lt}from"fs";import Rc from"path";function Dh(t){try{let e=Tc("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();return e&&e!=="HEAD"?e:null}catch{return null}}var $h=pr("liveGitBranch",t=>Dh(t));function Wh(t){try{return Tc("git",["rev-parse","--is-inside-work-tree"],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()==="true"}catch{return!1}}var Mh=pr("isGitWorkTree",t=>Wh(t)),Fh=["current","branch","worktree"];function Ic(t){return Fh.includes(t)}function Bh(t){return Ic(t.isolation)?t.boundBranch===null&&t.currentBranch===null&&t.gitWorkTree===!1?{status:"not-applicable"}:t.boundBranch===null?t.currentBranch===null?{status:"unbound-detached"}:{status:"needs-heal",branch:t.currentBranch}:t.currentBranch===t.boundBranch?{status:"ok"}:{status:"drift",boundBranch:t.boundBranch,currentBranch:t.currentBranch}:{status:"not-applicable"}}async function er(t,e){let n=Rc.join(t,".comet.yaml"),r=(0,ps.parseDocument)(await Lt.readFile(n,"utf8"),{uniqueKeys:!1});if(r.errors.length>0)throw new Error(`Invalid .comet.yaml: ${r.errors[0].message}`);let i=r.toJS()??{},s=typeof i.isolation=="string"?i.isolation:null,o=typeof i.bound_branch=="string"&&i.bound_branch!==""?i.bound_branch:null,a=Ic(s),c=$h(e.cwd),l=a&&o===null&&c===null?Mh(e.cwd):!0,d=Bh({isolation:s,boundBranch:o,currentBranch:c,gitWorkTree:l});return d.status==="needs-heal"&&e.heal?(await Kh(t,d.branch),{status:"healed",branch:d.branch,bindingRequired:a,currentBranch:c}):{...d,bindingRequired:a,currentBranch:c}}async function Kh(t,e){let n=Rc.join(t,".comet.yaml"),r=(0,ps.parseDocument)(await Lt.readFile(n,"utf8"),{uniqueKeys:!1});r.set("bound_branch",e);let i=`${n}.${qh()}.tmp`;try{await Lt.writeFile(i,r.toString(),"utf8"),await Lt.rename(i,n)}catch(s){throw await Lt.rm(i,{force:!0}),s}}function Yh(t){return t??"detached HEAD"}function tr(t,e,n){return`change '${t}' is bound to branch '${e}', but current branch is '${Yh(n)}'`}function nr(t){return`change '${t}' uses a branch-bound workspace mode but has no bound branch and HEAD is detached; checkout a branch first before continuing.`}es();import Uh from"path";var hs="comet.selection.v2",Hh=16*1024;function Lc(t){return Uh.join(t,".comet","current-change.json")}function Jh(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function jc(t){return t===null||typeof t=="string"}function Vh(t){let e;try{e=JSON.parse(t)}catch(n){throw new Error(`current change selection contains invalid JSON: ${n instanceof Error?n.message:String(n)}`,{cause:n})}if(!Jh(e))throw new Error("current change selection must be a JSON object");if(e.version===1){if(typeof e.change!="string")throw new Error("legacy current change selection change must be a string");if(e.branch!==void 0&&!jc(e.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:hs,workflow:"classic",change:e.change,branch:e.branch??null},legacy:!0}}if(e.schema!==hs)throw new Error(`current change selection schema must be ${hs}`);if(e.workflow!=="native"&&e.workflow!=="classic")throw new Error("current change selection workflow must be native or classic");if(typeof e.change!="string")throw new Error("current change selection change must be a string");if(!jc(e.branch))throw new Error("current change selection branch must be a string or null");if(e.workflow==="native"&&e.branch!==null)throw new Error("Native current change selection branch must be null");return{selection:e,legacy:!1}}async function qc(t){let e;try{let r=Lc(t),{bytes:i}=await Vn(r,Hh,{label:"current change selection"});e=i.toString("utf8")}catch(r){if(r.code==="ENOENT")return{status:"missing"};throw new Error(`cannot read current change selection: ${r instanceof Error?r.message:String(r)}`,{cause:r})}return{status:"selected",...Vh(e)}}var lr=Bt(_t(),1);Ne();ne();import cr from"path";or();var vs=["full","hotfix","tweak"],Xc=1,Zc=["open","design","build","verify","archive"],cm=["en","zh-CN"],lm=["off","beta"],um=["subagent-driven-development","executing-plans","direct"],fm=["plan-ready"],dm=["confirmed"],pm=["tdd","direct"],hm=["off","standard","thorough"],mm=["current","branch","worktree"],gm=["light","full"],wm=["pending","pass","fail"],ym=["pending","handled"],bm=["pending","confirmed"],ks=["workflow","language","phase","context_compression","build_mode","build_pause","subagent_dispatch","tdd_mode","review_mode","isolation","bound_branch","verify_mode","auto_transition","base_ref","design_doc","plan","verify_result","verify_failures","verification_report","branch_status","created_at","verified_at","archive_confirmation","archived","direct_override","handoff_context","handoff_hash","classic_profile","classic_migration"],vm=["run_id"],el=new Set([...ks,...vm]),km=["workflow","phase","design_doc","plan","build_mode","isolation","verify_mode","verify_result","verified_at","archived"];function Qc(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function Je(t,e){let n=t[e];if(n==null||n==="")return null;if(typeof n!="string")throw new Error(`Invalid Classic state: ${e} must be a string or null`);return n}function D(t,e,n,r=!0){let i=t[e];if(i==null||i===""){if(r)return null;throw new Error(`Invalid Classic state: ${e} is required`)}if(typeof i!="string"||!n.includes(i))throw new Error(`Invalid Classic state: ${e} must be one of ${n.join(", ")}${r?" or null":""}`);return i}function bs(t,e,n=!0){let r=t[e];if(r==null||r===""){if(n)return null;throw new Error(`Invalid Classic state: ${e} is required`)}if(typeof r!="boolean")throw new Error(`Invalid Classic state: ${e} must be true or false`);return r}function Sm(t,e,n=0){let r=t[e];if(r==null||r==="")return n;if(typeof r!="number"||!Number.isInteger(r)||r<0)throw new Error(`Invalid Classic state: ${e} must be a non-negative integer`);return r}function ar(t,e){let n=Je(t,e);if(n===null)return null;if(/^(?:[A-Za-z]:|[\\/]|~)/u.test(n)||n.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Classic state: ${e} must be a relative repository path`);return n}function Cm(t,e){let n=Je(t,e);if(n!==null&&!/^[a-f0-9]{64}$/u.test(n))throw new Error(`Invalid Classic state: ${e} must be a sha256 hex digest`);return n}function Em(t){let e=t.classic_migration;if(e==null||e==="")return null;if(e!==Xc)throw new Error(`Invalid Classic state: classic_migration must be ${Xc}`);return e}function _m(t){if(!ks.some(n=>Qc(t,n)))return null;for(let n of km)if(!Qc(t,n))return null;return{workflow:D(t,"workflow",vs,!1),language:D(t,"language",cm),phase:D(t,"phase",Zc,!1),contextCompression:D(t,"context_compression",lm),buildMode:D(t,"build_mode",um),buildPause:D(t,"build_pause",fm),subagentDispatch:D(t,"subagent_dispatch",dm),tddMode:D(t,"tdd_mode",pm),reviewMode:D(t,"review_mode",hm),isolation:D(t,"isolation",mm),boundBranch:Je(t,"bound_branch"),verifyMode:D(t,"verify_mode",gm),autoTransition:bs(t,"auto_transition"),baseRef:Je(t,"base_ref"),designDoc:ar(t,"design_doc"),plan:ar(t,"plan"),verifyResult:D(t,"verify_result",wm,!1),verifyFailures:Sm(t,"verify_failures"),verificationReport:ar(t,"verification_report"),branchStatus:D(t,"branch_status",ym),createdAt:Je(t,"created_at"),verifiedAt:Je(t,"verified_at"),archiveConfirmation:D(t,"archive_confirmation",bm),archived:bs(t,"archived",!1),directOverride:bs(t,"direct_override"),handoffContext:ar(t,"handoff_context"),handoffHash:Cm(t,"handoff_hash"),classicProfile:D(t,"classic_profile",vs),classicMigration:Em(t)}}function tl(t,e){let n=e??null;if(n===null&&e===void 0&&t.run_id&&t.skill)try{n=ir(t)}catch(r){let i=r instanceof Error?r.message:String(r);throw new Error(i.replace(/^Invalid Run state:/u,"Invalid Classic state:"),{cause:r})}return{classic:_m(t),run:n,unknownKeys:Object.keys(t).filter(r=>!el.has(r))}}function nl(t){let e=t.workflow,n=t.phase,r=t.archived,i=t.design_doc;return{workflow:typeof e=="string"&&vs.includes(e)?e:null,phase:typeof n=="string"&&Zc.includes(n)?n:null,archived:r===!0,designDoc:typeof i=="string"&&i!==""?i:null,unknownKeys:Object.keys(t).filter(s=>!el.has(s))}}or();var Pm=2*1024*1024;function $t(t){let e=t.toJS();if(e===null)return{};if(typeof e!="object"||Array.isArray(e))throw new Error("Invalid Classic state document: root must be a mapping");return e}function Om(t){let e=["skill","skill_version","skill_hash","orchestration","current_step","iteration","pending","pending_ref","trajectory_ref","context_ref","artifacts_ref","checkpoint_ref","run_status","run_retries"];for(let n of e)t.delete(n)}function Nm(t){let e=!1;for(let n of["build_command","verify_command"])t.has(n)&&(t.delete(n),e=!0);return e}async function rl(t){let e;try{e=(await J(cr.dirname(t),cr.basename(t),Pm,{label:"Classic state document"})).bytes.toString("utf8")}catch(r){if(r.code!=="ENOENT")throw r;return new lr.Document({})}let n=(0,lr.parseDocument)(e);if(n.errors.length>0)throw new Error(`Invalid Classic state document: ${n.errors[0].message}`);return $t(n),n}async function ur(t,e={}){let n=e.migrate!==!1,r=cr.join(t,".comet.yaml"),i=await rl(r),s=$t(i),o=Nm(i);o&&(s=$t(i));let a=await ws(t);if(!a&&s.run_id&&s.skill){let{runStateFromDocument:c}=await Promise.resolve().then(()=>(or(),zc));a=c(s),a&&n&&(await ys(t,a),Om(i),o=!0)}return o&&n&&await re(r,i.toString(),{containedRoot:t}),tl($t(i),a)}async function il(t){let e=await rl(cr.join(t,".comet.yaml"));return nl($t(e))}var Am=Ve("readCometCurrentSelection",t=>qc(t));async function xm(t,e){fs(e);let n=await jt(e,t);if(!n.stateExists)throw new Error(`Cannot select current change '${e}': active change state not found`);let r=await ur(n.directory,{migrate:!1});if(!r.classic)throw new Error(`Cannot select current change '${e}': Classic state is incomplete`);if(r.classic.archived)throw new Error(`Cannot select current change '${e}': change is archived`);return n.directory}async function sl(t){let e;try{e=await Am(t)}catch(s){return{status:"stale",reason:s instanceof Error?s.message:String(s)}}if(e.status==="missing")return{status:"missing"};if(e.selection.workflow!=="classic")return{status:"stale",reason:`current change '${e.selection.change}' belongs to Native, not Classic`};let n=e.selection,r;try{r=await xm(t,n.change)}catch(s){return{status:"stale",reason:s instanceof Error?s.message:String(s)}}let i=await er(r,{heal:!1,cwd:t});return i.status==="drift"?{status:"stale",reason:tr(n.change,i.boundBranch,i.currentBranch)}:i.status==="unbound-detached"?{status:"stale",reason:nr(n.change)}:i.status==="ok"?{status:"selected",selection:n}:n.branch!==null&&i.currentBranch!==n.branch?{status:"stale",reason:`current change '${n.change}' was selected on branch '${n.branch}', current branch is '${i.currentBranch??"detached HEAD"}'`}:{status:"selected",selection:n}}import xe from"node:path";async function ol(t,e){if(!e||e==="null")return{status:"missing",recordedPath:null};let n=await Ae(t),r=xe.resolve(t,e),i=xe.relative(n.superpowersPlansDir,r);return xe.isAbsolute(e)||!i||i.startsWith(`..${xe.sep}`)||xe.isAbsolute(i)||i.includes(xe.sep)||xe.extname(i).toLowerCase()!==".md"?{status:"broken",recordedPath:e}:await Oc(t,e,{label:`Classic build plan ${e}`,expected:"file"})?{status:"ready",recordedPath:e}:{status:"broken",recordedPath:e}}function V(t,e){return{exitCode:t,stderr:e+` -`}}function X(t){return V(0,`[COMET-HOOK] allowed: ${t}`)}function Rm(){if(process.env.FILE_PATH)return process.env.FILE_PATH;if(process.stdin.isTTY)return"";let t=Tm(0,"utf8");if(!t)return"";try{let e=JSON.parse(t);return typeof e.tool_input?.file_path=="string"?e.tool_input.file_path:""}catch{return""}}function Mt(t){return t.replaceAll("\\","/").replace(/\/+/gu,"/")}function Te(t){let e=Mt(t);return process.platform==="win32"?e.toLowerCase():e}function Im(t){let e=t.indexOf("--project-root"),n=e>=0?t[e+1]:void 0;return K.resolve(n&&!n.startsWith("--")?n:process.cwd())}function al(t,e){let n=Mt(K.relative(e,t));return n===""?"":n.startsWith("../")||n===".."||K.isAbsolute(n)?null:n}async function jm(t){let e=K.resolve(t),n=K.parse(e).root,r=[],i=e;for(;i&&i!==n;)try{let s=await fr.realpath(i);return K.join(s,...r.reverse())}catch(s){let o=s.code;if(o!=="ENOENT"&&o!=="ENOTDIR")throw s;r.push(K.basename(i)),i=K.dirname(i)}try{let s=await fr.realpath(n);return K.join(s,...r.reverse())}catch{return null}}async function Lm(t,e){let n=K.isAbsolute(t)?t:K.resolve(e,t),r=Mt(n),i=al(n,e);if(i!==null)return i;try{let s=await jm(n),o=await fr.realpath(e);if(s){let a=al(s,o);if(a!==null)return a;r=Mt(s)}}catch{if(!K.isAbsolute(t))return Mt(t).replace(/^\.\//u,"")}return r.replace(/^\.\//u,"")}async function fl(t){try{let e=await ur(t,{migrate:!1}),n=Array.from(new Set(e.unknownKeys)).sort();if(n.length>0)throw new Error(`Invalid Classic state: unknown field(s): ${n.join(", ")}`);if(!e.classic)throw new Error("Classic state projection is unavailable");return{changeDir:t,phase:e.classic.phase,classic:e.classic,archived:e.classic.archived}}catch(e){let n=await il(t);return n.phase?{changeDir:t,phase:n.phase,classic:null,archived:n.archived,invalidState:e instanceof Error&&e.message.includes("unknown field")}:null}}async function qm(t){let e=(await Ae(t)).changesDir,n=[];if(!(await He(t,e,{label:"Classic changes directory",expected:"directory"})).exists)return n;for(let i of(await fr.readdir(e,{withFileTypes:!0})).sort((s,o)=>s.name.localeCompare(o.name))){if(i.name==="archive"||us(i.name))continue;let s=await jt(i.name,t);if(!s.exists||!s.stateExists)continue;let o=await fl(s.directory);!o||o.archived||n.push(o)}return n}var Ss=Ve("classicActiveChanges",t=>qm(t)),dl=Ve("classicPlanReadiness",ol);function pl(t,e){return`${I(t,e.superpowersRoot)}/`}function hl(t,e){return Te(t).startsWith(Te(e))}function Dm(t,e){return[{prefix:`${I(t,e.superpowersSpecsDir)}/`,field:"designDoc",wireField:"design_doc",phase:"design"},{prefix:`${I(t,e.superpowersPlansDir)}/`,field:"plan",wireField:"plan",phase:"build"},{prefix:`${I(t,e.superpowersReportsDir)}/`,field:"verificationReport",wireField:"verification_report",phase:"verify"}]}function $m(t,e){let n=Te(t),r=e.find(s=>n.startsWith(Te(s.prefix)));if(!r)return null;let i=n.slice(Te(r.prefix).length);return!i||i.includes("/")||!i.endsWith(".md")?null:r}function ml(t,e){return t.classic?.[e.field]??null}function Wm(t,e){return t.classic!==null&&t.phase===e.phase&&!ml(t,e)}async function cl(t,e,n){return Wm(e,n)?!0:n.field!=="plan"||e.phase!=="build"?!1:(await dl(t,e.classic?.plan??null)).status==="broken"}function gl(t){return t.phase==="design"||t.phase==="build"||t.phase==="verify"}function ie(t){return t.changeDir?K.basename(t.changeDir):null}var Mm=new Set(["design","plan","verify","verification","verification-report","report"]);function ll(t){return t.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}function Fm(t,e){return[e.classic?.designDoc,e.classic?.plan,e.classic?.verificationReport].some(r=>r&&Te(r)===Te(t))}function Bm(t,e){let r=(t.split("/").at(-1)??t).replace(/\.[^.]+$/u,"");if(r===e)return!0;let i=[...Mm].map(ll).join("|");return new RegExp(`(^|[-_.])${ll(e)}[-_.](${i})$`,"u").test(r)}async function Km(t,e){let n=await Ss(e),r=n.find(o=>Fm(t,o));if(r)return{governing:r,match:"recorded"};let s=n.filter(gl).filter(o=>{let a=ie(o);return a!==null&&Bm(t,a)}).sort((o,a)=>(ie(a)?.length??0)-(ie(o)?.length??0))[0];return s?{governing:s,match:"named"}:null}async function ul(t,e,n){let r=await Ss(t);if(r.length===0)return null;if(n)return r.find(o=>ie(o)===n)??{blockedResult:Wt(e,`selected change '${n}' is no longer active`)};let i=await sl(t);if(i.status==="stale")return{blockedResult:Wt(e,i.reason)};if(i.status==="selected"){let s=r.find(o=>ie(o)===i.selection.change);return s||{blockedResult:Wt(e,`selected change '${i.selection.change}' is no longer active`)}}if(r.length===1){let s=r[0];if(s.changeDir!==null){let o=await er(s.changeDir,{heal:!1,cwd:t}),a=ie(s)??"unknown";if(o.status==="drift")return{blockedResult:Wt(e,tr(a,o.boundBranch,o.currentBranch))};if(o.status==="unbound-detached")return{blockedResult:Wt(e,nr(a))}}return s}return{blockedResult:Zm(e,r.map(s=>ie(s)).filter(Boolean))}}async function Ym(t,e,n,r){let i=`${I(e,n.changesDir)}/`;if(t.startsWith(i)){let s=t.slice(i.length),[o]=s.split("/");if(o&&o!=="archive"){let a=await jt(o,e);if(a.stateExists){let c=await fl(a.directory);return c||{changeDir:a.directory,phase:"open",classic:null,archived:!1}}return{changeDir:a.directory,phase:"open",classic:null,archived:!1}}}if(hl(t,pl(e,n))){let s=await Km(t,e);if(s?.match==="recorded")return{...s.governing,superpowersArtifact:"matched"};let o=$m(t,Dm(e,n));if(s)return o?{...s.governing,superpowersArtifact:await cl(e,s.governing,o)?"matched":"unmatched",superpowersSlot:o}:{...s.governing,superpowersArtifact:"matched"};if(o){let l=await ul(e,t,r);return!l||"blockedResult"in l?l:{...l,superpowersArtifact:await cl(e,l,o)?"matched":"unmatched",superpowersSlot:o}}let a=await Ss(e),c=r?a.find(l=>ie(l)===r)??null:a[0]??null;return c?{...c,superpowersArtifact:"unmatched"}:null}return ul(e,t,r)}function Um(t){return!t.includes("/")&&t.endsWith(".md")}function Hm(t){return t.startsWith(".comet/")||t.includes("/.comet/")}function Jm(t){return t===".superpowers"||t.startsWith(".superpowers/")}function Vm(t,e,n){if(!t.startsWith(n))return null;let r=t.endsWith("/.comet.yaml")||t.endsWith("/.openspec.yaml"),i=t.endsWith("/proposal.md")||t.endsWith("/design.md")||t.endsWith("/tasks.md"),s=t.includes("/.comet/"),o=t.includes("/specs/");return e==="open"&&(i||r||s||o)?`${t} (phase: open, openspec artifacts)`:e==="design"&&(i||r||s||o)?`${t} (phase: design, handoff/spec)`:e==="build"&&(t.endsWith("/tasks.md")||r||o)?`${t} (phase: build, spec/tasks)`:e==="verify"&&(t.endsWith("/tasks.md")||r)?`${t} (phase: verify, tasks/state)`:e==="archive"&&r?`${t} (phase: archive, state)`:null}function Gm(t,e){let n=e==="open"?[" BLOCKED: source writes are not allowed during open"," This phase does not allow source writes"," ALLOWED: create proposal/design/tasks artifacts and run guard"," NEXT: finish clarification and artifacts, then run guard --apply"]:e==="design"?[" BLOCKED: source writes are not allowed during design"," This phase does not allow source writes"," ALLOWED: run brainstorming, create the Design Doc, and run guard"," NEXT: finish the Design Doc, then run comet guard design --apply to enter build"]:[" BLOCKED: source writes are not allowed during archive"," This phase does not allow source writes"," ALLOWED: confirm archive state and run the archive script"];return V(2,["","╔══════════════════════════════════════════╗","║ COMET PHASE GUARD — WRITE BLOCKED ║","╚══════════════════════════════════════════╝","",` Current phase: ${e}`,` Target file: ${t}`,"",...n,""].join(` -`))}function zm(t){return V(2,["","╔══════════════════════════════════════════╗","║ COMET PHASE GUARD — WRITE BLOCKED ║","╚══════════════════════════════════════════╝",""," Current phase: build (workflow: full), but design_doc is empty",` Target file: ${t}`,""," BLOCKED: full workflow source writes require a recorded Design Doc"," This phase does not allow source writes until design_doc is recorded"," NEXT: return to design, create/link the Design Doc, then run guard again",""].join(` -`))}function Xm(t,e,n,r,i){let s=ie(e)??"",o=n.status==="missing",a=o?"classic-build-plan-missing":"classic-build-plan-broken",c=o?"plan is not recorded":"the recorded plan path does not resolve to a file",l=o?[]:[`RECORDED_PLAN: ${n.recordedPath}`],d=e.changeDir?I(r,e.changeDir):"",u=I(r,i.superpowersPlansDir),f=o?`comet state set ${s} plan `:`comet state set ${s} plan `,m=o?["2. Load the Superpowers writing-plans Skill.",`3. Read the Design Doc path from "comet state get ${s} design_doc" and read ${d}/tasks.md.`,`4. Create the implementation plan under ${u}/.`,"5. Record the plan path:",` ${f}`]:[`2. Restore the plan file at ${n.recordedPath}, or load the Superpowers writing-plans Skill and create a replacement under ${u}/.`,"3. When creating a replacement, record its path:",` ${f}`];return V(2,["","╔══════════════════════════════════════════╗","║ COMET PHASE GUARD — WRITE BLOCKED ║","╚══════════════════════════════════════════╝","",`ERROR_CODE: ${a}`,`CHANGE: ${s}`,"WORKFLOW: full","PHASE: build",`TARGET: ${t}`,`STATE: ${c}`,...l,"","BLOCKED: project source writes require a ready Superpowers implementation plan.","","ALLOWED_RECOVERY_WRITES:",`- ${u}/.md`,"- Comet state updates performed by the comet CLI",`- ${d} artifacts allowed by the build phase`,"","RECOVERY:",`1. Invoke /comet-build for ${s} and resume Step 1.`,...m,`${o?"6":"4"}. Verify recovery:`,` comet state check ${s} build --recover`,"","SUCCESS: plan is reported as DONE and recovery advances beyond plan creation.",`RETRY: retry the original Write/Edit for ${t} only after SUCCESS.`,"PROHIBITED: do not treat tasks.md as the implementation plan or write project source before SUCCESS.","If writing-plans is unavailable, stop and report the missing Skill instead of bypassing this check.",""].join(` -`))}function Qm(t,e){let n=e.superpowersSlot,r=n?ml(e,n):null,i=n?e.phase!==n.phase?[` BLOCKED: ${n.wireField} cannot be first-written in phase ${e.phase}`,` Expected phase: ${n.phase}`," NEXT: resume the matching Comet phase or use an already recorded artifact path"]:r?[` BLOCKED: ${n.wireField} is already recorded for this change`,` Recorded path: ${r}`," NEXT: write the recorded artifact or explicitly correct the state path"]:[" BLOCKED: standard Superpowers artifact state is incomplete"," NEXT: validate the active change state, then retry the matching phase"]:[" BLOCKED: unmatched Superpowers artifact"," This docs/superpowers/ path does not match any active change artifact"," NEXT: use a recorded artifact path or a standard phase artifact directory"];return V(2,["","╔══════════════════════════════════════════╗","║ COMET PHASE GUARD — WRITE BLOCKED ║","╚══════════════════════════════════════════╝","",` Current phase: ${e.phase}`,` Target file: ${t}`,"",...i,""].join(` -`))}function Zm(t,e){return V(2,["","╔══════════════════════════════════════════╗","║ COMET PHASE GUARD — WRITE BLOCKED ║","╚══════════════════════════════════════════╝",""," BLOCKED: multiple active changes require a current change",` Target file: ${t}`,` Active changes: ${e.join(", ")}`,""," NEXT: run comet state select , then retry the source write",""].join(` +`,n)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let n=Wn(e),r=Ke(n);return r.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let n=Wn(e),r=Ke(n);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,n){return this.type!=="comment"||this.indent<=n?!1:e.every(r=>r.type==="newline"||r.type==="space")}*documentEnd(e){this.type!=="doc-mode"&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};ac.Parser=Hi});var dc=g(Et=>{"use strict";var cc=Ii(),qp=mt(),Ct=yt(),Dp=Tr(),$p=_(),Wp=Ui(),lc=Ji();function uc(t){let e=t.prettyErrors!==!1;return{lineCounter:t.lineCounter||e&&new Wp.LineCounter||null,prettyErrors:e}}function Mp(t,e={}){let{lineCounter:n,prettyErrors:r}=uc(e),i=new lc.Parser(n?.addNewLine),s=new cc.Composer(e),o=Array.from(s.compose(i.parse(t)));if(r&&n)for(let a of o)a.errors.forEach(Ct.prettifyError(t,n)),a.warnings.forEach(Ct.prettifyError(t,n));return o.length>0?o:Object.assign([],{empty:!0},s.streamInfo())}function fc(t,e={}){let{lineCounter:n,prettyErrors:r}=uc(e),i=new lc.Parser(n?.addNewLine),s=new cc.Composer(e),o=null;for(let a of s.compose(i.parse(t),!0,t.length))if(!o)o=a;else if(o.options.logLevel!=="silent"){o.errors.push(new Ct.YAMLParseError(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return r&&n&&(o.errors.forEach(Ct.prettifyError(t,n)),o.warnings.forEach(Ct.prettifyError(t,n))),o}function Fp(t,e,n){let r;typeof e=="function"?r=e:n===void 0&&e&&typeof e=="object"&&(n=e);let i=fc(t,n);if(!i)return null;if(i.warnings.forEach(s=>Dp.warn(i.options.logLevel,s)),i.errors.length>0){if(i.options.logLevel!=="silent")throw i.errors[0];i.errors=[]}return i.toJS(Object.assign({reviver:r},n))}function Bp(t,e,n){let r=null;if(typeof e=="function"||Array.isArray(e)?r=e:n===void 0&&e&&(n=e),typeof n=="string"&&(n=n.length),typeof n=="number"){let i=Math.round(n);n=i<1?void 0:i>8?{indent:8}:{indent:i}}if(t===void 0){let{keepUndefined:i}=n??e??{};if(!i)return}return $p.isDocument(t)&&!r?t.toString(n):new qp.Document(t,r,n).toString(n)}Et.parse=Fp;Et.parseAllDocuments=Mp;Et.parseDocument=fc;Et.stringify=Bp});var _t=g(P=>{"use strict";var Kp=Ii(),Yp=mt(),Up=pi(),Vi=yt(),Hp=Ze(),me=_(),Jp=ue(),Vp=N(),Gp=de(),zp=pe(),Xp=Dn(),Qp=Ki(),Zp=Ui(),eh=Ji(),Fn=dc(),pc=Ge();P.Composer=Kp.Composer;P.Document=Yp.Document;P.Schema=Up.Schema;P.YAMLError=Vi.YAMLError;P.YAMLParseError=Vi.YAMLParseError;P.YAMLWarning=Vi.YAMLWarning;P.Alias=Hp.Alias;P.isAlias=me.isAlias;P.isCollection=me.isCollection;P.isDocument=me.isDocument;P.isMap=me.isMap;P.isNode=me.isNode;P.isPair=me.isPair;P.isScalar=me.isScalar;P.isSeq=me.isSeq;P.Pair=Jp.Pair;P.Scalar=Vp.Scalar;P.YAMLMap=Gp.YAMLMap;P.YAMLSeq=zp.YAMLSeq;P.CST=Xp;P.Lexer=Qp.Lexer;P.LineCounter=Zp.LineCounter;P.Parser=eh.Parser;P.parse=Fn.parse;P.parseAllDocuments=Fn.parseAllDocuments;P.parseDocument=Fn.parseDocument;P.stringify=Fn.stringify;P.visit=pc.visit;P.visitAsync=pc.visitAsync});import Bn from"path";function rh(t,e){if(typeof t!="string")throw new Error(`${e} must be a string`);let n=t.trim();if(n.length===0||Bn.posix.isAbsolute(n)||Bn.win32.isAbsolute(n)||/^(?:~|[\\/])/u.test(n))throw new Error(`${e} must be a project-relative path`);if(n===".")return[];let r=n.replaceAll("\\","/").split("/");if(r.some(i=>i===".."))throw new Error(`${e} must stay inside the project root`);if(r.some(i=>i===""||i==="."))throw new Error(`${e} must not contain empty or dot path segments`);return r}function Kn(t){let e=rh(t,"native.artifact_root");return e.length===0?".":e.join("/")}function mc(t,e="docs"){let n=t??e;if(n!=="legacy"&&n!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return n}function Nt(t,e,n=!1){if(typeof t!="string")throw new Error(`${e} must be a string`);let r=t.trim().replaceAll("\\","/");if(r.length===0||Bn.posix.isAbsolute(r)||Bn.win32.isAbsolute(r)||/^(?:~|[\\/])/u.test(r))throw new Error(`${e} must be relative to its declared path base`);let i=r.split("/");if(i.some(s=>s===".."))throw new Error(`${e} must stay inside its declared path base`);if(i.some(s=>s===""||s==="."))throw new Error(`${e} must not contain empty or dot path segments`);if(!n&&/[*?]/u.test(r))throw new Error(`${e} cannot contain wildcards`);return i.join("/")}function Pt(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function gc(t,e,n){let r=t??e;if(r!=="en"&&r!=="zh-CN")throw new Error(`${n} must be en or zh-CN`);return r}function wc(t,e){if(typeof t!="string"||t.length===0||t.includes("\\")||t.includes("\0")||t.startsWith("/")||t.split("/").includes(".."))throw new Error(`${e} contains an unsafe pattern`);if(t.length>zi)throw new Error(`${e} exceeds ${zi} characters`);let n=0;for(let r=0;rXi)throw new Error(`${e} contains more than ${Xi} wildcard tokens`);return t}function hc(t,e,n){if(t===void 0)return[...n];if(!Array.isArray(t))throw new Error(`${e} contains an unsafe pattern`);return[...new Set(t.map(r=>wc(r,e)))].sort((r,i)=>r.localeCompare(i,"en"))}function Gi(t,e,n){let r=t??e;if(!Number.isSafeInteger(r)||r<1)throw new Error(`${n} must be a positive integer`);return r}function ih(t){if(t===void 0)return{...ee,include:[...ee.include],exclude:[...ee.exclude]};let e=Pt(t,"native.snapshot");return{include:hc(e.include,"native.snapshot.include",ee.include),exclude:hc(e.exclude,"native.snapshot.exclude",ee.exclude),max_files:Gi(e.max_files,ee.max_files,"native.snapshot.max_files"),max_total_bytes:Gi(e.max_total_bytes,ee.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:Gi(e.max_duration_ms,ee.max_duration_ms,"native.snapshot.max_duration_ms")}}function sh(t){if(t===void 0)return;let e=Pt(t,"native.pending_root_move"),n=e.id,r=e.from_artifact_root,i=e.to_artifact_root,s=e.stage;if(typeof n!="string"||!/^[a-f0-9-]{8,}$/u.test(n))throw new Error("native.pending_root_move.id is invalid");if(typeof r!="string"||typeof i!="string")throw new Error("native.pending_root_move roots must be strings");if(s!=="copying"&&s!=="ready"&&s!=="switched")throw new Error("native.pending_root_move.stage is invalid");let o;if(e.cleanup!==void 0){let a=Pt(e.cleanup,"native.pending_root_move.cleanup"),c=a.kind,l=a.state,d=a.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof d!="string"||!/^[a-f0-9]{64}$/u.test(d))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:d}}return{id:n,fromArtifactRoot:Kn(r),toArtifactRoot:Kn(i),stage:s,...o?{cleanup:o}:{}}}function oh(t,e={}){let n=Pt(t,"native"),r=n.artifact_root??(e.allowMissingArtifactRoot?"docs":void 0);if(typeof r!="string")throw new Error("native.artifact_root must be a string");let i=n.clarification_mode??"sequential";if(i!=="sequential"&&i!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let s=n.archive_confirmation??"automatic";if(s!=="automatic"&&s!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=n.max_verify_failures??th;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let a=sh(n.pending_root_move);return{artifact_root:Kn(r),language:gc(n.language,"en","native.language"),clarification_mode:i,archive_confirmation:s,max_verify_failures:o,snapshot:ih(n.snapshot),...a?{pending_root_move:a}:{}}}function ah(t){let e=Pt(t,"classic"),n=e.context_compression??"off";if(n!=="off"&&n!=="beta")throw new Error("classic.context_compression must be off or beta");let r=e.review_mode??"standard";if(r!=="off"&&r!=="standard"&&r!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let i=e.auto_transition??!0;if(typeof i!="boolean")throw new Error("classic.auto_transition must be true or false");return{artifact_layout:mc(e.artifact_layout),language:gc(e.language,"zh-CN","classic.language"),context_compression:n,review_mode:r,auto_transition:i}}function ch(t){let e=t??!0;if(typeof e!="boolean")throw new Error("ambient_resume must be true or false");return e}function lh(t,e,n,r,i){let s=t.schema!==void 0;if(!(s||t.default_workflow!==void 0||t.workflows!==void 0||!i.allowPartialProject&&t.native!==void 0)||i.allowPartialProject&&!s)return null;if(t.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(t.default_workflow!=="native"&&t.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let a=t.workflows??[t.default_workflow];if(!Array.isArray(a)||a.length===0||a.some(l=>l!=="native"&&l!=="classic"))throw new Error("workflows must contain native and/or classic");let c=[...new Set(a)];if(!c.includes(t.default_workflow))throw new Error("workflows must include default_workflow");if(c.includes("native")&&!e)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:t.default_workflow,workflows:c,ambient_resume:r,...e?{native:e}:{},...n?{classic:n}:{}}}function Ye(t,e={}){let n=(0,Qi.parseDocument)(t,{uniqueKeys:!0});if(n.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${n.errors[0].message}`);let r=n.toJS();if(r==null)return{value:{},config:null,ambient_resume:!0};if(typeof r!="object"||Array.isArray(r))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let i=r,s=ch(i.ambient_resume),o=i.native===void 0?void 0:oh(i.native,{allowMissingArtifactRoot:e.allowMissingNativeFields}),a=i.classic===void 0?void 0:ah(i.classic),c=lh(i,o,a,s,{allowPartialProject:e.allowPartialProject??!1});return{value:i,config:c,ambient_resume:s,...o?{native:o}:{},...a?{classic:a}:{}}}var Qi,Ot,zi,Xi,th,nh,ee,ge=L(()=>{"use strict";Qi=Bt(_t(),1),Ot=64*1024,zi=1024,Xi=64,th=5,nh=[".agents/skills/**",".amazonq/skills/**",".augment/skills/**",".bob/skills/**",".claude/skills/**",".cline/skills/**",".codebuddy/skills/**",".continue/skills/**",".cospec/skills/**",".crush/skills/**",".cursor/skills/**",".factory/skills/**",".forge/skills/**",".gemini/skills/**",".github/skills/**",".iflow/skills/**",".junie/skills/**",".kilocode/skills/**",".kimi-code/skills/**",".kiro/skills/**",".lingma/skills/**",".mimocode/skills/**",".opencode/skills/**",".pi/skills/**",".qoder/skills/**",".qwen/skills/**",".roo/skills/**",".trae-cn/skills/**",".trae/skills/**",".windsurf/skills/**",".zcode/skills/**"],ee={include:["**/*"],exclude:[...nh],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4}});function we(t){return t!==0&&t!==0n&&t!=="0"}function Yn(t,e){return we(t.dev)&&we(e.dev)&&we(t.ino)&&we(e.ino)}function te(t,e){let n=we(t.dev)&&we(e.dev);if(n&&t.dev!==e.dev)return!1;let r=we(t.ino)&&we(e.ino);return r&&t.ino!==e.ino?!1:n&&r?!0:t.birthtime===e.birthtime}var Un=L(()=>{"use strict"});import{constants as Hn,promises as Oe}from"fs";function Zi(t){return"birthtimeNs"in t&&typeof t.birthtimeNs=="bigint"?t.birthtimeNs:t.birthtimeMs}function yc(t){return"ctimeNs"in t&&typeof t.ctimeNs=="bigint"?t.ctimeNs:t.ctimeMs}function At(t){return{dev:t.dev,ino:t.ino,birthtime:Zi(t)}}function Jn(t,e){let n=At(t),r=At(e);return Yn(n,r)?te(n,r):te(n,r)&&Zi(t)===Zi(e)&&yc(t)===yc(e)&&t.size===e.size}async function Vn(t,e,n={}){if(!Number.isSafeInteger(e)||e<1)throw new Error("race-safe read byte limit must be a positive integer");let r=n.label??"file",i=n.bigint===!0,s=await Oe.lstat(t,{bigint:i});if(!s.isFile()||s.isSymbolicLink())throw new ye("not-regular-file",`${r} must be a regular file`);if(BigInt(s.size)>BigInt(e))throw new ye("too-large",`${r} exceeds ${e} bytes`);let o=await Oe.realpath(t);await n.verify?.("pre-open",{realPath:o,identity:At(s)});let a=process.platform==="win32"?Hn.O_RDONLY:Hn.O_RDONLY|Hn.O_NOFOLLOW|Hn.O_NONBLOCK,c;try{c=await Oe.open(t,a)}catch(l){throw l.code==="ELOOP"?new ye("not-regular-file",`${r} must be a regular file`,{cause:l}):l}try{let[l,d,u]=await Promise.all([c.stat({bigint:i}),Oe.lstat(t,{bigint:i}),Oe.realpath(t)]);if(!l.isFile()||!d.isFile()||d.isSymbolicLink()||u!==o||!Jn(s,l)||!Jn(s,d))throw new ye("changed",`${r} changed while opening`);await n.verify?.("post-open",{realPath:u,identity:At(l)}),await n.hooks?.afterOpen?.();let f=[],m=0,w=Buffer.allocUnsafe(Math.min(64*1024,e+1));for(;;){let v=e+1-m,{bytesRead:k}=await c.read(w,0,Math.min(w.length,v),null);if(k===0)break;if(m+=k,m>e)throw new ye("too-large",`${r} exceeds ${e} bytes`);f.push(Buffer.from(w.subarray(0,k)))}await n.hooks?.beforeFinalCheck?.();let[p,h,y]=await Promise.all([c.stat({bigint:i}),Oe.lstat(t,{bigint:i}),Oe.realpath(t)]);if(!h.isFile()||h.isSymbolicLink()||y!==o||!Jn(s,p)||!Jn(s,h))throw new ye("changed",`${r} changed while reading`);return await n.verify?.("post-read",{realPath:y,identity:At(p)}),{bytes:Buffer.concat(f,m),stat:p,realPath:y}}finally{await c.close()}}var ye,es=L(()=>{"use strict";Un();ye=class extends Error{reason;constructor(e,n,r){super(n,r),this.name="RaceSafeReadError",this.reason=e}}});import{promises as Gn}from"fs";import be from"path";function uh(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}function ts(t,e){let n=be.relative(t,e);return n===""||!be.isAbsolute(n)&&n!==".."&&!n.startsWith(`..${be.sep}`)}async function bc(t,e){let n=be.resolve(t),r=await Gn.lstat(n);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${e} project root must be a real directory`);return Gn.realpath(n)}async function vc(t,e,n,r){let i=t;for(let s=0;s{if(!ts(s,a.realPath))throw new Error(`${r.label} resolves outside the project root`);await vc(i.projectRoot,s,i.relative.split("/"),{label:r.label,expected:"file"})}})}var ne=L(()=>{"use strict";es();ge()});import{createHash as fh}from"crypto";function dh(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function ns(t,e={}){return(await zn(t,e)).document}async function ph(t){try{return(await J(t,xt,Ot,{label:xt})).bytes}catch(e){if(dh(e))return null;throw e}}function hh(t){return t?{exists:!0,sha256:fh("sha256").update(t).digest("hex")}:{exists:!1,sha256:null}}async function zn(t,e={}){let n=await ph(t);return{document:n?Ye(n.toString("utf8"),e):null,identity:hh(n)}}var xt,Tt=L(()=>{"use strict";ge();ne();xt=".comet/config.yaml"});import{randomUUID as mh}from"crypto";import{constants as gh,promises as A}from"fs";import j from"path";async function rs(t,e){try{return await A.link(t,e),{linked:!0}}catch(n){let r=n.code;if(r!=="ENOTSUP"&&r!=="EOPNOTSUPP")throw n}return await A.copyFile(t,e,gh.COPYFILE_EXCL),{linked:!1}}function Ue(t,e){let n=j.relative(t,e);return n===""||!j.isAbsolute(n)&&n!==".."&&!n.startsWith(`..${j.sep}`)}function Qn(t){return{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs}}function wh(t,e){return te(t,Qn(e))}function Xn(t,e){let n=Qn(t),r=Qn(e);return Yn(n,r)?te(n,r):te(n,r)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.size===e.size}async function Zn(t){let e=await A.lstat(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Contained atomic write parent must be a real directory: ${t}`);return{path:t,realPath:await A.realpath(t),...Qn(e)}}async function ve(t){for(let e of t){let n=await A.lstat(e.path);if(!n.isDirectory()||n.isSymbolicLink()||!wh(e,n)||await A.realpath(e.path)!==e.realPath)throw new Error(`Contained atomic write parent changed before commit: ${e.path}`)}}async function yh(t,e){let n=j.resolve(t),r=j.resolve(e);if(!Ue(n,r))throw new Error(`Contained atomic write parent is outside its managed root: ${e}`);let i=[await Zn(n)],s=j.relative(n,r).split(j.sep).filter(Boolean),o=n;for(let a of s){await ve(i),o=j.join(o,a);try{await A.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await Zn(o);if(!Ue(i[0].realPath,c.realPath))throw new Error(`Contained atomic write parent resolves outside its managed root: ${o}`);i.push(c)}return await ve(i),i}async function bh(t,e){let n=j.resolve(t),r=j.resolve(e);if(!Ue(n,r))throw new Error(`Contained file parent is outside its managed root: ${e}`);let i=[await Zn(n)],s=j.relative(n,r).split(j.sep).filter(Boolean),o=n;for(let a of s){o=j.join(o,a);try{let c=await Zn(o);if(!Ue(i[0].realPath,c.realPath))throw new Error(`Contained file parent resolves outside its managed root: ${o}`);i.push(c)}catch(c){if(c.code==="ENOENT")return null;throw c}}return await ve(i),i}async function kc(t){let e;try{e=await A.open(t,"r"),await e.sync()}catch(n){let r=n.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(r??""))throw n}finally{await e?.close()}}async function vh(t,e,n){let r=j.dirname(t),i=await yh(n.containedRoot,r),s=j.join(r,`.${j.basename(t)}.${mh()}.tmp`),o,a;try{await n.beforeTemporaryOpen?.(),o=await A.open(s,"wx"),a=await o.stat();let[c,l]=await Promise.all([A.lstat(s),A.realpath(s)]);if(await ve(i),!c.isFile()||c.isSymbolicLink()||!Xn(a,c)||!Ue(i[0].realPath,l))throw new Error("Contained atomic write temporary file opened outside its managed parent");if(typeof e=="string"?await o.writeFile(e,"utf8"):await o.writeFile(e),await o.sync(),!Xn(a,await o.stat()))throw new Error("Contained atomic write temporary file changed while writing");await o.close(),o=void 0,await n.beforeCommit?.(),await ve(i);let d=await A.lstat(s);if(!d.isFile()||d.isSymbolicLink()||!Xn(d,a))throw new Error("Contained atomic write temporary file changed before commit");n.exclusive?(await rs(s,t),await A.unlink(s)):await A.rename(s,t),await kc(r)}catch(c){await o?.close();try{await ve(i),await A.rm(s,{force:!0})}catch{}throw c}}async function re(t,e,n){await vh(t,e,n)}async function is(t,e){let n=j.dirname(t),r=await bh(e.containedRoot,n);if(!r)return!1;let i,s;try{i=await A.lstat(t),s=await A.realpath(t)}catch(c){if(c.code==="ENOENT")return!1;throw c}if(!i.isFile()||i.isSymbolicLink()||!Ue(r[0].realPath,s))throw new Error("Contained file removal target must be a regular file inside its managed root");await e.beforeRemove?.(),await ve(r);let[o,a]=await Promise.all([A.lstat(t),A.realpath(t)]);if(!o.isFile()||o.isSymbolicLink()||!Xn(i,o)||a!==s)throw new Error("Contained file removal target changed before removal");return await A.unlink(t),await ve(r),await kc(n),!0}var Ne=L(()=>{"use strict";Un()});var Gw,ss=L(()=>{"use strict";Ne();Tt();ne();Gw=16*1024});var as=L(()=>{"use strict";Ne();ge();Tt();ne();ss()});var rr=L(()=>{"use strict"});var qc=L(()=>{"use strict"});var hs=L(()=>{"use strict";rr()});var Dc=L(()=>{"use strict";rr();hs()});var rm,$c=L(()=>{"use strict";rm=Bt(_t(),1);Ne();ge();ne()});var Wc=L(()=>{"use strict";rr();Ne();qc();Dc();ge();$c();ne();Tt();as();ss();hs()});import{TextDecoder as im}from"util";function Mc(t){return{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs}}function sm(t,e){try{return new im("utf-8",{fatal:!0}).decode(t.bytes)}catch(n){throw new Error(`${e} is not valid UTF-8`,{cause:n})}}async function ms(t,e,n,r,i={}){try{let s=await J(t,e,n,{label:r,hooks:i.hooks});return{result:s,text:sm(s,r)}}catch(s){let o=s.code;if(o==="ENOENT"||o==="ENOTDIR")return null;throw s}}async function Fc(t,e,n,r,i={}){return(await ms(t,e,n,r,i))?.text??null}async function Bc(t,e,n,r,i,s={}){if(Buffer.byteLength(n,"utf8")>r)throw new Error(`${i} exceeds ${r} bytes`);let o=await ms(t,e,r,i),a=await F(t,e,{label:i,expected:"file"});await re(a.target,n,{containedRoot:a.projectRoot,beforeCommit:async()=>{await s.beforeCommit?.();let c=await ms(t,e,r,i);if(!(!o&&!c)){if(!o||!c)throw new Error(`${i} changed before commit`);if(o.result.realPath!==c.result.realPath||!te(Mc(o.result.stat),Mc(c.result.stat))||o.text!==c.text)throw new Error(`${i} changed before commit`)}}})}async function Kc(t,e,n,r={}){let i=await F(t,e,{label:n,expected:"file"});return i.exists?is(i.target,{containedRoot:i.projectRoot,beforeRemove:r.beforeRemove}):!1}var Yc=L(()=>{"use strict";Wc();Un()});var Gc={};Cl(Gc,{RUN_STATE_FILE:()=>sr,applyRunStateToDocument:()=>Hc,readRunState:()=>gs,removeRunState:()=>Vc,runStateFromDocument:()=>ir,writeRunState:()=>ws});import om from"path";function Dt(t,e){let n=t[e];if(typeof n!="string"||n.length===0)throw new Error(`Invalid Run state: ${e} must be a non-empty string`);return n}function qt(t,e){let n=Dt(t,e);if(om.isAbsolute(n)||/^(?:[A-Za-z]:|[\\/]|~)/u.test(n)||n.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Run state: ${e} must stay inside the change directory`);return n}function am(t){let e=t.run_retries??"{}",n;try{n=typeof e=="string"?JSON.parse(e):e}catch(r){throw new Error("Invalid Run state: run_retries must be a JSON object",{cause:r})}if(!n||typeof n!="object"||Array.isArray(n))throw new Error("Invalid Run state: run_retries must be a JSON object");for(let r of Object.values(n))if(!Number.isInteger(r)||Number(r)<0)throw new Error("Invalid Run state: retry counts must be non-negative integers");return n}function ir(t){if(!t.run_id)return null;let e=Dt(t,"run_id"),n=Dt(t,"skill"),r=Dt(t,"skill_version"),i=Dt(t,"skill_hash"),s=qt(t,"pending_ref"),o=qt(t,"trajectory_ref"),a=qt(t,"context_ref"),c=qt(t,"artifacts_ref"),l=qt(t,"checkpoint_ref"),d=Number(t.iteration);if(!Number.isInteger(d)||d<0)throw new Error("Invalid Run state: iteration must be a non-negative integer");if(t.orchestration!=="deterministic"&&t.orchestration!=="adaptive")throw new Error("Invalid Run state: orchestration must be deterministic or adaptive");if(t.run_status!=="running"&&t.run_status!=="waiting"&&t.run_status!=="completed"&&t.run_status!=="failed")throw new Error("Invalid Run state: run_status is invalid");return{runId:e,skill:n,skillVersion:r,skillHash:i,orchestration:t.orchestration,currentStep:Uc(t,"current_step"),iteration:d,pending:Uc(t,"pending"),pendingRef:s,trajectoryRef:o,contextRef:a,artifactsRef:c,checkpointRef:l,status:t.run_status,retries:am(t)}}function Hc(t,e){e?t.run_id=e.runId:delete t.run_id}function cm(t){return{runId:t.runId,skill:t.skill,skillVersion:t.skillVersion,skillHash:t.skillHash,orchestration:t.orchestration,currentStep:t.currentStep,iteration:t.iteration,pending:t.pending,pendingRef:t.pendingRef,trajectoryRef:t.trajectoryRef,contextRef:t.contextRef,artifactsRef:t.artifactsRef,checkpointRef:t.checkpointRef,status:t.status,retries:t.retries}}function lm(t){let e={run_id:t.runId,skill:t.skill,skill_version:t.skillVersion,skill_hash:t.skillHash,orchestration:t.orchestration,current_step:t.currentStep,iteration:t.iteration,pending:t.pending,pending_ref:t.pendingRef,trajectory_ref:t.trajectoryRef,context_ref:t.contextRef,artifacts_ref:t.artifactsRef,checkpoint_ref:t.checkpointRef,run_status:t.status,run_retries:JSON.stringify(t.retries)};return ir(e)}async function gs(t,e={}){let n=await Fc(t,sr,Jc,"Run state",e);if(n===null)return null;let r=JSON.parse(n);return lm(r)}async function ws(t,e,n={}){await Bc(t,sr,JSON.stringify(cm(e),null,2),Jc,"Run state",n)}async function Vc(t,e={}){await Kc(t,sr,"Run state",e)}var Uc,sr,Jc,or=L(()=>{"use strict";Yc();Uc=(t,e)=>{let n=t[e];return n==null?null:String(n)};sr=".comet/run-state.json",Jc=256*1024});import{promises as fr,readFileSync as Im}from"fs";import K from"path";var Cs=null;function Es(t,e){let n=t;for(let r of e)n+="\0"+(typeof r=="string"?r:JSON.stringify(r));return n}function Ve(t,e){return(...n)=>{let r=Cs;if(r===null)return e(...n);let i=Es(`async:${t}`,n),s=r.entries.get(i);if(s)return s.value;let o=e(...n).catch(a=>{throw r.entries.delete(i),a});return r.entries.set(i,{value:o}),o}}function pr(t,e){return(...n)=>{let r=Cs;if(r===null)return e(...n);let i=Es(`sync:${t}`,n),s=r.entries.get(i);if(s)return s.value;let o=e(...n);return r.entries.set(i,{value:o}),o}}import{promises as _h}from"fs";import M from"path";import{promises as _l}from"fs";async function hr(t){try{return await _l.access(t),!0}catch(e){if(Pl(e))return!1;throw e}}function Pl(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}ge();Tt();as();ne();var Rt=class extends Error{code="classic-layout-unavailable";constructor(e="Classic artifact layout is unavailable from .comet/config.yaml"){super(e),this.name="ClassicLayoutUnavailableError"}},Ec=".comet/config.yaml";function Ph(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function Oh(t){await F(t,Ec,{label:Ec,expected:"file"})}function _c(t,e){let n=M.resolve(t),r=e==="docs"?M.join(n,"docs"):n,i=M.join(r,"openspec"),s=M.join(n,"docs","superpowers");return{projectRoot:n,artifactLayout:e,openSpecBase:r,openSpecRoot:i,changesDir:M.join(i,"changes"),archiveDir:M.join(i,"changes","archive"),specsDir:M.join(i,"specs"),superpowersRoot:s,superpowersSpecsDir:M.join(s,"specs"),superpowersPlansDir:M.join(s,"plans"),superpowersReportsDir:M.join(s,"reports")}}async function Nh(t){await Oh(t);let e=await ns(t,{allowPartialProject:!0,allowMissingNativeFields:!0});if(!e?.config)throw new Rt;if(!(e.config.workflows??[e.config.default_workflow]).includes("classic"))throw new Rt("Classic artifact layout is unavailable because Classic is not enabled");return e.classic?.artifact_layout??"legacy"}async function Ah(t,e){return _c(t,e??await Nh(t))}async function xh(t){try{return await _h.lstat(t),!0}catch(e){if(Ph(e))return!1;throw e}}async function Th(t,e){let n=await Ah(t,e),r=n.artifactLayout==="legacy"?"docs":"legacy",i=_c(t,r).openSpecRoot,[s,o]=await Promise.all([F(n.projectRoot,q(n.projectRoot,n.openSpecRoot),{label:"Configured Classic OpenSpec root",expected:"directory"}),xh(i)]),a=s.exists;return{paths:n,configuredRootExists:a,alternateRoot:i,alternateRootExists:o,dualRoots:a&&o}}async function Rh(t){let e=[t.openSpecRoot,t.changesDir,t.archiveDir,t.specsDir,t.superpowersRoot,t.superpowersSpecsDir,t.superpowersPlansDir,t.superpowersReportsDir];for(let n of e){let r=q(t.projectRoot,n);await F(t.projectRoot,r,{label:`Classic managed physical path ${r}`,expected:"directory"})}}async function Ae(t,e){let n=await Th(t,e);if(await Rh(n.paths),!n.configuredRootExists){let r=q(n.paths.projectRoot,n.paths.openSpecRoot),i=q(n.paths.projectRoot,n.alternateRoot);throw new Rt(`Configured Classic OpenSpec root is missing: ${r} (alternate ${i} is ${n.alternateRootExists?"present":"missing"})`)}return n.paths}async function cs(t,e){let n=M.join(M.resolve(t),".comet","classic-root-move.json");if(await hr(n))throw new Error("Classic root move transaction is incomplete; inspect it with comet doctor and recover it explicitly before writing");let r=await Ae(t,e);if(!await hr(r.openSpecRoot))throw new Error(`Configured Classic OpenSpec root is missing: ${q(r.projectRoot,r.openSpecRoot)}`);return r}function q(t,e){return M.relative(M.resolve(t),e).replaceAll("\\","/")}import Oc from"path";Ne();ge();ne();import It from"path";var gy=2*1024*1024;function jh(t,e,n){let r=It.resolve(t),i=It.isAbsolute(e)?It.resolve(e):It.resolve(r,e),s=It.relative(r,i).replaceAll("\\","/");return{root:r,relative:Nt(s,n),target:i}}async function He(t,e,n){let r=jh(t,e,n.label);return F(r.root,r.relative,n)}async function Pc(t,e,n){return(await He(t,e,{label:n.label,expected:n.expected??"any"})).exists}function ls(t){return t?/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t)?t.includes("..")?"Change name cannot contain '..' (path traversal not allowed)":null:`Invalid change name: '${t}' +Valid format: lowercase kebab-case (a-z, 0-9, single hyphens)`:"Change name cannot be empty"}function us(t){let e=ls(t);if(e)throw new Error(e)}function Lh(t,e){return{label:q(t,e),directory:e}}async function qh(t,e,n){let r=Lh(t,e);if(!(await He(t,e,{label:n,expected:"directory"})).exists)return{change:r,exists:!1,stateExists:!1};let s=await He(t,Oc.join(e,".comet.yaml"),{label:`${n} state`,expected:"file"});return{change:r,exists:!0,stateExists:s.exists}}async function jt(t,e=process.cwd()){us(t);let n=await Ae(e),r=await qh(n.projectRoot,Oc.join(n.changesDir,t),`Classic active change ${t}`);return{...r.change,exists:r.exists,stateExists:r.stateExists}}import{promises as fs}from"fs";import B from"path";function Nc(t,e){let n=B.relative(t,e);return n===""||n!==".."&&!n.startsWith(`..${B.sep}`)&&!B.isAbsolute(n)}async function Dh(t){let e=B.resolve(t),n=B.parse(e).root,r=[],i=e;for(;i&&i!==n;)try{let s=await fs.realpath(i);return B.join(s,...r.reverse())}catch(s){let o=s.code;if(o!=="ENOENT"&&o!=="ENOTDIR")throw s;r.push(B.basename(i)),i=B.dirname(i)}try{let s=await fs.realpath(n);return B.join(s,...r.reverse())}catch{return null}}async function Ac(t,e){let n=B.resolve(t),r=await fs.realpath(n),i=[],s=[];for(let o of e){let a=B.isAbsolute(o)?B.resolve(o):B.resolve(n,o),c=await Dh(a);((c?Nc(r,c):Nc(n,a))?i:s).push(o)}return{projectTargets:i,externalTargets:s}}var ds=Bt(_t(),1);import{execFileSync as xc}from"child_process";import{randomUUID as $h}from"crypto";import{promises as Lt}from"fs";import Tc from"path";function Wh(t){try{let e=xc("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();return e&&e!=="HEAD"?e:null}catch{return null}}var Mh=pr("liveGitBranch",t=>Wh(t));function Fh(t){try{return xc("git",["rev-parse","--is-inside-work-tree"],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()==="true"}catch{return!1}}var Bh=pr("isGitWorkTree",t=>Fh(t)),Kh=["current","branch","worktree"];function Rc(t){return Kh.includes(t)}function Yh(t){return Rc(t.isolation)?t.boundBranch===null&&t.currentBranch===null&&t.gitWorkTree===!1?{status:"not-applicable"}:t.boundBranch===null?t.currentBranch===null?{status:"unbound-detached"}:{status:"needs-heal",branch:t.currentBranch}:t.currentBranch===t.boundBranch?{status:"ok"}:{status:"drift",boundBranch:t.boundBranch,currentBranch:t.currentBranch}:{status:"not-applicable"}}async function er(t,e){let n=Tc.join(t,".comet.yaml"),r=(0,ds.parseDocument)(await Lt.readFile(n,"utf8"),{uniqueKeys:!1});if(r.errors.length>0)throw new Error(`Invalid .comet.yaml: ${r.errors[0].message}`);let i=r.toJS()??{},s=typeof i.isolation=="string"?i.isolation:null,o=typeof i.bound_branch=="string"&&i.bound_branch!==""?i.bound_branch:null,a=Rc(s),c=Mh(e.cwd),l=a&&o===null&&c===null?Bh(e.cwd):!0,d=Yh({isolation:s,boundBranch:o,currentBranch:c,gitWorkTree:l});return d.status==="needs-heal"&&e.heal?(await Uh(t,d.branch),{status:"healed",branch:d.branch,bindingRequired:a,currentBranch:c}):{...d,bindingRequired:a,currentBranch:c}}async function Uh(t,e){let n=Tc.join(t,".comet.yaml"),r=(0,ds.parseDocument)(await Lt.readFile(n,"utf8"),{uniqueKeys:!1});r.set("bound_branch",e);let i=`${n}.${$h()}.tmp`;try{await Lt.writeFile(i,r.toString(),"utf8"),await Lt.rename(i,n)}catch(s){throw await Lt.rm(i,{force:!0}),s}}function Hh(t){return t??"detached HEAD"}function tr(t,e,n){return`change '${t}' is bound to branch '${e}', but current branch is '${Hh(n)}'`}function nr(t){return`change '${t}' uses a branch-bound workspace mode but has no bound branch and HEAD is detached; checkout a branch first before continuing.`}es();import Jh from"path";var ps="comet.selection.v2",Vh=16*1024;function jc(t){return Jh.join(t,".comet","current-change.json")}function Gh(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function Ic(t){return t===null||typeof t=="string"}function zh(t){let e;try{e=JSON.parse(t)}catch(n){throw new Error(`current change selection contains invalid JSON: ${n instanceof Error?n.message:String(n)}`,{cause:n})}if(!Gh(e))throw new Error("current change selection must be a JSON object");if(e.version===1){if(typeof e.change!="string")throw new Error("legacy current change selection change must be a string");if(e.branch!==void 0&&!Ic(e.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:ps,workflow:"classic",change:e.change,branch:e.branch??null},legacy:!0}}if(e.schema!==ps)throw new Error(`current change selection schema must be ${ps}`);if(e.workflow!=="native"&&e.workflow!=="classic")throw new Error("current change selection workflow must be native or classic");if(typeof e.change!="string")throw new Error("current change selection change must be a string");if(!Ic(e.branch))throw new Error("current change selection branch must be a string or null");if(e.workflow==="native"&&e.branch!==null)throw new Error("Native current change selection branch must be null");return{selection:e,legacy:!1}}async function Lc(t){let e;try{let r=jc(t),{bytes:i}=await Vn(r,Vh,{label:"current change selection"});e=i.toString("utf8")}catch(r){if(r.code==="ENOENT")return{status:"missing"};throw new Error(`cannot read current change selection: ${r instanceof Error?r.message:String(r)}`,{cause:r})}return{status:"selected",...zh(e)}}var lr=Bt(_t(),1);Ne();ne();import cr from"path";or();var bs=["full","hotfix","tweak"],zc=1,Qc=["open","design","build","verify","archive"],um=["en","zh-CN"],fm=["off","beta"],dm=["subagent-driven-development","executing-plans","direct"],pm=["plan-ready"],hm=["confirmed"],mm=["tdd","direct"],gm=["off","standard","thorough"],wm=["current","branch","worktree"],ym=["light","full"],bm=["pending","pass","fail"],vm=["pending","handled"],km=["pending","confirmed"],vs=["workflow","language","phase","context_compression","build_mode","build_pause","subagent_dispatch","tdd_mode","review_mode","isolation","bound_branch","verify_mode","auto_transition","base_ref","design_doc","plan","verify_result","verify_failures","verification_report","branch_status","created_at","verified_at","archive_confirmation","archived","direct_override","handoff_context","handoff_hash","classic_profile","classic_migration"],Sm=["run_id"],Zc=new Set([...vs,...Sm]),Cm=["workflow","phase","design_doc","plan","build_mode","isolation","verify_mode","verify_result","verified_at","archived"];function Xc(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function Je(t,e){let n=t[e];if(n==null||n==="")return null;if(typeof n!="string")throw new Error(`Invalid Classic state: ${e} must be a string or null`);return n}function D(t,e,n,r=!0){let i=t[e];if(i==null||i===""){if(r)return null;throw new Error(`Invalid Classic state: ${e} is required`)}if(typeof i!="string"||!n.includes(i))throw new Error(`Invalid Classic state: ${e} must be one of ${n.join(", ")}${r?" or null":""}`);return i}function ys(t,e,n=!0){let r=t[e];if(r==null||r===""){if(n)return null;throw new Error(`Invalid Classic state: ${e} is required`)}if(typeof r!="boolean")throw new Error(`Invalid Classic state: ${e} must be true or false`);return r}function Em(t,e,n=0){let r=t[e];if(r==null||r==="")return n;if(typeof r!="number"||!Number.isInteger(r)||r<0)throw new Error(`Invalid Classic state: ${e} must be a non-negative integer`);return r}function ar(t,e){let n=Je(t,e);if(n===null)return null;if(/^(?:[A-Za-z]:|[\\/]|~)/u.test(n)||n.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Classic state: ${e} must be a relative repository path`);return n}function _m(t,e){let n=Je(t,e);if(n!==null&&!/^[a-f0-9]{64}$/u.test(n))throw new Error(`Invalid Classic state: ${e} must be a sha256 hex digest`);return n}function Pm(t){let e=t.classic_migration;if(e==null||e==="")return null;if(e!==zc)throw new Error(`Invalid Classic state: classic_migration must be ${zc}`);return e}function Om(t){if(!vs.some(n=>Xc(t,n)))return null;for(let n of Cm)if(!Xc(t,n))return null;return{workflow:D(t,"workflow",bs,!1),language:D(t,"language",um),phase:D(t,"phase",Qc,!1),contextCompression:D(t,"context_compression",fm),buildMode:D(t,"build_mode",dm),buildPause:D(t,"build_pause",pm),subagentDispatch:D(t,"subagent_dispatch",hm),tddMode:D(t,"tdd_mode",mm),reviewMode:D(t,"review_mode",gm),isolation:D(t,"isolation",wm),boundBranch:Je(t,"bound_branch"),verifyMode:D(t,"verify_mode",ym),autoTransition:ys(t,"auto_transition"),baseRef:Je(t,"base_ref"),designDoc:ar(t,"design_doc"),plan:ar(t,"plan"),verifyResult:D(t,"verify_result",bm,!1),verifyFailures:Em(t,"verify_failures"),verificationReport:ar(t,"verification_report"),branchStatus:D(t,"branch_status",vm),createdAt:Je(t,"created_at"),verifiedAt:Je(t,"verified_at"),archiveConfirmation:D(t,"archive_confirmation",km),archived:ys(t,"archived",!1),directOverride:ys(t,"direct_override"),handoffContext:ar(t,"handoff_context"),handoffHash:_m(t,"handoff_hash"),classicProfile:D(t,"classic_profile",bs),classicMigration:Pm(t)}}function el(t,e){let n=e??null;if(n===null&&e===void 0&&t.run_id&&t.skill)try{n=ir(t)}catch(r){let i=r instanceof Error?r.message:String(r);throw new Error(i.replace(/^Invalid Run state:/u,"Invalid Classic state:"),{cause:r})}return{classic:Om(t),run:n,unknownKeys:Object.keys(t).filter(r=>!Zc.has(r))}}function tl(t){let e=t.workflow,n=t.phase,r=t.archived,i=t.design_doc;return{workflow:typeof e=="string"&&bs.includes(e)?e:null,phase:typeof n=="string"&&Qc.includes(n)?n:null,archived:r===!0,designDoc:typeof i=="string"&&i!==""?i:null,unknownKeys:Object.keys(t).filter(s=>!Zc.has(s))}}or();var Nm=2*1024*1024;function $t(t){let e=t.toJS();if(e===null)return{};if(typeof e!="object"||Array.isArray(e))throw new Error("Invalid Classic state document: root must be a mapping");return e}function Am(t){let e=["skill","skill_version","skill_hash","orchestration","current_step","iteration","pending","pending_ref","trajectory_ref","context_ref","artifacts_ref","checkpoint_ref","run_status","run_retries"];for(let n of e)t.delete(n)}function xm(t){let e=!1;for(let n of["build_command","verify_command"])t.has(n)&&(t.delete(n),e=!0);return e}async function nl(t){let e;try{e=(await J(cr.dirname(t),cr.basename(t),Nm,{label:"Classic state document"})).bytes.toString("utf8")}catch(r){if(r.code!=="ENOENT")throw r;return new lr.Document({})}let n=(0,lr.parseDocument)(e);if(n.errors.length>0)throw new Error(`Invalid Classic state document: ${n.errors[0].message}`);return $t(n),n}async function ur(t,e={}){let n=e.migrate!==!1,r=cr.join(t,".comet.yaml"),i=await nl(r),s=$t(i),o=xm(i);o&&(s=$t(i));let a=await gs(t);if(!a&&s.run_id&&s.skill){let{runStateFromDocument:c}=await Promise.resolve().then(()=>(or(),Gc));a=c(s),a&&n&&(await ws(t,a),Am(i),o=!0)}return o&&n&&await re(r,i.toString(),{containedRoot:t}),el($t(i),a)}async function rl(t){let e=await nl(cr.join(t,".comet.yaml"));return tl($t(e))}var Tm=Ve("readCometCurrentSelection",t=>Lc(t));async function Rm(t,e){us(e);let n=await jt(e,t);if(!n.stateExists)throw new Error(`Cannot select current change '${e}': active change state not found`);let r=await ur(n.directory,{migrate:!1});if(!r.classic)throw new Error(`Cannot select current change '${e}': Classic state is incomplete`);if(r.classic.archived)throw new Error(`Cannot select current change '${e}': change is archived`);return n.directory}async function il(t){let e;try{e=await Tm(t)}catch(s){return{status:"stale",reason:s instanceof Error?s.message:String(s)}}if(e.status==="missing")return{status:"missing"};if(e.selection.workflow!=="classic")return{status:"stale",reason:`current change '${e.selection.change}' belongs to Native, not Classic`};let n=e.selection,r;try{r=await Rm(t,n.change)}catch(s){return{status:"stale",reason:s instanceof Error?s.message:String(s)}}let i=await er(r,{heal:!1,cwd:t});return i.status==="drift"?{status:"stale",reason:tr(n.change,i.boundBranch,i.currentBranch)}:i.status==="unbound-detached"?{status:"stale",reason:nr(n.change)}:i.status==="ok"?{status:"selected",selection:n}:n.branch!==null&&i.currentBranch!==n.branch?{status:"stale",reason:`current change '${n.change}' was selected on branch '${n.branch}', current branch is '${i.currentBranch??"detached HEAD"}'`}:{status:"selected",selection:n}}import xe from"node:path";async function sl(t,e){if(!e||e==="null")return{status:"missing",recordedPath:null};let n=await Ae(t),r=xe.resolve(t,e),i=xe.relative(n.superpowersPlansDir,r);return xe.isAbsolute(e)||!i||i.startsWith(`..${xe.sep}`)||xe.isAbsolute(i)||i.includes(xe.sep)||xe.extname(i).toLowerCase()!==".md"?{status:"broken",recordedPath:e}:await Pc(t,e,{label:`Classic build plan ${e}`,expected:"file"})?{status:"ready",recordedPath:e}:{status:"broken",recordedPath:e}}function V(t,e){return{exitCode:t,stderr:e+` +`}}function X(t){return V(0,`[COMET-HOOK] allowed: ${t}`)}function jm(){if(process.env.FILE_PATH)return process.env.FILE_PATH;if(process.stdin.isTTY)return"";let t=Im(0,"utf8");if(!t)return"";try{let e=JSON.parse(t);return typeof e.tool_input?.file_path=="string"?e.tool_input.file_path:""}catch{return""}}function Mt(t){return t.replaceAll("\\","/").replace(/\/+/gu,"/")}function Te(t){let e=Mt(t);return process.platform==="win32"?e.toLowerCase():e}function Lm(t){let e=t.indexOf("--project-root"),n=e>=0?t[e+1]:void 0;return K.resolve(n&&!n.startsWith("--")?n:process.cwd())}function ol(t,e){let n=Mt(K.relative(e,t));return n===""?"":n.startsWith("../")||n===".."||K.isAbsolute(n)?null:n}async function qm(t){let e=K.resolve(t),n=K.parse(e).root,r=[],i=e;for(;i&&i!==n;)try{let s=await fr.realpath(i);return K.join(s,...r.reverse())}catch(s){let o=s.code;if(o!=="ENOENT"&&o!=="ENOTDIR")throw s;r.push(K.basename(i)),i=K.dirname(i)}try{let s=await fr.realpath(n);return K.join(s,...r.reverse())}catch{return null}}async function Dm(t,e){let n=K.isAbsolute(t)?t:K.resolve(e,t),r=Mt(n),i=ol(n,e);if(i!==null)return i;try{let s=await qm(n),o=await fr.realpath(e);if(s){let a=ol(s,o);if(a!==null)return a;r=Mt(s)}}catch{if(!K.isAbsolute(t))return Mt(t).replace(/^\.\//u,"")}return r.replace(/^\.\//u,"")}async function ul(t){try{let e=await ur(t,{migrate:!1}),n=Array.from(new Set(e.unknownKeys)).sort();if(n.length>0)throw new Error(`Invalid Classic state: unknown field(s): ${n.join(", ")}`);if(!e.classic)throw new Error("Classic state projection is unavailable");return{changeDir:t,phase:e.classic.phase,classic:e.classic,archived:e.classic.archived}}catch(e){let n=await rl(t);return n.phase?{changeDir:t,phase:n.phase,classic:null,archived:n.archived,invalidState:e instanceof Error&&e.message.includes("unknown field")}:null}}async function $m(t){let e=(await Ae(t)).changesDir,n=[];if(!(await He(t,e,{label:"Classic changes directory",expected:"directory"})).exists)return n;for(let i of(await fr.readdir(e,{withFileTypes:!0})).sort((s,o)=>s.name.localeCompare(o.name))){if(i.name==="archive"||ls(i.name))continue;let s=await jt(i.name,t);if(!s.exists||!s.stateExists)continue;let o=await ul(s.directory);!o||o.archived||n.push(o)}return n}var ks=Ve("classicActiveChanges",t=>$m(t)),fl=Ve("classicPlanReadiness",sl);function dl(t,e){return`${q(t,e.superpowersRoot)}/`}function pl(t,e){return Te(t).startsWith(Te(e))}function Wm(t,e){return[{prefix:`${q(t,e.superpowersSpecsDir)}/`,field:"designDoc",wireField:"design_doc",phase:"design"},{prefix:`${q(t,e.superpowersPlansDir)}/`,field:"plan",wireField:"plan",phase:"build"},{prefix:`${q(t,e.superpowersReportsDir)}/`,field:"verificationReport",wireField:"verification_report",phase:"verify"}]}function Mm(t,e){let n=Te(t),r=e.find(s=>n.startsWith(Te(s.prefix)));if(!r)return null;let i=n.slice(Te(r.prefix).length);return!i||i.includes("/")||!i.endsWith(".md")?null:r}function hl(t,e){return t.classic?.[e.field]??null}function Fm(t,e){return t.classic!==null&&t.phase===e.phase&&!hl(t,e)}async function al(t,e,n){return Fm(e,n)?!0:n.field!=="plan"||e.phase!=="build"?!1:(await fl(t,e.classic?.plan??null)).status==="broken"}function ml(t){return t.phase==="design"||t.phase==="build"||t.phase==="verify"}function ie(t){return t.changeDir?K.basename(t.changeDir):null}var Bm=new Set(["design","plan","verify","verification","verification-report","report"]);function cl(t){return t.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}function Km(t,e){return[e.classic?.designDoc,e.classic?.plan,e.classic?.verificationReport].some(r=>r&&Te(r)===Te(t))}function Ym(t,e){let r=(t.split("/").at(-1)??t).replace(/\.[^.]+$/u,"");if(r===e)return!0;let i=[...Bm].map(cl).join("|");return new RegExp(`(^|[-_.])${cl(e)}[-_.](${i})$`,"u").test(r)}async function Um(t,e){let n=await ks(e),r=n.find(o=>Km(t,o));if(r)return{governing:r,match:"recorded"};let s=n.filter(ml).filter(o=>{let a=ie(o);return a!==null&&Ym(t,a)}).sort((o,a)=>(ie(a)?.length??0)-(ie(o)?.length??0))[0];return s?{governing:s,match:"named"}:null}async function ll(t,e,n){let r=await ks(t);if(r.length===0)return null;if(n)return r.find(o=>ie(o)===n)??{blockedResult:Wt(e,`selected change '${n}' is no longer active`)};let i=await il(t);if(i.status==="stale")return{blockedResult:Wt(e,i.reason)};if(i.status==="selected"){let s=r.find(o=>ie(o)===i.selection.change);return s||{blockedResult:Wt(e,`selected change '${i.selection.change}' is no longer active`)}}if(r.length===1){let s=r[0];if(s.changeDir!==null){let o=await er(s.changeDir,{heal:!1,cwd:t}),a=ie(s)??"unknown";if(o.status==="drift")return{blockedResult:Wt(e,tr(a,o.boundBranch,o.currentBranch))};if(o.status==="unbound-detached")return{blockedResult:Wt(e,nr(a))}}return s}return{blockedResult:tg(e,r.map(s=>ie(s)).filter(Boolean))}}async function Hm(t,e,n,r){let i=`${q(e,n.changesDir)}/`;if(t.startsWith(i)){let s=t.slice(i.length),[o]=s.split("/");if(o&&o!=="archive"){let a=await jt(o,e);if(a.stateExists){let c=await ul(a.directory);return c||{changeDir:a.directory,phase:"open",classic:null,archived:!1}}return{changeDir:a.directory,phase:"open",classic:null,archived:!1}}}if(pl(t,dl(e,n))){let s=await Um(t,e);if(s?.match==="recorded")return{...s.governing,superpowersArtifact:"matched"};let o=Mm(t,Wm(e,n));if(s)return o?{...s.governing,superpowersArtifact:await al(e,s.governing,o)?"matched":"unmatched",superpowersSlot:o}:{...s.governing,superpowersArtifact:"matched"};if(o){let l=await ll(e,t,r);return!l||"blockedResult"in l?l:{...l,superpowersArtifact:await al(e,l,o)?"matched":"unmatched",superpowersSlot:o}}let a=await ks(e),c=r?a.find(l=>ie(l)===r)??null:a[0]??null;return c?{...c,superpowersArtifact:"unmatched"}:null}return ll(e,t,r)}function Jm(t){return!t.includes("/")&&t.endsWith(".md")}function Vm(t){return t.startsWith(".comet/")||t.includes("/.comet/")}function Gm(t){return t===".superpowers"||t.startsWith(".superpowers/")}function zm(t,e,n){if(!t.startsWith(n))return null;let r=t.endsWith("/.comet.yaml")||t.endsWith("/.openspec.yaml"),i=t.endsWith("/proposal.md")||t.endsWith("/design.md")||t.endsWith("/tasks.md"),s=t.includes("/.comet/"),o=t.includes("/specs/");return e==="open"&&(i||r||s||o)?`${t} (phase: open, openspec artifacts)`:e==="design"&&(i||r||s||o)?`${t} (phase: design, handoff/spec)`:e==="build"&&(t.endsWith("/tasks.md")||r||o)?`${t} (phase: build, spec/tasks)`:e==="verify"&&(t.endsWith("/tasks.md")||r)?`${t} (phase: verify, tasks/state)`:e==="archive"&&r?`${t} (phase: archive, state)`:null}function Xm(t,e){let n=e==="open"?[" BLOCKED: source writes are not allowed during open"," This phase does not allow source writes"," ALLOWED: create proposal/design/tasks artifacts and run guard"," NEXT: finish clarification and artifacts, then run guard --apply"]:e==="design"?[" BLOCKED: source writes are not allowed during design"," This phase does not allow source writes"," ALLOWED: run brainstorming, create the Design Doc, and run guard"," NEXT: finish the Design Doc, then run comet guard design --apply to enter build"]:[" BLOCKED: source writes are not allowed during archive"," This phase does not allow source writes"," ALLOWED: confirm archive state and run the archive script"];return V(2,["","╔══════════════════════════════════════════╗","║ COMET PHASE GUARD — WRITE BLOCKED ║","╚══════════════════════════════════════════╝","",` Current phase: ${e}`,` Target file: ${t}`,"",...n,""].join(` +`))}function Qm(t){return V(2,["","╔══════════════════════════════════════════╗","║ COMET PHASE GUARD — WRITE BLOCKED ║","╚══════════════════════════════════════════╝",""," Current phase: build (workflow: full), but design_doc is empty",` Target file: ${t}`,""," BLOCKED: full workflow source writes require a recorded Design Doc"," This phase does not allow source writes until design_doc is recorded"," NEXT: return to design, create/link the Design Doc, then run guard again",""].join(` +`))}function Zm(t,e,n,r,i){let s=ie(e)??"",o=n.status==="missing",a=o?"classic-build-plan-missing":"classic-build-plan-broken",c=o?"plan is not recorded":"the recorded plan path does not resolve to a file",l=o?[]:[`RECORDED_PLAN: ${n.recordedPath}`],d=e.changeDir?q(r,e.changeDir):"",u=q(r,i.superpowersPlansDir),f=o?`comet state set ${s} plan `:`comet state set ${s} plan `,m=o?["2. Load the Superpowers writing-plans Skill.",`3. Read the Design Doc path from "comet state get ${s} design_doc" and read ${d}/tasks.md.`,`4. Create the implementation plan under ${u}/.`,"5. Record the plan path:",` ${f}`]:[`2. Restore the plan file at ${n.recordedPath}, or load the Superpowers writing-plans Skill and create a replacement under ${u}/.`,"3. When creating a replacement, record its path:",` ${f}`];return V(2,["","╔══════════════════════════════════════════╗","║ COMET PHASE GUARD — WRITE BLOCKED ║","╚══════════════════════════════════════════╝","",`ERROR_CODE: ${a}`,`CHANGE: ${s}`,"WORKFLOW: full","PHASE: build",`TARGET: ${t}`,`STATE: ${c}`,...l,"","BLOCKED: project source writes require a ready Superpowers implementation plan.","","ALLOWED_RECOVERY_WRITES:",`- ${u}/.md`,"- Comet state updates performed by the comet CLI",`- ${d} artifacts allowed by the build phase`,"","RECOVERY:",`1. Invoke /comet-build for ${s} and resume Step 1.`,...m,`${o?"6":"4"}. Verify recovery:`,` comet state check ${s} build --recover`,"","SUCCESS: plan is reported as DONE and recovery advances beyond plan creation.",`RETRY: retry the original Write/Edit for ${t} only after SUCCESS.`,"PROHIBITED: do not treat tasks.md as the implementation plan or write project source before SUCCESS.","If writing-plans is unavailable, stop and report the missing Skill instead of bypassing this check.",""].join(` +`))}function eg(t,e){let n=e.superpowersSlot,r=n?hl(e,n):null,i=n?e.phase!==n.phase?[` BLOCKED: ${n.wireField} cannot be first-written in phase ${e.phase}`,` Expected phase: ${n.phase}`," NEXT: resume the matching Comet phase or use an already recorded artifact path"]:r?[` BLOCKED: ${n.wireField} is already recorded for this change`,` Recorded path: ${r}`," NEXT: write the recorded artifact or explicitly correct the state path"]:[" BLOCKED: standard Superpowers artifact state is incomplete"," NEXT: validate the active change state, then retry the matching phase"]:[" BLOCKED: unmatched Superpowers artifact"," This docs/superpowers/ path does not match any active change artifact"," NEXT: use a recorded artifact path or a standard phase artifact directory"];return V(2,["","╔══════════════════════════════════════════╗","║ COMET PHASE GUARD — WRITE BLOCKED ║","╚══════════════════════════════════════════╝","",` Current phase: ${e.phase}`,` Target file: ${t}`,"",...i,""].join(` +`))}function tg(t,e){return V(2,["","╔══════════════════════════════════════════╗","║ COMET PHASE GUARD — WRITE BLOCKED ║","╚══════════════════════════════════════════╝",""," BLOCKED: multiple active changes require a current change",` Target file: ${t}`,` Active changes: ${e.join(", ")}`,""," NEXT: run comet state select , then retry the source write",""].join(` `))}function Wt(t,e){return V(2,["","╔══════════════════════════════════════════╗","║ COMET PHASE GUARD — WRITE BLOCKED ║","╚══════════════════════════════════════════╝",""," BLOCKED: current change selection is stale or invalid",` Target file: ${t}`,` Reason: ${e}`,""," NEXT: run comet state select , then retry the source write",""].join(` -`))}async function eg(t,e,n,r=xc){try{if((await r(t,[e])).projectTargets.length===0)return X(`${e} (outside guarded project)`)}catch(l){return V(2,[`[COMET-HOOK] blocked: scope could not be determined safely for ${e}.`,`REASON: ${l instanceof Error?l.message:String(l)}`,"NEXT: verify that the project root is accessible, then retry the write."].join(` -`))}let i=await Lm(e,t),s;try{s=await ls(t)}catch(l){return V(2,`[COMET-HOOK] blocked: ${l instanceof Error?l.message:String(l)}`)}if(Hm(i))return X(`${i} (whitelist: comet config)`);if(Jm(i))return X(`${i} (whitelist: superpowers workspace)`);if(i==="CLAUDE.md"||i==="CHANGELOG.md"||i==="README.md"||Um(i))return X(`${i} (whitelist: root markdown)`);let o;try{o=await Ym(i,t,s,n)}catch(l){return V(2,`[COMET-HOOK] blocked: ${l instanceof Error?l.message:String(l)}`)}if(!o)return X("no active comet change");if("blockedResult"in o)return o.blockedResult;if(o.archived)return X(`${i} (own change archived)`);let a=o.phase,c=Vm(i,a,`${I(t,s.openSpecRoot)}/`);if(c)return X(c);if(hl(i,pl(t,s))){if(o.superpowersArtifact==="matched"&&gl(o))return X(`${i} (phase: ${a}, superpowers)`);if(o.superpowersArtifact==="unmatched")return Qm(i,o)}if(o.invalidState)return V(2,`[COMET-HOOK] blocked: active Classic state is invalid; repair .comet.yaml before writing ${i}`);if(a==="build"&&o.classic?.workflow==="full"&&!o.classic.designDoc)return zm(i);if(a==="build"&&o.classic?.workflow==="full"){let l=await dl(t,o.classic.plan);if(l.status!=="ready")return Xm(i,o,l,t,s)}return a==="build"||a==="verify"?X(`${i} (phase: ${a})`):Gm(i,a)}var wl=async t=>{let e=Im(t),n=Rm();return n?eg(e,n):X("no file path in tool input")};function tg(t,e){return{exitCode:e.exitCode,stdout:JSON.stringify({command:t,exitCode:e.exitCode,...e.stdout===void 0?{}:{stdout:e.stdout},...e.stderr===void 0?{}:{stderr:e.stderr}})+` -`}}async function yl(t,e,n=process.argv.slice(2)){let r=n.includes("--json"),i=n.filter(a=>a!=="--json"),s;try{s=await e(i,{json:r})}catch(a){s={exitCode:70,stderr:a instanceof Error?a.message:String(a)}}let o=r?tg(t,s):s;return o.stdout&&process.stdout.write(o.stdout),o.stderr&&process.stderr.write(o.stderr+(o.stderr.endsWith(` +`))}async function ng(t,e,n,r=Ac){try{if((await r(t,[e])).projectTargets.length===0)return X(`${e} (outside guarded project)`)}catch(l){return V(2,[`[COMET-HOOK] blocked: scope could not be determined safely for ${e}.`,`REASON: ${l instanceof Error?l.message:String(l)}`,"NEXT: verify that the project root is accessible, then retry the write."].join(` +`))}let i=await Dm(e,t),s;try{s=await cs(t)}catch(l){return V(2,`[COMET-HOOK] blocked: ${l instanceof Error?l.message:String(l)}`)}if(Vm(i))return X(`${i} (whitelist: comet config)`);if(Gm(i))return X(`${i} (whitelist: superpowers workspace)`);if(i==="CLAUDE.md"||i==="CHANGELOG.md"||i==="README.md"||Jm(i))return X(`${i} (whitelist: root markdown)`);let o;try{o=await Hm(i,t,s,n)}catch(l){return V(2,`[COMET-HOOK] blocked: ${l instanceof Error?l.message:String(l)}`)}if(!o)return X("no active comet change");if("blockedResult"in o)return o.blockedResult;if(o.archived)return X(`${i} (own change archived)`);let a=o.phase,c=zm(i,a,`${q(t,s.openSpecRoot)}/`);if(c)return X(c);if(pl(i,dl(t,s))){if(o.superpowersArtifact==="matched"&&ml(o))return X(`${i} (phase: ${a}, superpowers)`);if(o.superpowersArtifact==="unmatched")return eg(i,o)}if(o.invalidState)return V(2,`[COMET-HOOK] blocked: active Classic state is invalid; repair .comet.yaml before writing ${i}`);if(a==="build"&&o.classic?.workflow==="full"&&!o.classic.designDoc)return Qm(i);if(a==="build"&&o.classic?.workflow==="full"){let l=await fl(t,o.classic.plan);if(l.status!=="ready")return Zm(i,o,l,t,s)}return a==="build"||a==="verify"?X(`${i} (phase: ${a})`):Xm(i,a)}var gl=async t=>{let e=Lm(t),n=jm();return n?ng(e,n):X("no file path in tool input")};function rg(t,e){return{exitCode:e.exitCode,stdout:JSON.stringify({command:t,exitCode:e.exitCode,...e.stdout===void 0?{}:{stdout:e.stdout},...e.stderr===void 0?{}:{stderr:e.stderr}})+` +`}}async function wl(t,e,n=process.argv.slice(2)){let r=n.includes("--json"),i=n.filter(a=>a!=="--json"),s;try{s=await e(i,{json:r})}catch(a){s={exitCode:70,stderr:a instanceof Error?a.message:String(a)}}let o=r?rg(t,s):s;return o.stdout&&process.stdout.write(o.stdout),o.stderr&&process.stderr.write(o.stderr+(o.stderr.endsWith(` `)?"":` -`)),o.exitCode}process.exitCode=await yl("hook-guard",wl); +`)),o.exitCode}process.exitCode=await wl("hook-guard",gl); diff --git a/assets/skills/comet/scripts/comet-hook-router.mjs b/assets/skills/comet/scripts/comet-hook-router.mjs index 6bddde477..a40e2dbd8 100644 --- a/assets/skills/comet/scripts/comet-hook-router.mjs +++ b/assets/skills/comet/scripts/comet-hook-router.mjs @@ -1,17 +1,17 @@ #!/usr/bin/env node import { createRequire as __cometCreateRequire } from 'module'; const require = __cometCreateRequire(import.meta.url); -var Wf=Object.create;var kn=Object.defineProperty;var qf=Object.getOwnPropertyDescriptor;var Hf=Object.getOwnPropertyNames;var Gf=Object.getPrototypeOf,zf=Object.prototype.hasOwnProperty;var ji=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,i)=>(typeof require<"u"?require:e)[i]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var M=(t,e,i)=>()=>{if(i)throw i[0];try{return t&&(e=t(t=0)),e}catch(r){throw i=[r],r}};var v=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(i){throw e=0,i}},Vf=(t,e)=>{for(var i in e)kn(t,i,{get:e[i],enumerable:!0})},Kf=(t,e,i,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Hf(e))!zf.call(t,n)&&n!==i&&kn(t,n,{get:()=>e[n],enumerable:!(r=qf(e,n))||r.enumerable});return t};var xt=(t,e,i)=>(i=t!=null?Wf(Gf(t)):{},Kf(e||!t||!t.__esModule?kn(i,"default",{value:t,enumerable:!0}):i,t));var C=v(D=>{"use strict";var Sn=Symbol.for("yaml.alias"),Ja=Symbol.for("yaml.document"),Li=Symbol.for("yaml.map"),Ua=Symbol.for("yaml.pair"),En=Symbol.for("yaml.scalar"),$i=Symbol.for("yaml.seq"),he=Symbol.for("yaml.node.type"),Jf=t=>!!t&&typeof t=="object"&&t[he]===Sn,Uf=t=>!!t&&typeof t=="object"&&t[he]===Ja,Yf=t=>!!t&&typeof t=="object"&&t[he]===Li,Xf=t=>!!t&&typeof t=="object"&&t[he]===Ua,Ya=t=>!!t&&typeof t=="object"&&t[he]===En,Qf=t=>!!t&&typeof t=="object"&&t[he]===$i;function Xa(t){if(t&&typeof t=="object")switch(t[he]){case Li:case $i:return!0}return!1}function Zf(t){if(t&&typeof t=="object")switch(t[he]){case Sn:case Li:case En:case $i:return!0}return!1}var ed=t=>(Ya(t)||Xa(t))&&!!t.anchor;D.ALIAS=Sn;D.DOC=Ja;D.MAP=Li;D.NODE_TYPE=he;D.PAIR=Ua;D.SCALAR=En;D.SEQ=$i;D.hasAnchor=ed;D.isAlias=Jf;D.isCollection=Xa;D.isDocument=Uf;D.isMap=Yf;D.isNode=Zf;D.isPair=Xf;D.isScalar=Ya;D.isSeq=Qf});var Rt=v(Cn=>{"use strict";var L=C(),W=Symbol("break visit"),Qa=Symbol("skip children"),se=Symbol("remove node");function Di(t,e){let i=Za(e);L.isDocument(t)?rt(null,t.contents,i,Object.freeze([t]))===se&&(t.contents=null):rt(null,t,i,Object.freeze([]))}Di.BREAK=W;Di.SKIP=Qa;Di.REMOVE=se;function rt(t,e,i,r){let n=es(t,e,i,r);if(L.isNode(n)||L.isPair(n))return ts(t,r,n),rt(t,n,i,r);if(typeof n!="symbol"){if(L.isCollection(e)){r=Object.freeze(r.concat(e));for(let o=0;o{"use strict";var is=C(),td=Rt(),id={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},rd=t=>t.replace(/[!,[\]{}]/g,e=>id[e]),_t=class t{constructor(e,i){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},t.defaultYaml,e),this.tags=Object.assign({},t.defaultTags,i)}clone(){let e=new t(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){let e=new t(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:t.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},t.defaultTags);break}return e}add(e,i){this.atNextDocument&&(this.yaml={explicit:t.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},t.defaultTags),this.atNextDocument=!1);let r=e.trim().split(/[ \t]+/),n=r.shift();switch(n){case"%TAG":{if(r.length!==2&&(i(0,"%TAG directive should contain exactly two parts"),r.length<2))return!1;let[o,a]=r;return this.tags[o]=a,!0}case"%YAML":{if(this.yaml.explicit=!0,r.length!==1)return i(0,"%YAML directive should contain exactly one part"),!1;let[o]=r;if(o==="1.1"||o==="1.2")return this.yaml.version=o,!0;{let a=/^\d+\.\d+$/.test(o);return i(6,`Unsupported YAML version ${o}`,a),!1}}default:return i(0,`Unknown directive ${n}`,!0),!1}}tagName(e,i){if(e==="!")return"!";if(e[0]!=="!")return i(`Not a valid tag: ${e}`),null;if(e[1]==="<"){let a=e.slice(2,-1);return a==="!"||a==="!!"?(i(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&i("Verbatim tags must end with a >"),a)}let[,r,n]=e.match(/^(.*!)([^!]*)$/s);n||i(`The ${e} tag has no suffix`);let o=this.tags[r];if(o)try{return o+decodeURIComponent(n)}catch(a){return i(String(a)),null}return r==="!"?e:(i(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[i,r]of Object.entries(this.tags))if(e.startsWith(r))return i+rd(e.substring(r.length));return e[0]==="!"?e:`!<${e}>`}toString(e){let i=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],r=Object.entries(this.tags),n;if(e&&r.length>0&&is.isNode(e.contents)){let o={};td.visit(e.contents,(a,s)=>{is.isNode(s)&&s.tag&&(o[s.tag]=!0)}),n=Object.keys(o)}else n=[];for(let[o,a]of r)o==="!!"&&a==="tag:yaml.org,2002:"||(!e||n.some(s=>s.startsWith(a)))&&i.push(`%TAG ${o} ${a}`);return i.join(` -`)}};_t.defaultYaml={explicit:!1,version:"1.2"};_t.defaultTags={"!!":"tag:yaml.org,2002:"};rs.Directives=_t});var Mi=v(At=>{"use strict";var ns=C(),nd=Rt();function od(t){if(/[\x00-\x19\s,[\]{}]/.test(t)){let i=`Anchor must not contain whitespace or control characters: ${JSON.stringify(t)}`;throw new Error(i)}return!0}function os(t){let e=new Set;return nd.visit(t,{Value(i,r){r.anchor&&e.add(r.anchor)}}),e}function as(t,e){for(let i=1;;++i){let r=`${t}${i}`;if(!e.has(r))return r}}function ad(t,e){let i=[],r=new Map,n=null;return{onAnchor:o=>{i.push(o),n??(n=os(t));let a=as(e,n);return n.add(a),a},setAnchors:()=>{for(let o of i){let a=r.get(o);if(typeof a=="object"&&a.anchor&&(ns.isScalar(a.node)||ns.isCollection(a.node)))a.node.anchor=a.anchor;else{let s=new Error("Failed to resolve repeated object (this should not happen)");throw s.source=o,s}}},sourceObjects:r}}At.anchorIsValid=od;At.anchorNames=os;At.createNodeAnchors=ad;At.findNewAnchor=as});var xn=v(ss=>{"use strict";function Tt(t,e,i,r){if(r&&typeof r=="object")if(Array.isArray(r))for(let n=0,o=r.length;n{"use strict";var sd=C();function cs(t,e,i){if(Array.isArray(t))return t.map((r,n)=>cs(r,String(n),i));if(t&&typeof t.toJSON=="function"){if(!i||!sd.hasAnchor(t))return t.toJSON(e,i);let r={aliasCount:0,count:1,res:void 0};i.anchors.set(t,r),i.onCreate=o=>{r.res=o,delete i.onCreate};let n=t.toJSON(e,i);return i.onCreate&&i.onCreate(n),n}return typeof t=="bigint"&&!i?.keep?Number(t):t}ls.toJS=cs});var Fi=v(fs=>{"use strict";var cd=xn(),us=C(),ld=Ne(),Rn=class{constructor(e){Object.defineProperty(this,us.NODE_TYPE,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:i,maxAliasCount:r,onAnchor:n,reviver:o}={}){if(!us.isDocument(e))throw new TypeError("A document argument is required");let a={anchors:new Map,doc:e,keep:!0,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},s=ld.toJS(this,"",a);if(typeof n=="function")for(let{count:c,res:l}of a.anchors.values())n(l,c);return typeof o=="function"?cd.applyReviver(o,{"":s},"",s):s}};fs.NodeBase=Rn});var Ot=v(ds=>{"use strict";var ud=Mi(),fd=Rt(),ot=C(),dd=Fi(),hd=Ne(),_n=class extends dd.NodeBase{constructor(e){super(ot.ALIAS),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,i){if(i?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let r;i?.aliasResolveCache?r=i.aliasResolveCache:(r=[],fd.visit(e,{Node:(o,a)=>{(ot.isAlias(a)||ot.hasAnchor(a))&&r.push(a)}}),i&&(i.aliasResolveCache=r));let n;for(let o of r){if(o===this)break;o.anchor===this.source&&(n=o)}return n}toJSON(e,i){if(!i)return{source:this.source};let{anchors:r,doc:n,maxAliasCount:o}=i,a=this.resolve(n,i);if(!a){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let s=r.get(a);if(s||(hd.toJS(a,null,i),s=r.get(a)),s?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(o>=0&&(s.count+=1,s.aliasCount===0&&(s.aliasCount=Wi(n,a,r)),s.count*s.aliasCount>o)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return s.res}toString(e,i,r){let n=`*${this.source}`;if(e){if(ud.anchorIsValid(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let o=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(o)}if(e.implicitKey)return`${n} `}return n}};function Wi(t,e,i){if(ot.isAlias(e)){let r=e.resolve(t),n=i&&r&&i.get(r);return n?n.count*n.aliasCount:0}else if(ot.isCollection(e)){let r=0;for(let n of e.items){let o=Wi(t,n,i);o>r&&(r=o)}return r}else if(ot.isPair(e)){let r=Wi(t,e.key,i),n=Wi(t,e.value,i);return Math.max(r,n)}return 1}ds.Alias=_n});var O=v(An=>{"use strict";var md=C(),pd=Fi(),gd=Ne(),wd=t=>!t||typeof t!="function"&&typeof t!="object",ke=class extends pd.NodeBase{constructor(e){super(md.SCALAR),this.value=e}toJSON(e,i){return i?.keep?this.value:gd.toJS(this.value,e,i)}toString(){return String(this.value)}};ke.BLOCK_FOLDED="BLOCK_FOLDED";ke.BLOCK_LITERAL="BLOCK_LITERAL";ke.PLAIN="PLAIN";ke.QUOTE_DOUBLE="QUOTE_DOUBLE";ke.QUOTE_SINGLE="QUOTE_SINGLE";An.Scalar=ke;An.isScalarValue=wd});var It=v(ms=>{"use strict";var vd=Ot(),Le=C(),hs=O(),yd="tag:yaml.org,2002:";function bd(t,e,i){if(e){let r=i.filter(o=>o.tag===e),n=r.find(o=>!o.format)??r[0];if(!n)throw new Error(`Tag ${e} not found`);return n}return i.find(r=>r.identify?.(t)&&!r.format)}function Nd(t,e,i){if(Le.isDocument(t)&&(t=t.contents),Le.isNode(t))return t;if(Le.isPair(t)){let u=i.schema[Le.MAP].createNode?.(i.schema,null,i);return u.items.push(t),u}(t instanceof String||t instanceof Number||t instanceof Boolean||typeof BigInt<"u"&&t instanceof BigInt)&&(t=t.valueOf());let{aliasDuplicateObjects:r,onAnchor:n,onTagObj:o,schema:a,sourceObjects:s}=i,c;if(r&&t&&typeof t=="object"){if(c=s.get(t),c)return c.anchor??(c.anchor=n(t)),new vd.Alias(c.anchor);c={anchor:null,node:null},s.set(t,c)}e?.startsWith("!!")&&(e=yd+e.slice(2));let l=bd(t,e,a.tags);if(!l){if(t&&typeof t.toJSON=="function"&&(t=t.toJSON()),!t||typeof t!="object"){let u=new hs.Scalar(t);return c&&(c.node=u),u}l=t instanceof Map?a[Le.MAP]:Symbol.iterator in Object(t)?a[Le.SEQ]:a[Le.MAP]}o&&(o(l),delete i.onTagObj);let f=l?.createNode?l.createNode(i.schema,t,i):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(i.schema,t,i):new hs.Scalar(t);return e?f.tag=e:l.default||(f.tag=l.tag),c&&(c.node=f),f}ms.createNode=Nd});var Hi=v(qi=>{"use strict";var kd=It(),ce=C(),Sd=Fi();function Tn(t,e,i){let r=i;for(let n=e.length-1;n>=0;--n){let o=e[n];if(typeof o=="number"&&Number.isInteger(o)&&o>=0){let a=[];a[o]=r,r=a}else r=new Map([[o,r]])}return kd.createNode(r,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:t,sourceObjects:new Map})}var ps=t=>t==null||typeof t=="object"&&!!t[Symbol.iterator]().next().done,On=class extends Sd.NodeBase{constructor(e,i){super(e),Object.defineProperty(this,"schema",{value:i,configurable:!0,enumerable:!1,writable:!0})}clone(e){let i=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(i.schema=e),i.items=i.items.map(r=>ce.isNode(r)||ce.isPair(r)?r.clone(e):r),this.range&&(i.range=this.range.slice()),i}addIn(e,i){if(ps(e))this.add(i);else{let[r,...n]=e,o=this.get(r,!0);if(ce.isCollection(o))o.addIn(n,i);else if(o===void 0&&this.schema)this.set(r,Tn(this.schema,n,i));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}}deleteIn(e){let[i,...r]=e;if(r.length===0)return this.delete(i);let n=this.get(i,!0);if(ce.isCollection(n))return n.deleteIn(r);throw new Error(`Expected YAML collection at ${i}. Remaining path: ${r}`)}getIn(e,i){let[r,...n]=e,o=this.get(r,!0);return n.length===0?!i&&ce.isScalar(o)?o.value:o:ce.isCollection(o)?o.getIn(n,i):void 0}hasAllNullValues(e){return this.items.every(i=>{if(!ce.isPair(i))return!1;let r=i.value;return r==null||e&&ce.isScalar(r)&&r.value==null&&!r.commentBefore&&!r.comment&&!r.tag})}hasIn(e){let[i,...r]=e;if(r.length===0)return this.has(i);let n=this.get(i,!0);return ce.isCollection(n)?n.hasIn(r):!1}setIn(e,i){let[r,...n]=e;if(n.length===0)this.set(r,i);else{let o=this.get(r,!0);if(ce.isCollection(o))o.setIn(n,i);else if(o===void 0&&this.schema)this.set(r,Tn(this.schema,n,i));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}}};qi.Collection=On;qi.collectionFromPath=Tn;qi.isEmptyPath=ps});var jt=v(Gi=>{"use strict";var Ed=t=>t.replace(/^(?!$)(?: $)?/gm,"#");function In(t,e){return/^\n+$/.test(t)?t.substring(1):e?t.replace(/^(?! *$)/gm,e):t}var Cd=(t,e,i)=>t.endsWith(` +var qf=Object.create;var kn=Object.defineProperty;var Hf=Object.getOwnPropertyDescriptor;var Gf=Object.getOwnPropertyNames;var zf=Object.getPrototypeOf,Vf=Object.prototype.hasOwnProperty;var ji=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,i)=>(typeof require<"u"?require:e)[i]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var B=(t,e,i)=>()=>{if(i)throw i[0];try{return t&&(e=t(t=0)),e}catch(r){throw i=[r],r}};var v=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(i){throw e=0,i}},Kf=(t,e)=>{for(var i in e)kn(t,i,{get:e[i],enumerable:!0})},Jf=(t,e,i,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Gf(e))!Vf.call(t,n)&&n!==i&&kn(t,n,{get:()=>e[n],enumerable:!(r=Hf(e,n))||r.enumerable});return t};var xt=(t,e,i)=>(i=t!=null?qf(zf(t)):{},Jf(e||!t||!t.__esModule?kn(i,"default",{value:t,enumerable:!0}):i,t));var C=v($=>{"use strict";var Sn=Symbol.for("yaml.alias"),Ja=Symbol.for("yaml.document"),Li=Symbol.for("yaml.map"),Ua=Symbol.for("yaml.pair"),En=Symbol.for("yaml.scalar"),$i=Symbol.for("yaml.seq"),he=Symbol.for("yaml.node.type"),Uf=t=>!!t&&typeof t=="object"&&t[he]===Sn,Yf=t=>!!t&&typeof t=="object"&&t[he]===Ja,Xf=t=>!!t&&typeof t=="object"&&t[he]===Li,Qf=t=>!!t&&typeof t=="object"&&t[he]===Ua,Ya=t=>!!t&&typeof t=="object"&&t[he]===En,Zf=t=>!!t&&typeof t=="object"&&t[he]===$i;function Xa(t){if(t&&typeof t=="object")switch(t[he]){case Li:case $i:return!0}return!1}function ed(t){if(t&&typeof t=="object")switch(t[he]){case Sn:case Li:case En:case $i:return!0}return!1}var td=t=>(Ya(t)||Xa(t))&&!!t.anchor;$.ALIAS=Sn;$.DOC=Ja;$.MAP=Li;$.NODE_TYPE=he;$.PAIR=Ua;$.SCALAR=En;$.SEQ=$i;$.hasAnchor=td;$.isAlias=Uf;$.isCollection=Xa;$.isDocument=Yf;$.isMap=Xf;$.isNode=ed;$.isPair=Qf;$.isScalar=Ya;$.isSeq=Zf});var Rt=v(Cn=>{"use strict";var L=C(),W=Symbol("break visit"),Qa=Symbol("skip children"),se=Symbol("remove node");function Di(t,e){let i=Za(e);L.isDocument(t)?rt(null,t.contents,i,Object.freeze([t]))===se&&(t.contents=null):rt(null,t,i,Object.freeze([]))}Di.BREAK=W;Di.SKIP=Qa;Di.REMOVE=se;function rt(t,e,i,r){let n=es(t,e,i,r);if(L.isNode(n)||L.isPair(n))return ts(t,r,n),rt(t,n,i,r);if(typeof n!="symbol"){if(L.isCollection(e)){r=Object.freeze(r.concat(e));for(let o=0;o{"use strict";var is=C(),id=Rt(),rd={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},nd=t=>t.replace(/[!,[\]{}]/g,e=>rd[e]),_t=class t{constructor(e,i){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},t.defaultYaml,e),this.tags=Object.assign({},t.defaultTags,i)}clone(){let e=new t(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){let e=new t(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:t.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},t.defaultTags);break}return e}add(e,i){this.atNextDocument&&(this.yaml={explicit:t.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},t.defaultTags),this.atNextDocument=!1);let r=e.trim().split(/[ \t]+/),n=r.shift();switch(n){case"%TAG":{if(r.length!==2&&(i(0,"%TAG directive should contain exactly two parts"),r.length<2))return!1;let[o,a]=r;return this.tags[o]=a,!0}case"%YAML":{if(this.yaml.explicit=!0,r.length!==1)return i(0,"%YAML directive should contain exactly one part"),!1;let[o]=r;if(o==="1.1"||o==="1.2")return this.yaml.version=o,!0;{let a=/^\d+\.\d+$/.test(o);return i(6,`Unsupported YAML version ${o}`,a),!1}}default:return i(0,`Unknown directive ${n}`,!0),!1}}tagName(e,i){if(e==="!")return"!";if(e[0]!=="!")return i(`Not a valid tag: ${e}`),null;if(e[1]==="<"){let a=e.slice(2,-1);return a==="!"||a==="!!"?(i(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&i("Verbatim tags must end with a >"),a)}let[,r,n]=e.match(/^(.*!)([^!]*)$/s);n||i(`The ${e} tag has no suffix`);let o=this.tags[r];if(o)try{return o+decodeURIComponent(n)}catch(a){return i(String(a)),null}return r==="!"?e:(i(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[i,r]of Object.entries(this.tags))if(e.startsWith(r))return i+nd(e.substring(r.length));return e[0]==="!"?e:`!<${e}>`}toString(e){let i=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],r=Object.entries(this.tags),n;if(e&&r.length>0&&is.isNode(e.contents)){let o={};id.visit(e.contents,(a,s)=>{is.isNode(s)&&s.tag&&(o[s.tag]=!0)}),n=Object.keys(o)}else n=[];for(let[o,a]of r)o==="!!"&&a==="tag:yaml.org,2002:"||(!e||n.some(s=>s.startsWith(a)))&&i.push(`%TAG ${o} ${a}`);return i.join(` +`)}};_t.defaultYaml={explicit:!1,version:"1.2"};_t.defaultTags={"!!":"tag:yaml.org,2002:"};rs.Directives=_t});var Mi=v(At=>{"use strict";var ns=C(),od=Rt();function ad(t){if(/[\x00-\x19\s,[\]{}]/.test(t)){let i=`Anchor must not contain whitespace or control characters: ${JSON.stringify(t)}`;throw new Error(i)}return!0}function os(t){let e=new Set;return od.visit(t,{Value(i,r){r.anchor&&e.add(r.anchor)}}),e}function as(t,e){for(let i=1;;++i){let r=`${t}${i}`;if(!e.has(r))return r}}function sd(t,e){let i=[],r=new Map,n=null;return{onAnchor:o=>{i.push(o),n??(n=os(t));let a=as(e,n);return n.add(a),a},setAnchors:()=>{for(let o of i){let a=r.get(o);if(typeof a=="object"&&a.anchor&&(ns.isScalar(a.node)||ns.isCollection(a.node)))a.node.anchor=a.anchor;else{let s=new Error("Failed to resolve repeated object (this should not happen)");throw s.source=o,s}}},sourceObjects:r}}At.anchorIsValid=ad;At.anchorNames=os;At.createNodeAnchors=sd;At.findNewAnchor=as});var xn=v(ss=>{"use strict";function Tt(t,e,i,r){if(r&&typeof r=="object")if(Array.isArray(r))for(let n=0,o=r.length;n{"use strict";var cd=C();function cs(t,e,i){if(Array.isArray(t))return t.map((r,n)=>cs(r,String(n),i));if(t&&typeof t.toJSON=="function"){if(!i||!cd.hasAnchor(t))return t.toJSON(e,i);let r={aliasCount:0,count:1,res:void 0};i.anchors.set(t,r),i.onCreate=o=>{r.res=o,delete i.onCreate};let n=t.toJSON(e,i);return i.onCreate&&i.onCreate(n),n}return typeof t=="bigint"&&!i?.keep?Number(t):t}ls.toJS=cs});var Fi=v(fs=>{"use strict";var ld=xn(),us=C(),ud=Ne(),Rn=class{constructor(e){Object.defineProperty(this,us.NODE_TYPE,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:i,maxAliasCount:r,onAnchor:n,reviver:o}={}){if(!us.isDocument(e))throw new TypeError("A document argument is required");let a={anchors:new Map,doc:e,keep:!0,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},s=ud.toJS(this,"",a);if(typeof n=="function")for(let{count:c,res:l}of a.anchors.values())n(l,c);return typeof o=="function"?ld.applyReviver(o,{"":s},"",s):s}};fs.NodeBase=Rn});var Ot=v(ds=>{"use strict";var fd=Mi(),dd=Rt(),ot=C(),hd=Fi(),md=Ne(),_n=class extends hd.NodeBase{constructor(e){super(ot.ALIAS),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,i){if(i?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let r;i?.aliasResolveCache?r=i.aliasResolveCache:(r=[],dd.visit(e,{Node:(o,a)=>{(ot.isAlias(a)||ot.hasAnchor(a))&&r.push(a)}}),i&&(i.aliasResolveCache=r));let n;for(let o of r){if(o===this)break;o.anchor===this.source&&(n=o)}return n}toJSON(e,i){if(!i)return{source:this.source};let{anchors:r,doc:n,maxAliasCount:o}=i,a=this.resolve(n,i);if(!a){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let s=r.get(a);if(s||(md.toJS(a,null,i),s=r.get(a)),s?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(o>=0&&(s.count+=1,s.aliasCount===0&&(s.aliasCount=Wi(n,a,r)),s.count*s.aliasCount>o)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return s.res}toString(e,i,r){let n=`*${this.source}`;if(e){if(fd.anchorIsValid(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let o=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(o)}if(e.implicitKey)return`${n} `}return n}};function Wi(t,e,i){if(ot.isAlias(e)){let r=e.resolve(t),n=i&&r&&i.get(r);return n?n.count*n.aliasCount:0}else if(ot.isCollection(e)){let r=0;for(let n of e.items){let o=Wi(t,n,i);o>r&&(r=o)}return r}else if(ot.isPair(e)){let r=Wi(t,e.key,i),n=Wi(t,e.value,i);return Math.max(r,n)}return 1}ds.Alias=_n});var O=v(An=>{"use strict";var pd=C(),gd=Fi(),wd=Ne(),vd=t=>!t||typeof t!="function"&&typeof t!="object",ke=class extends gd.NodeBase{constructor(e){super(pd.SCALAR),this.value=e}toJSON(e,i){return i?.keep?this.value:wd.toJS(this.value,e,i)}toString(){return String(this.value)}};ke.BLOCK_FOLDED="BLOCK_FOLDED";ke.BLOCK_LITERAL="BLOCK_LITERAL";ke.PLAIN="PLAIN";ke.QUOTE_DOUBLE="QUOTE_DOUBLE";ke.QUOTE_SINGLE="QUOTE_SINGLE";An.Scalar=ke;An.isScalarValue=vd});var It=v(ms=>{"use strict";var yd=Ot(),Le=C(),hs=O(),bd="tag:yaml.org,2002:";function Nd(t,e,i){if(e){let r=i.filter(o=>o.tag===e),n=r.find(o=>!o.format)??r[0];if(!n)throw new Error(`Tag ${e} not found`);return n}return i.find(r=>r.identify?.(t)&&!r.format)}function kd(t,e,i){if(Le.isDocument(t)&&(t=t.contents),Le.isNode(t))return t;if(Le.isPair(t)){let u=i.schema[Le.MAP].createNode?.(i.schema,null,i);return u.items.push(t),u}(t instanceof String||t instanceof Number||t instanceof Boolean||typeof BigInt<"u"&&t instanceof BigInt)&&(t=t.valueOf());let{aliasDuplicateObjects:r,onAnchor:n,onTagObj:o,schema:a,sourceObjects:s}=i,c;if(r&&t&&typeof t=="object"){if(c=s.get(t),c)return c.anchor??(c.anchor=n(t)),new yd.Alias(c.anchor);c={anchor:null,node:null},s.set(t,c)}e?.startsWith("!!")&&(e=bd+e.slice(2));let l=Nd(t,e,a.tags);if(!l){if(t&&typeof t.toJSON=="function"&&(t=t.toJSON()),!t||typeof t!="object"){let u=new hs.Scalar(t);return c&&(c.node=u),u}l=t instanceof Map?a[Le.MAP]:Symbol.iterator in Object(t)?a[Le.SEQ]:a[Le.MAP]}o&&(o(l),delete i.onTagObj);let f=l?.createNode?l.createNode(i.schema,t,i):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(i.schema,t,i):new hs.Scalar(t);return e?f.tag=e:l.default||(f.tag=l.tag),c&&(c.node=f),f}ms.createNode=kd});var Hi=v(qi=>{"use strict";var Sd=It(),ce=C(),Ed=Fi();function Tn(t,e,i){let r=i;for(let n=e.length-1;n>=0;--n){let o=e[n];if(typeof o=="number"&&Number.isInteger(o)&&o>=0){let a=[];a[o]=r,r=a}else r=new Map([[o,r]])}return Sd.createNode(r,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:t,sourceObjects:new Map})}var ps=t=>t==null||typeof t=="object"&&!!t[Symbol.iterator]().next().done,On=class extends Ed.NodeBase{constructor(e,i){super(e),Object.defineProperty(this,"schema",{value:i,configurable:!0,enumerable:!1,writable:!0})}clone(e){let i=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(i.schema=e),i.items=i.items.map(r=>ce.isNode(r)||ce.isPair(r)?r.clone(e):r),this.range&&(i.range=this.range.slice()),i}addIn(e,i){if(ps(e))this.add(i);else{let[r,...n]=e,o=this.get(r,!0);if(ce.isCollection(o))o.addIn(n,i);else if(o===void 0&&this.schema)this.set(r,Tn(this.schema,n,i));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}}deleteIn(e){let[i,...r]=e;if(r.length===0)return this.delete(i);let n=this.get(i,!0);if(ce.isCollection(n))return n.deleteIn(r);throw new Error(`Expected YAML collection at ${i}. Remaining path: ${r}`)}getIn(e,i){let[r,...n]=e,o=this.get(r,!0);return n.length===0?!i&&ce.isScalar(o)?o.value:o:ce.isCollection(o)?o.getIn(n,i):void 0}hasAllNullValues(e){return this.items.every(i=>{if(!ce.isPair(i))return!1;let r=i.value;return r==null||e&&ce.isScalar(r)&&r.value==null&&!r.commentBefore&&!r.comment&&!r.tag})}hasIn(e){let[i,...r]=e;if(r.length===0)return this.has(i);let n=this.get(i,!0);return ce.isCollection(n)?n.hasIn(r):!1}setIn(e,i){let[r,...n]=e;if(n.length===0)this.set(r,i);else{let o=this.get(r,!0);if(ce.isCollection(o))o.setIn(n,i);else if(o===void 0&&this.schema)this.set(r,Tn(this.schema,n,i));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}}};qi.Collection=On;qi.collectionFromPath=Tn;qi.isEmptyPath=ps});var jt=v(Gi=>{"use strict";var Cd=t=>t.replace(/^(?!$)(?: $)?/gm,"#");function In(t,e){return/^\n+$/.test(t)?t.substring(1):e?t.replace(/^(?! *$)/gm,e):t}var Pd=(t,e,i)=>t.endsWith(` `)?In(i,e):i.includes(` `)?` -`+In(i,e):(t.endsWith(" ")?"":" ")+i;Gi.indentComment=In;Gi.lineComment=Cd;Gi.stringifyComment=Ed});var ws=v(Lt=>{"use strict";var Pd="flow",jn="block",zi="quoted";function xd(t,e,i="flow",{indentAtStart:r,lineWidth:n=80,minContentWidth:o=20,onFold:a,onOverflow:s}={}){if(!n||n<0)return t;nn-Math.max(2,o)?l.push(0):u=n-r);let d,m,w=!1,h=-1,p=-1,y=-1;i===jn&&(h=gs(t,h,e.length),h!==-1&&(u=h+c));for(let k;k=t[h+=1];){if(i===zi&&k==="\\"){switch(p=h,t[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}y=h}if(k===` +`+In(i,e):(t.endsWith(" ")?"":" ")+i;Gi.indentComment=In;Gi.lineComment=Pd;Gi.stringifyComment=Cd});var ws=v(Lt=>{"use strict";var xd="flow",jn="block",zi="quoted";function Rd(t,e,i="flow",{indentAtStart:r,lineWidth:n=80,minContentWidth:o=20,onFold:a,onOverflow:s}={}){if(!n||n<0)return t;nn-Math.max(2,o)?l.push(0):u=n-r);let d,m,w=!1,h=-1,p=-1,y=-1;i===jn&&(h=gs(t,h,e.length),h!==-1&&(u=h+c));for(let k;k=t[h+=1];){if(i===zi&&k==="\\"){switch(p=h,t[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}y=h}if(k===` `)i===jn&&(h=gs(t,h,e.length)),u=h+e.length+c,d=void 0;else{if(k===" "&&m&&m!==" "&&m!==` `&&m!==" "){let S=t[h+1];S&&S!==" "&&S!==` `&&S!==" "&&(d=h)}if(h>=u)if(d)l.push(d),u=d+c,d=void 0;else if(i===zi){for(;m===" "||m===" ";)m=k,k=t[h+=1],w=!0;let S=h>y+1?h-2:p-1;if(f[S])return t;l.push(S),f[S]=!0,u=S+c,d=void 0}else w=!0}m=k}if(w&&s&&s(),l.length===0)return t;a&&a();let b=t.slice(0,l[0]);for(let k=0;k{"use strict";var Z=O(),Se=ws(),Ki=(t,e)=>({indentAtStart:e?t.indent.length:t.indentAtStart,lineWidth:t.options.lineWidth,minContentWidth:t.options.minContentWidth}),Ji=t=>/^(%|---|\.\.\.)/m.test(t);function Rd(t,e,i){if(!e||e<0)return!1;let r=e-i,n=t.length;if(n<=r)return!1;for(let o=0,a=0;o{"use strict";var Z=O(),Se=ws(),Ki=(t,e)=>({indentAtStart:e?t.indent.length:t.indentAtStart,lineWidth:t.options.lineWidth,minContentWidth:t.options.minContentWidth}),Ji=t=>/^(%|---|\.\.\.)/m.test(t);function _d(t,e,i){if(!e||e<0)return!1;let r=e-i,n=t.length;if(n<=r)return!1;for(let o=0,a=0;or)return!0;if(a=o+1,n-a<=r)return!1}return!0}function $t(t,e){let i=JSON.stringify(t);if(e.options.doubleQuotedAsJSON)return i;let{implicitKey:r}=e,n=e.options.doubleQuotedMinMultiLineLength,o=e.indent||(Ji(t)?" ":""),a="",s=0;for(let c=0,l=i[c];l;l=i[++c])if(l===" "&&i[c+1]==="\\"&&i[c+2]==="n"&&(a+=i.slice(s,c)+"\\ ",c+=1,s=c,l="\\"),l==="\\")switch(i[c+1]){case"u":{a+=i.slice(s,c);let f=i.substr(c+2,4);switch(f){case"0000":a+="\\0";break;case"0007":a+="\\a";break;case"000b":a+="\\v";break;case"001b":a+="\\e";break;case"0085":a+="\\N";break;case"00a0":a+="\\_";break;case"2028":a+="\\L";break;case"2029":a+="\\P";break;default:f.substr(0,2)==="00"?a+="\\x"+f.substr(2):a+=i.substr(c,6)}c+=5,s=c+1}break;case"n":if(r||i[c+2]==='"'||i.length `;let u,d;for(d=i.length;d>0;--d){let E=i[d-1];if(E!==` `&&E!==" "&&E!==" ")break}let m=i.substring(d),w=m.indexOf(` @@ -29,12 +29,12 @@ ${i}`)+"'";return e.implicitKey?r:Se.foldFlowLines(r,i,Se.FOLD_FLOW,Ki(e,!1))}fu `)y=p;else break}let b=i.substring(0,y{g=!0});let N=Se.foldFlowLines(`${b}${E}${m}`,l,Se.FOLD_BLOCK,P);if(!g)return`>${S} ${l}${N}`}return i=i.replace(/\n+/g,`$&${l}`),`|${S} -${l}${b}${i}${m}`}function _d(t,e,i,r){let{type:n,value:o}=t,{actualString:a,implicitKey:s,indent:c,indentStep:l,inFlow:f}=e;if(s&&o.includes(` +${l}${b}${i}${m}`}function Ad(t,e,i,r){let{type:n,value:o}=t,{actualString:a,implicitKey:s,indent:c,indentStep:l,inFlow:f}=e;if(s&&o.includes(` `)||f&&/[[\]{},]/.test(o))return at(o,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(o))return s||f||!o.includes(` `)?at(o,e):Vi(t,e,i,r);if(!s&&!f&&n!==Z.Scalar.PLAIN&&o.includes(` `))return Vi(t,e,i,r);if(Ji(o)){if(c==="")return e.forceBlockIndent=!0,Vi(t,e,i,r);if(s&&c===l)return at(o,e)}let u=o.replace(/\n+/g,`$& -${c}`);if(a){let d=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(u),{compat:m,tags:w}=e.doc.schema;if(w.some(d)||m?.some(d))return at(o,e)}return s?u:Se.foldFlowLines(u,c,Se.FOLD_FLOW,Ki(e,!1))}function Ad(t,e,i,r){let{implicitKey:n,inFlow:o}=e,a=typeof t.value=="string"?t:Object.assign({},t,{value:String(t.value)}),{type:s}=t;s!==Z.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(a.value)&&(s=Z.Scalar.QUOTE_DOUBLE);let c=f=>{switch(f){case Z.Scalar.BLOCK_FOLDED:case Z.Scalar.BLOCK_LITERAL:return n||o?at(a.value,e):Vi(a,e,i,r);case Z.Scalar.QUOTE_DOUBLE:return $t(a.value,e);case Z.Scalar.QUOTE_SINGLE:return Ln(a.value,e);case Z.Scalar.PLAIN:return _d(a,e,i,r);default:return null}},l=c(s);if(l===null){let{defaultKeyType:f,defaultStringType:u}=e.options,d=n&&f||u;if(l=c(d),l===null)throw new Error(`Unsupported default string type ${d}`)}return l}vs.stringifyString=Ad});var Bt=v(Dn=>{"use strict";var Td=Mi(),Ee=C(),Od=jt(),Id=Dt();function jd(t,e){let i=Object.assign({blockQuote:!0,commentString:Od.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},t.schema.toStringOptions,e),r;switch(i.collectionStyle){case"block":r=!1;break;case"flow":r=!0;break;default:r=null}return{anchors:new Set,doc:t,flowCollectionPadding:i.flowCollectionPadding?" ":"",indent:"",indentStep:typeof i.indent=="number"?" ".repeat(i.indent):" ",inFlow:r,options:i}}function Ld(t,e){if(e.tag){let n=t.filter(o=>o.tag===e.tag);if(n.length>0)return n.find(o=>o.format===e.format)??n[0]}let i,r;if(Ee.isScalar(e)){r=e.value;let n=t.filter(o=>o.identify?.(r));if(n.length>1){let o=n.filter(a=>a.test);o.length>0&&(n=o)}i=n.find(o=>o.format===e.format)??n.find(o=>!o.format)}else r=e,i=t.find(n=>n.nodeClass&&r instanceof n.nodeClass);if(!i){let n=r?.constructor?.name??(r===null?"null":typeof r);throw new Error(`Tag not resolved for ${n} value`)}return i}function $d(t,e,{anchors:i,doc:r}){if(!r.directives)return"";let n=[],o=(Ee.isScalar(t)||Ee.isCollection(t))&&t.anchor;o&&Td.anchorIsValid(o)&&(i.add(o),n.push(`&${o}`));let a=t.tag??(e.default?null:e.tag);return a&&n.push(r.directives.tagString(a)),n.join(" ")}function Dd(t,e,i,r){if(Ee.isPair(t))return t.toString(e,i,r);if(Ee.isAlias(t)){if(e.doc.directives)return t.toString(e);if(e.resolvedAliases?.has(t))throw new TypeError("Cannot stringify circular structure without alias nodes");e.resolvedAliases?e.resolvedAliases.add(t):e.resolvedAliases=new Set([t]),t=t.resolve(e.doc)}let n,o=Ee.isNode(t)?t:e.doc.createNode(t,{onTagObj:c=>n=c});n??(n=Ld(e.doc.schema.tags,o));let a=$d(o,n,e);a.length>0&&(e.indentAtStart=(e.indentAtStart??0)+a.length+1);let s=typeof n.stringify=="function"?n.stringify(o,e,i,r):Ee.isScalar(o)?Id.stringifyString(o,e,i,r):o.toString(e,i,r);return a?Ee.isScalar(o)||s[0]==="{"||s[0]==="["?`${a} ${s}`:`${a} -${e.indent}${s}`:s}Dn.createStringifyContext=jd;Dn.stringify=Dd});var ks=v(Ns=>{"use strict";var me=C(),ys=O(),bs=Bt(),Mt=jt();function Bd({key:t,value:e},i,r,n){let{allNullValues:o,doc:a,indent:s,indentStep:c,options:{commentString:l,indentSeq:f,simpleKeys:u}}=i,d=me.isNode(t)&&t.comment||null;if(u){if(d)throw new Error("With simple keys, key nodes cannot have comments");if(me.isCollection(t)||!me.isNode(t)&&typeof t=="object"){let P="With simple keys, collection cannot be used as a key value";throw new Error(P)}}let m=!u&&(!t||d&&e==null&&!i.inFlow||me.isCollection(t)||(me.isScalar(t)?t.type===ys.Scalar.BLOCK_FOLDED||t.type===ys.Scalar.BLOCK_LITERAL:typeof t=="object"));i=Object.assign({},i,{allNullValues:!1,implicitKey:!m&&(u||!o),indent:s+c});let w=!1,h=!1,p=bs.stringify(t,i,()=>w=!0,()=>h=!0);if(!m&&!i.inFlow&&p.length>1024){if(u)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");m=!0}if(i.inFlow){if(o||e==null)return w&&r&&r(),p===""?"?":m?`? ${p}`:p}else if(o&&!u||e==null&&m)return p=`? ${p}`,d&&!w?p+=Mt.lineComment(p,i.indent,l(d)):h&&n&&n(),p;w&&(d=null),m?(d&&(p+=Mt.lineComment(p,i.indent,l(d))),p=`? ${p} +${c}`);if(a){let d=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(u),{compat:m,tags:w}=e.doc.schema;if(w.some(d)||m?.some(d))return at(o,e)}return s?u:Se.foldFlowLines(u,c,Se.FOLD_FLOW,Ki(e,!1))}function Td(t,e,i,r){let{implicitKey:n,inFlow:o}=e,a=typeof t.value=="string"?t:Object.assign({},t,{value:String(t.value)}),{type:s}=t;s!==Z.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(a.value)&&(s=Z.Scalar.QUOTE_DOUBLE);let c=f=>{switch(f){case Z.Scalar.BLOCK_FOLDED:case Z.Scalar.BLOCK_LITERAL:return n||o?at(a.value,e):Vi(a,e,i,r);case Z.Scalar.QUOTE_DOUBLE:return $t(a.value,e);case Z.Scalar.QUOTE_SINGLE:return Ln(a.value,e);case Z.Scalar.PLAIN:return Ad(a,e,i,r);default:return null}},l=c(s);if(l===null){let{defaultKeyType:f,defaultStringType:u}=e.options,d=n&&f||u;if(l=c(d),l===null)throw new Error(`Unsupported default string type ${d}`)}return l}vs.stringifyString=Td});var Bt=v(Dn=>{"use strict";var Od=Mi(),Ee=C(),Id=jt(),jd=Dt();function Ld(t,e){let i=Object.assign({blockQuote:!0,commentString:Id.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},t.schema.toStringOptions,e),r;switch(i.collectionStyle){case"block":r=!1;break;case"flow":r=!0;break;default:r=null}return{anchors:new Set,doc:t,flowCollectionPadding:i.flowCollectionPadding?" ":"",indent:"",indentStep:typeof i.indent=="number"?" ".repeat(i.indent):" ",inFlow:r,options:i}}function $d(t,e){if(e.tag){let n=t.filter(o=>o.tag===e.tag);if(n.length>0)return n.find(o=>o.format===e.format)??n[0]}let i,r;if(Ee.isScalar(e)){r=e.value;let n=t.filter(o=>o.identify?.(r));if(n.length>1){let o=n.filter(a=>a.test);o.length>0&&(n=o)}i=n.find(o=>o.format===e.format)??n.find(o=>!o.format)}else r=e,i=t.find(n=>n.nodeClass&&r instanceof n.nodeClass);if(!i){let n=r?.constructor?.name??(r===null?"null":typeof r);throw new Error(`Tag not resolved for ${n} value`)}return i}function Dd(t,e,{anchors:i,doc:r}){if(!r.directives)return"";let n=[],o=(Ee.isScalar(t)||Ee.isCollection(t))&&t.anchor;o&&Od.anchorIsValid(o)&&(i.add(o),n.push(`&${o}`));let a=t.tag??(e.default?null:e.tag);return a&&n.push(r.directives.tagString(a)),n.join(" ")}function Bd(t,e,i,r){if(Ee.isPair(t))return t.toString(e,i,r);if(Ee.isAlias(t)){if(e.doc.directives)return t.toString(e);if(e.resolvedAliases?.has(t))throw new TypeError("Cannot stringify circular structure without alias nodes");e.resolvedAliases?e.resolvedAliases.add(t):e.resolvedAliases=new Set([t]),t=t.resolve(e.doc)}let n,o=Ee.isNode(t)?t:e.doc.createNode(t,{onTagObj:c=>n=c});n??(n=$d(e.doc.schema.tags,o));let a=Dd(o,n,e);a.length>0&&(e.indentAtStart=(e.indentAtStart??0)+a.length+1);let s=typeof n.stringify=="function"?n.stringify(o,e,i,r):Ee.isScalar(o)?jd.stringifyString(o,e,i,r):o.toString(e,i,r);return a?Ee.isScalar(o)||s[0]==="{"||s[0]==="["?`${a} ${s}`:`${a} +${e.indent}${s}`:s}Dn.createStringifyContext=Ld;Dn.stringify=Bd});var ks=v(Ns=>{"use strict";var me=C(),ys=O(),bs=Bt(),Mt=jt();function Md({key:t,value:e},i,r,n){let{allNullValues:o,doc:a,indent:s,indentStep:c,options:{commentString:l,indentSeq:f,simpleKeys:u}}=i,d=me.isNode(t)&&t.comment||null;if(u){if(d)throw new Error("With simple keys, key nodes cannot have comments");if(me.isCollection(t)||!me.isNode(t)&&typeof t=="object"){let P="With simple keys, collection cannot be used as a key value";throw new Error(P)}}let m=!u&&(!t||d&&e==null&&!i.inFlow||me.isCollection(t)||(me.isScalar(t)?t.type===ys.Scalar.BLOCK_FOLDED||t.type===ys.Scalar.BLOCK_LITERAL:typeof t=="object"));i=Object.assign({},i,{allNullValues:!1,implicitKey:!m&&(u||!o),indent:s+c});let w=!1,h=!1,p=bs.stringify(t,i,()=>w=!0,()=>h=!0);if(!m&&!i.inFlow&&p.length>1024){if(u)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");m=!0}if(i.inFlow){if(o||e==null)return w&&r&&r(),p===""?"?":m?`? ${p}`:p}else if(o&&!u||e==null&&m)return p=`? ${p}`,d&&!w?p+=Mt.lineComment(p,i.indent,l(d)):h&&n&&n(),p;w&&(d=null),m?(d&&(p+=Mt.lineComment(p,i.indent,l(d))),p=`? ${p} ${s}:`):(p=`${p}:`,d&&(p+=Mt.lineComment(p,i.indent,l(d))));let y,b,k;me.isNode(e)?(y=!!e.spaceBefore,b=e.commentBefore,k=e.comment):(y=!1,b=null,k=null,e&&typeof e=="object"&&(e=a.createNode(e))),i.implicitKey=!1,!m&&!d&&me.isScalar(e)&&(i.indentAtStart=p.length+1),h=!1,!f&&c.length>=2&&!i.inFlow&&!m&&me.isSeq(e)&&!e.flow&&!e.tag&&!e.anchor&&(i.indent=i.indent.substring(2));let S=!1,E=bs.stringify(e,i,()=>S=!0,()=>h=!0),g=" ";if(d||y||b){if(g=y?` `:"",b){let P=l(b);g+=` ${Mt.indentComment(P,i.indent)}`}E===""&&!i.inFlow?g===` @@ -42,34 +42,34 @@ ${Mt.indentComment(P,i.indent)}`}E===""&&!i.inFlow?g===` `):g+=` ${i.indent}`}else if(!m&&me.isCollection(e)){let P=E[0],N=E.indexOf(` -`),_=N!==-1,G=i.inFlow??e.flow??e.items.length===0;if(_||!G){let it=!1;if(_&&(P==="&"||P==="!")){let j=E.indexOf(" ");P==="&"&&j!==-1&&j{"use strict";var Ss=ji("process");function Md(t,...e){t==="debug"&&console.log(...e)}function Fd(t,e){(t==="debug"||t==="warn")&&(typeof Ss.emitWarning=="function"?Ss.emitWarning(e):console.warn(e))}Bn.debug=Md;Bn.warn=Fd});var Zi=v(Qi=>{"use strict";var Xi=C(),Es=O(),Ui="<<",Yi={identify:t=>t===Ui||typeof t=="symbol"&&t.description===Ui,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new Es.Scalar(Symbol(Ui)),{addToJSMap:Cs}),stringify:()=>Ui},Wd=(t,e)=>(Yi.identify(e)||Xi.isScalar(e)&&(!e.type||e.type===Es.Scalar.PLAIN)&&Yi.identify(e.value))&&t?.doc.schema.tags.some(i=>i.tag===Yi.tag&&i.default);function Cs(t,e,i){let r=Ps(t,i);if(Xi.isSeq(r))for(let n of r.items)Fn(t,e,n);else if(Array.isArray(r))for(let n of r)Fn(t,e,n);else Fn(t,e,r)}function Fn(t,e,i){let r=Ps(t,i);if(!Xi.isMap(r))throw new Error("Merge sources must be maps or map aliases");let n=r.toJSON(null,t,Map);for(let[o,a]of n)e instanceof Map?e.has(o)||e.set(o,a):e instanceof Set?e.add(o):Object.prototype.hasOwnProperty.call(e,o)||Object.defineProperty(e,o,{value:a,writable:!0,enumerable:!0,configurable:!0});return e}function Ps(t,e){return t&&Xi.isAlias(e)?e.resolve(t.doc,t):e}Qi.addMergeToJSMap=Cs;Qi.isMergeKey=Wd;Qi.merge=Yi});var qn=v(_s=>{"use strict";var qd=Mn(),xs=Zi(),Hd=Bt(),Rs=C(),Wn=Ne();function Gd(t,e,{key:i,value:r}){if(Rs.isNode(i)&&i.addToJSMap)i.addToJSMap(t,e,r);else if(xs.isMergeKey(t,i))xs.addMergeToJSMap(t,e,r);else{let n=Wn.toJS(i,"",t);if(e instanceof Map)e.set(n,Wn.toJS(r,n,t));else if(e instanceof Set)e.add(n);else{let o=zd(i,n,t),a=Wn.toJS(r,o,t);o in e?Object.defineProperty(e,o,{value:a,writable:!0,enumerable:!0,configurable:!0}):e[o]=a}}return e}function zd(t,e,i){if(e===null)return"";if(typeof e!="object")return String(e);if(Rs.isNode(t)&&i?.doc){let r=Hd.createStringifyContext(i.doc,{});r.anchors=new Set;for(let o of i.anchors.keys())r.anchors.add(o.anchor);r.inFlow=!0,r.inStringifyKey=!0;let n=t.toString(r);if(!i.mapKeyWarned){let o=JSON.stringify(n);o.length>40&&(o=o.substring(0,36)+'..."'),qd.warn(i.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${o}. Set mapAsMap: true to use object keys.`),i.mapKeyWarned=!0}return n}return JSON.stringify(e)}_s.addPairToJSMap=Gd});var Ce=v(Hn=>{"use strict";var As=It(),Vd=ks(),Kd=qn(),er=C();function Jd(t,e,i){let r=As.createNode(t,void 0,i),n=As.createNode(e,void 0,i);return new tr(r,n)}var tr=class t{constructor(e,i=null){Object.defineProperty(this,er.NODE_TYPE,{value:er.PAIR}),this.key=e,this.value=i}clone(e){let{key:i,value:r}=this;return er.isNode(i)&&(i=i.clone(e)),er.isNode(r)&&(r=r.clone(e)),new t(i,r)}toJSON(e,i){let r=i?.mapAsMap?new Map:{};return Kd.addPairToJSMap(i,r,this)}toString(e,i,r){return e?.doc?Vd.stringifyPair(this,e,i,r):JSON.stringify(this)}};Hn.Pair=tr;Hn.createPair=Jd});var Gn=v(Os=>{"use strict";var $e=C(),Ts=Bt(),ir=jt();function Ud(t,e,i){return(e.inFlow??t.flow?Xd:Yd)(t,e,i)}function Yd({comment:t,items:e},i,{blockItemPrefix:r,flowChars:n,itemIndent:o,onChompKeep:a,onComment:s}){let{indent:c,options:{commentString:l}}=i,f=Object.assign({},i,{indent:o,type:null}),u=!1,d=[];for(let w=0;wp=null,()=>u=!0);p&&(y+=ir.lineComment(y,o,l(p))),u&&p&&(u=!1),d.push(r+y)}let m;if(d.length===0)m=n.start+n.end;else{m=d[0];for(let w=1;w{"use strict";var Ss=ji("process");function Fd(t,...e){t==="debug"&&console.log(...e)}function Wd(t,e){(t==="debug"||t==="warn")&&(typeof Ss.emitWarning=="function"?Ss.emitWarning(e):console.warn(e))}Bn.debug=Fd;Bn.warn=Wd});var Zi=v(Qi=>{"use strict";var Xi=C(),Es=O(),Ui="<<",Yi={identify:t=>t===Ui||typeof t=="symbol"&&t.description===Ui,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new Es.Scalar(Symbol(Ui)),{addToJSMap:Cs}),stringify:()=>Ui},qd=(t,e)=>(Yi.identify(e)||Xi.isScalar(e)&&(!e.type||e.type===Es.Scalar.PLAIN)&&Yi.identify(e.value))&&t?.doc.schema.tags.some(i=>i.tag===Yi.tag&&i.default);function Cs(t,e,i){let r=Ps(t,i);if(Xi.isSeq(r))for(let n of r.items)Fn(t,e,n);else if(Array.isArray(r))for(let n of r)Fn(t,e,n);else Fn(t,e,r)}function Fn(t,e,i){let r=Ps(t,i);if(!Xi.isMap(r))throw new Error("Merge sources must be maps or map aliases");let n=r.toJSON(null,t,Map);for(let[o,a]of n)e instanceof Map?e.has(o)||e.set(o,a):e instanceof Set?e.add(o):Object.prototype.hasOwnProperty.call(e,o)||Object.defineProperty(e,o,{value:a,writable:!0,enumerable:!0,configurable:!0});return e}function Ps(t,e){return t&&Xi.isAlias(e)?e.resolve(t.doc,t):e}Qi.addMergeToJSMap=Cs;Qi.isMergeKey=qd;Qi.merge=Yi});var qn=v(_s=>{"use strict";var Hd=Mn(),xs=Zi(),Gd=Bt(),Rs=C(),Wn=Ne();function zd(t,e,{key:i,value:r}){if(Rs.isNode(i)&&i.addToJSMap)i.addToJSMap(t,e,r);else if(xs.isMergeKey(t,i))xs.addMergeToJSMap(t,e,r);else{let n=Wn.toJS(i,"",t);if(e instanceof Map)e.set(n,Wn.toJS(r,n,t));else if(e instanceof Set)e.add(n);else{let o=Vd(i,n,t),a=Wn.toJS(r,o,t);o in e?Object.defineProperty(e,o,{value:a,writable:!0,enumerable:!0,configurable:!0}):e[o]=a}}return e}function Vd(t,e,i){if(e===null)return"";if(typeof e!="object")return String(e);if(Rs.isNode(t)&&i?.doc){let r=Gd.createStringifyContext(i.doc,{});r.anchors=new Set;for(let o of i.anchors.keys())r.anchors.add(o.anchor);r.inFlow=!0,r.inStringifyKey=!0;let n=t.toString(r);if(!i.mapKeyWarned){let o=JSON.stringify(n);o.length>40&&(o=o.substring(0,36)+'..."'),Hd.warn(i.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${o}. Set mapAsMap: true to use object keys.`),i.mapKeyWarned=!0}return n}return JSON.stringify(e)}_s.addPairToJSMap=zd});var Ce=v(Hn=>{"use strict";var As=It(),Kd=ks(),Jd=qn(),er=C();function Ud(t,e,i){let r=As.createNode(t,void 0,i),n=As.createNode(e,void 0,i);return new tr(r,n)}var tr=class t{constructor(e,i=null){Object.defineProperty(this,er.NODE_TYPE,{value:er.PAIR}),this.key=e,this.value=i}clone(e){let{key:i,value:r}=this;return er.isNode(i)&&(i=i.clone(e)),er.isNode(r)&&(r=r.clone(e)),new t(i,r)}toJSON(e,i){let r=i?.mapAsMap?new Map:{};return Jd.addPairToJSMap(i,r,this)}toString(e,i,r){return e?.doc?Kd.stringifyPair(this,e,i,r):JSON.stringify(this)}};Hn.Pair=tr;Hn.createPair=Ud});var Gn=v(Os=>{"use strict";var $e=C(),Ts=Bt(),ir=jt();function Yd(t,e,i){return(e.inFlow??t.flow?Qd:Xd)(t,e,i)}function Xd({comment:t,items:e},i,{blockItemPrefix:r,flowChars:n,itemIndent:o,onChompKeep:a,onComment:s}){let{indent:c,options:{commentString:l}}=i,f=Object.assign({},i,{indent:o,type:null}),u=!1,d=[];for(let w=0;wp=null,()=>u=!0);p&&(y+=ir.lineComment(y,o,l(p))),u&&p&&(u=!1),d.push(r+y)}let m;if(d.length===0)m=n.start+n.end;else{m=d[0];for(let w=1;wp=null);l||(l=u.length>f||y.includes(` +`+ir.indentComment(l(t),c),s&&s()):u&&a&&a(),m}function Qd({items:t},e,{flowChars:i,itemIndent:r}){let{indent:n,indentStep:o,flowCollectionPadding:a,options:{commentString:s}}=e;r+=o;let c=Object.assign({},e,{indent:r,inFlow:!0,type:null}),l=!1,f=0,u=[];for(let w=0;wp=null);l||(l=u.length>f||y.includes(` `)),w0&&(l||(l=u.reduce((b,k)=>b+k.length+2,2)+(y.length+2)>e.options.lineWidth)),l&&(y+=",")),p&&(y+=ir.lineComment(y,r,s(p))),u.push(y),f=u.length}let{start:d,end:m}=i;if(u.length===0)return d+m;if(!l){let w=u.reduce((h,p)=>h+p.length+2,2);l=e.options.lineWidth>0&&w>e.options.lineWidth}if(l){let w=d;for(let h of u)w+=h?` ${o}${n}${h}`:` `;return`${w} -${n}${m}`}else return`${d}${a}${u.join(" ")}${a}${m}`}function rr({indent:t,options:{commentString:e}},i,r,n){if(r&&n&&(r=r.replace(/^\n+/,"")),r){let o=ir.indentComment(e(r),t);i.push(o.trimStart())}}Os.stringifyCollection=Ud});var xe=v(Vn=>{"use strict";var Qd=Gn(),Zd=qn(),eh=Hi(),Pe=C(),nr=Ce(),th=O();function Ft(t,e){let i=Pe.isScalar(e)?e.value:e;for(let r of t)if(Pe.isPair(r)&&(r.key===e||r.key===i||Pe.isScalar(r.key)&&r.key.value===i))return r}var zn=class extends eh.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(Pe.MAP,e),this.items=[]}static from(e,i,r){let{keepUndefined:n,replacer:o}=r,a=new this(e),s=(c,l)=>{if(typeof o=="function")l=o.call(i,c,l);else if(Array.isArray(o)&&!o.includes(c))return;(l!==void 0||n)&&a.items.push(nr.createPair(c,l,r))};if(i instanceof Map)for(let[c,l]of i)s(c,l);else if(i&&typeof i=="object")for(let c of Object.keys(i))s(c,i[c]);return typeof e.sortMapEntries=="function"&&a.items.sort(e.sortMapEntries),a}add(e,i){let r;Pe.isPair(e)?r=e:!e||typeof e!="object"||!("key"in e)?r=new nr.Pair(e,e?.value):r=new nr.Pair(e.key,e.value);let n=Ft(this.items,r.key),o=this.schema?.sortMapEntries;if(n){if(!i)throw new Error(`Key ${r.key} already set`);Pe.isScalar(n.value)&&th.isScalarValue(r.value)?n.value.value=r.value:n.value=r.value}else if(o){let a=this.items.findIndex(s=>o(r,s)<0);a===-1?this.items.push(r):this.items.splice(a,0,r)}else this.items.push(r)}delete(e){let i=Ft(this.items,e);return i?this.items.splice(this.items.indexOf(i),1).length>0:!1}get(e,i){let n=Ft(this.items,e)?.value;return(!i&&Pe.isScalar(n)?n.value:n)??void 0}has(e){return!!Ft(this.items,e)}set(e,i){this.add(new nr.Pair(e,i),!0)}toJSON(e,i,r){let n=r?new r:i?.mapAsMap?new Map:{};i?.onCreate&&i.onCreate(n);for(let o of this.items)Zd.addPairToJSMap(i,n,o);return n}toString(e,i,r){if(!e)return JSON.stringify(this);for(let n of this.items)if(!Pe.isPair(n))throw new Error(`Map items must all be pairs; found ${JSON.stringify(n)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),Qd.stringifyCollection(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:r,onComment:i})}};Vn.YAMLMap=zn;Vn.findPair=Ft});var st=v(js=>{"use strict";var ih=C(),Is=xe(),rh={collection:"map",default:!0,nodeClass:Is.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(t,e){return ih.isMap(t)||e("Expected a mapping for this tag"),t},createNode:(t,e,i)=>Is.YAMLMap.from(t,e,i)};js.map=rh});var Re=v(Ls=>{"use strict";var nh=It(),oh=Gn(),ah=Hi(),ar=C(),sh=O(),ch=Ne(),Kn=class extends ah.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(ar.SEQ,e),this.items=[]}add(e){this.items.push(e)}delete(e){let i=or(e);return typeof i!="number"?!1:this.items.splice(i,1).length>0}get(e,i){let r=or(e);if(typeof r!="number")return;let n=this.items[r];return!i&&ar.isScalar(n)?n.value:n}has(e){let i=or(e);return typeof i=="number"&&i=0?e:null}Ls.YAMLSeq=Kn});var ct=v(Ds=>{"use strict";var lh=C(),$s=Re(),uh={collection:"seq",default:!0,nodeClass:$s.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(t,e){return lh.isSeq(t)||e("Expected a sequence for this tag"),t},createNode:(t,e,i)=>$s.YAMLSeq.from(t,e,i)};Ds.seq=uh});var Wt=v(Bs=>{"use strict";var fh=Dt(),dh={identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify(t,e,i,r){return e=Object.assign({actualString:!0},e),fh.stringifyString(t,e,i,r)}};Bs.string=dh});var sr=v(Ws=>{"use strict";var Ms=O(),Fs={identify:t=>t==null,createNode:()=>new Ms.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Ms.Scalar(null),stringify:({source:t},e)=>typeof t=="string"&&Fs.test.test(t)?t:e.options.nullStr};Ws.nullTag=Fs});var Jn=v(Hs=>{"use strict";var hh=O(),qs={identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:t=>new hh.Scalar(t[0]==="t"||t[0]==="T"),stringify({source:t,value:e},i){if(t&&qs.test.test(t)){let r=t[0]==="t"||t[0]==="T";if(e===r)return t}return e?i.options.trueStr:i.options.falseStr}};Hs.boolTag=qs});var lt=v(Gs=>{"use strict";function mh({format:t,minFractionDigits:e,tag:i,value:r}){if(typeof r=="bigint")return String(r);let n=typeof r=="number"?r:Number(r);if(!isFinite(n))return isNaN(n)?".nan":n<0?"-.inf":".inf";let o=Object.is(r,-0)?"-0":JSON.stringify(r);if(!t&&e&&(!i||i==="tag:yaml.org,2002:float")&&/^-?\d/.test(o)&&!o.includes("e")){let a=o.indexOf(".");a<0&&(a=o.length,o+=".");let s=e-(o.length-a-1);for(;s-- >0;)o+="0"}return o}Gs.stringifyNumber=mh});var Yn=v(cr=>{"use strict";var ph=O(),Un=lt(),gh={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:t=>t.slice(-3).toLowerCase()==="nan"?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Un.stringifyNumber},wh={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t),stringify(t){let e=Number(t.value);return isFinite(e)?e.toExponential():Un.stringifyNumber(t)}},vh={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(t){let e=new ph.Scalar(parseFloat(t)),i=t.indexOf(".");return i!==-1&&t[t.length-1]==="0"&&(e.minFractionDigits=t.length-i-1),e},stringify:Un.stringifyNumber};cr.float=vh;cr.floatExp=wh;cr.floatNaN=gh});var Qn=v(ur=>{"use strict";var zs=lt(),lr=t=>typeof t=="bigint"||Number.isInteger(t),Xn=(t,e,i,{intAsBigInt:r})=>r?BigInt(t):parseInt(t.substring(e),i);function Vs(t,e,i){let{value:r}=t;return lr(r)&&r>=0?i+r.toString(e):zs.stringifyNumber(t)}var yh={identify:t=>lr(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(t,e,i)=>Xn(t,2,8,i),stringify:t=>Vs(t,8,"0o")},bh={identify:lr,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(t,e,i)=>Xn(t,0,10,i),stringify:zs.stringifyNumber},Nh={identify:t=>lr(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(t,e,i)=>Xn(t,2,16,i),stringify:t=>Vs(t,16,"0x")};ur.int=bh;ur.intHex=Nh;ur.intOct=yh});var Js=v(Ks=>{"use strict";var kh=st(),Sh=sr(),Eh=ct(),Ch=Wt(),Ph=Jn(),Zn=Yn(),eo=Qn(),xh=[kh.map,Eh.seq,Ch.string,Sh.nullTag,Ph.boolTag,eo.intOct,eo.int,eo.intHex,Zn.floatNaN,Zn.floatExp,Zn.float];Ks.schema=xh});var Xs=v(Ys=>{"use strict";var Rh=O(),_h=st(),Ah=ct();function Us(t){return typeof t=="bigint"||Number.isInteger(t)}var fr=({value:t})=>JSON.stringify(t),Th=[{identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify:fr},{identify:t=>t==null,createNode:()=>new Rh.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:fr},{identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:t=>t==="true",stringify:fr},{identify:Us,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(t,e,{intAsBigInt:i})=>i?BigInt(t):parseInt(t,10),stringify:({value:t})=>Us(t)?t.toString():JSON.stringify(t)},{identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:t=>parseFloat(t),stringify:fr}],Oh={default:!0,tag:"",test:/^/,resolve(t,e){return e(`Unresolved plain scalar ${JSON.stringify(t)}`),t}},Ih=[_h.map,Ah.seq].concat(Th,Oh);Ys.schema=Ih});var io=v(Qs=>{"use strict";var qt=ji("buffer"),to=O(),jh=Dt(),Lh={identify:t=>t instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(t,e){if(typeof qt.Buffer=="function")return qt.Buffer.from(t,"base64");if(typeof atob=="function"){let i=atob(t.replace(/[\n\r]/g,"")),r=new Uint8Array(i.length);for(let n=0;n{"use strict";var dr=C(),ro=Ce(),$h=O(),Dh=Re();function Zs(t,e){if(dr.isSeq(t))for(let i=0;i1&&e("Each pair must have its own sequence indicator");let n=r.items[0]||new ro.Pair(new $h.Scalar(null));if(r.commentBefore&&(n.key.commentBefore=n.key.commentBefore?`${r.commentBefore} +${n}${m}`}else return`${d}${a}${u.join(" ")}${a}${m}`}function rr({indent:t,options:{commentString:e}},i,r,n){if(r&&n&&(r=r.replace(/^\n+/,"")),r){let o=ir.indentComment(e(r),t);i.push(o.trimStart())}}Os.stringifyCollection=Yd});var xe=v(Vn=>{"use strict";var Zd=Gn(),eh=qn(),th=Hi(),Pe=C(),nr=Ce(),ih=O();function Ft(t,e){let i=Pe.isScalar(e)?e.value:e;for(let r of t)if(Pe.isPair(r)&&(r.key===e||r.key===i||Pe.isScalar(r.key)&&r.key.value===i))return r}var zn=class extends th.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(Pe.MAP,e),this.items=[]}static from(e,i,r){let{keepUndefined:n,replacer:o}=r,a=new this(e),s=(c,l)=>{if(typeof o=="function")l=o.call(i,c,l);else if(Array.isArray(o)&&!o.includes(c))return;(l!==void 0||n)&&a.items.push(nr.createPair(c,l,r))};if(i instanceof Map)for(let[c,l]of i)s(c,l);else if(i&&typeof i=="object")for(let c of Object.keys(i))s(c,i[c]);return typeof e.sortMapEntries=="function"&&a.items.sort(e.sortMapEntries),a}add(e,i){let r;Pe.isPair(e)?r=e:!e||typeof e!="object"||!("key"in e)?r=new nr.Pair(e,e?.value):r=new nr.Pair(e.key,e.value);let n=Ft(this.items,r.key),o=this.schema?.sortMapEntries;if(n){if(!i)throw new Error(`Key ${r.key} already set`);Pe.isScalar(n.value)&&ih.isScalarValue(r.value)?n.value.value=r.value:n.value=r.value}else if(o){let a=this.items.findIndex(s=>o(r,s)<0);a===-1?this.items.push(r):this.items.splice(a,0,r)}else this.items.push(r)}delete(e){let i=Ft(this.items,e);return i?this.items.splice(this.items.indexOf(i),1).length>0:!1}get(e,i){let n=Ft(this.items,e)?.value;return(!i&&Pe.isScalar(n)?n.value:n)??void 0}has(e){return!!Ft(this.items,e)}set(e,i){this.add(new nr.Pair(e,i),!0)}toJSON(e,i,r){let n=r?new r:i?.mapAsMap?new Map:{};i?.onCreate&&i.onCreate(n);for(let o of this.items)eh.addPairToJSMap(i,n,o);return n}toString(e,i,r){if(!e)return JSON.stringify(this);for(let n of this.items)if(!Pe.isPair(n))throw new Error(`Map items must all be pairs; found ${JSON.stringify(n)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),Zd.stringifyCollection(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:r,onComment:i})}};Vn.YAMLMap=zn;Vn.findPair=Ft});var st=v(js=>{"use strict";var rh=C(),Is=xe(),nh={collection:"map",default:!0,nodeClass:Is.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(t,e){return rh.isMap(t)||e("Expected a mapping for this tag"),t},createNode:(t,e,i)=>Is.YAMLMap.from(t,e,i)};js.map=nh});var Re=v(Ls=>{"use strict";var oh=It(),ah=Gn(),sh=Hi(),ar=C(),ch=O(),lh=Ne(),Kn=class extends sh.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(ar.SEQ,e),this.items=[]}add(e){this.items.push(e)}delete(e){let i=or(e);return typeof i!="number"?!1:this.items.splice(i,1).length>0}get(e,i){let r=or(e);if(typeof r!="number")return;let n=this.items[r];return!i&&ar.isScalar(n)?n.value:n}has(e){let i=or(e);return typeof i=="number"&&i=0?e:null}Ls.YAMLSeq=Kn});var ct=v(Ds=>{"use strict";var uh=C(),$s=Re(),fh={collection:"seq",default:!0,nodeClass:$s.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(t,e){return uh.isSeq(t)||e("Expected a sequence for this tag"),t},createNode:(t,e,i)=>$s.YAMLSeq.from(t,e,i)};Ds.seq=fh});var Wt=v(Bs=>{"use strict";var dh=Dt(),hh={identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify(t,e,i,r){return e=Object.assign({actualString:!0},e),dh.stringifyString(t,e,i,r)}};Bs.string=hh});var sr=v(Ws=>{"use strict";var Ms=O(),Fs={identify:t=>t==null,createNode:()=>new Ms.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Ms.Scalar(null),stringify:({source:t},e)=>typeof t=="string"&&Fs.test.test(t)?t:e.options.nullStr};Ws.nullTag=Fs});var Jn=v(Hs=>{"use strict";var mh=O(),qs={identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:t=>new mh.Scalar(t[0]==="t"||t[0]==="T"),stringify({source:t,value:e},i){if(t&&qs.test.test(t)){let r=t[0]==="t"||t[0]==="T";if(e===r)return t}return e?i.options.trueStr:i.options.falseStr}};Hs.boolTag=qs});var lt=v(Gs=>{"use strict";function ph({format:t,minFractionDigits:e,tag:i,value:r}){if(typeof r=="bigint")return String(r);let n=typeof r=="number"?r:Number(r);if(!isFinite(n))return isNaN(n)?".nan":n<0?"-.inf":".inf";let o=Object.is(r,-0)?"-0":JSON.stringify(r);if(!t&&e&&(!i||i==="tag:yaml.org,2002:float")&&/^-?\d/.test(o)&&!o.includes("e")){let a=o.indexOf(".");a<0&&(a=o.length,o+=".");let s=e-(o.length-a-1);for(;s-- >0;)o+="0"}return o}Gs.stringifyNumber=ph});var Yn=v(cr=>{"use strict";var gh=O(),Un=lt(),wh={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:t=>t.slice(-3).toLowerCase()==="nan"?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Un.stringifyNumber},vh={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t),stringify(t){let e=Number(t.value);return isFinite(e)?e.toExponential():Un.stringifyNumber(t)}},yh={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(t){let e=new gh.Scalar(parseFloat(t)),i=t.indexOf(".");return i!==-1&&t[t.length-1]==="0"&&(e.minFractionDigits=t.length-i-1),e},stringify:Un.stringifyNumber};cr.float=yh;cr.floatExp=vh;cr.floatNaN=wh});var Qn=v(ur=>{"use strict";var zs=lt(),lr=t=>typeof t=="bigint"||Number.isInteger(t),Xn=(t,e,i,{intAsBigInt:r})=>r?BigInt(t):parseInt(t.substring(e),i);function Vs(t,e,i){let{value:r}=t;return lr(r)&&r>=0?i+r.toString(e):zs.stringifyNumber(t)}var bh={identify:t=>lr(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(t,e,i)=>Xn(t,2,8,i),stringify:t=>Vs(t,8,"0o")},Nh={identify:lr,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(t,e,i)=>Xn(t,0,10,i),stringify:zs.stringifyNumber},kh={identify:t=>lr(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(t,e,i)=>Xn(t,2,16,i),stringify:t=>Vs(t,16,"0x")};ur.int=Nh;ur.intHex=kh;ur.intOct=bh});var Js=v(Ks=>{"use strict";var Sh=st(),Eh=sr(),Ch=ct(),Ph=Wt(),xh=Jn(),Zn=Yn(),eo=Qn(),Rh=[Sh.map,Ch.seq,Ph.string,Eh.nullTag,xh.boolTag,eo.intOct,eo.int,eo.intHex,Zn.floatNaN,Zn.floatExp,Zn.float];Ks.schema=Rh});var Xs=v(Ys=>{"use strict";var _h=O(),Ah=st(),Th=ct();function Us(t){return typeof t=="bigint"||Number.isInteger(t)}var fr=({value:t})=>JSON.stringify(t),Oh=[{identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify:fr},{identify:t=>t==null,createNode:()=>new _h.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:fr},{identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:t=>t==="true",stringify:fr},{identify:Us,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(t,e,{intAsBigInt:i})=>i?BigInt(t):parseInt(t,10),stringify:({value:t})=>Us(t)?t.toString():JSON.stringify(t)},{identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:t=>parseFloat(t),stringify:fr}],Ih={default:!0,tag:"",test:/^/,resolve(t,e){return e(`Unresolved plain scalar ${JSON.stringify(t)}`),t}},jh=[Ah.map,Th.seq].concat(Oh,Ih);Ys.schema=jh});var io=v(Qs=>{"use strict";var qt=ji("buffer"),to=O(),Lh=Dt(),$h={identify:t=>t instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(t,e){if(typeof qt.Buffer=="function")return qt.Buffer.from(t,"base64");if(typeof atob=="function"){let i=atob(t.replace(/[\n\r]/g,"")),r=new Uint8Array(i.length);for(let n=0;n{"use strict";var dr=C(),ro=Ce(),Dh=O(),Bh=Re();function Zs(t,e){if(dr.isSeq(t))for(let i=0;i1&&e("Each pair must have its own sequence indicator");let n=r.items[0]||new ro.Pair(new Dh.Scalar(null));if(r.commentBefore&&(n.key.commentBefore=n.key.commentBefore?`${r.commentBefore} ${n.key.commentBefore}`:r.commentBefore),r.comment){let o=n.value??n.key;o.comment=o.comment?`${r.comment} -${o.comment}`:r.comment}r=n}t.items[i]=dr.isPair(r)?r:new ro.Pair(r)}}else e("Expected a sequence for this tag");return t}function ec(t,e,i){let{replacer:r}=i,n=new Dh.YAMLSeq(t);n.tag="tag:yaml.org,2002:pairs";let o=0;if(e&&Symbol.iterator in Object(e))for(let a of e){typeof r=="function"&&(a=r.call(e,String(o++),a));let s,c;if(Array.isArray(a))if(a.length===2)s=a[0],c=a[1];else throw new TypeError(`Expected [key, value] tuple: ${a}`);else if(a&&a instanceof Object){let l=Object.keys(a);if(l.length===1)s=l[0],c=a[s];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else s=a;n.items.push(ro.createPair(s,c,i))}return n}var Bh={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Zs,createNode:ec};hr.createPairs=ec;hr.pairs=Bh;hr.resolvePairs=Zs});var ao=v(oo=>{"use strict";var tc=C(),no=Ne(),Ht=xe(),Mh=Re(),ic=mr(),De=class t extends Mh.YAMLSeq{constructor(){super(),this.add=Ht.YAMLMap.prototype.add.bind(this),this.delete=Ht.YAMLMap.prototype.delete.bind(this),this.get=Ht.YAMLMap.prototype.get.bind(this),this.has=Ht.YAMLMap.prototype.has.bind(this),this.set=Ht.YAMLMap.prototype.set.bind(this),this.tag=t.tag}toJSON(e,i){if(!i)return super.toJSON(e);let r=new Map;i?.onCreate&&i.onCreate(r);for(let n of this.items){let o,a;if(tc.isPair(n)?(o=no.toJS(n.key,"",i),a=no.toJS(n.value,o,i)):o=no.toJS(n,"",i),r.has(o))throw new Error("Ordered maps must not include duplicate keys");r.set(o,a)}return r}static from(e,i,r){let n=ic.createPairs(e,i,r),o=new this;return o.items=n.items,o}};De.tag="tag:yaml.org,2002:omap";var Fh={collection:"seq",identify:t=>t instanceof Map,nodeClass:De,default:!1,tag:"tag:yaml.org,2002:omap",resolve(t,e){let i=ic.resolvePairs(t,e),r=[];for(let{key:n}of i.items)tc.isScalar(n)&&(r.includes(n.value)?e(`Ordered maps must not include duplicate keys: ${n.value}`):r.push(n.value));return Object.assign(new De,i)},createNode:(t,e,i)=>De.from(t,e,i)};oo.YAMLOMap=De;oo.omap=Fh});var sc=v(so=>{"use strict";var rc=O();function nc({value:t,source:e},i){return e&&(t?oc:ac).test.test(e)?e:t?i.options.trueStr:i.options.falseStr}var oc={identify:t=>t===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new rc.Scalar(!0),stringify:nc},ac={identify:t=>t===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new rc.Scalar(!1),stringify:nc};so.falseTag=ac;so.trueTag=oc});var cc=v(pr=>{"use strict";var Wh=O(),co=lt(),qh={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:t=>t.slice(-3).toLowerCase()==="nan"?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:co.stringifyNumber},Hh={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t.replace(/_/g,"")),stringify(t){let e=Number(t.value);return isFinite(e)?e.toExponential():co.stringifyNumber(t)}},Gh={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(t){let e=new Wh.Scalar(parseFloat(t.replace(/_/g,""))),i=t.indexOf(".");if(i!==-1){let r=t.substring(i+1).replace(/_/g,"");r[r.length-1]==="0"&&(e.minFractionDigits=r.length)}return e},stringify:co.stringifyNumber};pr.float=Gh;pr.floatExp=Hh;pr.floatNaN=qh});var uc=v(zt=>{"use strict";var lc=lt(),Gt=t=>typeof t=="bigint"||Number.isInteger(t);function gr(t,e,i,{intAsBigInt:r}){let n=t[0];if((n==="-"||n==="+")&&(e+=1),t=t.substring(e).replace(/_/g,""),r){switch(i){case 2:t=`0b${t}`;break;case 8:t=`0o${t}`;break;case 16:t=`0x${t}`;break}let a=BigInt(t);return n==="-"?BigInt(-1)*a:a}let o=parseInt(t,i);return n==="-"?-1*o:o}function lo(t,e,i){let{value:r}=t;if(Gt(r)){let n=r.toString(e);return r<0?"-"+i+n.substr(1):i+n}return lc.stringifyNumber(t)}var zh={identify:Gt,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(t,e,i)=>gr(t,2,2,i),stringify:t=>lo(t,2,"0b")},Vh={identify:Gt,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(t,e,i)=>gr(t,1,8,i),stringify:t=>lo(t,8,"0")},Kh={identify:Gt,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(t,e,i)=>gr(t,0,10,i),stringify:lc.stringifyNumber},Jh={identify:Gt,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(t,e,i)=>gr(t,2,16,i),stringify:t=>lo(t,16,"0x")};zt.int=Kh;zt.intBin=zh;zt.intHex=Jh;zt.intOct=Vh});var fo=v(uo=>{"use strict";var yr=C(),wr=Ce(),vr=xe(),Be=class t extends vr.YAMLMap{constructor(e){super(e),this.tag=t.tag}add(e){let i;yr.isPair(e)?i=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?i=new wr.Pair(e.key,null):i=new wr.Pair(e,null),vr.findPair(this.items,i.key)||this.items.push(i)}get(e,i){let r=vr.findPair(this.items,e);return!i&&yr.isPair(r)?yr.isScalar(r.key)?r.key.value:r.key:r}set(e,i){if(typeof i!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof i}`);let r=vr.findPair(this.items,e);r&&!i?this.items.splice(this.items.indexOf(r),1):!r&&i&&this.items.push(new wr.Pair(e))}toJSON(e,i){return super.toJSON(e,i,Set)}toString(e,i,r){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),i,r);throw new Error("Set items must all have null values")}static from(e,i,r){let{replacer:n}=r,o=new this(e);if(i&&Symbol.iterator in Object(i))for(let a of i)typeof n=="function"&&(a=n.call(i,a,a)),o.items.push(wr.createPair(a,null,r));return o}};Be.tag="tag:yaml.org,2002:set";var Uh={collection:"map",identify:t=>t instanceof Set,nodeClass:Be,default:!1,tag:"tag:yaml.org,2002:set",createNode:(t,e,i)=>Be.from(t,e,i),resolve(t,e){if(yr.isMap(t)){if(t.hasAllNullValues(!0))return Object.assign(new Be,t);e("Set items must all have null values")}else e("Expected a mapping for this tag");return t}};uo.YAMLSet=Be;uo.set=Uh});var mo=v(br=>{"use strict";var Yh=lt();function ho(t,e){let i=t[0],r=i==="-"||i==="+"?t.substring(1):t,n=a=>e?BigInt(a):Number(a),o=r.replace(/_/g,"").split(":").reduce((a,s)=>a*n(60)+n(s),n(0));return i==="-"?n(-1)*o:o}function fc(t){let{value:e}=t,i=a=>a;if(typeof e=="bigint")i=a=>BigInt(a);else if(isNaN(e)||!isFinite(e))return Yh.stringifyNumber(t);let r="";e<0&&(r="-",e*=i(-1));let n=i(60),o=[e%n];return e<60?o.unshift(0):(e=(e-o[0])/n,o.unshift(e%n),e>=60&&(e=(e-o[0])/n,o.unshift(e))),r+o.map(a=>String(a).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var Xh={identify:t=>typeof t=="bigint"||Number.isInteger(t),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(t,e,{intAsBigInt:i})=>ho(t,i),stringify:fc},Qh={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:t=>ho(t,!1),stringify:fc},dc={identify:t=>t instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(t){let e=t.match(dc.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,i,r,n,o,a,s]=e.map(Number),c=e[7]?Number((e[7]+"00").substr(1,3)):0,l=Date.UTC(i,r-1,n,o||0,a||0,s||0,c),f=e[8];if(f&&f!=="Z"){let u=ho(f,!1);Math.abs(u)<30&&(u*=60),l-=6e4*u}return new Date(l)},stringify:({value:t})=>t?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};br.floatTime=Qh;br.intTime=Xh;br.timestamp=dc});var pc=v(mc=>{"use strict";var Zh=st(),em=sr(),tm=ct(),im=Wt(),rm=io(),hc=sc(),po=cc(),Nr=uc(),nm=Zi(),om=ao(),am=mr(),sm=fo(),go=mo(),cm=[Zh.map,tm.seq,im.string,em.nullTag,hc.trueTag,hc.falseTag,Nr.intBin,Nr.intOct,Nr.int,Nr.intHex,po.floatNaN,po.floatExp,po.float,rm.binary,nm.merge,om.omap,am.pairs,sm.set,go.intTime,go.floatTime,go.timestamp];mc.schema=cm});var Cc=v(yo=>{"use strict";var yc=st(),lm=sr(),bc=ct(),um=Wt(),fm=Jn(),wo=Yn(),vo=Qn(),dm=Js(),hm=Xs(),Nc=io(),Vt=Zi(),kc=ao(),Sc=mr(),gc=pc(),Ec=fo(),kr=mo(),wc=new Map([["core",dm.schema],["failsafe",[yc.map,bc.seq,um.string]],["json",hm.schema],["yaml11",gc.schema],["yaml-1.1",gc.schema]]),vc={binary:Nc.binary,bool:fm.boolTag,float:wo.float,floatExp:wo.floatExp,floatNaN:wo.floatNaN,floatTime:kr.floatTime,int:vo.int,intHex:vo.intHex,intOct:vo.intOct,intTime:kr.intTime,map:yc.map,merge:Vt.merge,null:lm.nullTag,omap:kc.omap,pairs:Sc.pairs,seq:bc.seq,set:Ec.set,timestamp:kr.timestamp},mm={"tag:yaml.org,2002:binary":Nc.binary,"tag:yaml.org,2002:merge":Vt.merge,"tag:yaml.org,2002:omap":kc.omap,"tag:yaml.org,2002:pairs":Sc.pairs,"tag:yaml.org,2002:set":Ec.set,"tag:yaml.org,2002:timestamp":kr.timestamp};function pm(t,e,i){let r=wc.get(e);if(r&&!t)return i&&!r.includes(Vt.merge)?r.concat(Vt.merge):r.slice();let n=r;if(!n)if(Array.isArray(t))n=[];else{let o=Array.from(wc.keys()).filter(a=>a!=="yaml11").map(a=>JSON.stringify(a)).join(", ");throw new Error(`Unknown schema "${e}"; use one of ${o} or define customTags array`)}if(Array.isArray(t))for(let o of t)n=n.concat(o);else typeof t=="function"&&(n=t(n.slice()));return i&&(n=n.concat(Vt.merge)),n.reduce((o,a)=>{let s=typeof a=="string"?vc[a]:a;if(!s){let c=JSON.stringify(a),l=Object.keys(vc).map(f=>JSON.stringify(f)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return o.includes(s)||o.push(s),o},[])}yo.coreKnownTags=mm;yo.getTags=pm});var ko=v(Pc=>{"use strict";var bo=C(),gm=st(),wm=ct(),vm=Wt(),Sr=Cc(),ym=(t,e)=>t.keye.key?1:0,No=class t{constructor({compat:e,customTags:i,merge:r,resolveKnownTags:n,schema:o,sortMapEntries:a,toStringDefaults:s}){this.compat=Array.isArray(e)?Sr.getTags(e,"compat"):e?Sr.getTags(null,e):null,this.name=typeof o=="string"&&o||"core",this.knownTags=n?Sr.coreKnownTags:{},this.tags=Sr.getTags(i,this.name,r),this.toStringOptions=s??null,Object.defineProperty(this,bo.MAP,{value:gm.map}),Object.defineProperty(this,bo.SCALAR,{value:vm.string}),Object.defineProperty(this,bo.SEQ,{value:wm.seq}),this.sortMapEntries=typeof a=="function"?a:a===!0?ym:null}clone(){let e=Object.create(t.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};Pc.Schema=No});var Rc=v(xc=>{"use strict";var bm=C(),So=Bt(),Kt=jt();function Nm(t,e){let i=[],r=e.directives===!0;if(e.directives!==!1&&t.directives){let c=t.directives.toString(t);c?(i.push(c),r=!0):t.directives.docStart&&(r=!0)}r&&i.push("---");let n=So.createStringifyContext(t,e),{commentString:o}=n.options;if(t.commentBefore){i.length!==1&&i.unshift("");let c=o(t.commentBefore);i.unshift(Kt.indentComment(c,""))}let a=!1,s=null;if(t.contents){if(bm.isNode(t.contents)){if(t.contents.spaceBefore&&r&&i.push(""),t.contents.commentBefore){let f=o(t.contents.commentBefore);i.push(Kt.indentComment(f,""))}n.forceBlockIndent=!!t.comment,s=t.contents.comment}let c=s?void 0:()=>a=!0,l=So.stringify(t.contents,n,()=>s=null,c);s&&(l+=Kt.lineComment(l,"",o(s))),(l[0]==="|"||l[0]===">")&&i[i.length-1]==="---"?i[i.length-1]=`--- ${l}`:i.push(l)}else i.push(So.stringify(t.contents,n));if(t.directives?.docEnd)if(t.comment){let c=o(t.comment);c.includes(` +${o.comment}`:r.comment}r=n}t.items[i]=dr.isPair(r)?r:new ro.Pair(r)}}else e("Expected a sequence for this tag");return t}function ec(t,e,i){let{replacer:r}=i,n=new Bh.YAMLSeq(t);n.tag="tag:yaml.org,2002:pairs";let o=0;if(e&&Symbol.iterator in Object(e))for(let a of e){typeof r=="function"&&(a=r.call(e,String(o++),a));let s,c;if(Array.isArray(a))if(a.length===2)s=a[0],c=a[1];else throw new TypeError(`Expected [key, value] tuple: ${a}`);else if(a&&a instanceof Object){let l=Object.keys(a);if(l.length===1)s=l[0],c=a[s];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else s=a;n.items.push(ro.createPair(s,c,i))}return n}var Mh={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Zs,createNode:ec};hr.createPairs=ec;hr.pairs=Mh;hr.resolvePairs=Zs});var ao=v(oo=>{"use strict";var tc=C(),no=Ne(),Ht=xe(),Fh=Re(),ic=mr(),De=class t extends Fh.YAMLSeq{constructor(){super(),this.add=Ht.YAMLMap.prototype.add.bind(this),this.delete=Ht.YAMLMap.prototype.delete.bind(this),this.get=Ht.YAMLMap.prototype.get.bind(this),this.has=Ht.YAMLMap.prototype.has.bind(this),this.set=Ht.YAMLMap.prototype.set.bind(this),this.tag=t.tag}toJSON(e,i){if(!i)return super.toJSON(e);let r=new Map;i?.onCreate&&i.onCreate(r);for(let n of this.items){let o,a;if(tc.isPair(n)?(o=no.toJS(n.key,"",i),a=no.toJS(n.value,o,i)):o=no.toJS(n,"",i),r.has(o))throw new Error("Ordered maps must not include duplicate keys");r.set(o,a)}return r}static from(e,i,r){let n=ic.createPairs(e,i,r),o=new this;return o.items=n.items,o}};De.tag="tag:yaml.org,2002:omap";var Wh={collection:"seq",identify:t=>t instanceof Map,nodeClass:De,default:!1,tag:"tag:yaml.org,2002:omap",resolve(t,e){let i=ic.resolvePairs(t,e),r=[];for(let{key:n}of i.items)tc.isScalar(n)&&(r.includes(n.value)?e(`Ordered maps must not include duplicate keys: ${n.value}`):r.push(n.value));return Object.assign(new De,i)},createNode:(t,e,i)=>De.from(t,e,i)};oo.YAMLOMap=De;oo.omap=Wh});var sc=v(so=>{"use strict";var rc=O();function nc({value:t,source:e},i){return e&&(t?oc:ac).test.test(e)?e:t?i.options.trueStr:i.options.falseStr}var oc={identify:t=>t===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new rc.Scalar(!0),stringify:nc},ac={identify:t=>t===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new rc.Scalar(!1),stringify:nc};so.falseTag=ac;so.trueTag=oc});var cc=v(pr=>{"use strict";var qh=O(),co=lt(),Hh={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:t=>t.slice(-3).toLowerCase()==="nan"?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:co.stringifyNumber},Gh={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t.replace(/_/g,"")),stringify(t){let e=Number(t.value);return isFinite(e)?e.toExponential():co.stringifyNumber(t)}},zh={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(t){let e=new qh.Scalar(parseFloat(t.replace(/_/g,""))),i=t.indexOf(".");if(i!==-1){let r=t.substring(i+1).replace(/_/g,"");r[r.length-1]==="0"&&(e.minFractionDigits=r.length)}return e},stringify:co.stringifyNumber};pr.float=zh;pr.floatExp=Gh;pr.floatNaN=Hh});var uc=v(zt=>{"use strict";var lc=lt(),Gt=t=>typeof t=="bigint"||Number.isInteger(t);function gr(t,e,i,{intAsBigInt:r}){let n=t[0];if((n==="-"||n==="+")&&(e+=1),t=t.substring(e).replace(/_/g,""),r){switch(i){case 2:t=`0b${t}`;break;case 8:t=`0o${t}`;break;case 16:t=`0x${t}`;break}let a=BigInt(t);return n==="-"?BigInt(-1)*a:a}let o=parseInt(t,i);return n==="-"?-1*o:o}function lo(t,e,i){let{value:r}=t;if(Gt(r)){let n=r.toString(e);return r<0?"-"+i+n.substr(1):i+n}return lc.stringifyNumber(t)}var Vh={identify:Gt,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(t,e,i)=>gr(t,2,2,i),stringify:t=>lo(t,2,"0b")},Kh={identify:Gt,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(t,e,i)=>gr(t,1,8,i),stringify:t=>lo(t,8,"0")},Jh={identify:Gt,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(t,e,i)=>gr(t,0,10,i),stringify:lc.stringifyNumber},Uh={identify:Gt,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(t,e,i)=>gr(t,2,16,i),stringify:t=>lo(t,16,"0x")};zt.int=Jh;zt.intBin=Vh;zt.intHex=Uh;zt.intOct=Kh});var fo=v(uo=>{"use strict";var yr=C(),wr=Ce(),vr=xe(),Be=class t extends vr.YAMLMap{constructor(e){super(e),this.tag=t.tag}add(e){let i;yr.isPair(e)?i=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?i=new wr.Pair(e.key,null):i=new wr.Pair(e,null),vr.findPair(this.items,i.key)||this.items.push(i)}get(e,i){let r=vr.findPair(this.items,e);return!i&&yr.isPair(r)?yr.isScalar(r.key)?r.key.value:r.key:r}set(e,i){if(typeof i!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof i}`);let r=vr.findPair(this.items,e);r&&!i?this.items.splice(this.items.indexOf(r),1):!r&&i&&this.items.push(new wr.Pair(e))}toJSON(e,i){return super.toJSON(e,i,Set)}toString(e,i,r){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),i,r);throw new Error("Set items must all have null values")}static from(e,i,r){let{replacer:n}=r,o=new this(e);if(i&&Symbol.iterator in Object(i))for(let a of i)typeof n=="function"&&(a=n.call(i,a,a)),o.items.push(wr.createPair(a,null,r));return o}};Be.tag="tag:yaml.org,2002:set";var Yh={collection:"map",identify:t=>t instanceof Set,nodeClass:Be,default:!1,tag:"tag:yaml.org,2002:set",createNode:(t,e,i)=>Be.from(t,e,i),resolve(t,e){if(yr.isMap(t)){if(t.hasAllNullValues(!0))return Object.assign(new Be,t);e("Set items must all have null values")}else e("Expected a mapping for this tag");return t}};uo.YAMLSet=Be;uo.set=Yh});var mo=v(br=>{"use strict";var Xh=lt();function ho(t,e){let i=t[0],r=i==="-"||i==="+"?t.substring(1):t,n=a=>e?BigInt(a):Number(a),o=r.replace(/_/g,"").split(":").reduce((a,s)=>a*n(60)+n(s),n(0));return i==="-"?n(-1)*o:o}function fc(t){let{value:e}=t,i=a=>a;if(typeof e=="bigint")i=a=>BigInt(a);else if(isNaN(e)||!isFinite(e))return Xh.stringifyNumber(t);let r="";e<0&&(r="-",e*=i(-1));let n=i(60),o=[e%n];return e<60?o.unshift(0):(e=(e-o[0])/n,o.unshift(e%n),e>=60&&(e=(e-o[0])/n,o.unshift(e))),r+o.map(a=>String(a).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var Qh={identify:t=>typeof t=="bigint"||Number.isInteger(t),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(t,e,{intAsBigInt:i})=>ho(t,i),stringify:fc},Zh={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:t=>ho(t,!1),stringify:fc},dc={identify:t=>t instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(t){let e=t.match(dc.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,i,r,n,o,a,s]=e.map(Number),c=e[7]?Number((e[7]+"00").substr(1,3)):0,l=Date.UTC(i,r-1,n,o||0,a||0,s||0,c),f=e[8];if(f&&f!=="Z"){let u=ho(f,!1);Math.abs(u)<30&&(u*=60),l-=6e4*u}return new Date(l)},stringify:({value:t})=>t?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};br.floatTime=Zh;br.intTime=Qh;br.timestamp=dc});var pc=v(mc=>{"use strict";var em=st(),tm=sr(),im=ct(),rm=Wt(),nm=io(),hc=sc(),po=cc(),Nr=uc(),om=Zi(),am=ao(),sm=mr(),cm=fo(),go=mo(),lm=[em.map,im.seq,rm.string,tm.nullTag,hc.trueTag,hc.falseTag,Nr.intBin,Nr.intOct,Nr.int,Nr.intHex,po.floatNaN,po.floatExp,po.float,nm.binary,om.merge,am.omap,sm.pairs,cm.set,go.intTime,go.floatTime,go.timestamp];mc.schema=lm});var Cc=v(yo=>{"use strict";var yc=st(),um=sr(),bc=ct(),fm=Wt(),dm=Jn(),wo=Yn(),vo=Qn(),hm=Js(),mm=Xs(),Nc=io(),Vt=Zi(),kc=ao(),Sc=mr(),gc=pc(),Ec=fo(),kr=mo(),wc=new Map([["core",hm.schema],["failsafe",[yc.map,bc.seq,fm.string]],["json",mm.schema],["yaml11",gc.schema],["yaml-1.1",gc.schema]]),vc={binary:Nc.binary,bool:dm.boolTag,float:wo.float,floatExp:wo.floatExp,floatNaN:wo.floatNaN,floatTime:kr.floatTime,int:vo.int,intHex:vo.intHex,intOct:vo.intOct,intTime:kr.intTime,map:yc.map,merge:Vt.merge,null:um.nullTag,omap:kc.omap,pairs:Sc.pairs,seq:bc.seq,set:Ec.set,timestamp:kr.timestamp},pm={"tag:yaml.org,2002:binary":Nc.binary,"tag:yaml.org,2002:merge":Vt.merge,"tag:yaml.org,2002:omap":kc.omap,"tag:yaml.org,2002:pairs":Sc.pairs,"tag:yaml.org,2002:set":Ec.set,"tag:yaml.org,2002:timestamp":kr.timestamp};function gm(t,e,i){let r=wc.get(e);if(r&&!t)return i&&!r.includes(Vt.merge)?r.concat(Vt.merge):r.slice();let n=r;if(!n)if(Array.isArray(t))n=[];else{let o=Array.from(wc.keys()).filter(a=>a!=="yaml11").map(a=>JSON.stringify(a)).join(", ");throw new Error(`Unknown schema "${e}"; use one of ${o} or define customTags array`)}if(Array.isArray(t))for(let o of t)n=n.concat(o);else typeof t=="function"&&(n=t(n.slice()));return i&&(n=n.concat(Vt.merge)),n.reduce((o,a)=>{let s=typeof a=="string"?vc[a]:a;if(!s){let c=JSON.stringify(a),l=Object.keys(vc).map(f=>JSON.stringify(f)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return o.includes(s)||o.push(s),o},[])}yo.coreKnownTags=pm;yo.getTags=gm});var ko=v(Pc=>{"use strict";var bo=C(),wm=st(),vm=ct(),ym=Wt(),Sr=Cc(),bm=(t,e)=>t.keye.key?1:0,No=class t{constructor({compat:e,customTags:i,merge:r,resolveKnownTags:n,schema:o,sortMapEntries:a,toStringDefaults:s}){this.compat=Array.isArray(e)?Sr.getTags(e,"compat"):e?Sr.getTags(null,e):null,this.name=typeof o=="string"&&o||"core",this.knownTags=n?Sr.coreKnownTags:{},this.tags=Sr.getTags(i,this.name,r),this.toStringOptions=s??null,Object.defineProperty(this,bo.MAP,{value:wm.map}),Object.defineProperty(this,bo.SCALAR,{value:ym.string}),Object.defineProperty(this,bo.SEQ,{value:vm.seq}),this.sortMapEntries=typeof a=="function"?a:a===!0?bm:null}clone(){let e=Object.create(t.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};Pc.Schema=No});var Rc=v(xc=>{"use strict";var Nm=C(),So=Bt(),Kt=jt();function km(t,e){let i=[],r=e.directives===!0;if(e.directives!==!1&&t.directives){let c=t.directives.toString(t);c?(i.push(c),r=!0):t.directives.docStart&&(r=!0)}r&&i.push("---");let n=So.createStringifyContext(t,e),{commentString:o}=n.options;if(t.commentBefore){i.length!==1&&i.unshift("");let c=o(t.commentBefore);i.unshift(Kt.indentComment(c,""))}let a=!1,s=null;if(t.contents){if(Nm.isNode(t.contents)){if(t.contents.spaceBefore&&r&&i.push(""),t.contents.commentBefore){let f=o(t.contents.commentBefore);i.push(Kt.indentComment(f,""))}n.forceBlockIndent=!!t.comment,s=t.contents.comment}let c=s?void 0:()=>a=!0,l=So.stringify(t.contents,n,()=>s=null,c);s&&(l+=Kt.lineComment(l,"",o(s))),(l[0]==="|"||l[0]===">")&&i[i.length-1]==="---"?i[i.length-1]=`--- ${l}`:i.push(l)}else i.push(So.stringify(t.contents,n));if(t.directives?.docEnd)if(t.comment){let c=o(t.comment);c.includes(` `)?(i.push("..."),i.push(Kt.indentComment(c,""))):i.push(`... ${c}`)}else i.push("...");else{let c=t.comment;c&&a&&(c=c.replace(/^\n+/,"")),c&&((!a||s)&&i[i.length-1]!==""&&i.push(""),i.push(Kt.indentComment(o(c),"")))}return i.join(` `)+` -`}xc.stringifyDocument=Nm});var Jt=v(_c=>{"use strict";var km=Ot(),ut=Hi(),V=C(),Sm=Ce(),Em=Ne(),Cm=ko(),Pm=Rc(),Eo=Mi(),xm=xn(),Rm=It(),Co=Pn(),Po=class t{constructor(e,i,r){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,V.NODE_TYPE,{value:V.DOC});let n=null;typeof i=="function"||Array.isArray(i)?n=i:r===void 0&&i&&(r=i,i=void 0);let o=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},r);this.options=o;let{version:a}=o;r?._directives?(this.directives=r._directives.atDocument(),this.directives.yaml.explicit&&(a=this.directives.yaml.version)):this.directives=new Co.Directives({version:a}),this.setSchema(a,r),this.contents=e===void 0?null:this.createNode(e,n,r)}clone(){let e=Object.create(t.prototype,{[V.NODE_TYPE]:{value:V.DOC}});return e.commentBefore=this.commentBefore,e.comment=this.comment,e.errors=this.errors.slice(),e.warnings=this.warnings.slice(),e.options=Object.assign({},this.options),this.directives&&(e.directives=this.directives.clone()),e.schema=this.schema.clone(),e.contents=V.isNode(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){ft(this.contents)&&this.contents.add(e)}addIn(e,i){ft(this.contents)&&this.contents.addIn(e,i)}createAlias(e,i){if(!e.anchor){let r=Eo.anchorNames(this);e.anchor=!i||r.has(i)?Eo.findNewAnchor(i||"a",r):i}return new km.Alias(e.anchor)}createNode(e,i,r){let n;if(typeof i=="function")e=i.call({"":e},"",e),n=i;else if(Array.isArray(i)){let p=b=>typeof b=="number"||b instanceof String||b instanceof Number,y=i.filter(p).map(String);y.length>0&&(i=i.concat(y)),n=i}else r===void 0&&i&&(r=i,i=void 0);let{aliasDuplicateObjects:o,anchorPrefix:a,flow:s,keepUndefined:c,onTagObj:l,tag:f}=r??{},{onAnchor:u,setAnchors:d,sourceObjects:m}=Eo.createNodeAnchors(this,a||"a"),w={aliasDuplicateObjects:o??!0,keepUndefined:c??!1,onAnchor:u,onTagObj:l,replacer:n,schema:this.schema,sourceObjects:m},h=Rm.createNode(e,f,w);return s&&V.isCollection(h)&&(h.flow=!0),d(),h}createPair(e,i,r={}){let n=this.createNode(e,null,r),o=this.createNode(i,null,r);return new Sm.Pair(n,o)}delete(e){return ft(this.contents)?this.contents.delete(e):!1}deleteIn(e){return ut.isEmptyPath(e)?this.contents==null?!1:(this.contents=null,!0):ft(this.contents)?this.contents.deleteIn(e):!1}get(e,i){return V.isCollection(this.contents)?this.contents.get(e,i):void 0}getIn(e,i){return ut.isEmptyPath(e)?!i&&V.isScalar(this.contents)?this.contents.value:this.contents:V.isCollection(this.contents)?this.contents.getIn(e,i):void 0}has(e){return V.isCollection(this.contents)?this.contents.has(e):!1}hasIn(e){return ut.isEmptyPath(e)?this.contents!==void 0:V.isCollection(this.contents)?this.contents.hasIn(e):!1}set(e,i){this.contents==null?this.contents=ut.collectionFromPath(this.schema,[e],i):ft(this.contents)&&this.contents.set(e,i)}setIn(e,i){ut.isEmptyPath(e)?this.contents=i:this.contents==null?this.contents=ut.collectionFromPath(this.schema,Array.from(e),i):ft(this.contents)&&this.contents.setIn(e,i)}setSchema(e,i={}){typeof e=="number"&&(e=String(e));let r;switch(e){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new Co.Directives({version:"1.1"}),r={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=e:this.directives=new Co.Directives({version:e}),r={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,r=null;break;default:{let n=JSON.stringify(e);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${n}`)}}if(i.schema instanceof Object)this.schema=i.schema;else if(r)this.schema=new Cm.Schema(Object.assign(r,i));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:e,jsonArg:i,mapAsMap:r,maxAliasCount:n,onAnchor:o,reviver:a}={}){let s={anchors:new Map,doc:this,keep:!e,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},c=Em.toJS(this.contents,i??"",s);if(typeof o=="function")for(let{count:l,res:f}of s.anchors.values())o(f,l);return typeof a=="function"?xm.applyReviver(a,{"":c},"",c):c}toJSON(e,i){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:i})}toString(e={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let i=JSON.stringify(e.indent);throw new Error(`"indent" option must be a positive integer, not ${i}`)}return Pm.stringifyDocument(this,e)}};function ft(t){if(V.isCollection(t))return!0;throw new Error("Expected a YAML collection as document contents")}_c.Document=Po});var Xt=v(Yt=>{"use strict";var Ut=class extends Error{constructor(e,i,r,n){super(),this.name=e,this.code=r,this.message=n,this.pos=i}},xo=class extends Ut{constructor(e,i,r){super("YAMLParseError",e,i,r)}},Ro=class extends Ut{constructor(e,i,r){super("YAMLWarning",e,i,r)}},_m=(t,e)=>i=>{if(i.pos[0]===-1)return;i.linePos=i.pos.map(s=>e.linePos(s));let{line:r,col:n}=i.linePos[0];i.message+=` at line ${r}, column ${n}`;let o=n-1,a=t.substring(e.lineStarts[r-1],e.lineStarts[r]).replace(/[\n\r]+$/,"");if(o>=60&&a.length>80){let s=Math.min(o-39,a.length-79);a="…"+a.substring(s),o-=s-1}if(a.length>80&&(a=a.substring(0,79)+"…"),r>1&&/^ *$/.test(a.substring(0,o))){let s=t.substring(e.lineStarts[r-2],e.lineStarts[r-1]);s.length>80&&(s=s.substring(0,79)+`… +`}xc.stringifyDocument=km});var Jt=v(_c=>{"use strict";var Sm=Ot(),ut=Hi(),V=C(),Em=Ce(),Cm=Ne(),Pm=ko(),xm=Rc(),Eo=Mi(),Rm=xn(),_m=It(),Co=Pn(),Po=class t{constructor(e,i,r){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,V.NODE_TYPE,{value:V.DOC});let n=null;typeof i=="function"||Array.isArray(i)?n=i:r===void 0&&i&&(r=i,i=void 0);let o=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},r);this.options=o;let{version:a}=o;r?._directives?(this.directives=r._directives.atDocument(),this.directives.yaml.explicit&&(a=this.directives.yaml.version)):this.directives=new Co.Directives({version:a}),this.setSchema(a,r),this.contents=e===void 0?null:this.createNode(e,n,r)}clone(){let e=Object.create(t.prototype,{[V.NODE_TYPE]:{value:V.DOC}});return e.commentBefore=this.commentBefore,e.comment=this.comment,e.errors=this.errors.slice(),e.warnings=this.warnings.slice(),e.options=Object.assign({},this.options),this.directives&&(e.directives=this.directives.clone()),e.schema=this.schema.clone(),e.contents=V.isNode(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){ft(this.contents)&&this.contents.add(e)}addIn(e,i){ft(this.contents)&&this.contents.addIn(e,i)}createAlias(e,i){if(!e.anchor){let r=Eo.anchorNames(this);e.anchor=!i||r.has(i)?Eo.findNewAnchor(i||"a",r):i}return new Sm.Alias(e.anchor)}createNode(e,i,r){let n;if(typeof i=="function")e=i.call({"":e},"",e),n=i;else if(Array.isArray(i)){let p=b=>typeof b=="number"||b instanceof String||b instanceof Number,y=i.filter(p).map(String);y.length>0&&(i=i.concat(y)),n=i}else r===void 0&&i&&(r=i,i=void 0);let{aliasDuplicateObjects:o,anchorPrefix:a,flow:s,keepUndefined:c,onTagObj:l,tag:f}=r??{},{onAnchor:u,setAnchors:d,sourceObjects:m}=Eo.createNodeAnchors(this,a||"a"),w={aliasDuplicateObjects:o??!0,keepUndefined:c??!1,onAnchor:u,onTagObj:l,replacer:n,schema:this.schema,sourceObjects:m},h=_m.createNode(e,f,w);return s&&V.isCollection(h)&&(h.flow=!0),d(),h}createPair(e,i,r={}){let n=this.createNode(e,null,r),o=this.createNode(i,null,r);return new Em.Pair(n,o)}delete(e){return ft(this.contents)?this.contents.delete(e):!1}deleteIn(e){return ut.isEmptyPath(e)?this.contents==null?!1:(this.contents=null,!0):ft(this.contents)?this.contents.deleteIn(e):!1}get(e,i){return V.isCollection(this.contents)?this.contents.get(e,i):void 0}getIn(e,i){return ut.isEmptyPath(e)?!i&&V.isScalar(this.contents)?this.contents.value:this.contents:V.isCollection(this.contents)?this.contents.getIn(e,i):void 0}has(e){return V.isCollection(this.contents)?this.contents.has(e):!1}hasIn(e){return ut.isEmptyPath(e)?this.contents!==void 0:V.isCollection(this.contents)?this.contents.hasIn(e):!1}set(e,i){this.contents==null?this.contents=ut.collectionFromPath(this.schema,[e],i):ft(this.contents)&&this.contents.set(e,i)}setIn(e,i){ut.isEmptyPath(e)?this.contents=i:this.contents==null?this.contents=ut.collectionFromPath(this.schema,Array.from(e),i):ft(this.contents)&&this.contents.setIn(e,i)}setSchema(e,i={}){typeof e=="number"&&(e=String(e));let r;switch(e){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new Co.Directives({version:"1.1"}),r={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=e:this.directives=new Co.Directives({version:e}),r={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,r=null;break;default:{let n=JSON.stringify(e);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${n}`)}}if(i.schema instanceof Object)this.schema=i.schema;else if(r)this.schema=new Pm.Schema(Object.assign(r,i));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:e,jsonArg:i,mapAsMap:r,maxAliasCount:n,onAnchor:o,reviver:a}={}){let s={anchors:new Map,doc:this,keep:!e,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},c=Cm.toJS(this.contents,i??"",s);if(typeof o=="function")for(let{count:l,res:f}of s.anchors.values())o(f,l);return typeof a=="function"?Rm.applyReviver(a,{"":c},"",c):c}toJSON(e,i){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:i})}toString(e={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let i=JSON.stringify(e.indent);throw new Error(`"indent" option must be a positive integer, not ${i}`)}return xm.stringifyDocument(this,e)}};function ft(t){if(V.isCollection(t))return!0;throw new Error("Expected a YAML collection as document contents")}_c.Document=Po});var Xt=v(Yt=>{"use strict";var Ut=class extends Error{constructor(e,i,r,n){super(),this.name=e,this.code=r,this.message=n,this.pos=i}},xo=class extends Ut{constructor(e,i,r){super("YAMLParseError",e,i,r)}},Ro=class extends Ut{constructor(e,i,r){super("YAMLWarning",e,i,r)}},Am=(t,e)=>i=>{if(i.pos[0]===-1)return;i.linePos=i.pos.map(s=>e.linePos(s));let{line:r,col:n}=i.linePos[0];i.message+=` at line ${r}, column ${n}`;let o=n-1,a=t.substring(e.lineStarts[r-1],e.lineStarts[r]).replace(/[\n\r]+$/,"");if(o>=60&&a.length>80){let s=Math.min(o-39,a.length-79);a="…"+a.substring(s),o-=s-1}if(a.length>80&&(a=a.substring(0,79)+"…"),r>1&&/^ *$/.test(a.substring(0,o))){let s=t.substring(e.lineStarts[r-2],e.lineStarts[r-1]);s.length>80&&(s=s.substring(0,79)+`… `),a=s+a}if(/[^ ]/.test(a)){let s=1,c=i.linePos[1];c?.line===r&&c.col>n&&(s=Math.max(1,Math.min(c.col-n,80-o)));let l=" ".repeat(o)+"^".repeat(s);i.message+=`: ${a} ${l} -`}};Yt.YAMLError=Ut;Yt.YAMLParseError=xo;Yt.YAMLWarning=Ro;Yt.prettifyError=_m});var Qt=v(Ac=>{"use strict";function Am(t,{flow:e,indicator:i,next:r,offset:n,onError:o,parentIndent:a,startOnNewline:s}){let c=!1,l=s,f=s,u="",d="",m=!1,w=!1,h=null,p=null,y=null,b=null,k=null,S=null,E=null;for(let N of t)switch(w&&(N.type!=="space"&&N.type!=="newline"&&N.type!=="comma"&&o(N.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),w=!1),h&&(l&&N.type!=="comment"&&N.type!=="newline"&&o(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),h=null),N.type){case"space":!e&&(i!=="doc-start"||r?.type!=="flow-collection")&&N.source.includes(" ")&&(h=N),f=!0;break;case"comment":{f||o(N,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let _=N.source.substring(1)||" ";u?u+=d+_:u=_,d="",l=!1;break}case"newline":l?u?u+=N.source:(!S||i!=="seq-item-ind")&&(c=!0):d+=N.source,l=!0,m=!0,(p||y)&&(b=N),f=!0;break;case"anchor":p&&o(N,"MULTIPLE_ANCHORS","A node can have at most one anchor"),N.source.endsWith(":")&&o(N.offset+N.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),p=N,E??(E=N.offset),l=!1,f=!1,w=!0;break;case"tag":{y&&o(N,"MULTIPLE_TAGS","A node can have at most one tag"),y=N,E??(E=N.offset),l=!1,f=!1,w=!0;break}case i:(p||y)&&o(N,"BAD_PROP_ORDER",`Anchors and tags must be after the ${N.source} indicator`),S&&o(N,"UNEXPECTED_TOKEN",`Unexpected ${N.source} in ${e??"collection"}`),S=N,l=i==="seq-item-ind"||i==="explicit-key-ind",f=!1;break;case"comma":if(e){k&&o(N,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),k=N,l=!1,f=!1;break}default:o(N,"UNEXPECTED_TOKEN",`Unexpected ${N.type} token`),l=!1,f=!1}let g=t[t.length-1],P=g?g.offset+g.source.length:n;return w&&r&&r.type!=="space"&&r.type!=="newline"&&r.type!=="comma"&&(r.type!=="scalar"||r.source!=="")&&o(r.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),h&&(l&&h.indent<=a||r?.type==="block-map"||r?.type==="block-seq")&&o(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:k,found:S,spaceBefore:c,comment:u,hasNewline:m,anchor:p,tag:y,newlineAfterProp:b,end:P,start:E??P}}Ac.resolveProps=Am});var Er=v(Tc=>{"use strict";function _o(t){if(!t)return null;switch(t.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(t.source.includes(` -`))return!0;if(t.end){for(let e of t.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(let e of t.items){for(let i of e.start)if(i.type==="newline")return!0;if(e.sep){for(let i of e.sep)if(i.type==="newline")return!0}if(_o(e.key)||_o(e.value))return!0}return!1;default:return!0}}Tc.containsNewline=_o});var Ao=v(Oc=>{"use strict";var Tm=Er();function Om(t,e,i){if(e?.type==="flow-collection"){let r=e.end[0];r.indent===t&&(r.source==="]"||r.source==="}")&&Tm.containsNewline(e)&&i(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Oc.flowIndentCheck=Om});var To=v(jc=>{"use strict";var Ic=C();function Im(t,e,i){let{uniqueKeys:r}=t.options;if(r===!1)return!1;let n=typeof r=="function"?r:(o,a)=>o===a||Ic.isScalar(o)&&Ic.isScalar(a)&&o.value===a.value;return e.some(o=>n(o.key,i))}jc.mapIncludes=Im});var Fc=v(Mc=>{"use strict";var Lc=Ce(),jm=xe(),$c=Qt(),Lm=Er(),Dc=Ao(),$m=To(),Bc="All mapping items must start at the same column";function Dm({composeNode:t,composeEmptyNode:e},i,r,n,o){let a=o?.nodeClass??jm.YAMLMap,s=new a(i.schema);i.atRoot&&(i.atRoot=!1);let c=r.offset,l=null;for(let f of r.items){let{start:u,key:d,sep:m,value:w}=f,h=$c.resolveProps(u,{indicator:"explicit-key-ind",next:d??m?.[0],offset:c,onError:n,parentIndent:r.indent,startOnNewline:!0}),p=!h.found;if(p){if(d&&(d.type==="block-seq"?n(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in d&&d.indent!==r.indent&&n(c,"BAD_INDENT",Bc)),!h.anchor&&!h.tag&&!m){l=h.end,h.comment&&(s.comment?s.comment+=` -`+h.comment:s.comment=h.comment);continue}(h.newlineAfterProp||Lm.containsNewline(d))&&n(d??u[u.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else h.found?.indent!==r.indent&&n(c,"BAD_INDENT",Bc);i.atKey=!0;let y=h.end,b=d?t(i,d,h,n):e(i,y,u,null,h,n);i.schema.compat&&Dc.flowIndentCheck(r.indent,d,n),i.atKey=!1,$m.mapIncludes(i,s.items,b)&&n(y,"DUPLICATE_KEY","Map keys must be unique");let k=$c.resolveProps(m??[],{indicator:"map-value-ind",next:w,offset:b.range[2],onError:n,parentIndent:r.indent,startOnNewline:!d||d.type==="block-scalar"});if(c=k.end,k.found){p&&(w?.type==="block-map"&&!k.hasNewline&&n(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),i.options.strict&&h.start{"use strict";var Bm=Re(),Mm=Qt(),Fm=Ao();function Wm({composeNode:t,composeEmptyNode:e},i,r,n,o){let a=o?.nodeClass??Bm.YAMLSeq,s=new a(i.schema);i.atRoot&&(i.atRoot=!1),i.atKey&&(i.atKey=!1);let c=r.offset,l=null;for(let{start:f,value:u}of r.items){let d=Mm.resolveProps(f,{indicator:"seq-item-ind",next:u,offset:c,onError:n,parentIndent:r.indent,startOnNewline:!0});if(!d.found)if(d.anchor||d.tag||u)u?.type==="block-seq"?n(d.end,"BAD_INDENT","All sequence items must start at the same column"):n(c,"MISSING_CHAR","Sequence item without - indicator");else{l=d.end,d.comment&&(s.comment=d.comment);continue}let m=u?t(i,u,d,n):e(i,d.end,f,null,d,n);i.schema.compat&&Fm.flowIndentCheck(r.indent,u,n),c=m.range[2],s.items.push(m)}return s.range=[r.offset,c,l??c],s}Wc.resolveBlockSeq=Wm});var dt=v(Hc=>{"use strict";function qm(t,e,i,r){let n="";if(t){let o=!1,a="";for(let s of t){let{source:c,type:l}=s;switch(l){case"space":o=!0;break;case"comment":{i&&!o&&r(s,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let f=c.substring(1)||" ";n?n+=a+f:n=f,a="";break}case"newline":n&&(a+=c),o=!0;break;default:r(s,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}e+=c.length}}return{comment:n,offset:e}}Hc.resolveEnd=qm});var Kc=v(Vc=>{"use strict";var Hm=C(),Gm=Ce(),Gc=xe(),zm=Re(),Vm=dt(),zc=Qt(),Km=Er(),Jm=To(),Oo="Block collections are not allowed within flow collections",Io=t=>t&&(t.type==="block-map"||t.type==="block-seq");function Um({composeNode:t,composeEmptyNode:e},i,r,n,o){let a=r.start.source==="{",s=a?"flow map":"flow sequence",c=o?.nodeClass??(a?Gc.YAMLMap:zm.YAMLSeq),l=new c(i.schema);l.flow=!0;let f=i.atRoot;f&&(i.atRoot=!1),i.atKey&&(i.atKey=!1);let u=r.offset+r.start.source.length;for(let p=0;p0){let p=Vm.resolveEnd(w,h,i.options.strict,n);p.comment&&(l.comment?l.comment+=` -`+p.comment:l.comment=p.comment),l.range=[r.offset,h,p.offset]}else l.range=[r.offset,h,h];return l}Vc.resolveFlowCollection=Um});var Uc=v(Jc=>{"use strict";var Ym=C(),Xm=O(),Qm=xe(),Zm=Re(),ep=Fc(),tp=qc(),ip=Kc();function jo(t,e,i,r,n,o){let a=i.type==="block-map"?ep.resolveBlockMap(t,e,i,r,o):i.type==="block-seq"?tp.resolveBlockSeq(t,e,i,r,o):ip.resolveFlowCollection(t,e,i,r,o),s=a.constructor;return n==="!"||n===s.tagName?(a.tag=s.tagName,a):(n&&(a.tag=n),a)}function rp(t,e,i,r,n){let o=r.tag,a=o?e.directives.tagName(o.source,d=>n(o,"TAG_RESOLVE_FAILED",d)):null;if(i.type==="block-seq"){let{anchor:d,newlineAfterProp:m}=r,w=d&&o?d.offset>o.offset?d:o:d??o;w&&(!m||m.offsetd.tag===a&&d.collection===s);if(!c){let d=e.schema.knownTags[a];if(d?.collection===s)e.schema.tags.push(Object.assign({},d,{default:!1})),c=d;else return d?n(o,"BAD_COLLECTION_TYPE",`${d.tag} used for ${s} collection, but expects ${d.collection??"scalar"}`,!0):n(o,"TAG_RESOLVE_FAILED",`Unresolved tag: ${a}`,!0),jo(t,e,i,n,a)}let l=jo(t,e,i,n,a,c),f=c.resolve?.(l,d=>n(o,"TAG_RESOLVE_FAILED",d),e.options)??l,u=Ym.isNode(f)?f:new Xm.Scalar(f);return u.range=l.range,u.tag=a,c?.format&&(u.format=c.format),u}Jc.composeCollection=rp});var $o=v(Yc=>{"use strict";var Lo=O();function np(t,e,i){let r=e.offset,n=op(e,t.options.strict,i);if(!n)return{value:"",type:null,comment:"",range:[r,r,r]};let o=n.mode===">"?Lo.Scalar.BLOCK_FOLDED:Lo.Scalar.BLOCK_LITERAL,a=e.source?ap(e.source):[],s=a.length;for(let h=a.length-1;h>=0;--h){let p=a[h][1];if(p===""||p==="\r")s=h;else break}if(s===0){let h=n.chomp==="+"&&a.length>0?` +`}};Yt.YAMLError=Ut;Yt.YAMLParseError=xo;Yt.YAMLWarning=Ro;Yt.prettifyError=Am});var Qt=v(Ac=>{"use strict";function Tm(t,{flow:e,indicator:i,next:r,offset:n,onError:o,parentIndent:a,startOnNewline:s}){let c=!1,l=s,f=s,u="",d="",m=!1,w=!1,h=null,p=null,y=null,b=null,k=null,S=null,E=null;for(let N of t)switch(w&&(N.type!=="space"&&N.type!=="newline"&&N.type!=="comma"&&o(N.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),w=!1),h&&(l&&N.type!=="comment"&&N.type!=="newline"&&o(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),h=null),N.type){case"space":!e&&(i!=="doc-start"||r?.type!=="flow-collection")&&N.source.includes(" ")&&(h=N),f=!0;break;case"comment":{f||o(N,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let _=N.source.substring(1)||" ";u?u+=d+_:u=_,d="",l=!1;break}case"newline":l?u?u+=N.source:(!S||i!=="seq-item-ind")&&(c=!0):d+=N.source,l=!0,m=!0,(p||y)&&(b=N),f=!0;break;case"anchor":p&&o(N,"MULTIPLE_ANCHORS","A node can have at most one anchor"),N.source.endsWith(":")&&o(N.offset+N.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),p=N,E??(E=N.offset),l=!1,f=!1,w=!0;break;case"tag":{y&&o(N,"MULTIPLE_TAGS","A node can have at most one tag"),y=N,E??(E=N.offset),l=!1,f=!1,w=!0;break}case i:(p||y)&&o(N,"BAD_PROP_ORDER",`Anchors and tags must be after the ${N.source} indicator`),S&&o(N,"UNEXPECTED_TOKEN",`Unexpected ${N.source} in ${e??"collection"}`),S=N,l=i==="seq-item-ind"||i==="explicit-key-ind",f=!1;break;case"comma":if(e){k&&o(N,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),k=N,l=!1,f=!1;break}default:o(N,"UNEXPECTED_TOKEN",`Unexpected ${N.type} token`),l=!1,f=!1}let g=t[t.length-1],P=g?g.offset+g.source.length:n;return w&&r&&r.type!=="space"&&r.type!=="newline"&&r.type!=="comma"&&(r.type!=="scalar"||r.source!=="")&&o(r.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),h&&(l&&h.indent<=a||r?.type==="block-map"||r?.type==="block-seq")&&o(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:k,found:S,spaceBefore:c,comment:u,hasNewline:m,anchor:p,tag:y,newlineAfterProp:b,end:P,start:E??P}}Ac.resolveProps=Tm});var Er=v(Tc=>{"use strict";function _o(t){if(!t)return null;switch(t.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(t.source.includes(` +`))return!0;if(t.end){for(let e of t.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(let e of t.items){for(let i of e.start)if(i.type==="newline")return!0;if(e.sep){for(let i of e.sep)if(i.type==="newline")return!0}if(_o(e.key)||_o(e.value))return!0}return!1;default:return!0}}Tc.containsNewline=_o});var Ao=v(Oc=>{"use strict";var Om=Er();function Im(t,e,i){if(e?.type==="flow-collection"){let r=e.end[0];r.indent===t&&(r.source==="]"||r.source==="}")&&Om.containsNewline(e)&&i(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Oc.flowIndentCheck=Im});var To=v(jc=>{"use strict";var Ic=C();function jm(t,e,i){let{uniqueKeys:r}=t.options;if(r===!1)return!1;let n=typeof r=="function"?r:(o,a)=>o===a||Ic.isScalar(o)&&Ic.isScalar(a)&&o.value===a.value;return e.some(o=>n(o.key,i))}jc.mapIncludes=jm});var Fc=v(Mc=>{"use strict";var Lc=Ce(),Lm=xe(),$c=Qt(),$m=Er(),Dc=Ao(),Dm=To(),Bc="All mapping items must start at the same column";function Bm({composeNode:t,composeEmptyNode:e},i,r,n,o){let a=o?.nodeClass??Lm.YAMLMap,s=new a(i.schema);i.atRoot&&(i.atRoot=!1);let c=r.offset,l=null;for(let f of r.items){let{start:u,key:d,sep:m,value:w}=f,h=$c.resolveProps(u,{indicator:"explicit-key-ind",next:d??m?.[0],offset:c,onError:n,parentIndent:r.indent,startOnNewline:!0}),p=!h.found;if(p){if(d&&(d.type==="block-seq"?n(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in d&&d.indent!==r.indent&&n(c,"BAD_INDENT",Bc)),!h.anchor&&!h.tag&&!m){l=h.end,h.comment&&(s.comment?s.comment+=` +`+h.comment:s.comment=h.comment);continue}(h.newlineAfterProp||$m.containsNewline(d))&&n(d??u[u.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else h.found?.indent!==r.indent&&n(c,"BAD_INDENT",Bc);i.atKey=!0;let y=h.end,b=d?t(i,d,h,n):e(i,y,u,null,h,n);i.schema.compat&&Dc.flowIndentCheck(r.indent,d,n),i.atKey=!1,Dm.mapIncludes(i,s.items,b)&&n(y,"DUPLICATE_KEY","Map keys must be unique");let k=$c.resolveProps(m??[],{indicator:"map-value-ind",next:w,offset:b.range[2],onError:n,parentIndent:r.indent,startOnNewline:!d||d.type==="block-scalar"});if(c=k.end,k.found){p&&(w?.type==="block-map"&&!k.hasNewline&&n(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),i.options.strict&&h.start{"use strict";var Mm=Re(),Fm=Qt(),Wm=Ao();function qm({composeNode:t,composeEmptyNode:e},i,r,n,o){let a=o?.nodeClass??Mm.YAMLSeq,s=new a(i.schema);i.atRoot&&(i.atRoot=!1),i.atKey&&(i.atKey=!1);let c=r.offset,l=null;for(let{start:f,value:u}of r.items){let d=Fm.resolveProps(f,{indicator:"seq-item-ind",next:u,offset:c,onError:n,parentIndent:r.indent,startOnNewline:!0});if(!d.found)if(d.anchor||d.tag||u)u?.type==="block-seq"?n(d.end,"BAD_INDENT","All sequence items must start at the same column"):n(c,"MISSING_CHAR","Sequence item without - indicator");else{l=d.end,d.comment&&(s.comment=d.comment);continue}let m=u?t(i,u,d,n):e(i,d.end,f,null,d,n);i.schema.compat&&Wm.flowIndentCheck(r.indent,u,n),c=m.range[2],s.items.push(m)}return s.range=[r.offset,c,l??c],s}Wc.resolveBlockSeq=qm});var dt=v(Hc=>{"use strict";function Hm(t,e,i,r){let n="";if(t){let o=!1,a="";for(let s of t){let{source:c,type:l}=s;switch(l){case"space":o=!0;break;case"comment":{i&&!o&&r(s,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let f=c.substring(1)||" ";n?n+=a+f:n=f,a="";break}case"newline":n&&(a+=c),o=!0;break;default:r(s,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}e+=c.length}}return{comment:n,offset:e}}Hc.resolveEnd=Hm});var Kc=v(Vc=>{"use strict";var Gm=C(),zm=Ce(),Gc=xe(),Vm=Re(),Km=dt(),zc=Qt(),Jm=Er(),Um=To(),Oo="Block collections are not allowed within flow collections",Io=t=>t&&(t.type==="block-map"||t.type==="block-seq");function Ym({composeNode:t,composeEmptyNode:e},i,r,n,o){let a=r.start.source==="{",s=a?"flow map":"flow sequence",c=o?.nodeClass??(a?Gc.YAMLMap:Vm.YAMLSeq),l=new c(i.schema);l.flow=!0;let f=i.atRoot;f&&(i.atRoot=!1),i.atKey&&(i.atKey=!1);let u=r.offset+r.start.source.length;for(let p=0;p0){let p=Km.resolveEnd(w,h,i.options.strict,n);p.comment&&(l.comment?l.comment+=` +`+p.comment:l.comment=p.comment),l.range=[r.offset,h,p.offset]}else l.range=[r.offset,h,h];return l}Vc.resolveFlowCollection=Ym});var Uc=v(Jc=>{"use strict";var Xm=C(),Qm=O(),Zm=xe(),ep=Re(),tp=Fc(),ip=qc(),rp=Kc();function jo(t,e,i,r,n,o){let a=i.type==="block-map"?tp.resolveBlockMap(t,e,i,r,o):i.type==="block-seq"?ip.resolveBlockSeq(t,e,i,r,o):rp.resolveFlowCollection(t,e,i,r,o),s=a.constructor;return n==="!"||n===s.tagName?(a.tag=s.tagName,a):(n&&(a.tag=n),a)}function np(t,e,i,r,n){let o=r.tag,a=o?e.directives.tagName(o.source,d=>n(o,"TAG_RESOLVE_FAILED",d)):null;if(i.type==="block-seq"){let{anchor:d,newlineAfterProp:m}=r,w=d&&o?d.offset>o.offset?d:o:d??o;w&&(!m||m.offsetd.tag===a&&d.collection===s);if(!c){let d=e.schema.knownTags[a];if(d?.collection===s)e.schema.tags.push(Object.assign({},d,{default:!1})),c=d;else return d?n(o,"BAD_COLLECTION_TYPE",`${d.tag} used for ${s} collection, but expects ${d.collection??"scalar"}`,!0):n(o,"TAG_RESOLVE_FAILED",`Unresolved tag: ${a}`,!0),jo(t,e,i,n,a)}let l=jo(t,e,i,n,a,c),f=c.resolve?.(l,d=>n(o,"TAG_RESOLVE_FAILED",d),e.options)??l,u=Xm.isNode(f)?f:new Qm.Scalar(f);return u.range=l.range,u.tag=a,c?.format&&(u.format=c.format),u}Jc.composeCollection=np});var $o=v(Yc=>{"use strict";var Lo=O();function op(t,e,i){let r=e.offset,n=ap(e,t.options.strict,i);if(!n)return{value:"",type:null,comment:"",range:[r,r,r]};let o=n.mode===">"?Lo.Scalar.BLOCK_FOLDED:Lo.Scalar.BLOCK_LITERAL,a=e.source?sp(e.source):[],s=a.length;for(let h=a.length-1;h>=0;--h){let p=a[h][1];if(p===""||p==="\r")s=h;else break}if(s===0){let h=n.chomp==="+"&&a.length>0?` `.repeat(Math.max(1,a.length-1)):"",p=r+n.length;return e.source&&(p+=e.source.length),{value:h,type:o,comment:n.comment,range:[r,p,p]}}let c=e.indent+n.indent,l=e.offset+n.length,f=0;for(let h=0;hc&&(c=p.length);else{p.length=s;--h)a[h][0].length>c&&(s=h+1);let u="",d="",m=!1;for(let h=0;hc||y[0]===" "?(d===" "?d=` @@ -84,41 +84,41 @@ ${l} `+a[h][0].slice(c);u[u.length-1]!==` `&&(u+=` `);break;default:u+=` -`}let w=r+n.length+e.source.length;return{value:u,type:o,comment:n.comment,range:[r,w,w]}}function op({offset:t,props:e},i,r){if(e[0].type!=="block-scalar-header")return r(e[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:n}=e[0],o=n[0],a=0,s="",c=-1;for(let d=1;d{"use strict";var Do=O(),sp=dt();function cp(t,e,i){let{offset:r,type:n,source:o,end:a}=t,s,c,l=(d,m,w)=>i(r+d,m,w);switch(n){case"scalar":s=Do.Scalar.PLAIN,c=lp(o,l);break;case"single-quoted-scalar":s=Do.Scalar.QUOTE_SINGLE,c=up(o,l);break;case"double-quoted-scalar":s=Do.Scalar.QUOTE_DOUBLE,c=fp(o,l);break;default:return i(t,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${n}`),{value:"",type:null,comment:"",range:[r,r+o.length,r+o.length]}}let f=r+o.length,u=sp.resolveEnd(a,f,e,i);return{value:c,type:s,comment:u.comment,range:[r,f,u.offset]}}function lp(t,e){let i="";switch(t[0]){case" ":i="a tab character";break;case",":i="flow indicator character ,";break;case"%":i="directive indicator character %";break;case"|":case">":{i=`block scalar indicator ${t[0]}`;break}case"@":case"`":{i=`reserved character ${t[0]}`;break}}return i&&e(0,"BAD_SCALAR_START",`Plain value cannot start with ${i}`),Xc(t)}function up(t,e){return(t[t.length-1]!=="'"||t.length===1)&&e(t.length,"MISSING_CHAR","Missing closing 'quote"),Xc(t.slice(1,-1)).replace(/''/g,"'")}function Xc(t){let e,i;try{e=new RegExp(`(.*?)(?{"use strict";var Do=O(),cp=dt();function lp(t,e,i){let{offset:r,type:n,source:o,end:a}=t,s,c,l=(d,m,w)=>i(r+d,m,w);switch(n){case"scalar":s=Do.Scalar.PLAIN,c=up(o,l);break;case"single-quoted-scalar":s=Do.Scalar.QUOTE_SINGLE,c=fp(o,l);break;case"double-quoted-scalar":s=Do.Scalar.QUOTE_DOUBLE,c=dp(o,l);break;default:return i(t,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${n}`),{value:"",type:null,comment:"",range:[r,r+o.length,r+o.length]}}let f=r+o.length,u=cp.resolveEnd(a,f,e,i);return{value:c,type:s,comment:u.comment,range:[r,f,u.offset]}}function up(t,e){let i="";switch(t[0]){case" ":i="a tab character";break;case",":i="flow indicator character ,";break;case"%":i="directive indicator character %";break;case"|":case">":{i=`block scalar indicator ${t[0]}`;break}case"@":case"`":{i=`reserved character ${t[0]}`;break}}return i&&e(0,"BAD_SCALAR_START",`Plain value cannot start with ${i}`),Xc(t)}function fp(t,e){return(t[t.length-1]!=="'"||t.length===1)&&e(t.length,"MISSING_CHAR","Missing closing 'quote"),Xc(t.slice(1,-1)).replace(/''/g,"'")}function Xc(t){let e,i;try{e=new RegExp(`(.*?)(?o?t.slice(o,r+1):n)}else i+=n}return(t[t.length-1]!=='"'||t.length===1)&&e(t.length,"MISSING_CHAR",'Missing closing "quote'),i}function dp(t,e){let i="",r=t[e+1];for(;(r===" "||r===" "||r===` +`)&&(i+=r>o?t.slice(o,r+1):n)}else i+=n}return(t[t.length-1]!=='"'||t.length===1)&&e(t.length,"MISSING_CHAR",'Missing closing "quote'),i}function hp(t,e){let i="",r=t[e+1];for(;(r===" "||r===" "||r===` `||r==="\r")&&!(r==="\r"&&t[e+2]!==` `);)r===` `&&(i+=` -`),e+=1,r=t[e+1];return i||(i=" "),{fold:i,offset:e}}var hp={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:` -`,r:"\r",t:" ",v:"\v",N:"…",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function mp(t,e,i,r){let n=t.substr(e,i),a=n.length===i&&/^[0-9a-fA-F]+$/.test(n)?parseInt(n,16):NaN;try{return String.fromCodePoint(a)}catch{let s=t.substr(e-2,i+2);return r(e-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),s}}Qc.resolveFlowScalar=cp});var tl=v(el=>{"use strict";var Me=C(),Zc=O(),pp=$o(),gp=Bo();function wp(t,e,i,r){let{value:n,type:o,comment:a,range:s}=e.type==="block-scalar"?pp.resolveBlockScalar(t,e,r):gp.resolveFlowScalar(e,t.options.strict,r),c=i?t.directives.tagName(i.source,u=>r(i,"TAG_RESOLVE_FAILED",u)):null,l;t.options.stringKeys&&t.atKey?l=t.schema[Me.SCALAR]:c?l=vp(t.schema,n,c,i,r):e.type==="scalar"?l=yp(t,n,e,r):l=t.schema[Me.SCALAR];let f;try{let u=l.resolve(n,d=>r(i??e,"TAG_RESOLVE_FAILED",d),t.options);f=Me.isScalar(u)?u:new Zc.Scalar(u)}catch(u){let d=u instanceof Error?u.message:String(u);r(i??e,"TAG_RESOLVE_FAILED",d),f=new Zc.Scalar(n)}return f.range=s,f.source=n,o&&(f.type=o),c&&(f.tag=c),l.format&&(f.format=l.format),a&&(f.comment=a),f}function vp(t,e,i,r,n){if(i==="!")return t[Me.SCALAR];let o=[];for(let s of t.tags)if(!s.collection&&s.tag===i)if(s.default&&s.test)o.push(s);else return s;for(let s of o)if(s.test?.test(e))return s;let a=t.knownTags[i];return a&&!a.collection?(t.tags.push(Object.assign({},a,{default:!1,test:void 0})),a):(n(r,"TAG_RESOLVE_FAILED",`Unresolved tag: ${i}`,i!=="tag:yaml.org,2002:str"),t[Me.SCALAR])}function yp({atKey:t,directives:e,schema:i},r,n,o){let a=i.tags.find(s=>(s.default===!0||t&&s.default==="key")&&s.test?.test(r))||i[Me.SCALAR];if(i.compat){let s=i.compat.find(c=>c.default&&c.test?.test(r))??i[Me.SCALAR];if(a.tag!==s.tag){let c=e.tagString(a.tag),l=e.tagString(s.tag),f=`Value may be parsed as either ${c} or ${l}`;o(n,"TAG_RESOLVE_FAILED",f,!0)}}return a}el.composeScalar=wp});var rl=v(il=>{"use strict";function bp(t,e,i){if(e){i??(i=e.length);for(let r=i-1;r>=0;--r){let n=e[r];switch(n.type){case"space":case"comment":case"newline":t-=n.source.length;continue}for(n=e[++r];n?.type==="space";)t+=n.source.length,n=e[++r];break}}return t}il.emptyScalarPosition=bp});var al=v(Fo=>{"use strict";var Np=Ot(),kp=C(),Sp=Uc(),nl=tl(),Ep=dt(),Cp=rl(),Pp={composeNode:ol,composeEmptyNode:Mo};function ol(t,e,i,r){let n=t.atKey,{spaceBefore:o,comment:a,anchor:s,tag:c}=i,l,f=!0;switch(e.type){case"alias":l=xp(t,e,r),(s||c)&&r(e,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=nl.composeScalar(t,e,c,r),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=Sp.composeCollection(Pp,t,e,i,r),s&&(l.anchor=s.source.substring(1))}catch(u){let d=u instanceof Error?u.message:String(u);r(e,"RESOURCE_EXHAUSTION",d)}break;default:{let u=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;r(e,"UNEXPECTED_TOKEN",u),f=!1}}return l??(l=Mo(t,e.offset,void 0,null,i,r)),s&&l.anchor===""&&r(s,"BAD_ALIAS","Anchor cannot be an empty string"),n&&t.options.stringKeys&&(!kp.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&r(c??e,"NON_STRING_KEY","With stringKeys, all keys must be strings"),o&&(l.spaceBefore=!0),a&&(e.type==="scalar"&&e.source===""?l.comment=a:l.commentBefore=a),t.options.keepSourceTokens&&f&&(l.srcToken=e),l}function Mo(t,e,i,r,{spaceBefore:n,comment:o,anchor:a,tag:s,end:c},l){let f={type:"scalar",offset:Cp.emptyScalarPosition(e,i,r),indent:-1,source:""},u=nl.composeScalar(t,f,s,l);return a&&(u.anchor=a.source.substring(1),u.anchor===""&&l(a,"BAD_ALIAS","Anchor cannot be an empty string")),n&&(u.spaceBefore=!0),o&&(u.comment=o,u.range[2]=c),u}function xp({options:t},{offset:e,source:i,end:r},n){let o=new Np.Alias(i.substring(1));o.source===""&&n(e,"BAD_ALIAS","Alias cannot be an empty string"),o.source.endsWith(":")&&n(e+i.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let a=e+i.length,s=Ep.resolveEnd(r,a,t.strict,n);return o.range=[e,a,s.offset],s.comment&&(o.comment=s.comment),o}Fo.composeEmptyNode=Mo;Fo.composeNode=ol});var ll=v(cl=>{"use strict";var Rp=Jt(),sl=al(),_p=dt(),Ap=Qt();function Tp(t,e,{offset:i,start:r,value:n,end:o},a){let s=Object.assign({_directives:e},t),c=new Rp.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},f=Ap.resolveProps(r,{indicator:"doc-start",next:n??o?.[0],offset:i,onError:a,parentIndent:0,startOnNewline:!0});f.found&&(c.directives.docStart=!0,n&&(n.type==="block-map"||n.type==="block-seq")&&!f.hasNewline&&a(f.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=n?sl.composeNode(l,n,f,a):sl.composeEmptyNode(l,f.end,r,null,f,a);let u=c.contents.range[2],d=_p.resolveEnd(o,u,!1,a);return d.comment&&(c.comment=d.comment),c.range=[i,u,d.offset],c}cl.composeDoc=Tp});var qo=v(dl=>{"use strict";var Op=ji("process"),Ip=Pn(),jp=Jt(),Zt=Xt(),ul=C(),Lp=ll(),$p=dt();function ei(t){if(typeof t=="number")return[t,t+1];if(Array.isArray(t))return t.length===2?t:[t[0],t[1]];let{offset:e,source:i}=t;return[e,e+(typeof i=="string"?i.length:1)]}function fl(t){let e="",i=!1,r=!1;for(let n=0;n{"use strict";var Me=C(),Zc=O(),gp=$o(),wp=Bo();function vp(t,e,i,r){let{value:n,type:o,comment:a,range:s}=e.type==="block-scalar"?gp.resolveBlockScalar(t,e,r):wp.resolveFlowScalar(e,t.options.strict,r),c=i?t.directives.tagName(i.source,u=>r(i,"TAG_RESOLVE_FAILED",u)):null,l;t.options.stringKeys&&t.atKey?l=t.schema[Me.SCALAR]:c?l=yp(t.schema,n,c,i,r):e.type==="scalar"?l=bp(t,n,e,r):l=t.schema[Me.SCALAR];let f;try{let u=l.resolve(n,d=>r(i??e,"TAG_RESOLVE_FAILED",d),t.options);f=Me.isScalar(u)?u:new Zc.Scalar(u)}catch(u){let d=u instanceof Error?u.message:String(u);r(i??e,"TAG_RESOLVE_FAILED",d),f=new Zc.Scalar(n)}return f.range=s,f.source=n,o&&(f.type=o),c&&(f.tag=c),l.format&&(f.format=l.format),a&&(f.comment=a),f}function yp(t,e,i,r,n){if(i==="!")return t[Me.SCALAR];let o=[];for(let s of t.tags)if(!s.collection&&s.tag===i)if(s.default&&s.test)o.push(s);else return s;for(let s of o)if(s.test?.test(e))return s;let a=t.knownTags[i];return a&&!a.collection?(t.tags.push(Object.assign({},a,{default:!1,test:void 0})),a):(n(r,"TAG_RESOLVE_FAILED",`Unresolved tag: ${i}`,i!=="tag:yaml.org,2002:str"),t[Me.SCALAR])}function bp({atKey:t,directives:e,schema:i},r,n,o){let a=i.tags.find(s=>(s.default===!0||t&&s.default==="key")&&s.test?.test(r))||i[Me.SCALAR];if(i.compat){let s=i.compat.find(c=>c.default&&c.test?.test(r))??i[Me.SCALAR];if(a.tag!==s.tag){let c=e.tagString(a.tag),l=e.tagString(s.tag),f=`Value may be parsed as either ${c} or ${l}`;o(n,"TAG_RESOLVE_FAILED",f,!0)}}return a}el.composeScalar=vp});var rl=v(il=>{"use strict";function Np(t,e,i){if(e){i??(i=e.length);for(let r=i-1;r>=0;--r){let n=e[r];switch(n.type){case"space":case"comment":case"newline":t-=n.source.length;continue}for(n=e[++r];n?.type==="space";)t+=n.source.length,n=e[++r];break}}return t}il.emptyScalarPosition=Np});var al=v(Fo=>{"use strict";var kp=Ot(),Sp=C(),Ep=Uc(),nl=tl(),Cp=dt(),Pp=rl(),xp={composeNode:ol,composeEmptyNode:Mo};function ol(t,e,i,r){let n=t.atKey,{spaceBefore:o,comment:a,anchor:s,tag:c}=i,l,f=!0;switch(e.type){case"alias":l=Rp(t,e,r),(s||c)&&r(e,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=nl.composeScalar(t,e,c,r),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=Ep.composeCollection(xp,t,e,i,r),s&&(l.anchor=s.source.substring(1))}catch(u){let d=u instanceof Error?u.message:String(u);r(e,"RESOURCE_EXHAUSTION",d)}break;default:{let u=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;r(e,"UNEXPECTED_TOKEN",u),f=!1}}return l??(l=Mo(t,e.offset,void 0,null,i,r)),s&&l.anchor===""&&r(s,"BAD_ALIAS","Anchor cannot be an empty string"),n&&t.options.stringKeys&&(!Sp.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&r(c??e,"NON_STRING_KEY","With stringKeys, all keys must be strings"),o&&(l.spaceBefore=!0),a&&(e.type==="scalar"&&e.source===""?l.comment=a:l.commentBefore=a),t.options.keepSourceTokens&&f&&(l.srcToken=e),l}function Mo(t,e,i,r,{spaceBefore:n,comment:o,anchor:a,tag:s,end:c},l){let f={type:"scalar",offset:Pp.emptyScalarPosition(e,i,r),indent:-1,source:""},u=nl.composeScalar(t,f,s,l);return a&&(u.anchor=a.source.substring(1),u.anchor===""&&l(a,"BAD_ALIAS","Anchor cannot be an empty string")),n&&(u.spaceBefore=!0),o&&(u.comment=o,u.range[2]=c),u}function Rp({options:t},{offset:e,source:i,end:r},n){let o=new kp.Alias(i.substring(1));o.source===""&&n(e,"BAD_ALIAS","Alias cannot be an empty string"),o.source.endsWith(":")&&n(e+i.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let a=e+i.length,s=Cp.resolveEnd(r,a,t.strict,n);return o.range=[e,a,s.offset],s.comment&&(o.comment=s.comment),o}Fo.composeEmptyNode=Mo;Fo.composeNode=ol});var ll=v(cl=>{"use strict";var _p=Jt(),sl=al(),Ap=dt(),Tp=Qt();function Op(t,e,{offset:i,start:r,value:n,end:o},a){let s=Object.assign({_directives:e},t),c=new _p.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},f=Tp.resolveProps(r,{indicator:"doc-start",next:n??o?.[0],offset:i,onError:a,parentIndent:0,startOnNewline:!0});f.found&&(c.directives.docStart=!0,n&&(n.type==="block-map"||n.type==="block-seq")&&!f.hasNewline&&a(f.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=n?sl.composeNode(l,n,f,a):sl.composeEmptyNode(l,f.end,r,null,f,a);let u=c.contents.range[2],d=Ap.resolveEnd(o,u,!1,a);return d.comment&&(c.comment=d.comment),c.range=[i,u,d.offset],c}cl.composeDoc=Op});var qo=v(dl=>{"use strict";var Ip=ji("process"),jp=Pn(),Lp=Jt(),Zt=Xt(),ul=C(),$p=ll(),Dp=dt();function ei(t){if(typeof t=="number")return[t,t+1];if(Array.isArray(t))return t.length===2?t:[t[0],t[1]];let{offset:e,source:i}=t;return[e,e+(typeof i=="string"?i.length:1)]}function fl(t){let e="",i=!1,r=!1;for(let n=0;n{let a=ei(i);o?this.warnings.push(new Zt.YAMLWarning(a,r,n)):this.errors.push(new Zt.YAMLParseError(a,r,n))},this.directives=new Ip.Directives({version:e.version||"1.2"}),this.options=e}decorate(e,i){let{comment:r,afterEmptyLine:n}=fl(this.prelude);if(r){let o=e.contents;if(i)e.comment=e.comment?`${e.comment} +`)+(o.substring(1)||" "),i=!0,r=!1;break;case"%":t[n+1]?.[0]!=="#"&&(n+=1),i=!1;break;default:i||(r=!0),i=!1}}return{comment:e,afterEmptyLine:r}}var Wo=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(i,r,n,o)=>{let a=ei(i);o?this.warnings.push(new Zt.YAMLWarning(a,r,n)):this.errors.push(new Zt.YAMLParseError(a,r,n))},this.directives=new jp.Directives({version:e.version||"1.2"}),this.options=e}decorate(e,i){let{comment:r,afterEmptyLine:n}=fl(this.prelude);if(r){let o=e.contents;if(i)e.comment=e.comment?`${e.comment} ${r}`:r;else if(n||e.directives.docStart||!o)e.commentBefore=r;else if(ul.isCollection(o)&&!o.flow&&o.items.length>0){let a=o.items[0];ul.isPair(a)&&(a=a.key);let s=a.commentBefore;a.commentBefore=s?`${r} ${s}`:r}else{let a=o.commentBefore;o.commentBefore=a?`${r} -${a}`:r}}if(i){for(let o=0;o{let o=ei(e);o[0]+=i,this.onError(o,"BAD_DIRECTIVE",r,n)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let i=Lp.composeDoc(this.options,this.directives,e,this.onError);this.atDirectives&&!i.directives.docStart&&this.onError(e,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(i,!1),this.doc&&(yield this.doc),this.doc=i,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(e.source);break;case"error":{let i=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,r=new Zt.YAMLParseError(ei(e),"UNEXPECTED_TOKEN",i);this.atDirectives||!this.doc?this.errors.push(r):this.doc.errors.push(r);break}case"doc-end":{if(!this.doc){let r="Unexpected doc-end without preceding document";this.errors.push(new Zt.YAMLParseError(ei(e),"UNEXPECTED_TOKEN",r));break}this.doc.directives.docEnd=!0;let i=$p.resolveEnd(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),i.comment){let r=this.doc.comment;this.doc.comment=r?`${r} -${i.comment}`:i.comment}this.doc.range[2]=i.offset;break}default:this.errors.push(new Zt.YAMLParseError(ei(e),"UNEXPECTED_TOKEN",`Unsupported token ${e.type}`))}}*end(e=!1,i=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let r=Object.assign({_directives:this.directives},this.options),n=new jp.Document(void 0,r);this.atDirectives&&this.onError(i,"MISSING_CHAR","Missing directives-end indicator line"),n.range=[0,i,i],this.decorate(n,!1),yield n}}};dl.Composer=Wo});var pl=v(Cr=>{"use strict";var Dp=$o(),Bp=Bo(),Mp=Xt(),hl=Dt();function Fp(t,e=!0,i){if(t){let r=(n,o,a)=>{let s=typeof n=="number"?n:Array.isArray(n)?n[0]:n.offset;if(i)i(s,o,a);else throw new Mp.YAMLParseError([s,s+1],o,a)};switch(t.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return Bp.resolveFlowScalar(t,e,r);case"block-scalar":return Dp.resolveBlockScalar({options:{strict:e}},t,r)}}return null}function Wp(t,e){let{implicitKey:i=!1,indent:r,inFlow:n=!1,offset:o=-1,type:a="PLAIN"}=e,s=hl.stringifyString({type:a,value:t},{implicitKey:i,indent:r>0?" ".repeat(r):"",inFlow:n,options:{blockQuote:!0,lineWidth:-1}}),c=e.end??[{type:"newline",offset:-1,indent:r,source:` +${a}`:r}}if(i){for(let o=0;o{let o=ei(e);o[0]+=i,this.onError(o,"BAD_DIRECTIVE",r,n)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let i=$p.composeDoc(this.options,this.directives,e,this.onError);this.atDirectives&&!i.directives.docStart&&this.onError(e,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(i,!1),this.doc&&(yield this.doc),this.doc=i,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(e.source);break;case"error":{let i=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,r=new Zt.YAMLParseError(ei(e),"UNEXPECTED_TOKEN",i);this.atDirectives||!this.doc?this.errors.push(r):this.doc.errors.push(r);break}case"doc-end":{if(!this.doc){let r="Unexpected doc-end without preceding document";this.errors.push(new Zt.YAMLParseError(ei(e),"UNEXPECTED_TOKEN",r));break}this.doc.directives.docEnd=!0;let i=Dp.resolveEnd(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),i.comment){let r=this.doc.comment;this.doc.comment=r?`${r} +${i.comment}`:i.comment}this.doc.range[2]=i.offset;break}default:this.errors.push(new Zt.YAMLParseError(ei(e),"UNEXPECTED_TOKEN",`Unsupported token ${e.type}`))}}*end(e=!1,i=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let r=Object.assign({_directives:this.directives},this.options),n=new Lp.Document(void 0,r);this.atDirectives&&this.onError(i,"MISSING_CHAR","Missing directives-end indicator line"),n.range=[0,i,i],this.decorate(n,!1),yield n}}};dl.Composer=Wo});var pl=v(Cr=>{"use strict";var Bp=$o(),Mp=Bo(),Fp=Xt(),hl=Dt();function Wp(t,e=!0,i){if(t){let r=(n,o,a)=>{let s=typeof n=="number"?n:Array.isArray(n)?n[0]:n.offset;if(i)i(s,o,a);else throw new Fp.YAMLParseError([s,s+1],o,a)};switch(t.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return Mp.resolveFlowScalar(t,e,r);case"block-scalar":return Bp.resolveBlockScalar({options:{strict:e}},t,r)}}return null}function qp(t,e){let{implicitKey:i=!1,indent:r,inFlow:n=!1,offset:o=-1,type:a="PLAIN"}=e,s=hl.stringifyString({type:a,value:t},{implicitKey:i,indent:r>0?" ".repeat(r):"",inFlow:n,options:{blockQuote:!0,lineWidth:-1}}),c=e.end??[{type:"newline",offset:-1,indent:r,source:` `}];switch(s[0]){case"|":case">":{let l=s.indexOf(` `),f=s.substring(0,l),u=s.substring(l+1)+` `,d=[{type:"block-scalar-header",offset:o,indent:r,source:f}];return ml(d,c)||d.push({type:"newline",offset:-1,indent:r,source:` -`}),{type:"block-scalar",offset:o,indent:r,props:d,source:u}}case'"':return{type:"double-quoted-scalar",offset:o,indent:r,source:s,end:c};case"'":return{type:"single-quoted-scalar",offset:o,indent:r,source:s,end:c};default:return{type:"scalar",offset:o,indent:r,source:s,end:c}}}function qp(t,e,i={}){let{afterKey:r=!1,implicitKey:n=!1,inFlow:o=!1,type:a}=i,s="indent"in t?t.indent:null;if(r&&typeof s=="number"&&(s+=2),!a)switch(t.type){case"single-quoted-scalar":a="QUOTE_SINGLE";break;case"double-quoted-scalar":a="QUOTE_DOUBLE";break;case"block-scalar":{let l=t.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");a=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:a="PLAIN"}let c=hl.stringifyString({type:a,value:e},{implicitKey:n||s===null,indent:s!==null&&s>0?" ".repeat(s):"",inFlow:o,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":Hp(t,c);break;case'"':Ho(t,c,"double-quoted-scalar");break;case"'":Ho(t,c,"single-quoted-scalar");break;default:Ho(t,c,"scalar")}}function Hp(t,e){let i=e.indexOf(` +`}),{type:"block-scalar",offset:o,indent:r,props:d,source:u}}case'"':return{type:"double-quoted-scalar",offset:o,indent:r,source:s,end:c};case"'":return{type:"single-quoted-scalar",offset:o,indent:r,source:s,end:c};default:return{type:"scalar",offset:o,indent:r,source:s,end:c}}}function Hp(t,e,i={}){let{afterKey:r=!1,implicitKey:n=!1,inFlow:o=!1,type:a}=i,s="indent"in t?t.indent:null;if(r&&typeof s=="number"&&(s+=2),!a)switch(t.type){case"single-quoted-scalar":a="QUOTE_SINGLE";break;case"double-quoted-scalar":a="QUOTE_DOUBLE";break;case"block-scalar":{let l=t.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");a=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:a="PLAIN"}let c=hl.stringifyString({type:a,value:e},{implicitKey:n||s===null,indent:s!==null&&s>0?" ".repeat(s):"",inFlow:o,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":Gp(t,c);break;case'"':Ho(t,c,"double-quoted-scalar");break;case"'":Ho(t,c,"single-quoted-scalar");break;default:Ho(t,c,"scalar")}}function Gp(t,e){let i=e.indexOf(` `),r=e.substring(0,i),n=e.substring(i+1)+` `;if(t.type==="block-scalar"){let o=t.props[0];if(o.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o.source=r,t.source=n}else{let{offset:o}=t,a="indent"in t?t.indent:-1,s=[{type:"block-scalar-header",offset:o,indent:a,source:r}];ml(s,"end"in t?t.end:void 0)||s.push({type:"newline",offset:-1,indent:a,source:` `});for(let c of Object.keys(t))c!=="type"&&c!=="offset"&&delete t[c];Object.assign(t,{type:"block-scalar",indent:a,props:s,source:n})}}function ml(t,e){if(e)for(let i of e)switch(i.type){case"space":case"comment":t.push(i);break;case"newline":return t.push(i),!0}return!1}function Ho(t,e,i){switch(t.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":t.type=i,t.source=e;break;case"block-scalar":{let r=t.props.slice(1),n=e.length;t.props[0].type==="block-scalar-header"&&(n-=t.props[0].source.length);for(let o of r)o.offset+=n;delete t.props,Object.assign(t,{type:i,source:e,end:r});break}case"block-map":case"block-seq":{let n={type:"newline",offset:t.offset+e.length,indent:t.indent,source:` -`};delete t.items,Object.assign(t,{type:i,source:e,end:[n]});break}default:{let r="indent"in t?t.indent:-1,n="end"in t&&Array.isArray(t.end)?t.end.filter(o=>o.type==="space"||o.type==="comment"||o.type==="newline"):[];for(let o of Object.keys(t))o!=="type"&&o!=="offset"&&delete t[o];Object.assign(t,{type:i,indent:r,source:e,end:n})}}}Cr.createScalarToken=Wp;Cr.resolveAsScalar=Fp;Cr.setScalarValue=qp});var wl=v(gl=>{"use strict";var Gp=t=>"type"in t?xr(t):Pr(t);function xr(t){switch(t.type){case"block-scalar":{let e="";for(let i of t.props)e+=xr(i);return e+t.source}case"block-map":case"block-seq":{let e="";for(let i of t.items)e+=Pr(i);return e}case"flow-collection":{let e=t.start.source;for(let i of t.items)e+=Pr(i);for(let i of t.end)e+=i.source;return e}case"document":{let e=Pr(t);if(t.end)for(let i of t.end)e+=i.source;return e}default:{let e=t.source;if("end"in t&&t.end)for(let i of t.end)e+=i.source;return e}}}function Pr({start:t,key:e,sep:i,value:r}){let n="";for(let o of t)n+=o.source;if(e&&(n+=xr(e)),i)for(let o of i)n+=o.source;return r&&(n+=xr(r)),n}gl.stringify=Gp});var Nl=v(bl=>{"use strict";var Go=Symbol("break visit"),zp=Symbol("skip children"),vl=Symbol("remove item");function Fe(t,e){"type"in t&&t.type==="document"&&(t={start:t.start,value:t.value}),yl(Object.freeze([]),t,e)}Fe.BREAK=Go;Fe.SKIP=zp;Fe.REMOVE=vl;Fe.itemAtPath=(t,e)=>{let i=t;for(let[r,n]of e){let o=i?.[r];if(o&&"items"in o)i=o.items[n];else return}return i};Fe.parentCollection=(t,e)=>{let i=Fe.itemAtPath(t,e.slice(0,-1)),r=e[e.length-1][0],n=i?.[r];if(n&&"items"in n)return n;throw new Error("Parent collection not found")};function yl(t,e,i){let r=i(e,t);if(typeof r=="symbol")return r;for(let n of["key","value"]){let o=e[n];if(o&&"items"in o){for(let a=0;a{"use strict";var zo=pl(),Vp=wl(),Kp=Nl(),Vo="\uFEFF",Ko="",Jo="",Uo="",Jp=t=>!!t&&"items"in t,Up=t=>!!t&&(t.type==="scalar"||t.type==="single-quoted-scalar"||t.type==="double-quoted-scalar"||t.type==="block-scalar");function Yp(t){switch(t){case Vo:return"";case Ko:return"";case Jo:return"";case Uo:return"";default:return JSON.stringify(t)}}function Xp(t){switch(t){case Vo:return"byte-order-mark";case Ko:return"doc-mode";case Jo:return"flow-error-end";case Uo:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case` +`};delete t.items,Object.assign(t,{type:i,source:e,end:[n]});break}default:{let r="indent"in t?t.indent:-1,n="end"in t&&Array.isArray(t.end)?t.end.filter(o=>o.type==="space"||o.type==="comment"||o.type==="newline"):[];for(let o of Object.keys(t))o!=="type"&&o!=="offset"&&delete t[o];Object.assign(t,{type:i,indent:r,source:e,end:n})}}}Cr.createScalarToken=qp;Cr.resolveAsScalar=Wp;Cr.setScalarValue=Hp});var wl=v(gl=>{"use strict";var zp=t=>"type"in t?xr(t):Pr(t);function xr(t){switch(t.type){case"block-scalar":{let e="";for(let i of t.props)e+=xr(i);return e+t.source}case"block-map":case"block-seq":{let e="";for(let i of t.items)e+=Pr(i);return e}case"flow-collection":{let e=t.start.source;for(let i of t.items)e+=Pr(i);for(let i of t.end)e+=i.source;return e}case"document":{let e=Pr(t);if(t.end)for(let i of t.end)e+=i.source;return e}default:{let e=t.source;if("end"in t&&t.end)for(let i of t.end)e+=i.source;return e}}}function Pr({start:t,key:e,sep:i,value:r}){let n="";for(let o of t)n+=o.source;if(e&&(n+=xr(e)),i)for(let o of i)n+=o.source;return r&&(n+=xr(r)),n}gl.stringify=zp});var Nl=v(bl=>{"use strict";var Go=Symbol("break visit"),Vp=Symbol("skip children"),vl=Symbol("remove item");function Fe(t,e){"type"in t&&t.type==="document"&&(t={start:t.start,value:t.value}),yl(Object.freeze([]),t,e)}Fe.BREAK=Go;Fe.SKIP=Vp;Fe.REMOVE=vl;Fe.itemAtPath=(t,e)=>{let i=t;for(let[r,n]of e){let o=i?.[r];if(o&&"items"in o)i=o.items[n];else return}return i};Fe.parentCollection=(t,e)=>{let i=Fe.itemAtPath(t,e.slice(0,-1)),r=e[e.length-1][0],n=i?.[r];if(n&&"items"in n)return n;throw new Error("Parent collection not found")};function yl(t,e,i){let r=i(e,t);if(typeof r=="symbol")return r;for(let n of["key","value"]){let o=e[n];if(o&&"items"in o){for(let a=0;a{"use strict";var zo=pl(),Kp=wl(),Jp=Nl(),Vo="\uFEFF",Ko="",Jo="",Uo="",Up=t=>!!t&&"items"in t,Yp=t=>!!t&&(t.type==="scalar"||t.type==="single-quoted-scalar"||t.type==="double-quoted-scalar"||t.type==="block-scalar");function Xp(t){switch(t){case Vo:return"";case Ko:return"";case Jo:return"";case Uo:return"";default:return JSON.stringify(t)}}function Qp(t){switch(t){case Vo:return"byte-order-mark";case Ko:return"doc-mode";case Jo:return"flow-error-end";case Uo:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case` `:case`\r -`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(t[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}q.createScalarToken=zo.createScalarToken;q.resolveAsScalar=zo.resolveAsScalar;q.setScalarValue=zo.setScalarValue;q.stringify=Vp.stringify;q.visit=Kp.visit;q.BOM=Vo;q.DOCUMENT=Ko;q.FLOW_END=Jo;q.SCALAR=Uo;q.isCollection=Jp;q.isScalar=Up;q.prettyToken=Yp;q.tokenType=Xp});var Qo=v(Sl=>{"use strict";var ti=Rr();function ee(t){switch(t){case void 0:case" ":case` -`:case"\r":case" ":return!0;default:return!1}}var kl=new Set("0123456789ABCDEFabcdef"),Qp=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),_r=new Set(",[]{}"),Zp=new Set(` ,[]{} -\r `),Yo=t=>!t||Zp.has(t),Xo=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,i=!1){if(e){if(typeof e!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!i;let r=this.next??"stream";for(;r&&(i||this.hasChars(1));)r=yield*this.parseNext(r)}atLineEnd(){let e=this.pos,i=this.buffer[e];for(;i===" "||i===" ";)i=this.buffer[++e];return!i||i==="#"||i===` +`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(t[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}q.createScalarToken=zo.createScalarToken;q.resolveAsScalar=zo.resolveAsScalar;q.setScalarValue=zo.setScalarValue;q.stringify=Kp.stringify;q.visit=Jp.visit;q.BOM=Vo;q.DOCUMENT=Ko;q.FLOW_END=Jo;q.SCALAR=Uo;q.isCollection=Up;q.isScalar=Yp;q.prettyToken=Xp;q.tokenType=Qp});var Qo=v(Sl=>{"use strict";var ti=Rr();function ee(t){switch(t){case void 0:case" ":case` +`:case"\r":case" ":return!0;default:return!1}}var kl=new Set("0123456789ABCDEFabcdef"),Zp=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),_r=new Set(",[]{}"),eg=new Set(` ,[]{} +\r `),Yo=t=>!t||eg.has(t),Xo=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,i=!1){if(e){if(typeof e!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!i;let r=this.next??"stream";for(;r&&(i||this.hasChars(1));)r=yield*this.parseNext(r)}atLineEnd(){let e=this.pos,i=this.buffer[e];for(;i===" "||i===" ";)i=this.buffer[++e];return!i||i==="#"||i===` `?!0:i==="\r"?this.buffer[e+1]===` `:!1}charAt(e){return this.buffer[this.pos+e]}continueScalar(e){let i=this.buffer[e];if(this.indentNext>0){let r=0;for(;i===" ";)i=this.buffer[++r+e];if(i==="\r"){let n=this.buffer[r+e+1];if(n===` `||!n&&!this.atEnd)return e+r+1}return i===` @@ -133,34 +133,34 @@ ${i.comment}`:i.comment}this.doc.range[2]=i.offset;break}default:this.errors.pus `&&o>=this.pos&&o+1+i>s)e=o;else break}while(!0);return yield ti.SCALAR,yield*this.pushToIndex(e+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let e=this.flowLevel>0,i=this.pos-1,r=this.pos-1,n;for(;n=this.buffer[++r];)if(n===":"){let o=this.buffer[r+1];if(ee(o)||e&&_r.has(o))break;i=r}else if(ee(n)){let o=this.buffer[r+1];if(n==="\r"&&(o===` `?(r+=1,n=` `,o=this.buffer[r+1]):i=r),o==="#"||e&&_r.has(o))break;if(n===` -`){let a=this.continueScalar(r+1);if(a===-1)break;r=Math.max(r,a-2)}}else{if(e&&_r.has(n))break;i=r}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield ti.SCALAR,yield*this.pushToIndex(i+1,!0),e?"flow":"doc")}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,i){let r=this.buffer.slice(this.pos,e);return r?(yield r,this.pos+=r.length,r.length):(i&&(yield""),0)}*pushIndicators(){let e=0;e:for(;;){switch(this.charAt(0)){case"!":e+=yield*this.pushTag(),e+=yield*this.pushSpaces(!0);continue e;case"&":e+=yield*this.pushUntil(Yo),e+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let i=this.flowLevel>0,r=this.charAt(1);if(ee(r)||i&&_r.has(r)){i?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,e+=yield*this.pushCount(1),e+=yield*this.pushSpaces(!0);continue e}}}break e}return e}*pushTag(){if(this.charAt(1)==="<"){let e=this.pos+2,i=this.buffer[e];for(;!ee(i)&&i!==">";)i=this.buffer[++e];return yield*this.pushToIndex(i===">"?e+1:e,!1)}else{let e=this.pos+1,i=this.buffer[e];for(;i;)if(Qp.has(i))i=this.buffer[++e];else if(i==="%"&&kl.has(this.buffer[e+1])&&kl.has(this.buffer[e+2]))i=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];return e===` +`){let a=this.continueScalar(r+1);if(a===-1)break;r=Math.max(r,a-2)}}else{if(e&&_r.has(n))break;i=r}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield ti.SCALAR,yield*this.pushToIndex(i+1,!0),e?"flow":"doc")}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,i){let r=this.buffer.slice(this.pos,e);return r?(yield r,this.pos+=r.length,r.length):(i&&(yield""),0)}*pushIndicators(){let e=0;e:for(;;){switch(this.charAt(0)){case"!":e+=yield*this.pushTag(),e+=yield*this.pushSpaces(!0);continue e;case"&":e+=yield*this.pushUntil(Yo),e+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let i=this.flowLevel>0,r=this.charAt(1);if(ee(r)||i&&_r.has(r)){i?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,e+=yield*this.pushCount(1),e+=yield*this.pushSpaces(!0);continue e}}}break e}return e}*pushTag(){if(this.charAt(1)==="<"){let e=this.pos+2,i=this.buffer[e];for(;!ee(i)&&i!==">";)i=this.buffer[++e];return yield*this.pushToIndex(i===">"?e+1:e,!1)}else{let e=this.pos+1,i=this.buffer[e];for(;i;)if(Zp.has(i))i=this.buffer[++e];else if(i==="%"&&kl.has(this.buffer[e+1])&&kl.has(this.buffer[e+2]))i=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];return e===` `?yield*this.pushCount(1):e==="\r"&&this.charAt(1)===` -`?yield*this.pushCount(2):0}*pushSpaces(e){let i=this.pos-1,r;do r=this.buffer[++i];while(r===" "||e&&r===" ");let n=i-this.pos;return n>0&&(yield this.buffer.substr(this.pos,n),this.pos=i),n}*pushUntil(e){let i=this.pos,r=this.buffer[i];for(;!e(r);)r=this.buffer[++i];return yield*this.pushToIndex(i,!1)}};Sl.Lexer=Xo});var ea=v(El=>{"use strict";var Zo=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let i=0,r=this.lineStarts.length;for(;i>1;this.lineStarts[o]{"use strict";var eg=ji("process"),Cl=Rr(),tg=Qo();function _e(t,e){for(let i=0;i=0;)switch(t[e].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;t[++e]?.type==="space";);return t.splice(e,t.length)}function Tr(t,e){if(e.length<1e5)Array.prototype.push.apply(t,e);else for(let i=0;i0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let e=this.peek(1);if(this.type==="doc-end"&&e?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!e)return yield*this.stream();switch(e.type){case"document":return yield*this.document(e);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(e);case"block-scalar":return yield*this.blockScalar(e);case"block-map":return yield*this.blockMap(e);case"block-seq":return yield*this.blockSequence(e);case"flow-collection":return yield*this.flowCollection(e);case"doc-end":return yield*this.documentEnd(e)}yield*this.pop()}peek(e){return this.stack[this.stack.length-e]}*pop(e){let i=e??this.stack.pop();if(!i)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield i;else{let r=this.peek(1);switch(i.type==="block-scalar"?i.indent="indent"in r?r.indent:0:i.type==="flow-collection"&&r.type==="document"&&(i.indent=0),i.type==="flow-collection"&&xl(i),r.type){case"document":r.value=i;break;case"block-scalar":r.props.push(i);break;case"block-map":{let n=r.items[r.items.length-1];if(n.value){r.items.push({start:[],key:i,sep:[]}),this.onKeyLine=!0;return}else if(n.sep)n.value=i;else{Object.assign(n,{key:i,sep:[]}),this.onKeyLine=!n.explicitKey;return}break}case"block-seq":{let n=r.items[r.items.length-1];n.value?r.items.push({start:[],value:i}):n.value=i;break}case"flow-collection":{let n=r.items[r.items.length-1];!n||n.value?r.items.push({start:[],key:i,sep:[]}):n.sep?n.value=i:Object.assign(n,{key:i,sep:[]});return}default:yield*this.pop(),yield*this.pop(i)}if((r.type==="document"||r.type==="block-map"||r.type==="block-seq")&&(i.type==="block-map"||i.type==="block-seq")){let n=i.items[i.items.length-1];n&&!n.sep&&!n.value&&n.start.length>0&&Pl(n.start)===-1&&(i.indent===0||n.start.every(o=>o.type!=="comment"||o.indent0&&(yield this.buffer.substr(this.pos,n),this.pos=i),n}*pushUntil(e){let i=this.pos,r=this.buffer[i];for(;!e(r);)r=this.buffer[++i];return yield*this.pushToIndex(i,!1)}};Sl.Lexer=Xo});var ea=v(El=>{"use strict";var Zo=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let i=0,r=this.lineStarts.length;for(;i>1;this.lineStarts[o]{"use strict";var tg=ji("process"),Cl=Rr(),ig=Qo();function _e(t,e){for(let i=0;i=0;)switch(t[e].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;t[++e]?.type==="space";);return t.splice(e,t.length)}function Tr(t,e){if(e.length<1e5)Array.prototype.push.apply(t,e);else for(let i=0;i0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let e=this.peek(1);if(this.type==="doc-end"&&e?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!e)return yield*this.stream();switch(e.type){case"document":return yield*this.document(e);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(e);case"block-scalar":return yield*this.blockScalar(e);case"block-map":return yield*this.blockMap(e);case"block-seq":return yield*this.blockSequence(e);case"flow-collection":return yield*this.flowCollection(e);case"doc-end":return yield*this.documentEnd(e)}yield*this.pop()}peek(e){return this.stack[this.stack.length-e]}*pop(e){let i=e??this.stack.pop();if(!i)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield i;else{let r=this.peek(1);switch(i.type==="block-scalar"?i.indent="indent"in r?r.indent:0:i.type==="flow-collection"&&r.type==="document"&&(i.indent=0),i.type==="flow-collection"&&xl(i),r.type){case"document":r.value=i;break;case"block-scalar":r.props.push(i);break;case"block-map":{let n=r.items[r.items.length-1];if(n.value){r.items.push({start:[],key:i,sep:[]}),this.onKeyLine=!0;return}else if(n.sep)n.value=i;else{Object.assign(n,{key:i,sep:[]}),this.onKeyLine=!n.explicitKey;return}break}case"block-seq":{let n=r.items[r.items.length-1];n.value?r.items.push({start:[],value:i}):n.value=i;break}case"flow-collection":{let n=r.items[r.items.length-1];!n||n.value?r.items.push({start:[],key:i,sep:[]}):n.sep?n.value=i:Object.assign(n,{key:i,sep:[]});return}default:yield*this.pop(),yield*this.pop(i)}if((r.type==="document"||r.type==="block-map"||r.type==="block-seq")&&(i.type==="block-map"||i.type==="block-seq")){let n=i.items[i.items.length-1];n&&!n.sep&&!n.value&&n.start.length>0&&Pl(n.start)===-1&&(i.indent===0||n.start.every(o=>o.type!=="comment"||o.indent=e.indent){let r=!this.onKeyLine&&this.indent===e.indent,n=r&&(i.sep||i.explicitKey)&&this.type!=="seq-item-ind",o=[];if(n&&i.sep&&!i.value){let a=[];for(let s=0;se.indent&&(a.length=0);break;default:a.length=0}}a.length>=2&&(o=i.sep.splice(a[1]))}switch(this.type){case"anchor":case"tag":n||i.value?(o.push(this.sourceToken),e.items.push({start:o}),this.onKeyLine=!0):i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"explicit-key-ind":!i.sep&&!i.explicitKey?(i.start.push(this.sourceToken),i.explicitKey=!0):n||i.value?(o.push(this.sourceToken),e.items.push({start:o,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(i.explicitKey)if(i.sep)if(i.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(_e(i.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]});else if(Rl(i.key)&&!_e(i.sep,"newline")){let a=ht(i.start),s=i.key,c=i.sep;c.push(this.sourceToken),delete i.key,delete i.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:a,key:s,sep:c}]})}else o.length>0?i.sep=i.sep.concat(o,this.sourceToken):i.sep.push(this.sourceToken);else if(_e(i.start,"newline"))Object.assign(i,{key:null,sep:[this.sourceToken]});else{let a=ht(i.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:a,key:null,sep:[this.sourceToken]}]})}else i.sep?i.value||n?e.items.push({start:o,key:null,sep:[this.sourceToken]}):_e(i.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):i.sep.push(this.sourceToken):Object.assign(i,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let a=this.flowScalar(this.type);n||i.value?(e.items.push({start:o,key:a,sep:[]}),this.onKeyLine=!0):i.sep?this.stack.push(a):(Object.assign(i,{key:a,sep:[]}),this.onKeyLine=!0);return}default:{let a=this.startBlockValue(e);if(a){if(a.type==="block-seq"){if(!i.explicitKey&&i.sep&&!_e(i.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else r&&e.items.push({start:o});this.stack.push(a);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let i=e.items[e.items.length-1];switch(this.type){case"newline":if(i.value){let r="end"in i.value?i.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else i.start.push(this.sourceToken);return;case"space":case"comment":if(i.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(i.start,e.indent)){let n=e.items[e.items.length-2]?.value?.end;if(Array.isArray(n)){Tr(n,i.start),n.push(this.sourceToken),e.items.pop();return}}i.start.push(this.sourceToken)}return;case"anchor":case"tag":if(i.value||this.indent<=e.indent)break;i.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;i.value||_e(i.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):i.start.push(this.sourceToken);return}if(this.indent>e.indent){let r=this.startBlockValue(e);if(r){this.stack.push(r);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let i=e.items[e.items.length-1];if(this.type==="flow-error-end"){let r;do yield*this.pop(),r=this.peek(1);while(r?.type==="flow-collection")}else if(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!i||i.sep?e.items.push({start:[this.sourceToken]}):i.start.push(this.sourceToken);return;case"map-value-ind":!i||i.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):i.sep?i.sep.push(this.sourceToken):Object.assign(i,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!i||i.value?e.items.push({start:[this.sourceToken]}):i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let n=this.flowScalar(this.type);!i||i.value?e.items.push({start:[],key:n,sep:[]}):i.sep?this.stack.push(n):Object.assign(i,{key:n,sep:[]});return}case"flow-map-end":case"flow-seq-end":e.end.push(this.sourceToken);return}let r=this.startBlockValue(e);r?this.stack.push(r):(yield*this.pop(),yield*this.step())}else{let r=this.peek(2);if(r.type==="block-map"&&(this.type==="map-value-ind"&&r.indent===e.indent||this.type==="newline"&&!r.items[r.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&r.type!=="flow-collection"){let n=Ar(r),o=ht(n);xl(e);let a=e.end.splice(1,e.end.length);a.push(this.sourceToken);let s={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:o,key:e,sep:a}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let i=this.source.indexOf(` `)+1;for(;i!==0;)this.onNewLine(this.offset+i),i=this.source.indexOf(` -`,i)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let i=Ar(e),r=ht(i);return r.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let i=Ar(e),r=ht(i);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,i){return this.type!=="comment"||this.indent<=i?!1:e.every(r=>r.type==="newline"||r.type==="space")}*documentEnd(e){this.type!=="doc-mode"&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};_l.Parser=ta});var jl=v(ri=>{"use strict";var Al=qo(),ig=Jt(),ii=Xt(),rg=Mn(),ng=C(),og=ea(),Tl=ia();function Ol(t){let e=t.prettyErrors!==!1;return{lineCounter:t.lineCounter||e&&new og.LineCounter||null,prettyErrors:e}}function ag(t,e={}){let{lineCounter:i,prettyErrors:r}=Ol(e),n=new Tl.Parser(i?.addNewLine),o=new Al.Composer(e),a=Array.from(o.compose(n.parse(t)));if(r&&i)for(let s of a)s.errors.forEach(ii.prettifyError(t,i)),s.warnings.forEach(ii.prettifyError(t,i));return a.length>0?a:Object.assign([],{empty:!0},o.streamInfo())}function Il(t,e={}){let{lineCounter:i,prettyErrors:r}=Ol(e),n=new Tl.Parser(i?.addNewLine),o=new Al.Composer(e),a=null;for(let s of o.compose(n.parse(t),!0,t.length))if(!a)a=s;else if(a.options.logLevel!=="silent"){a.errors.push(new ii.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return r&&i&&(a.errors.forEach(ii.prettifyError(t,i)),a.warnings.forEach(ii.prettifyError(t,i))),a}function sg(t,e,i){let r;typeof e=="function"?r=e:i===void 0&&e&&typeof e=="object"&&(i=e);let n=Il(t,i);if(!n)return null;if(n.warnings.forEach(o=>rg.warn(n.options.logLevel,o)),n.errors.length>0){if(n.options.logLevel!=="silent")throw n.errors[0];n.errors=[]}return n.toJS(Object.assign({reviver:r},i))}function cg(t,e,i){let r=null;if(typeof e=="function"||Array.isArray(e)?r=e:i===void 0&&e&&(i=e),typeof i=="string"&&(i=i.length),typeof i=="number"){let n=Math.round(i);i=n<1?void 0:n>8?{indent:8}:{indent:n}}if(t===void 0){let{keepUndefined:n}=i??e??{};if(!n)return}return ng.isDocument(t)&&!r?t.toString(i):new ig.Document(t,r,i).toString(i)}ri.parse=sg;ri.parseAllDocuments=ag;ri.parseDocument=Il;ri.stringify=cg});var mt=v(x=>{"use strict";var lg=qo(),ug=Jt(),fg=ko(),ra=Xt(),dg=Ot(),Ae=C(),hg=Ce(),mg=O(),pg=xe(),gg=Re(),wg=Rr(),vg=Qo(),yg=ea(),bg=ia(),Or=jl(),Ll=Rt();x.Composer=lg.Composer;x.Document=ug.Document;x.Schema=fg.Schema;x.YAMLError=ra.YAMLError;x.YAMLParseError=ra.YAMLParseError;x.YAMLWarning=ra.YAMLWarning;x.Alias=dg.Alias;x.isAlias=Ae.isAlias;x.isCollection=Ae.isCollection;x.isDocument=Ae.isDocument;x.isMap=Ae.isMap;x.isNode=Ae.isNode;x.isPair=Ae.isPair;x.isScalar=Ae.isScalar;x.isSeq=Ae.isSeq;x.Pair=hg.Pair;x.Scalar=mg.Scalar;x.YAMLMap=pg.YAMLMap;x.YAMLSeq=gg.YAMLSeq;x.CST=wg;x.Lexer=vg.Lexer;x.LineCounter=yg.LineCounter;x.Parser=bg.Parser;x.parse=Or.parse;x.parseAllDocuments=Or.parseAllDocuments;x.parseDocument=Or.parseDocument;x.stringify=Or.stringify;x.visit=Ll.visit;x.visitAsync=Ll.visitAsync});import Ir from"path";function kg(t,e){if(typeof t!="string")throw new Error(`${e} must be a string`);let i=t.trim();if(i.length===0||Ir.posix.isAbsolute(i)||Ir.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${e} must be a project-relative path`);if(i===".")return[];let r=i.replaceAll("\\","/").split("/");if(r.some(n=>n===".."))throw new Error(`${e} must stay inside the project root`);if(r.some(n=>n===""||n==="."))throw new Error(`${e} must not contain empty or dot path segments`);return r}function pt(t){let e=kg(t,"native.artifact_root");return e.length===0?".":e.join("/")}function Bl(t,e="docs"){let i=t??e;if(i!=="legacy"&&i!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return i}function ai(t,e,i=!1){if(typeof t!="string")throw new Error(`${e} must be a string`);let r=t.trim().replaceAll("\\","/");if(r.length===0||Ir.posix.isAbsolute(r)||Ir.win32.isAbsolute(r)||/^(?:~|[\\/])/u.test(r))throw new Error(`${e} must be relative to its declared path base`);let n=r.split("/");if(n.some(o=>o===".."))throw new Error(`${e} must stay inside its declared path base`);if(n.some(o=>o===""||o==="."))throw new Error(`${e} must not contain empty or dot path segments`);if(!i&&/[*?]/u.test(r))throw new Error(`${e} cannot contain wildcards`);return n.join("/")}function ni(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function Ml(t,e,i){let r=t??e;if(r!=="en"&&r!=="zh-CN")throw new Error(`${i} must be en or zh-CN`);return r}function $r(t,e){if(typeof t!="string"||t.length===0||t.includes("\\")||t.includes("\0")||t.startsWith("/")||t.split("/").includes(".."))throw new Error(`${e} contains an unsafe pattern`);if(t.length>jr)throw new Error(`${e} exceeds ${jr} characters`);let i=0;for(let r=0;rLr)throw new Error(`${e} contains more than ${Lr} wildcard tokens`);return t}function $l(t,e,i){if(t===void 0)return[...i];if(!Array.isArray(t))throw new Error(`${e} contains an unsafe pattern`);return[...new Set(t.map(r=>$r(r,e)))].sort((r,n)=>r.localeCompare(n,"en"))}function na(t,e,i){let r=t??e;if(!Number.isSafeInteger(r)||r<1)throw new Error(`${i} must be a positive integer`);return r}function Sg(t){if(t===void 0)return{...le,include:[...le.include],exclude:[...le.exclude]};let e=ni(t,"native.snapshot");return{include:$l(e.include,"native.snapshot.include",le.include),exclude:$l(e.exclude,"native.snapshot.exclude",le.exclude),max_files:na(e.max_files,le.max_files,"native.snapshot.max_files"),max_total_bytes:na(e.max_total_bytes,le.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:na(e.max_duration_ms,le.max_duration_ms,"native.snapshot.max_duration_ms")}}function Eg(t){if(t===void 0)return;let e=ni(t,"native.pending_root_move"),i=e.id,r=e.from_artifact_root,n=e.to_artifact_root,o=e.stage;if(typeof i!="string"||!/^[a-f0-9-]{8,}$/u.test(i))throw new Error("native.pending_root_move.id is invalid");if(typeof r!="string"||typeof n!="string")throw new Error("native.pending_root_move roots must be strings");if(o!=="copying"&&o!=="ready"&&o!=="switched")throw new Error("native.pending_root_move.stage is invalid");let a;if(e.cleanup!==void 0){let s=ni(e.cleanup,"native.pending_root_move.cleanup"),c=s.kind,l=s.state,f=s.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof f!="string"||!/^[a-f0-9]{64}$/u.test(f))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");a={kind:c,state:l,manifestHash:f}}return{id:i,fromArtifactRoot:pt(r),toArtifactRoot:pt(n),stage:o,...a?{cleanup:a}:{}}}function Cg(t,e={}){let i=ni(t,"native"),r=i.artifact_root??(e.allowMissingArtifactRoot?"docs":void 0);if(typeof r!="string")throw new Error("native.artifact_root must be a string");let n=i.clarification_mode??"sequential";if(n!=="sequential"&&n!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let o=i.archive_confirmation??"automatic";if(o!=="automatic"&&o!=="required")throw new Error("native.archive_confirmation must be automatic or required");let a=i.max_verify_failures??Dl;if(!Number.isSafeInteger(a)||a<1)throw new Error("native.max_verify_failures must be a positive integer");let s=Eg(i.pending_root_move);return{artifact_root:pt(r),language:Ml(i.language,"en","native.language"),clarification_mode:n,archive_confirmation:o,max_verify_failures:a,snapshot:Sg(i.snapshot),...s?{pending_root_move:s}:{}}}function Pg(t){let e=ni(t,"classic"),i=e.context_compression??"off";if(i!=="off"&&i!=="beta")throw new Error("classic.context_compression must be off or beta");let r=e.review_mode??"standard";if(r!=="off"&&r!=="standard"&&r!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let n=e.auto_transition??!0;if(typeof n!="boolean")throw new Error("classic.auto_transition must be true or false");return{artifact_layout:Bl(e.artifact_layout),language:Ml(e.language,"zh-CN","classic.language"),context_compression:i,review_mode:r,auto_transition:n}}function xg(t){let e=t??!0;if(typeof e!="boolean")throw new Error("ambient_resume must be true or false");return e}function Rg(t,e,i,r,n){let o=t.schema!==void 0;if(!(o||t.default_workflow!==void 0||t.workflows!==void 0||!n.allowPartialProject&&t.native!==void 0)||n.allowPartialProject&&!o)return null;if(t.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(t.default_workflow!=="native"&&t.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let s=t.workflows??[t.default_workflow];if(!Array.isArray(s)||s.length===0||s.some(l=>l!=="native"&&l!=="classic"))throw new Error("workflows must contain native and/or classic");let c=[...new Set(s)];if(!c.includes(t.default_workflow))throw new Error("workflows must include default_workflow");if(c.includes("native")&&!e)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:t.default_workflow,workflows:c,ambient_resume:r,...e?{native:e}:{},...i?{classic:i}:{}}}function gt(t,e={}){let i=(0,oa.parseDocument)(t,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${i.errors[0].message}`);let r=i.toJS();if(r==null)return{value:{},config:null,ambient_resume:!0};if(typeof r!="object"||Array.isArray(r))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let n=r,o=xg(n.ambient_resume),a=n.native===void 0?void 0:Cg(n.native,{allowMissingArtifactRoot:e.allowMissingNativeFields}),s=n.classic===void 0?void 0:Pg(n.classic),c=Rg(n,a,s,o,{allowPartialProject:e.allowPartialProject??!1});return{value:n,config:c,ambient_resume:o,...a?{native:a}:{},...s?{classic:s}:{}}}var oa,oi,jr,Lr,Dl,Ng,le,ue=M(()=>{"use strict";oa=xt(mt(),1),oi=64*1024,jr=1024,Lr=64,Dl=5,Ng=[".agents/skills/**",".amazonq/skills/**",".augment/skills/**",".bob/skills/**",".claude/skills/**",".cline/skills/**",".codebuddy/skills/**",".continue/skills/**",".cospec/skills/**",".crush/skills/**",".cursor/skills/**",".factory/skills/**",".forge/skills/**",".gemini/skills/**",".github/skills/**",".iflow/skills/**",".junie/skills/**",".kilocode/skills/**",".kimi-code/skills/**",".kiro/skills/**",".lingma/skills/**",".mimocode/skills/**",".opencode/skills/**",".pi/skills/**",".qoder/skills/**",".qwen/skills/**",".roo/skills/**",".trae-cn/skills/**",".trae/skills/**",".windsurf/skills/**",".zcode/skills/**"],le={include:["**/*"],exclude:[...Ng],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4}});function Te(t){return t!==0&&t!==0n&&t!=="0"}function fe(t,e){return Te(t.dev)&&Te(e.dev)&&Te(t.ino)&&Te(e.ino)}function T(t,e){let i=Te(t.dev)&&Te(e.dev);if(i&&t.dev!==e.dev)return!1;let r=Te(t.ino)&&Te(e.ino);return r&&t.ino!==e.ino?!1:i&&r?!0:t.birthtime===e.birthtime}var fi=M(()=>{"use strict"});import{constants as Dr,promises as We}from"fs";function ua(t){return"birthtimeNs"in t&&typeof t.birthtimeNs=="bigint"?t.birthtimeNs:t.birthtimeMs}function Wl(t){return"ctimeNs"in t&&typeof t.ctimeNs=="bigint"?t.ctimeNs:t.ctimeMs}function di(t){return{dev:t.dev,ino:t.ino,birthtime:ua(t)}}function Br(t,e){let i=di(t),r=di(e);return fe(i,r)?T(i,r):T(i,r)&&ua(t)===ua(e)&&Wl(t)===Wl(e)&&t.size===e.size}async function hi(t,e,i={}){if(!Number.isSafeInteger(e)||e<1)throw new Error("race-safe read byte limit must be a positive integer");let r=i.label??"file",n=i.bigint===!0,o=await We.lstat(t,{bigint:n});if(!o.isFile()||o.isSymbolicLink())throw new ge("not-regular-file",`${r} must be a regular file`);if(BigInt(o.size)>BigInt(e))throw new ge("too-large",`${r} exceeds ${e} bytes`);let a=await We.realpath(t);await i.verify?.("pre-open",{realPath:a,identity:di(o)});let s=process.platform==="win32"?Dr.O_RDONLY:Dr.O_RDONLY|Dr.O_NOFOLLOW|Dr.O_NONBLOCK,c;try{c=await We.open(t,s)}catch(l){throw l.code==="ELOOP"?new ge("not-regular-file",`${r} must be a regular file`,{cause:l}):l}try{let[l,f,u]=await Promise.all([c.stat({bigint:n}),We.lstat(t,{bigint:n}),We.realpath(t)]);if(!l.isFile()||!f.isFile()||f.isSymbolicLink()||u!==a||!Br(o,l)||!Br(o,f))throw new ge("changed",`${r} changed while opening`);await i.verify?.("post-open",{realPath:u,identity:di(l)}),await i.hooks?.afterOpen?.();let d=[],m=0,w=Buffer.allocUnsafe(Math.min(64*1024,e+1));for(;;){let b=e+1-m,{bytesRead:k}=await c.read(w,0,Math.min(w.length,b),null);if(k===0)break;if(m+=k,m>e)throw new ge("too-large",`${r} exceeds ${e} bytes`);d.push(Buffer.from(w.subarray(0,k)))}await i.hooks?.beforeFinalCheck?.();let[h,p,y]=await Promise.all([c.stat({bigint:n}),We.lstat(t,{bigint:n}),We.realpath(t)]);if(!p.isFile()||p.isSymbolicLink()||y!==a||!Br(o,h)||!Br(o,p))throw new ge("changed",`${r} changed while reading`);return await i.verify?.("post-read",{realPath:y,identity:di(h)}),{bytes:Buffer.concat(d,m),stat:h,realPath:y}}finally{await c.close()}}var ge,Mr=M(()=>{"use strict";fi();ge=class extends Error{reason;constructor(e,i,r){super(i,r),this.name="RaceSafeReadError",this.reason=e}}});import{promises as Fr}from"fs";import Oe from"path";function jg(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}function fa(t,e){let i=Oe.relative(t,e);return i===""||!Oe.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Oe.sep}`)}async function ql(t,e){let i=Oe.resolve(t),r=await Fr.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${e} project root must be a real directory`);return Fr.realpath(i)}async function Hl(t,e,i,r){let n=t;for(let o=0;o{if(!fa(o,s.realPath))throw new Error(`${r.label} resolves outside the project root`);await Hl(n.projectRoot,o,n.relative.split("/"),{label:r.label,expected:"file"})}})}var we=M(()=>{"use strict";Mr();ue()});import{createHash as Lg}from"crypto";function $g(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function qe(t,e={}){return(await pi(t,e)).document}async function Dg(t){try{return(await te(t,mi,oi,{label:mi})).bytes}catch(e){if($g(e))return null;throw e}}function Bg(t){return t?{exists:!0,sha256:Lg("sha256").update(t).digest("hex")}:{exists:!1,sha256:null}}async function pi(t,e={}){let i=await Dg(t);return{document:i?gt(i.toString("utf8"),e):null,identity:Bg(i)}}async function da(t){return(await qe(t))?.config??null}var mi,He=M(()=>{"use strict";ue();we();mi=".comet/config.yaml"});import{randomUUID as Mg}from"crypto";import{constants as Fg,promises as I}from"fs";import B from"path";async function ha(t,e){try{return await I.link(t,e),{linked:!0}}catch(i){let r=i.code;if(r!=="ENOTSUP"&&r!=="EOPNOTSUPP")throw i}return await I.copyFile(t,e,Fg.COPYFILE_EXCL),{linked:!1}}function yt(t,e){let i=B.relative(t,e);return i===""||!B.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${B.sep}`)}function qr(t){return{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs}}function Wg(t,e){return T(t,qr(e))}function Wr(t,e){let i=qr(t),r=qr(e);return fe(i,r)?T(i,r):T(i,r)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.size===e.size}async function Hr(t){let e=await I.lstat(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Contained atomic write parent must be a real directory: ${t}`);return{path:t,realPath:await I.realpath(t),...qr(e)}}async function Ie(t){for(let e of t){let i=await I.lstat(e.path);if(!i.isDirectory()||i.isSymbolicLink()||!Wg(e,i)||await I.realpath(e.path)!==e.realPath)throw new Error(`Contained atomic write parent changed before commit: ${e.path}`)}}async function qg(t,e){let i=B.resolve(t),r=B.resolve(e);if(!yt(i,r))throw new Error(`Contained atomic write parent is outside its managed root: ${e}`);let n=[await Hr(i)],o=B.relative(i,r).split(B.sep).filter(Boolean),a=i;for(let s of o){await Ie(n),a=B.join(a,s);try{await I.mkdir(a)}catch(l){if(l.code!=="EEXIST")throw l}let c=await Hr(a);if(!yt(n[0].realPath,c.realPath))throw new Error(`Contained atomic write parent resolves outside its managed root: ${a}`);n.push(c)}return await Ie(n),n}async function Hg(t,e){let i=B.resolve(t),r=B.resolve(e);if(!yt(i,r))throw new Error(`Contained file parent is outside its managed root: ${e}`);let n=[await Hr(i)],o=B.relative(i,r).split(B.sep).filter(Boolean),a=i;for(let s of o){a=B.join(a,s);try{let c=await Hr(a);if(!yt(n[0].realPath,c.realPath))throw new Error(`Contained file parent resolves outside its managed root: ${a}`);n.push(c)}catch(c){if(c.code==="ENOENT")return null;throw c}}return await Ie(n),n}async function Gl(t){let e;try{e=await I.open(t,"r"),await e.sync()}catch(i){let r=i.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(r??""))throw i}finally{await e?.close()}}async function Gg(t,e,i){let r=B.dirname(t),n=await qg(i.containedRoot,r),o=B.join(r,`.${B.basename(t)}.${Mg()}.tmp`),a,s;try{await i.beforeTemporaryOpen?.(),a=await I.open(o,"wx"),s=await a.stat();let[c,l]=await Promise.all([I.lstat(o),I.realpath(o)]);if(await Ie(n),!c.isFile()||c.isSymbolicLink()||!Wr(s,c)||!yt(n[0].realPath,l))throw new Error("Contained atomic write temporary file opened outside its managed parent");if(typeof e=="string"?await a.writeFile(e,"utf8"):await a.writeFile(e),await a.sync(),!Wr(s,await a.stat()))throw new Error("Contained atomic write temporary file changed while writing");await a.close(),a=void 0,await i.beforeCommit?.(),await Ie(n);let f=await I.lstat(o);if(!f.isFile()||f.isSymbolicLink()||!Wr(f,s))throw new Error("Contained atomic write temporary file changed before commit");i.exclusive?(await ha(o,t),await I.unlink(o)):await I.rename(o,t),await Gl(r)}catch(c){await a?.close();try{await Ie(n),await I.rm(o,{force:!0})}catch{}throw c}}async function ve(t,e,i){await Gg(t,e,i)}async function ma(t,e){let i=B.dirname(t),r=await Hg(e.containedRoot,i);if(!r)return!1;let n,o;try{n=await I.lstat(t),o=await I.realpath(t)}catch(c){if(c.code==="ENOENT")return!1;throw c}if(!n.isFile()||n.isSymbolicLink()||!yt(r[0].realPath,o))throw new Error("Contained file removal target must be a regular file inside its managed root");await e.beforeRemove?.(),await Ie(r);let[a,s]=await Promise.all([I.lstat(t),I.realpath(t)]);if(!a.isFile()||a.isSymbolicLink()||!Wr(n,a)||s!==o)throw new Error("Contained file removal target changed before removal");return await I.unlink(t),await Ie(r),await Gl(i),!0}var Ge=M(()=>{"use strict";fi()});var vk,pa=M(()=>{"use strict";Ge();He();we();vk=16*1024});var zr=M(()=>{"use strict";Ge();ue();He();we();pa()});var Xr=M(()=>{"use strict"});var du=M(()=>{"use strict"});var Ra=M(()=>{"use strict";Xr()});var hu=M(()=>{"use strict";Xr();Ra()});var Iw,pu=M(()=>{"use strict";Iw=xt(mt(),1);Ge();ue();we()});var gu=M(()=>{"use strict";Xr();Ge();du();hu();ue();pu();we();He();zr();pa();Ra()});import{TextDecoder as Lw}from"util";function wu(t){return{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs}}function $w(t,e){try{return new Lw("utf-8",{fatal:!0}).decode(t.bytes)}catch(i){throw new Error(`${e} is not valid UTF-8`,{cause:i})}}async function _a(t,e,i,r,n={}){try{let o=await te(t,e,i,{label:r,hooks:n.hooks});return{result:o,text:$w(o,r)}}catch(o){let a=o.code;if(a==="ENOENT"||a==="ENOTDIR")return null;throw o}}async function vu(t,e,i,r,n={}){return(await _a(t,e,i,r,n))?.text??null}async function yu(t,e,i,r,n,o={}){if(Buffer.byteLength(i,"utf8")>r)throw new Error(`${n} exceeds ${r} bytes`);let a=await _a(t,e,r,n),s=await H(t,e,{label:n,expected:"file"});await ve(s.target,i,{containedRoot:s.projectRoot,beforeCommit:async()=>{await o.beforeCommit?.();let c=await _a(t,e,r,n);if(!(!a&&!c)){if(!a||!c)throw new Error(`${n} changed before commit`);if(a.result.realPath!==c.result.realPath||!T(wu(a.result.stat),wu(c.result.stat))||a.text!==c.text)throw new Error(`${n} changed before commit`)}}})}async function bu(t,e,i,r={}){let n=await H(t,e,{label:i,expected:"file"});return n.exists?ma(n.target,{containedRoot:n.projectRoot,beforeRemove:r.beforeRemove}):!1}var Nu=M(()=>{"use strict";gu();fi()});var Pu={};Vf(Pu,{RUN_STATE_FILE:()=>Qr,applyRunStateToDocument:()=>Su,readRunState:()=>Aa,removeRunState:()=>Cu,runStateFromDocument:()=>Si,writeRunState:()=>Ta});import Dw from"path";function ki(t,e){let i=t[e];if(typeof i!="string"||i.length===0)throw new Error(`Invalid Run state: ${e} must be a non-empty string`);return i}function Ni(t,e){let i=ki(t,e);if(Dw.isAbsolute(i)||/^(?:[A-Za-z]:|[\\/]|~)/u.test(i)||i.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Run state: ${e} must stay inside the change directory`);return i}function Bw(t){let e=t.run_retries??"{}",i;try{i=typeof e=="string"?JSON.parse(e):e}catch(r){throw new Error("Invalid Run state: run_retries must be a JSON object",{cause:r})}if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Invalid Run state: run_retries must be a JSON object");for(let r of Object.values(i))if(!Number.isInteger(r)||Number(r)<0)throw new Error("Invalid Run state: retry counts must be non-negative integers");return i}function Si(t){if(!t.run_id)return null;let e=ki(t,"run_id"),i=ki(t,"skill"),r=ki(t,"skill_version"),n=ki(t,"skill_hash"),o=Ni(t,"pending_ref"),a=Ni(t,"trajectory_ref"),s=Ni(t,"context_ref"),c=Ni(t,"artifacts_ref"),l=Ni(t,"checkpoint_ref"),f=Number(t.iteration);if(!Number.isInteger(f)||f<0)throw new Error("Invalid Run state: iteration must be a non-negative integer");if(t.orchestration!=="deterministic"&&t.orchestration!=="adaptive")throw new Error("Invalid Run state: orchestration must be deterministic or adaptive");if(t.run_status!=="running"&&t.run_status!=="waiting"&&t.run_status!=="completed"&&t.run_status!=="failed")throw new Error("Invalid Run state: run_status is invalid");return{runId:e,skill:i,skillVersion:r,skillHash:n,orchestration:t.orchestration,currentStep:ku(t,"current_step"),iteration:f,pending:ku(t,"pending"),pendingRef:o,trajectoryRef:a,contextRef:s,artifactsRef:c,checkpointRef:l,status:t.run_status,retries:Bw(t)}}function Su(t,e){e?t.run_id=e.runId:delete t.run_id}function Mw(t){return{runId:t.runId,skill:t.skill,skillVersion:t.skillVersion,skillHash:t.skillHash,orchestration:t.orchestration,currentStep:t.currentStep,iteration:t.iteration,pending:t.pending,pendingRef:t.pendingRef,trajectoryRef:t.trajectoryRef,contextRef:t.contextRef,artifactsRef:t.artifactsRef,checkpointRef:t.checkpointRef,status:t.status,retries:t.retries}}function Fw(t){let e={run_id:t.runId,skill:t.skill,skill_version:t.skillVersion,skill_hash:t.skillHash,orchestration:t.orchestration,current_step:t.currentStep,iteration:t.iteration,pending:t.pending,pending_ref:t.pendingRef,trajectory_ref:t.trajectoryRef,context_ref:t.contextRef,artifacts_ref:t.artifactsRef,checkpoint_ref:t.checkpointRef,run_status:t.status,run_retries:JSON.stringify(t.retries)};return Si(e)}async function Aa(t,e={}){let i=await vu(t,Qr,Eu,"Run state",e);if(i===null)return null;let r=JSON.parse(i);return Fw(r)}async function Ta(t,e,i={}){await yu(t,Qr,JSON.stringify(Mw(e),null,2),Eu,"Run state",i)}async function Cu(t,e={}){await bu(t,Qr,"Run state",e)}var ku,Qr,Eu,Ei=M(()=>{"use strict";Nu();ku=(t,e)=>{let i=t[e];return i==null?null:String(i)};Qr=".comet/run-state.json",Eu=256*1024});import Ff from"path";import{promises as Mf}from"fs";ue();import{promises as wt}from"fs";import R from"path";import _g from"os";var sa=".comet/config.yaml";async function aa(t){try{return await wt.lstat(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function Ag(t){try{let e=await wt.readFile(t,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(e)}catch(e){if(e.code==="ENOENT")return!1;throw e}}function si(t,e){let i=R.relative(t,e);return i===""||!R.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${R.sep}`)}async function ci(t){let e=[],i=t;for(;!await aa(i);){let n=R.dirname(i);if(n===i)break;e.push(R.basename(i)),i=n}let r=await wt.realpath(i);return R.resolve(r,...e.reverse())}async function Fl(t){try{return(await wt.lstat(t)).isSymbolicLink()}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function li(t){let e=R.resolve(t);try{(await wt.stat(e)).isDirectory()||(e=R.dirname(e))}catch(n){if(n.code!=="ENOENT")throw n}let i=e,r=R.resolve(_g.homedir());for(;;){if(!(e===r&&i!==r)){let a=R.join(e,...sa.split("/")),s=e===i||await Ag(a);if(await aa(a)&&s)return e}if(await aa(R.join(e,".git")))return e;let o=R.dirname(e);if(o===e)return i;e=o}}function ca(t){return pt(t)}async function Tg(t,e){let i=ca(e),r=R.resolve(t,...i.split("/")),n=await wt.realpath(t),o=await ci(r);if(!si(n,o))throw new Error("native.artifact_root resolves outside the project root");return r}async function la(t,e){let i=ca(e),r=await Tg(t,i),n=R.join(r,"comet");if(await Fl(n))throw new Error("The configured Native comet root must not be a symbolic link");let[o,a]=await Promise.all([ci(r),ci(n)]);if(!si(o,a))throw new Error("The configured Native comet root resolves outside its artifact root");return{projectRoot:R.resolve(t),configFile:R.join(t,...sa.split("/")),artifactRoot:r,artifactRootRef:i,nativeRoot:n,specsDir:R.join(n,"specs"),changesDir:R.join(n,"changes"),archiveDir:R.join(n,"archive"),runtimeDir:R.join(n,"runtime"),locksDir:R.join(n,"runtime","locks"),transactionsDir:R.join(n,"runtime","transactions")}}function vt(t,e){return si(R.resolve(t),R.resolve(e))}async function pe(t,e){let i=R.resolve(t),r=R.resolve(e);if(!si(i,r))throw new Error(`Path is outside the Native root: ${e}`);if(await Fl(i))throw new Error(`Native root must not be a symbolic link: ${t}`);let[n,o]=await Promise.all([ci(i),ci(r)]);if(!si(n,o))throw new Error(`Path resolves outside the Native root: ${e}`);return r}import{promises as Ug}from"fs";import A from"path";import{promises as Og}from"fs";async function ui(t){try{return await Og.access(t),!0}catch(e){if(Ig(e))return!1;throw e}}function Ig(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}ue();He();zr();we();var ze=class extends Error{code="classic-layout-unavailable";constructor(e="Classic artifact layout is unavailable from .comet/config.yaml"){super(e),this.name="ClassicLayoutUnavailableError"}},wa=class extends Error{constructor(i,r,n){let o=$(n,i),a=$(n,r);super(`Classic layout conflict: both ${o}/ and ${a}/ exist; run comet doctor and resolve the conflict before writing`);this.configuredRoot=i;this.alternateRoot=r;this.name="ClassicLayoutConflictError"}configuredRoot;alternateRoot;code="classic-layout-conflict"},Vl=".comet/config.yaml";function Yg(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function Kl(t){await H(t,Vl,{label:Vl,expected:"file"})}function Jl(t,e){let i=A.resolve(t),r=e==="docs"?A.join(i,"docs"):i,n=A.join(r,"openspec"),o=A.join(i,"docs","superpowers");return{projectRoot:i,artifactLayout:e,openSpecBase:r,openSpecRoot:n,changesDir:A.join(n,"changes"),archiveDir:A.join(n,"changes","archive"),specsDir:A.join(n,"specs"),superpowersRoot:o,superpowersSpecsDir:A.join(o,"specs"),superpowersPlansDir:A.join(o,"plans"),superpowersReportsDir:A.join(o,"reports")}}async function Xg(t){await Kl(t);let e=await qe(t,{allowPartialProject:!0,allowMissingNativeFields:!0});if(!e?.config)throw new ze;if(!(e.config.workflows??[e.config.default_workflow]).includes("classic"))throw new ze("Classic artifact layout is unavailable because Classic is not enabled");return e.classic?.artifact_layout??"legacy"}async function Qg(t,e){return Jl(t,e??await Xg(t))}async function Zg(t,e){let i=await Qg(t,e),r=i.artifactLayout==="legacy"?"docs":"legacy",n=Jl(t,r).openSpecRoot,[o,a]=await Promise.all([H(i.projectRoot,$(i.projectRoot,i.openSpecRoot),{label:"Configured Classic OpenSpec root",expected:"directory"}),H(i.projectRoot,$(i.projectRoot,n),{label:"Alternate Classic OpenSpec root",expected:"directory"})]),s=o.exists,c=a.exists;return{paths:i,configuredRootExists:s,alternateRoot:n,alternateRootExists:c,dualRoots:s&&c}}async function ew(t,e){let i=[t.openSpecRoot,t.changesDir,t.archiveDir,t.specsDir,e,t.superpowersRoot,t.superpowersSpecsDir,t.superpowersPlansDir,t.superpowersReportsDir];for(let r of i){let n=$(t.projectRoot,r);await H(t.projectRoot,n,{label:`Classic managed physical path ${n}`,expected:"directory"})}}async function ye(t,e,i={}){let r=await Zg(t,e);if(await ew(r.paths,r.alternateRoot),r.dualRoots&&!i.allowAlternateRoot)throw new wa(r.paths.openSpecRoot,r.alternateRoot,r.paths.projectRoot);if(!r.configuredRootExists){let n=$(r.paths.projectRoot,r.paths.openSpecRoot),o=$(r.paths.projectRoot,r.alternateRoot);throw new ze(`Configured Classic OpenSpec root is missing: ${n} (alternate ${o} is ${r.alternateRootExists?"present":"missing"})`)}return r.paths}async function Vr(t,e,i={}){let r=A.join(A.resolve(t),".comet","classic-root-move.json");if(await ui(r))throw new Error("Classic root move transaction is incomplete; inspect it with comet doctor and recover it explicitly before writing");let n=await ye(t,e,i);if(!await ui(n.openSpecRoot))throw new Error(`Configured Classic OpenSpec root is missing: ${$(n.projectRoot,n.openSpecRoot)}`);return n}async function Ul(t){let e=A.resolve(t),i=null;try{(await Ug.lstat(e)).isDirectory()||(e=A.dirname(e))}catch(r){if(!Yg(r))throw r}for(;;){A.basename(e)==="openspec"&&(i=A.dirname(e));let r=A.join(e,".comet","config.yaml"),n=!1;if(await ui(r))try{await Kl(e);let a=(await qe(e))?.value;n=!!a&&typeof a=="object"&&!Array.isArray(a)&&(a.schema==="comet.project.v1"||a.default_workflow!==void 0||a.native!==void 0)}catch{}if(n||await ui(A.join(e,".git")))return e;let o=A.dirname(e);if(o===e)return i??A.resolve(t);e=o}}function $(t,e){return A.relative(A.resolve(t),e).replaceAll("\\","/")}import{readFileSync as tw}from"fs";import Yl from"path";var iw=new Set(["applypatch","create","createfile","deletefile","edit","editfile","patch","strreplaceeditor","write","writefile","writefiletool"]),rw=new Set(["glob","grep","listfiles","read","readfile","search","view"]),Zl=["file_path","filePath","path","target_file","targetFile"],eu=["file_paths","filePaths","paths","files","targets"],tu=["operations","edits"],nw=["patch","diff","patchText","patch_text","changes"],va=new Set(["claude","codex","windsurf","github-copilot","gemini","amazon-q","qwen","kiro","codebuddy","qoder"]);function ya(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function Xl(t){return t.toLowerCase().replace(/[^a-z0-9]+/gu,"")}function ow(t){for(let e of["tool_name","toolName","tool","name"]){let i=t[e];if(typeof i=="string"&&i.trim())return i.trim()}return null}function aw(t){for(let e of["cwd","working_directory","workspaceRoot"]){let i=t[e];if(!(typeof i!="string"||!i.trim()||!Yl.isAbsolute(i.trim())))return Yl.resolve(i.trim())}}function sw(t){if(typeof t!="string")return t;let e=t.trim();if(!e.startsWith("{")&&!e.startsWith("["))return t;try{return JSON.parse(e)}catch{return t}}function cw(t){for(let e of["tool_input","toolInput","toolArgs","tool_args","arguments"])if(t[e]!==void 0)return sw(t[e]);return t}function Ql(t){let e=[],i=[/^\*\*\* (?:Add|Update|Delete) File:\s+(.+?)\s*$/gmu,/^\+\+\+\s+(?:b\/)?(.+?)\s*$/gmu];for(let r of i)for(let n of t.matchAll(r)){let o=n[1]?.trim();o&&o!=="/dev/null"&&e.push(o)}return e}function Ve(t,e){if(typeof e=="string"){let i=e.trim();i&&t.push(i);return}if(Array.isArray(e)){for(let i of e)Ve(t,i);return}if(ya(e)){for(let i of Zl)Ve(t,e[i]);for(let i of eu)Ve(t,e[i]);for(let i of tu)Ve(t,e[i])}}function lw(t,e){let i=[],r=[e,t].filter(ya);for(let n of r){for(let o of Zl)Ve(i,n[o]);for(let o of eu)Ve(i,n[o]);for(let o of tu)Ve(i,n[o]);for(let o of nw){let a=n[o];typeof a=="string"&&i.push(...Ql(a))}}return typeof e=="string"&&i.push(...Ql(e)),[...new Set(i)]}function gi(t,e){if(e?.trim())return{intent:"write",targets:[e.trim()],toolName:null};if(!t.trim())return{intent:"unknown",targets:[],toolName:null};let i;try{i=JSON.parse(t)}catch{return{intent:"unknown",targets:[],toolName:null}}if(!ya(i))return{intent:"unknown",targets:[],toolName:null};let r=ow(i),n=lw(i,cw(i)),o=aw(i);return r&&iw.has(Xl(r))?{intent:n.length>0?"write":"unknown",targets:n,toolName:r,...o?{cwd:o}:{}}:r&&rw.has(Xl(r))?{intent:"non-write",targets:[],toolName:r,...o?{cwd:o}:{}}:r?{intent:"unknown",targets:n,toolName:r,...o?{cwd:o}:{}}:{intent:n.length>0?"write":"unknown",targets:n,toolName:null,...o?{cwd:o}:{}}}function ba(){let t=process.env.FILE_PATH;if(t?.trim()||process.stdin.isTTY)return gi("",t);try{return gi(tw(0,"utf8"),t)}catch{return gi("",t)}}function iu(t,e){return va.has(t)?t==="github-copilot"?{exitCode:0,stdout:e.allowed?`{} +`,i)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let i=Ar(e),r=ht(i);return r.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let i=Ar(e),r=ht(i);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,i){return this.type!=="comment"||this.indent<=i?!1:e.every(r=>r.type==="newline"||r.type==="space")}*documentEnd(e){this.type!=="doc-mode"&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};_l.Parser=ta});var jl=v(ri=>{"use strict";var Al=qo(),rg=Jt(),ii=Xt(),ng=Mn(),og=C(),ag=ea(),Tl=ia();function Ol(t){let e=t.prettyErrors!==!1;return{lineCounter:t.lineCounter||e&&new ag.LineCounter||null,prettyErrors:e}}function sg(t,e={}){let{lineCounter:i,prettyErrors:r}=Ol(e),n=new Tl.Parser(i?.addNewLine),o=new Al.Composer(e),a=Array.from(o.compose(n.parse(t)));if(r&&i)for(let s of a)s.errors.forEach(ii.prettifyError(t,i)),s.warnings.forEach(ii.prettifyError(t,i));return a.length>0?a:Object.assign([],{empty:!0},o.streamInfo())}function Il(t,e={}){let{lineCounter:i,prettyErrors:r}=Ol(e),n=new Tl.Parser(i?.addNewLine),o=new Al.Composer(e),a=null;for(let s of o.compose(n.parse(t),!0,t.length))if(!a)a=s;else if(a.options.logLevel!=="silent"){a.errors.push(new ii.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return r&&i&&(a.errors.forEach(ii.prettifyError(t,i)),a.warnings.forEach(ii.prettifyError(t,i))),a}function cg(t,e,i){let r;typeof e=="function"?r=e:i===void 0&&e&&typeof e=="object"&&(i=e);let n=Il(t,i);if(!n)return null;if(n.warnings.forEach(o=>ng.warn(n.options.logLevel,o)),n.errors.length>0){if(n.options.logLevel!=="silent")throw n.errors[0];n.errors=[]}return n.toJS(Object.assign({reviver:r},i))}function lg(t,e,i){let r=null;if(typeof e=="function"||Array.isArray(e)?r=e:i===void 0&&e&&(i=e),typeof i=="string"&&(i=i.length),typeof i=="number"){let n=Math.round(i);i=n<1?void 0:n>8?{indent:8}:{indent:n}}if(t===void 0){let{keepUndefined:n}=i??e??{};if(!n)return}return og.isDocument(t)&&!r?t.toString(i):new rg.Document(t,r,i).toString(i)}ri.parse=cg;ri.parseAllDocuments=sg;ri.parseDocument=Il;ri.stringify=lg});var mt=v(x=>{"use strict";var ug=qo(),fg=Jt(),dg=ko(),ra=Xt(),hg=Ot(),Ae=C(),mg=Ce(),pg=O(),gg=xe(),wg=Re(),vg=Rr(),yg=Qo(),bg=ea(),Ng=ia(),Or=jl(),Ll=Rt();x.Composer=ug.Composer;x.Document=fg.Document;x.Schema=dg.Schema;x.YAMLError=ra.YAMLError;x.YAMLParseError=ra.YAMLParseError;x.YAMLWarning=ra.YAMLWarning;x.Alias=hg.Alias;x.isAlias=Ae.isAlias;x.isCollection=Ae.isCollection;x.isDocument=Ae.isDocument;x.isMap=Ae.isMap;x.isNode=Ae.isNode;x.isPair=Ae.isPair;x.isScalar=Ae.isScalar;x.isSeq=Ae.isSeq;x.Pair=mg.Pair;x.Scalar=pg.Scalar;x.YAMLMap=gg.YAMLMap;x.YAMLSeq=wg.YAMLSeq;x.CST=vg;x.Lexer=yg.Lexer;x.LineCounter=bg.LineCounter;x.Parser=Ng.Parser;x.parse=Or.parse;x.parseAllDocuments=Or.parseAllDocuments;x.parseDocument=Or.parseDocument;x.stringify=Or.stringify;x.visit=Ll.visit;x.visitAsync=Ll.visitAsync});import Ir from"path";function Sg(t,e){if(typeof t!="string")throw new Error(`${e} must be a string`);let i=t.trim();if(i.length===0||Ir.posix.isAbsolute(i)||Ir.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${e} must be a project-relative path`);if(i===".")return[];let r=i.replaceAll("\\","/").split("/");if(r.some(n=>n===".."))throw new Error(`${e} must stay inside the project root`);if(r.some(n=>n===""||n==="."))throw new Error(`${e} must not contain empty or dot path segments`);return r}function pt(t){let e=Sg(t,"native.artifact_root");return e.length===0?".":e.join("/")}function Bl(t,e="docs"){let i=t??e;if(i!=="legacy"&&i!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return i}function ai(t,e,i=!1){if(typeof t!="string")throw new Error(`${e} must be a string`);let r=t.trim().replaceAll("\\","/");if(r.length===0||Ir.posix.isAbsolute(r)||Ir.win32.isAbsolute(r)||/^(?:~|[\\/])/u.test(r))throw new Error(`${e} must be relative to its declared path base`);let n=r.split("/");if(n.some(o=>o===".."))throw new Error(`${e} must stay inside its declared path base`);if(n.some(o=>o===""||o==="."))throw new Error(`${e} must not contain empty or dot path segments`);if(!i&&/[*?]/u.test(r))throw new Error(`${e} cannot contain wildcards`);return n.join("/")}function ni(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function Ml(t,e,i){let r=t??e;if(r!=="en"&&r!=="zh-CN")throw new Error(`${i} must be en or zh-CN`);return r}function $r(t,e){if(typeof t!="string"||t.length===0||t.includes("\\")||t.includes("\0")||t.startsWith("/")||t.split("/").includes(".."))throw new Error(`${e} contains an unsafe pattern`);if(t.length>jr)throw new Error(`${e} exceeds ${jr} characters`);let i=0;for(let r=0;rLr)throw new Error(`${e} contains more than ${Lr} wildcard tokens`);return t}function $l(t,e,i){if(t===void 0)return[...i];if(!Array.isArray(t))throw new Error(`${e} contains an unsafe pattern`);return[...new Set(t.map(r=>$r(r,e)))].sort((r,n)=>r.localeCompare(n,"en"))}function na(t,e,i){let r=t??e;if(!Number.isSafeInteger(r)||r<1)throw new Error(`${i} must be a positive integer`);return r}function Eg(t){if(t===void 0)return{...le,include:[...le.include],exclude:[...le.exclude]};let e=ni(t,"native.snapshot");return{include:$l(e.include,"native.snapshot.include",le.include),exclude:$l(e.exclude,"native.snapshot.exclude",le.exclude),max_files:na(e.max_files,le.max_files,"native.snapshot.max_files"),max_total_bytes:na(e.max_total_bytes,le.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:na(e.max_duration_ms,le.max_duration_ms,"native.snapshot.max_duration_ms")}}function Cg(t){if(t===void 0)return;let e=ni(t,"native.pending_root_move"),i=e.id,r=e.from_artifact_root,n=e.to_artifact_root,o=e.stage;if(typeof i!="string"||!/^[a-f0-9-]{8,}$/u.test(i))throw new Error("native.pending_root_move.id is invalid");if(typeof r!="string"||typeof n!="string")throw new Error("native.pending_root_move roots must be strings");if(o!=="copying"&&o!=="ready"&&o!=="switched")throw new Error("native.pending_root_move.stage is invalid");let a;if(e.cleanup!==void 0){let s=ni(e.cleanup,"native.pending_root_move.cleanup"),c=s.kind,l=s.state,f=s.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof f!="string"||!/^[a-f0-9]{64}$/u.test(f))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");a={kind:c,state:l,manifestHash:f}}return{id:i,fromArtifactRoot:pt(r),toArtifactRoot:pt(n),stage:o,...a?{cleanup:a}:{}}}function Pg(t,e={}){let i=ni(t,"native"),r=i.artifact_root??(e.allowMissingArtifactRoot?"docs":void 0);if(typeof r!="string")throw new Error("native.artifact_root must be a string");let n=i.clarification_mode??"sequential";if(n!=="sequential"&&n!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let o=i.archive_confirmation??"automatic";if(o!=="automatic"&&o!=="required")throw new Error("native.archive_confirmation must be automatic or required");let a=i.max_verify_failures??Dl;if(!Number.isSafeInteger(a)||a<1)throw new Error("native.max_verify_failures must be a positive integer");let s=Cg(i.pending_root_move);return{artifact_root:pt(r),language:Ml(i.language,"en","native.language"),clarification_mode:n,archive_confirmation:o,max_verify_failures:a,snapshot:Eg(i.snapshot),...s?{pending_root_move:s}:{}}}function xg(t){let e=ni(t,"classic"),i=e.context_compression??"off";if(i!=="off"&&i!=="beta")throw new Error("classic.context_compression must be off or beta");let r=e.review_mode??"standard";if(r!=="off"&&r!=="standard"&&r!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let n=e.auto_transition??!0;if(typeof n!="boolean")throw new Error("classic.auto_transition must be true or false");return{artifact_layout:Bl(e.artifact_layout),language:Ml(e.language,"zh-CN","classic.language"),context_compression:i,review_mode:r,auto_transition:n}}function Rg(t){let e=t??!0;if(typeof e!="boolean")throw new Error("ambient_resume must be true or false");return e}function _g(t,e,i,r,n){let o=t.schema!==void 0;if(!(o||t.default_workflow!==void 0||t.workflows!==void 0||!n.allowPartialProject&&t.native!==void 0)||n.allowPartialProject&&!o)return null;if(t.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(t.default_workflow!=="native"&&t.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let s=t.workflows??[t.default_workflow];if(!Array.isArray(s)||s.length===0||s.some(l=>l!=="native"&&l!=="classic"))throw new Error("workflows must contain native and/or classic");let c=[...new Set(s)];if(!c.includes(t.default_workflow))throw new Error("workflows must include default_workflow");if(c.includes("native")&&!e)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:t.default_workflow,workflows:c,ambient_resume:r,...e?{native:e}:{},...i?{classic:i}:{}}}function gt(t,e={}){let i=(0,oa.parseDocument)(t,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${i.errors[0].message}`);let r=i.toJS();if(r==null)return{value:{},config:null,ambient_resume:!0};if(typeof r!="object"||Array.isArray(r))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let n=r,o=Rg(n.ambient_resume),a=n.native===void 0?void 0:Pg(n.native,{allowMissingArtifactRoot:e.allowMissingNativeFields}),s=n.classic===void 0?void 0:xg(n.classic),c=_g(n,a,s,o,{allowPartialProject:e.allowPartialProject??!1});return{value:n,config:c,ambient_resume:o,...a?{native:a}:{},...s?{classic:s}:{}}}var oa,oi,jr,Lr,Dl,kg,le,ue=B(()=>{"use strict";oa=xt(mt(),1),oi=64*1024,jr=1024,Lr=64,Dl=5,kg=[".agents/skills/**",".amazonq/skills/**",".augment/skills/**",".bob/skills/**",".claude/skills/**",".cline/skills/**",".codebuddy/skills/**",".continue/skills/**",".cospec/skills/**",".crush/skills/**",".cursor/skills/**",".factory/skills/**",".forge/skills/**",".gemini/skills/**",".github/skills/**",".iflow/skills/**",".junie/skills/**",".kilocode/skills/**",".kimi-code/skills/**",".kiro/skills/**",".lingma/skills/**",".mimocode/skills/**",".opencode/skills/**",".pi/skills/**",".qoder/skills/**",".qwen/skills/**",".roo/skills/**",".trae-cn/skills/**",".trae/skills/**",".windsurf/skills/**",".zcode/skills/**"],le={include:["**/*"],exclude:[...kg],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4}});function Te(t){return t!==0&&t!==0n&&t!=="0"}function fe(t,e){return Te(t.dev)&&Te(e.dev)&&Te(t.ino)&&Te(e.ino)}function T(t,e){let i=Te(t.dev)&&Te(e.dev);if(i&&t.dev!==e.dev)return!1;let r=Te(t.ino)&&Te(e.ino);return r&&t.ino!==e.ino?!1:i&&r?!0:t.birthtime===e.birthtime}var fi=B(()=>{"use strict"});import{constants as Dr,promises as We}from"fs";function ua(t){return"birthtimeNs"in t&&typeof t.birthtimeNs=="bigint"?t.birthtimeNs:t.birthtimeMs}function Wl(t){return"ctimeNs"in t&&typeof t.ctimeNs=="bigint"?t.ctimeNs:t.ctimeMs}function di(t){return{dev:t.dev,ino:t.ino,birthtime:ua(t)}}function Br(t,e){let i=di(t),r=di(e);return fe(i,r)?T(i,r):T(i,r)&&ua(t)===ua(e)&&Wl(t)===Wl(e)&&t.size===e.size}async function hi(t,e,i={}){if(!Number.isSafeInteger(e)||e<1)throw new Error("race-safe read byte limit must be a positive integer");let r=i.label??"file",n=i.bigint===!0,o=await We.lstat(t,{bigint:n});if(!o.isFile()||o.isSymbolicLink())throw new ge("not-regular-file",`${r} must be a regular file`);if(BigInt(o.size)>BigInt(e))throw new ge("too-large",`${r} exceeds ${e} bytes`);let a=await We.realpath(t);await i.verify?.("pre-open",{realPath:a,identity:di(o)});let s=process.platform==="win32"?Dr.O_RDONLY:Dr.O_RDONLY|Dr.O_NOFOLLOW|Dr.O_NONBLOCK,c;try{c=await We.open(t,s)}catch(l){throw l.code==="ELOOP"?new ge("not-regular-file",`${r} must be a regular file`,{cause:l}):l}try{let[l,f,u]=await Promise.all([c.stat({bigint:n}),We.lstat(t,{bigint:n}),We.realpath(t)]);if(!l.isFile()||!f.isFile()||f.isSymbolicLink()||u!==a||!Br(o,l)||!Br(o,f))throw new ge("changed",`${r} changed while opening`);await i.verify?.("post-open",{realPath:u,identity:di(l)}),await i.hooks?.afterOpen?.();let d=[],m=0,w=Buffer.allocUnsafe(Math.min(64*1024,e+1));for(;;){let b=e+1-m,{bytesRead:k}=await c.read(w,0,Math.min(w.length,b),null);if(k===0)break;if(m+=k,m>e)throw new ge("too-large",`${r} exceeds ${e} bytes`);d.push(Buffer.from(w.subarray(0,k)))}await i.hooks?.beforeFinalCheck?.();let[h,p,y]=await Promise.all([c.stat({bigint:n}),We.lstat(t,{bigint:n}),We.realpath(t)]);if(!p.isFile()||p.isSymbolicLink()||y!==a||!Br(o,h)||!Br(o,p))throw new ge("changed",`${r} changed while reading`);return await i.verify?.("post-read",{realPath:y,identity:di(h)}),{bytes:Buffer.concat(d,m),stat:h,realPath:y}}finally{await c.close()}}var ge,Mr=B(()=>{"use strict";fi();ge=class extends Error{reason;constructor(e,i,r){super(i,r),this.name="RaceSafeReadError",this.reason=e}}});import{promises as Fr}from"fs";import Oe from"path";function Lg(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}function fa(t,e){let i=Oe.relative(t,e);return i===""||!Oe.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Oe.sep}`)}async function ql(t,e){let i=Oe.resolve(t),r=await Fr.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${e} project root must be a real directory`);return Fr.realpath(i)}async function Hl(t,e,i,r){let n=t;for(let o=0;o{if(!fa(o,s.realPath))throw new Error(`${r.label} resolves outside the project root`);await Hl(n.projectRoot,o,n.relative.split("/"),{label:r.label,expected:"file"})}})}var we=B(()=>{"use strict";Mr();ue()});import{createHash as $g}from"crypto";function Dg(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function qe(t,e={}){return(await pi(t,e)).document}async function Bg(t){try{return(await te(t,mi,oi,{label:mi})).bytes}catch(e){if(Dg(e))return null;throw e}}function Mg(t){return t?{exists:!0,sha256:$g("sha256").update(t).digest("hex")}:{exists:!1,sha256:null}}async function pi(t,e={}){let i=await Bg(t);return{document:i?gt(i.toString("utf8"),e):null,identity:Mg(i)}}async function da(t){return(await qe(t))?.config??null}var mi,He=B(()=>{"use strict";ue();we();mi=".comet/config.yaml"});import{randomUUID as Fg}from"crypto";import{constants as Wg,promises as I}from"fs";import D from"path";async function ha(t,e){try{return await I.link(t,e),{linked:!0}}catch(i){let r=i.code;if(r!=="ENOTSUP"&&r!=="EOPNOTSUPP")throw i}return await I.copyFile(t,e,Wg.COPYFILE_EXCL),{linked:!1}}function yt(t,e){let i=D.relative(t,e);return i===""||!D.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${D.sep}`)}function qr(t){return{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs}}function qg(t,e){return T(t,qr(e))}function Wr(t,e){let i=qr(t),r=qr(e);return fe(i,r)?T(i,r):T(i,r)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.size===e.size}async function Hr(t){let e=await I.lstat(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Contained atomic write parent must be a real directory: ${t}`);return{path:t,realPath:await I.realpath(t),...qr(e)}}async function Ie(t){for(let e of t){let i=await I.lstat(e.path);if(!i.isDirectory()||i.isSymbolicLink()||!qg(e,i)||await I.realpath(e.path)!==e.realPath)throw new Error(`Contained atomic write parent changed before commit: ${e.path}`)}}async function Hg(t,e){let i=D.resolve(t),r=D.resolve(e);if(!yt(i,r))throw new Error(`Contained atomic write parent is outside its managed root: ${e}`);let n=[await Hr(i)],o=D.relative(i,r).split(D.sep).filter(Boolean),a=i;for(let s of o){await Ie(n),a=D.join(a,s);try{await I.mkdir(a)}catch(l){if(l.code!=="EEXIST")throw l}let c=await Hr(a);if(!yt(n[0].realPath,c.realPath))throw new Error(`Contained atomic write parent resolves outside its managed root: ${a}`);n.push(c)}return await Ie(n),n}async function Gg(t,e){let i=D.resolve(t),r=D.resolve(e);if(!yt(i,r))throw new Error(`Contained file parent is outside its managed root: ${e}`);let n=[await Hr(i)],o=D.relative(i,r).split(D.sep).filter(Boolean),a=i;for(let s of o){a=D.join(a,s);try{let c=await Hr(a);if(!yt(n[0].realPath,c.realPath))throw new Error(`Contained file parent resolves outside its managed root: ${a}`);n.push(c)}catch(c){if(c.code==="ENOENT")return null;throw c}}return await Ie(n),n}async function Gl(t){let e;try{e=await I.open(t,"r"),await e.sync()}catch(i){let r=i.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(r??""))throw i}finally{await e?.close()}}async function zg(t,e,i){let r=D.dirname(t),n=await Hg(i.containedRoot,r),o=D.join(r,`.${D.basename(t)}.${Fg()}.tmp`),a,s;try{await i.beforeTemporaryOpen?.(),a=await I.open(o,"wx"),s=await a.stat();let[c,l]=await Promise.all([I.lstat(o),I.realpath(o)]);if(await Ie(n),!c.isFile()||c.isSymbolicLink()||!Wr(s,c)||!yt(n[0].realPath,l))throw new Error("Contained atomic write temporary file opened outside its managed parent");if(typeof e=="string"?await a.writeFile(e,"utf8"):await a.writeFile(e),await a.sync(),!Wr(s,await a.stat()))throw new Error("Contained atomic write temporary file changed while writing");await a.close(),a=void 0,await i.beforeCommit?.(),await Ie(n);let f=await I.lstat(o);if(!f.isFile()||f.isSymbolicLink()||!Wr(f,s))throw new Error("Contained atomic write temporary file changed before commit");i.exclusive?(await ha(o,t),await I.unlink(o)):await I.rename(o,t),await Gl(r)}catch(c){await a?.close();try{await Ie(n),await I.rm(o,{force:!0})}catch{}throw c}}async function ve(t,e,i){await zg(t,e,i)}async function ma(t,e){let i=D.dirname(t),r=await Gg(e.containedRoot,i);if(!r)return!1;let n,o;try{n=await I.lstat(t),o=await I.realpath(t)}catch(c){if(c.code==="ENOENT")return!1;throw c}if(!n.isFile()||n.isSymbolicLink()||!yt(r[0].realPath,o))throw new Error("Contained file removal target must be a regular file inside its managed root");await e.beforeRemove?.(),await Ie(r);let[a,s]=await Promise.all([I.lstat(t),I.realpath(t)]);if(!a.isFile()||a.isSymbolicLink()||!Wr(n,a)||s!==o)throw new Error("Contained file removal target changed before removal");return await I.unlink(t),await Ie(r),await Gl(i),!0}var Ge=B(()=>{"use strict";fi()});var vk,pa=B(()=>{"use strict";Ge();He();we();vk=16*1024});var zr=B(()=>{"use strict";Ge();ue();He();we();pa()});var Xr=B(()=>{"use strict"});var hu=B(()=>{"use strict"});var Ra=B(()=>{"use strict";Xr()});var mu=B(()=>{"use strict";Xr();Ra()});var Iw,gu=B(()=>{"use strict";Iw=xt(mt(),1);Ge();ue();we()});var wu=B(()=>{"use strict";Xr();Ge();hu();mu();ue();gu();we();He();zr();pa();Ra()});import{TextDecoder as Lw}from"util";function vu(t){return{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs}}function $w(t,e){try{return new Lw("utf-8",{fatal:!0}).decode(t.bytes)}catch(i){throw new Error(`${e} is not valid UTF-8`,{cause:i})}}async function _a(t,e,i,r,n={}){try{let o=await te(t,e,i,{label:r,hooks:n.hooks});return{result:o,text:$w(o,r)}}catch(o){let a=o.code;if(a==="ENOENT"||a==="ENOTDIR")return null;throw o}}async function yu(t,e,i,r,n={}){return(await _a(t,e,i,r,n))?.text??null}async function bu(t,e,i,r,n,o={}){if(Buffer.byteLength(i,"utf8")>r)throw new Error(`${n} exceeds ${r} bytes`);let a=await _a(t,e,r,n),s=await G(t,e,{label:n,expected:"file"});await ve(s.target,i,{containedRoot:s.projectRoot,beforeCommit:async()=>{await o.beforeCommit?.();let c=await _a(t,e,r,n);if(!(!a&&!c)){if(!a||!c)throw new Error(`${n} changed before commit`);if(a.result.realPath!==c.result.realPath||!T(vu(a.result.stat),vu(c.result.stat))||a.text!==c.text)throw new Error(`${n} changed before commit`)}}})}async function Nu(t,e,i,r={}){let n=await G(t,e,{label:i,expected:"file"});return n.exists?ma(n.target,{containedRoot:n.projectRoot,beforeRemove:r.beforeRemove}):!1}var ku=B(()=>{"use strict";wu();fi()});var xu={};Kf(xu,{RUN_STATE_FILE:()=>Qr,applyRunStateToDocument:()=>Eu,readRunState:()=>Aa,removeRunState:()=>Pu,runStateFromDocument:()=>Si,writeRunState:()=>Ta});import Dw from"path";function ki(t,e){let i=t[e];if(typeof i!="string"||i.length===0)throw new Error(`Invalid Run state: ${e} must be a non-empty string`);return i}function Ni(t,e){let i=ki(t,e);if(Dw.isAbsolute(i)||/^(?:[A-Za-z]:|[\\/]|~)/u.test(i)||i.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Run state: ${e} must stay inside the change directory`);return i}function Bw(t){let e=t.run_retries??"{}",i;try{i=typeof e=="string"?JSON.parse(e):e}catch(r){throw new Error("Invalid Run state: run_retries must be a JSON object",{cause:r})}if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Invalid Run state: run_retries must be a JSON object");for(let r of Object.values(i))if(!Number.isInteger(r)||Number(r)<0)throw new Error("Invalid Run state: retry counts must be non-negative integers");return i}function Si(t){if(!t.run_id)return null;let e=ki(t,"run_id"),i=ki(t,"skill"),r=ki(t,"skill_version"),n=ki(t,"skill_hash"),o=Ni(t,"pending_ref"),a=Ni(t,"trajectory_ref"),s=Ni(t,"context_ref"),c=Ni(t,"artifacts_ref"),l=Ni(t,"checkpoint_ref"),f=Number(t.iteration);if(!Number.isInteger(f)||f<0)throw new Error("Invalid Run state: iteration must be a non-negative integer");if(t.orchestration!=="deterministic"&&t.orchestration!=="adaptive")throw new Error("Invalid Run state: orchestration must be deterministic or adaptive");if(t.run_status!=="running"&&t.run_status!=="waiting"&&t.run_status!=="completed"&&t.run_status!=="failed")throw new Error("Invalid Run state: run_status is invalid");return{runId:e,skill:i,skillVersion:r,skillHash:n,orchestration:t.orchestration,currentStep:Su(t,"current_step"),iteration:f,pending:Su(t,"pending"),pendingRef:o,trajectoryRef:a,contextRef:s,artifactsRef:c,checkpointRef:l,status:t.run_status,retries:Bw(t)}}function Eu(t,e){e?t.run_id=e.runId:delete t.run_id}function Mw(t){return{runId:t.runId,skill:t.skill,skillVersion:t.skillVersion,skillHash:t.skillHash,orchestration:t.orchestration,currentStep:t.currentStep,iteration:t.iteration,pending:t.pending,pendingRef:t.pendingRef,trajectoryRef:t.trajectoryRef,contextRef:t.contextRef,artifactsRef:t.artifactsRef,checkpointRef:t.checkpointRef,status:t.status,retries:t.retries}}function Fw(t){let e={run_id:t.runId,skill:t.skill,skill_version:t.skillVersion,skill_hash:t.skillHash,orchestration:t.orchestration,current_step:t.currentStep,iteration:t.iteration,pending:t.pending,pending_ref:t.pendingRef,trajectory_ref:t.trajectoryRef,context_ref:t.contextRef,artifacts_ref:t.artifactsRef,checkpoint_ref:t.checkpointRef,run_status:t.status,run_retries:JSON.stringify(t.retries)};return Si(e)}async function Aa(t,e={}){let i=await yu(t,Qr,Cu,"Run state",e);if(i===null)return null;let r=JSON.parse(i);return Fw(r)}async function Ta(t,e,i={}){await bu(t,Qr,JSON.stringify(Mw(e),null,2),Cu,"Run state",i)}async function Pu(t,e={}){await Nu(t,Qr,"Run state",e)}var Su,Qr,Cu,Ei=B(()=>{"use strict";ku();Su=(t,e)=>{let i=t[e];return i==null?null:String(i)};Qr=".comet/run-state.json",Cu=256*1024});import Wf from"path";import{promises as Ff}from"fs";ue();import{promises as wt}from"fs";import R from"path";import Ag from"os";var sa=".comet/config.yaml";async function aa(t){try{return await wt.lstat(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function Tg(t){try{let e=await wt.readFile(t,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(e)}catch(e){if(e.code==="ENOENT")return!1;throw e}}function si(t,e){let i=R.relative(t,e);return i===""||!R.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${R.sep}`)}async function ci(t){let e=[],i=t;for(;!await aa(i);){let n=R.dirname(i);if(n===i)break;e.push(R.basename(i)),i=n}let r=await wt.realpath(i);return R.resolve(r,...e.reverse())}async function Fl(t){try{return(await wt.lstat(t)).isSymbolicLink()}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function li(t){let e=R.resolve(t);try{(await wt.stat(e)).isDirectory()||(e=R.dirname(e))}catch(n){if(n.code!=="ENOENT")throw n}let i=e,r=R.resolve(Ag.homedir());for(;;){if(!(e===r&&i!==r)){let a=R.join(e,...sa.split("/")),s=e===i||await Tg(a);if(await aa(a)&&s)return e}if(await aa(R.join(e,".git")))return e;let o=R.dirname(e);if(o===e)return i;e=o}}function ca(t){return pt(t)}async function Og(t,e){let i=ca(e),r=R.resolve(t,...i.split("/")),n=await wt.realpath(t),o=await ci(r);if(!si(n,o))throw new Error("native.artifact_root resolves outside the project root");return r}async function la(t,e){let i=ca(e),r=await Og(t,i),n=R.join(r,"comet");if(await Fl(n))throw new Error("The configured Native comet root must not be a symbolic link");let[o,a]=await Promise.all([ci(r),ci(n)]);if(!si(o,a))throw new Error("The configured Native comet root resolves outside its artifact root");return{projectRoot:R.resolve(t),configFile:R.join(t,...sa.split("/")),artifactRoot:r,artifactRootRef:i,nativeRoot:n,specsDir:R.join(n,"specs"),changesDir:R.join(n,"changes"),archiveDir:R.join(n,"archive"),runtimeDir:R.join(n,"runtime"),locksDir:R.join(n,"runtime","locks"),transactionsDir:R.join(n,"runtime","transactions")}}function vt(t,e){return si(R.resolve(t),R.resolve(e))}async function pe(t,e){let i=R.resolve(t),r=R.resolve(e);if(!si(i,r))throw new Error(`Path is outside the Native root: ${e}`);if(await Fl(i))throw new Error(`Native root must not be a symbolic link: ${t}`);let[n,o]=await Promise.all([ci(i),ci(r)]);if(!si(n,o))throw new Error(`Path resolves outside the Native root: ${e}`);return r}import{promises as Kl}from"fs";import A from"path";import{promises as Ig}from"fs";async function ui(t){try{return await Ig.access(t),!0}catch(e){if(jg(e))return!1;throw e}}function jg(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}ue();He();zr();we();var ze=class extends Error{code="classic-layout-unavailable";constructor(e="Classic artifact layout is unavailable from .comet/config.yaml"){super(e),this.name="ClassicLayoutUnavailableError"}},Vl=".comet/config.yaml";function Jl(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function Ul(t){await G(t,Vl,{label:Vl,expected:"file"})}function Yl(t,e){let i=A.resolve(t),r=e==="docs"?A.join(i,"docs"):i,n=A.join(r,"openspec"),o=A.join(i,"docs","superpowers");return{projectRoot:i,artifactLayout:e,openSpecBase:r,openSpecRoot:n,changesDir:A.join(n,"changes"),archiveDir:A.join(n,"changes","archive"),specsDir:A.join(n,"specs"),superpowersRoot:o,superpowersSpecsDir:A.join(o,"specs"),superpowersPlansDir:A.join(o,"plans"),superpowersReportsDir:A.join(o,"reports")}}async function Yg(t){await Ul(t);let e=await qe(t,{allowPartialProject:!0,allowMissingNativeFields:!0});if(!e?.config)throw new ze;if(!(e.config.workflows??[e.config.default_workflow]).includes("classic"))throw new ze("Classic artifact layout is unavailable because Classic is not enabled");return e.classic?.artifact_layout??"legacy"}async function Xg(t,e){return Yl(t,e??await Yg(t))}async function Qg(t){try{return await Kl.lstat(t),!0}catch(e){if(Jl(e))return!1;throw e}}async function Zg(t,e){let i=await Xg(t,e),r=i.artifactLayout==="legacy"?"docs":"legacy",n=Yl(t,r).openSpecRoot,[o,a]=await Promise.all([G(i.projectRoot,M(i.projectRoot,i.openSpecRoot),{label:"Configured Classic OpenSpec root",expected:"directory"}),Qg(n)]),s=o.exists;return{paths:i,configuredRootExists:s,alternateRoot:n,alternateRootExists:a,dualRoots:s&&a}}async function ew(t){let e=[t.openSpecRoot,t.changesDir,t.archiveDir,t.specsDir,t.superpowersRoot,t.superpowersSpecsDir,t.superpowersPlansDir,t.superpowersReportsDir];for(let i of e){let r=M(t.projectRoot,i);await G(t.projectRoot,r,{label:`Classic managed physical path ${r}`,expected:"directory"})}}async function ye(t,e){let i=await Zg(t,e);if(await ew(i.paths),!i.configuredRootExists){let r=M(i.paths.projectRoot,i.paths.openSpecRoot),n=M(i.paths.projectRoot,i.alternateRoot);throw new ze(`Configured Classic OpenSpec root is missing: ${r} (alternate ${n} is ${i.alternateRootExists?"present":"missing"})`)}return i.paths}async function Vr(t,e){let i=A.join(A.resolve(t),".comet","classic-root-move.json");if(await ui(i))throw new Error("Classic root move transaction is incomplete; inspect it with comet doctor and recover it explicitly before writing");let r=await ye(t,e);if(!await ui(r.openSpecRoot))throw new Error(`Configured Classic OpenSpec root is missing: ${M(r.projectRoot,r.openSpecRoot)}`);return r}async function Xl(t){let e=A.resolve(t),i=null;try{(await Kl.lstat(e)).isDirectory()||(e=A.dirname(e))}catch(r){if(!Jl(r))throw r}for(;;){A.basename(e)==="openspec"&&(i=A.dirname(e));let r=A.join(e,".comet","config.yaml"),n=!1;if(await ui(r))try{await Ul(e);let a=(await qe(e))?.value;n=!!a&&typeof a=="object"&&!Array.isArray(a)&&(a.schema==="comet.project.v1"||a.default_workflow!==void 0||a.native!==void 0)}catch{}if(n||await ui(A.join(e,".git")))return e;let o=A.dirname(e);if(o===e)return i??A.resolve(t);e=o}}function M(t,e){return A.relative(A.resolve(t),e).replaceAll("\\","/")}import{readFileSync as tw}from"fs";import Ql from"path";var iw=new Set(["applypatch","create","createfile","deletefile","edit","editfile","patch","strreplaceeditor","write","writefile","writefiletool"]),rw=new Set(["glob","grep","listfiles","read","readfile","search","view"]),eu=["file_path","filePath","path","target_file","targetFile"],tu=["file_paths","filePaths","paths","files","targets"],iu=["operations","edits"],nw=["patch","diff","patchText","patch_text","changes"],va=new Set(["claude","codex","windsurf","github-copilot","gemini","amazon-q","qwen","kiro","codebuddy","qoder"]);function ya(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function Zl(t){return t.toLowerCase().replace(/[^a-z0-9]+/gu,"")}function ow(t){for(let e of["tool_name","toolName","tool","name"]){let i=t[e];if(typeof i=="string"&&i.trim())return i.trim()}return null}function aw(t){for(let e of["cwd","working_directory","workspaceRoot"]){let i=t[e];if(!(typeof i!="string"||!i.trim()||!Ql.isAbsolute(i.trim())))return Ql.resolve(i.trim())}}function sw(t){if(typeof t!="string")return t;let e=t.trim();if(!e.startsWith("{")&&!e.startsWith("["))return t;try{return JSON.parse(e)}catch{return t}}function cw(t){for(let e of["tool_input","toolInput","toolArgs","tool_args","arguments"])if(t[e]!==void 0)return sw(t[e]);return t}function wa(t){let e=[],i=[/^\*\*\* (?:Add|Update|Delete) File:\s+(.+?)\s*$/gmu,/^\+\+\+\s+(?:b\/)?(.+?)\s*$/gmu];for(let r of i)for(let n of t.matchAll(r)){let o=n[1]?.trim();o&&o!=="/dev/null"&&e.push(o)}return e}function Ve(t,e){if(typeof e=="string"){let i=e.trim();i&&t.push(i);return}if(Array.isArray(e)){for(let i of e)Ve(t,i);return}if(ya(e)){for(let i of eu)Ve(t,e[i]);for(let i of tu)Ve(t,e[i]);for(let i of iu)Ve(t,e[i])}}function lw(t,e){let i=[],r=[e,t].filter(ya);for(let n of r){for(let o of eu)Ve(i,n[o]);for(let o of tu)Ve(i,n[o]);for(let o of iu)Ve(i,n[o]);for(let o of nw){let a=n[o];typeof a=="string"&&i.push(...wa(a))}}return typeof e=="string"&&i.push(...wa(e)),[...new Set(i)]}function gi(t,e){if(e?.trim())return{intent:"write",targets:[e.trim()],toolName:null};if(!t.trim())return{intent:"unknown",targets:[],toolName:null};let i;try{i=JSON.parse(t)}catch{let a=wa(t);return a.length>0?{intent:"write",targets:[...new Set(a)],toolName:"apply_patch"}:{intent:"unknown",targets:[],toolName:null}}if(!ya(i))return{intent:"unknown",targets:[],toolName:null};let r=ow(i),n=lw(i,cw(i)),o=aw(i);return r&&iw.has(Zl(r))?{intent:n.length>0?"write":"unknown",targets:n,toolName:r,...o?{cwd:o}:{}}:r&&rw.has(Zl(r))?{intent:"non-write",targets:[],toolName:r,...o?{cwd:o}:{}}:r?{intent:"unknown",targets:n,toolName:r,...o?{cwd:o}:{}}:{intent:n.length>0?"write":"unknown",targets:n,toolName:null,...o?{cwd:o}:{}}}function ba(){let t=process.env.FILE_PATH;if(t?.trim()||process.stdin.isTTY)return gi("",t);try{return gi(tw(0,"utf8"),t)}catch{return gi("",t)}}function ru(t,e){return va.has(t)?t==="github-copilot"?{exitCode:0,stdout:e.allowed?`{} `:`${JSON.stringify({permissionDecision:"deny",permissionDecisionReason:e.reason})} `,stderr:""}:e.allowed?{exitCode:0,stdout:"",stderr:""}:{exitCode:2,stdout:"",stderr:`${e.reason} `}:{exitCode:64,stdout:"",stderr:`Unsupported Comet Hook platform: ${t} -`}}var wi=null;async function ru(t){if(wi!==null)return t();wi={entries:new Map};try{return await t()}finally{wi=null}}function nu(t,e){let i=t;for(let r of e)i+="\0"+(typeof r=="string"?r:JSON.stringify(r));return i}function K(t,e){return(...i)=>{let r=wi;if(r===null)return e(...i);let n=nu(`async:${t}`,i),o=r.entries.get(n);if(o)return o.value;let a=e(...i).catch(s=>{throw r.entries.delete(n),s});return r.entries.set(n,{value:a}),a}}function Na(t,e){return(...i)=>{let r=wi;if(r===null)return e(...i);let n=nu(`sync:${t}`,i),o=r.entries.get(n);if(o)return o.value;let a=e(...i);return r.entries.set(n,{value:a}),a}}import{promises as on,readFileSync as EE}from"fs";import J from"path";import au from"path";Ge();ue();we();import vi from"path";var Hk=2*1024*1024;function fw(t,e,i){let r=vi.resolve(t),n=vi.isAbsolute(e)?vi.resolve(e):vi.resolve(r,e),o=vi.relative(r,n).replaceAll("\\","/");return{root:r,relative:ai(o,i),target:n}}async function bt(t,e,i){let r=fw(t,e,i.label);return H(r.root,r.relative,i)}async function ou(t,e,i){return(await bt(t,e,{label:i.label,expected:i.expected??"any"})).exists}function ka(t){return t?/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t)?t.includes("..")?"Change name cannot contain '..' (path traversal not allowed)":null:`Invalid change name: '${t}' -Valid format: lowercase kebab-case (a-z, 0-9, single hyphens)`:"Change name cannot be empty"}function Sa(t){let e=ka(t);if(e)throw new Error(e)}function dw(t,e){return{label:$(t,e),directory:e}}async function hw(t,e,i){let r=dw(t,e);if(!(await bt(t,e,{label:i,expected:"directory"})).exists)return{change:r,exists:!1,stateExists:!1};let o=await bt(t,au.join(e,".comet.yaml"),{label:`${i} state`,expected:"file"});return{change:r,exists:!0,stateExists:o.exists}}async function yi(t,e=process.cwd()){Sa(t);let i=await ye(e),r=await hw(i.projectRoot,au.join(i.changesDir,t),`Classic active change ${t}`);return{...r.change,exists:r.exists,stateExists:r.stateExists}}import{promises as Ea}from"fs";import z from"path";function su(t,e){let i=z.relative(t,e);return i===""||i!==".."&&!i.startsWith(`..${z.sep}`)&&!z.isAbsolute(i)}async function mw(t){let e=z.resolve(t),i=z.parse(e).root,r=[],n=e;for(;n&&n!==i;)try{let o=await Ea.realpath(n);return z.join(o,...r.reverse())}catch(o){let a=o.code;if(a!=="ENOENT"&&a!=="ENOTDIR")throw o;r.push(z.basename(n)),n=z.dirname(n)}try{let o=await Ea.realpath(i);return z.join(o,...r.reverse())}catch{return null}}async function Kr(t,e){let i=z.resolve(t),r=await Ea.realpath(i),n=[],o=[];for(let a of e){let s=z.isAbsolute(a)?z.resolve(a):z.resolve(i,a),c=await mw(s);((c?su(r,c):su(i,s))?n:o).push(a)}return{projectTargets:n,externalTargets:o}}var Ca=xt(mt(),1);import{execFileSync as cu}from"child_process";import{randomUUID as pw}from"crypto";import{promises as bi}from"fs";import lu from"path";function gw(t){try{let e=cu("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();return e&&e!=="HEAD"?e:null}catch{return null}}var ww=Na("liveGitBranch",t=>gw(t));function vw(t){try{return cu("git",["rev-parse","--is-inside-work-tree"],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()==="true"}catch{return!1}}var yw=Na("isGitWorkTree",t=>vw(t)),bw=["current","branch","worktree"];function uu(t){return bw.includes(t)}function Nw(t){return uu(t.isolation)?t.boundBranch===null&&t.currentBranch===null&&t.gitWorkTree===!1?{status:"not-applicable"}:t.boundBranch===null?t.currentBranch===null?{status:"unbound-detached"}:{status:"needs-heal",branch:t.currentBranch}:t.currentBranch===t.boundBranch?{status:"ok"}:{status:"drift",boundBranch:t.boundBranch,currentBranch:t.currentBranch}:{status:"not-applicable"}}async function Jr(t,e){let i=lu.join(t,".comet.yaml"),r=(0,Ca.parseDocument)(await bi.readFile(i,"utf8"),{uniqueKeys:!1});if(r.errors.length>0)throw new Error(`Invalid .comet.yaml: ${r.errors[0].message}`);let n=r.toJS()??{},o=typeof n.isolation=="string"?n.isolation:null,a=typeof n.bound_branch=="string"&&n.bound_branch!==""?n.bound_branch:null,s=uu(o),c=ww(e.cwd),l=s&&a===null&&c===null?yw(e.cwd):!0,f=Nw({isolation:o,boundBranch:a,currentBranch:c,gitWorkTree:l});return f.status==="needs-heal"&&e.heal?(await kw(t,f.branch),{status:"healed",branch:f.branch,bindingRequired:s,currentBranch:c}):{...f,bindingRequired:s,currentBranch:c}}async function kw(t,e){let i=lu.join(t,".comet.yaml"),r=(0,Ca.parseDocument)(await bi.readFile(i,"utf8"),{uniqueKeys:!1});r.set("bound_branch",e);let n=`${i}.${pw()}.tmp`;try{await bi.writeFile(n,r.toString(),"utf8"),await bi.rename(n,i)}catch(o){throw await bi.rm(n,{force:!0}),o}}function Sw(t){return t??"detached HEAD"}function Ur(t,e,i){return`change '${t}' is bound to branch '${e}', but current branch is '${Sw(i)}'`}function Yr(t){return`change '${t}' uses a branch-bound workspace mode but has no bound branch and HEAD is detached; checkout a branch first before continuing.`}Mr();import Ew from"path";var Pa="comet.selection.v2",Cw=16*1024;function xa(t){return Ew.join(t,".comet","current-change.json")}function Pw(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function fu(t){return t===null||typeof t=="string"}function xw(t){let e;try{e=JSON.parse(t)}catch(i){throw new Error(`current change selection contains invalid JSON: ${i instanceof Error?i.message:String(i)}`,{cause:i})}if(!Pw(e))throw new Error("current change selection must be a JSON object");if(e.version===1){if(typeof e.change!="string")throw new Error("legacy current change selection change must be a string");if(e.branch!==void 0&&!fu(e.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:Pa,workflow:"classic",change:e.change,branch:e.branch??null},legacy:!0}}if(e.schema!==Pa)throw new Error(`current change selection schema must be ${Pa}`);if(e.workflow!=="native"&&e.workflow!=="classic")throw new Error("current change selection workflow must be native or classic");if(typeof e.change!="string")throw new Error("current change selection change must be a string");if(!fu(e.branch))throw new Error("current change selection branch must be a string or null");if(e.workflow==="native"&&e.branch!==null)throw new Error("Native current change selection branch must be null");return{selection:e,legacy:!1}}async function Nt(t){let e;try{let r=xa(t),{bytes:n}=await hi(r,Cw,{label:"current change selection"});e=n.toString("utf8")}catch(r){if(r.code==="ENOENT")return{status:"missing"};throw new Error(`cannot read current change selection: ${r instanceof Error?r.message:String(r)}`,{cause:r})}return{status:"selected",...xw(e)}}var tn=xt(mt(),1);Ge();we();import en from"path";Ei();var Ia=["full","hotfix","tweak"],xu=1,_u=["open","design","build","verify","archive"],Ww=["en","zh-CN"],qw=["off","beta"],Hw=["subagent-driven-development","executing-plans","direct"],Gw=["plan-ready"],zw=["confirmed"],Vw=["tdd","direct"],Kw=["off","standard","thorough"],Jw=["current","branch","worktree"],Uw=["light","full"],Yw=["pending","pass","fail"],Xw=["pending","handled"],Qw=["pending","confirmed"],ja=["workflow","language","phase","context_compression","build_mode","build_pause","subagent_dispatch","tdd_mode","review_mode","isolation","bound_branch","verify_mode","auto_transition","base_ref","design_doc","plan","verify_result","verify_failures","verification_report","branch_status","created_at","verified_at","archive_confirmation","archived","direct_override","handoff_context","handoff_hash","classic_profile","classic_migration"],Zw=["run_id"],Au=new Set([...ja,...Zw]),ev=["workflow","phase","design_doc","plan","build_mode","isolation","verify_mode","verify_result","verified_at","archived"];function Ru(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function kt(t,e){let i=t[e];if(i==null||i==="")return null;if(typeof i!="string")throw new Error(`Invalid Classic state: ${e} must be a string or null`);return i}function F(t,e,i,r=!0){let n=t[e];if(n==null||n===""){if(r)return null;throw new Error(`Invalid Classic state: ${e} is required`)}if(typeof n!="string"||!i.includes(n))throw new Error(`Invalid Classic state: ${e} must be one of ${i.join(", ")}${r?" or null":""}`);return n}function Oa(t,e,i=!0){let r=t[e];if(r==null||r===""){if(i)return null;throw new Error(`Invalid Classic state: ${e} is required`)}if(typeof r!="boolean")throw new Error(`Invalid Classic state: ${e} must be true or false`);return r}function tv(t,e,i=0){let r=t[e];if(r==null||r==="")return i;if(typeof r!="number"||!Number.isInteger(r)||r<0)throw new Error(`Invalid Classic state: ${e} must be a non-negative integer`);return r}function Zr(t,e){let i=kt(t,e);if(i===null)return null;if(/^(?:[A-Za-z]:|[\\/]|~)/u.test(i)||i.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Classic state: ${e} must be a relative repository path`);return i}function iv(t,e){let i=kt(t,e);if(i!==null&&!/^[a-f0-9]{64}$/u.test(i))throw new Error(`Invalid Classic state: ${e} must be a sha256 hex digest`);return i}function rv(t){let e=t.classic_migration;if(e==null||e==="")return null;if(e!==xu)throw new Error(`Invalid Classic state: classic_migration must be ${xu}`);return e}function nv(t){if(!ja.some(i=>Ru(t,i)))return null;for(let i of ev)if(!Ru(t,i))return null;return{workflow:F(t,"workflow",Ia,!1),language:F(t,"language",Ww),phase:F(t,"phase",_u,!1),contextCompression:F(t,"context_compression",qw),buildMode:F(t,"build_mode",Hw),buildPause:F(t,"build_pause",Gw),subagentDispatch:F(t,"subagent_dispatch",zw),tddMode:F(t,"tdd_mode",Vw),reviewMode:F(t,"review_mode",Kw),isolation:F(t,"isolation",Jw),boundBranch:kt(t,"bound_branch"),verifyMode:F(t,"verify_mode",Uw),autoTransition:Oa(t,"auto_transition"),baseRef:kt(t,"base_ref"),designDoc:Zr(t,"design_doc"),plan:Zr(t,"plan"),verifyResult:F(t,"verify_result",Yw,!1),verifyFailures:tv(t,"verify_failures"),verificationReport:Zr(t,"verification_report"),branchStatus:F(t,"branch_status",Xw),createdAt:kt(t,"created_at"),verifiedAt:kt(t,"verified_at"),archiveConfirmation:F(t,"archive_confirmation",Qw),archived:Oa(t,"archived",!1),directOverride:Oa(t,"direct_override"),handoffContext:Zr(t,"handoff_context"),handoffHash:iv(t,"handoff_hash"),classicProfile:F(t,"classic_profile",Ia),classicMigration:rv(t)}}function Tu(t,e){let i=e??null;if(i===null&&e===void 0&&t.run_id&&t.skill)try{i=Si(t)}catch(r){let n=r instanceof Error?r.message:String(r);throw new Error(n.replace(/^Invalid Run state:/u,"Invalid Classic state:"),{cause:r})}return{classic:nv(t),run:i,unknownKeys:Object.keys(t).filter(r=>!Au.has(r))}}function Ou(t){let e=t.workflow,i=t.phase,r=t.archived,n=t.design_doc;return{workflow:typeof e=="string"&&Ia.includes(e)?e:null,phase:typeof i=="string"&&_u.includes(i)?i:null,archived:r===!0,designDoc:typeof n=="string"&&n!==""?n:null,unknownKeys:Object.keys(t).filter(o=>!Au.has(o))}}Ei();var ov=2*1024*1024;function Ci(t){let e=t.toJS();if(e===null)return{};if(typeof e!="object"||Array.isArray(e))throw new Error("Invalid Classic state document: root must be a mapping");return e}function av(t){let e=["skill","skill_version","skill_hash","orchestration","current_step","iteration","pending","pending_ref","trajectory_ref","context_ref","artifacts_ref","checkpoint_ref","run_status","run_retries"];for(let i of e)t.delete(i)}function sv(t){let e=!1;for(let i of["build_command","verify_command"])t.has(i)&&(t.delete(i),e=!0);return e}async function Iu(t){let e;try{e=(await te(en.dirname(t),en.basename(t),ov,{label:"Classic state document"})).bytes.toString("utf8")}catch(r){if(r.code!=="ENOENT")throw r;return new tn.Document({})}let i=(0,tn.parseDocument)(e);if(i.errors.length>0)throw new Error(`Invalid Classic state document: ${i.errors[0].message}`);return Ci(i),i}async function rn(t,e={}){let i=e.migrate!==!1,r=en.join(t,".comet.yaml"),n=await Iu(r),o=Ci(n),a=sv(n);a&&(o=Ci(n));let s=await Aa(t);if(!s&&o.run_id&&o.skill){let{runStateFromDocument:c}=await Promise.resolve().then(()=>(Ei(),Pu));s=c(o),s&&i&&(await Ta(t,s),av(n),a=!0)}return a&&i&&await ve(r,n.toString(),{containedRoot:t}),Tu(Ci(n),s)}async function ju(t){let e=await Iu(en.join(t,".comet.yaml"));return Ou(Ci(e))}var fv=K("readCometCurrentSelection",t=>Nt(t));async function dv(t,e){Sa(e);let i=await yi(e,t);if(!i.stateExists)throw new Error(`Cannot select current change '${e}': active change state not found`);let r=await rn(i.directory,{migrate:!1});if(!r.classic)throw new Error(`Cannot select current change '${e}': Classic state is incomplete`);if(r.classic.archived)throw new Error(`Cannot select current change '${e}': change is archived`);return i.directory}async function nn(t){let e;try{e=await fv(t)}catch(o){return{status:"stale",reason:o instanceof Error?o.message:String(o)}}if(e.status==="missing")return{status:"missing"};if(e.selection.workflow!=="classic")return{status:"stale",reason:`current change '${e.selection.change}' belongs to Native, not Classic`};let i=e.selection,r;try{r=await dv(t,i.change)}catch(o){return{status:"stale",reason:o instanceof Error?o.message:String(o)}}let n=await Jr(r,{heal:!1,cwd:t});return n.status==="drift"?{status:"stale",reason:Ur(i.change,n.boundBranch,n.currentBranch)}:n.status==="unbound-detached"?{status:"stale",reason:Yr(i.change)}:n.status==="ok"?{status:"selected",selection:i}:i.branch!==null&&n.currentBranch!==i.branch?{status:"stale",reason:`current change '${i.change}' was selected on branch '${i.branch}', current branch is '${n.currentBranch??"detached HEAD"}'`}:{status:"selected",selection:i}}import Ke from"node:path";async function Lu(t,e){if(!e||e==="null")return{status:"missing",recordedPath:null};let i=await ye(t),r=Ke.resolve(t,e),n=Ke.relative(i.superpowersPlansDir,r);return Ke.isAbsolute(e)||!n||n.startsWith(`..${Ke.sep}`)||Ke.isAbsolute(n)||n.includes(Ke.sep)||Ke.extname(n).toLowerCase()!==".md"?{status:"broken",recordedPath:e}:await ou(t,e,{label:`Classic build plan ${e}`,expected:"file"})?{status:"ready",recordedPath:e}:{status:"broken",recordedPath:e}}function ie(t,e){return{exitCode:t,stderr:e+` -`}}function be(t){return ie(0,`[COMET-HOOK] allowed: ${t}`)}function xi(t){return t.replaceAll("\\","/").replace(/\/+/gu,"/")}function Je(t){let e=xi(t);return process.platform==="win32"?e.toLowerCase():e}function $u(t,e){let i=xi(J.relative(e,t));return i===""?"":i.startsWith("../")||i===".."||J.isAbsolute(i)?null:i}async function hv(t){let e=J.resolve(t),i=J.parse(e).root,r=[],n=e;for(;n&&n!==i;)try{let o=await on.realpath(n);return J.join(o,...r.reverse())}catch(o){let a=o.code;if(a!=="ENOENT"&&a!=="ENOTDIR")throw o;r.push(J.basename(n)),n=J.dirname(n)}try{let o=await on.realpath(i);return J.join(o,...r.reverse())}catch{return null}}async function mv(t,e){let i=J.isAbsolute(t)?t:J.resolve(e,t),r=xi(i),n=$u(i,e);if(n!==null)return n;try{let o=await hv(i),a=await on.realpath(e);if(o){let s=$u(o,a);if(s!==null)return s;r=xi(o)}}catch{if(!J.isAbsolute(t))return xi(t).replace(/^\.\//u,"")}return r.replace(/^\.\//u,"")}async function Fu(t){try{let e=await rn(t,{migrate:!1}),i=Array.from(new Set(e.unknownKeys)).sort();if(i.length>0)throw new Error(`Invalid Classic state: unknown field(s): ${i.join(", ")}`);if(!e.classic)throw new Error("Classic state projection is unavailable");return{changeDir:t,phase:e.classic.phase,classic:e.classic,archived:e.classic.archived}}catch(e){let i=await ju(t);return i.phase?{changeDir:t,phase:i.phase,classic:null,archived:i.archived,invalidState:e instanceof Error&&e.message.includes("unknown field")}:null}}async function pv(t){let e=(await ye(t)).changesDir,i=[];if(!(await bt(t,e,{label:"Classic changes directory",expected:"directory"})).exists)return i;for(let n of(await on.readdir(e,{withFileTypes:!0})).sort((o,a)=>o.name.localeCompare(a.name))){if(n.name==="archive"||ka(n.name))continue;let o=await yi(n.name,t);if(!o.exists||!o.stateExists)continue;let a=await Fu(o.directory);!a||a.archived||i.push(a)}return i}var Ri=K("classicActiveChanges",t=>pv(t)),Wu=K("classicPlanReadiness",Lu);async function qu(t){return(await Ri(t)).map(e=>({workflow:"classic",name:re(e),phase:e.phase}))}function Hu(t,e){return`${$(t,e.superpowersRoot)}/`}function Gu(t,e){return Je(t).startsWith(Je(e))}function gv(t,e){return[{prefix:`${$(t,e.superpowersSpecsDir)}/`,field:"designDoc",wireField:"design_doc",phase:"design"},{prefix:`${$(t,e.superpowersPlansDir)}/`,field:"plan",wireField:"plan",phase:"build"},{prefix:`${$(t,e.superpowersReportsDir)}/`,field:"verificationReport",wireField:"verification_report",phase:"verify"}]}function wv(t,e){let i=Je(t),r=e.find(o=>i.startsWith(Je(o.prefix)));if(!r)return null;let n=i.slice(Je(r.prefix).length);return!n||n.includes("/")||!n.endsWith(".md")?null:r}function zu(t,e){return t.classic?.[e.field]??null}function vv(t,e){return t.classic!==null&&t.phase===e.phase&&!zu(t,e)}async function Du(t,e,i){return vv(e,i)?!0:i.field!=="plan"||e.phase!=="build"?!1:(await Wu(t,e.classic?.plan??null)).status==="broken"}function Vu(t){return t.phase==="design"||t.phase==="build"||t.phase==="verify"}function re(t){return t.changeDir?J.basename(t.changeDir):null}var yv=new Set(["design","plan","verify","verification","verification-report","report"]);function Bu(t){return t.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}function bv(t,e){return[e.classic?.designDoc,e.classic?.plan,e.classic?.verificationReport].some(r=>r&&Je(r)===Je(t))}function Nv(t,e){let r=(t.split("/").at(-1)??t).replace(/\.[^.]+$/u,"");if(r===e)return!0;let n=[...yv].map(Bu).join("|");return new RegExp(`(^|[-_.])${Bu(e)}[-_.](${n})$`,"u").test(r)}async function kv(t,e){let i=await Ri(e),r=i.find(a=>bv(t,a));if(r)return{governing:r,match:"recorded"};let o=i.filter(Vu).filter(a=>{let s=re(a);return s!==null&&Nv(t,s)}).sort((a,s)=>(re(s)?.length??0)-(re(a)?.length??0))[0];return o?{governing:o,match:"named"}:null}async function Mu(t,e,i){let r=await Ri(t);if(r.length===0)return null;if(i)return r.find(a=>re(a)===i)??{blockedResult:Pi(e,`selected change '${i}' is no longer active`)};let n=await nn(t);if(n.status==="stale")return{blockedResult:Pi(e,n.reason)};if(n.status==="selected"){let o=r.find(a=>re(a)===n.selection.change);return o||{blockedResult:Pi(e,`selected change '${n.selection.change}' is no longer active`)}}if(r.length===1){let o=r[0];if(o.changeDir!==null){let a=await Jr(o.changeDir,{heal:!1,cwd:t}),s=re(o)??"unknown";if(a.status==="drift")return{blockedResult:Pi(e,Ur(s,a.boundBranch,a.currentBranch))};if(a.status==="unbound-detached")return{blockedResult:Pi(e,Yr(s))}}return o}return{blockedResult:Ov(e,r.map(o=>re(o)).filter(Boolean))}}async function Sv(t,e,i,r){let n=`${$(e,i.changesDir)}/`;if(t.startsWith(n)){let o=t.slice(n.length),[a]=o.split("/");if(a&&a!=="archive"){let s=await yi(a,e);if(s.stateExists){let c=await Fu(s.directory);return c||{changeDir:s.directory,phase:"open",classic:null,archived:!1}}return{changeDir:s.directory,phase:"open",classic:null,archived:!1}}}if(Gu(t,Hu(e,i))){let o=await kv(t,e);if(o?.match==="recorded")return{...o.governing,superpowersArtifact:"matched"};let a=wv(t,gv(e,i));if(o)return a?{...o.governing,superpowersArtifact:await Du(e,o.governing,a)?"matched":"unmatched",superpowersSlot:a}:{...o.governing,superpowersArtifact:"matched"};if(a){let l=await Mu(e,t,r);return!l||"blockedResult"in l?l:{...l,superpowersArtifact:await Du(e,l,a)?"matched":"unmatched",superpowersSlot:a}}let s=await Ri(e),c=r?s.find(l=>re(l)===r)??null:s[0]??null;return c?{...c,superpowersArtifact:"unmatched"}:null}return Mu(e,t,r)}function Ev(t){return!t.includes("/")&&t.endsWith(".md")}function Cv(t){return t.startsWith(".comet/")||t.includes("/.comet/")}function Pv(t){return t===".superpowers"||t.startsWith(".superpowers/")}function xv(t,e,i){if(!t.startsWith(i))return null;let r=t.endsWith("/.comet.yaml")||t.endsWith("/.openspec.yaml"),n=t.endsWith("/proposal.md")||t.endsWith("/design.md")||t.endsWith("/tasks.md"),o=t.includes("/.comet/"),a=t.includes("/specs/");return e==="open"&&(n||r||o||a)?`${t} (phase: open, openspec artifacts)`:e==="design"&&(n||r||o||a)?`${t} (phase: design, handoff/spec)`:e==="build"&&(t.endsWith("/tasks.md")||r||a)?`${t} (phase: build, spec/tasks)`:e==="verify"&&(t.endsWith("/tasks.md")||r)?`${t} (phase: verify, tasks/state)`:e==="archive"&&r?`${t} (phase: archive, state)`:null}function Rv(t,e){let i=e==="open"?[" BLOCKED: source writes are not allowed during open"," This phase does not allow source writes"," ALLOWED: create proposal/design/tasks artifacts and run guard"," NEXT: finish clarification and artifacts, then run guard --apply"]:e==="design"?[" BLOCKED: source writes are not allowed during design"," This phase does not allow source writes"," ALLOWED: run brainstorming, create the Design Doc, and run guard"," NEXT: finish the Design Doc, then run comet guard design --apply to enter build"]:[" BLOCKED: source writes are not allowed during archive"," This phase does not allow source writes"," ALLOWED: confirm archive state and run the archive script"];return ie(2,["","╔══════════════════════════════════════════╗","║ COMET PHASE GUARD — WRITE BLOCKED ║","╚══════════════════════════════════════════╝","",` Current phase: ${e}`,` Target file: ${t}`,"",...i,""].join(` +`}}var wi=null;async function nu(t){if(wi!==null)return t();wi={entries:new Map};try{return await t()}finally{wi=null}}function ou(t,e){let i=t;for(let r of e)i+="\0"+(typeof r=="string"?r:JSON.stringify(r));return i}function K(t,e){return(...i)=>{let r=wi;if(r===null)return e(...i);let n=ou(`async:${t}`,i),o=r.entries.get(n);if(o)return o.value;let a=e(...i).catch(s=>{throw r.entries.delete(n),s});return r.entries.set(n,{value:a}),a}}function Na(t,e){return(...i)=>{let r=wi;if(r===null)return e(...i);let n=ou(`sync:${t}`,i),o=r.entries.get(n);if(o)return o.value;let a=e(...i);return r.entries.set(n,{value:a}),a}}import{promises as on,readFileSync as EE}from"fs";import J from"path";import su from"path";Ge();ue();we();import vi from"path";var Hk=2*1024*1024;function fw(t,e,i){let r=vi.resolve(t),n=vi.isAbsolute(e)?vi.resolve(e):vi.resolve(r,e),o=vi.relative(r,n).replaceAll("\\","/");return{root:r,relative:ai(o,i),target:n}}async function bt(t,e,i){let r=fw(t,e,i.label);return G(r.root,r.relative,i)}async function au(t,e,i){return(await bt(t,e,{label:i.label,expected:i.expected??"any"})).exists}function ka(t){return t?/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t)?t.includes("..")?"Change name cannot contain '..' (path traversal not allowed)":null:`Invalid change name: '${t}' +Valid format: lowercase kebab-case (a-z, 0-9, single hyphens)`:"Change name cannot be empty"}function Sa(t){let e=ka(t);if(e)throw new Error(e)}function dw(t,e){return{label:M(t,e),directory:e}}async function hw(t,e,i){let r=dw(t,e);if(!(await bt(t,e,{label:i,expected:"directory"})).exists)return{change:r,exists:!1,stateExists:!1};let o=await bt(t,su.join(e,".comet.yaml"),{label:`${i} state`,expected:"file"});return{change:r,exists:!0,stateExists:o.exists}}async function yi(t,e=process.cwd()){Sa(t);let i=await ye(e),r=await hw(i.projectRoot,su.join(i.changesDir,t),`Classic active change ${t}`);return{...r.change,exists:r.exists,stateExists:r.stateExists}}import{promises as Ea}from"fs";import z from"path";function cu(t,e){let i=z.relative(t,e);return i===""||i!==".."&&!i.startsWith(`..${z.sep}`)&&!z.isAbsolute(i)}async function mw(t){let e=z.resolve(t),i=z.parse(e).root,r=[],n=e;for(;n&&n!==i;)try{let o=await Ea.realpath(n);return z.join(o,...r.reverse())}catch(o){let a=o.code;if(a!=="ENOENT"&&a!=="ENOTDIR")throw o;r.push(z.basename(n)),n=z.dirname(n)}try{let o=await Ea.realpath(i);return z.join(o,...r.reverse())}catch{return null}}async function Kr(t,e){let i=z.resolve(t),r=await Ea.realpath(i),n=[],o=[];for(let a of e){let s=z.isAbsolute(a)?z.resolve(a):z.resolve(i,a),c=await mw(s);((c?cu(r,c):cu(i,s))?n:o).push(a)}return{projectTargets:n,externalTargets:o}}var Ca=xt(mt(),1);import{execFileSync as lu}from"child_process";import{randomUUID as pw}from"crypto";import{promises as bi}from"fs";import uu from"path";function gw(t){try{let e=lu("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();return e&&e!=="HEAD"?e:null}catch{return null}}var ww=Na("liveGitBranch",t=>gw(t));function vw(t){try{return lu("git",["rev-parse","--is-inside-work-tree"],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()==="true"}catch{return!1}}var yw=Na("isGitWorkTree",t=>vw(t)),bw=["current","branch","worktree"];function fu(t){return bw.includes(t)}function Nw(t){return fu(t.isolation)?t.boundBranch===null&&t.currentBranch===null&&t.gitWorkTree===!1?{status:"not-applicable"}:t.boundBranch===null?t.currentBranch===null?{status:"unbound-detached"}:{status:"needs-heal",branch:t.currentBranch}:t.currentBranch===t.boundBranch?{status:"ok"}:{status:"drift",boundBranch:t.boundBranch,currentBranch:t.currentBranch}:{status:"not-applicable"}}async function Jr(t,e){let i=uu.join(t,".comet.yaml"),r=(0,Ca.parseDocument)(await bi.readFile(i,"utf8"),{uniqueKeys:!1});if(r.errors.length>0)throw new Error(`Invalid .comet.yaml: ${r.errors[0].message}`);let n=r.toJS()??{},o=typeof n.isolation=="string"?n.isolation:null,a=typeof n.bound_branch=="string"&&n.bound_branch!==""?n.bound_branch:null,s=fu(o),c=ww(e.cwd),l=s&&a===null&&c===null?yw(e.cwd):!0,f=Nw({isolation:o,boundBranch:a,currentBranch:c,gitWorkTree:l});return f.status==="needs-heal"&&e.heal?(await kw(t,f.branch),{status:"healed",branch:f.branch,bindingRequired:s,currentBranch:c}):{...f,bindingRequired:s,currentBranch:c}}async function kw(t,e){let i=uu.join(t,".comet.yaml"),r=(0,Ca.parseDocument)(await bi.readFile(i,"utf8"),{uniqueKeys:!1});r.set("bound_branch",e);let n=`${i}.${pw()}.tmp`;try{await bi.writeFile(n,r.toString(),"utf8"),await bi.rename(n,i)}catch(o){throw await bi.rm(n,{force:!0}),o}}function Sw(t){return t??"detached HEAD"}function Ur(t,e,i){return`change '${t}' is bound to branch '${e}', but current branch is '${Sw(i)}'`}function Yr(t){return`change '${t}' uses a branch-bound workspace mode but has no bound branch and HEAD is detached; checkout a branch first before continuing.`}Mr();import Ew from"path";var Pa="comet.selection.v2",Cw=16*1024;function xa(t){return Ew.join(t,".comet","current-change.json")}function Pw(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function du(t){return t===null||typeof t=="string"}function xw(t){let e;try{e=JSON.parse(t)}catch(i){throw new Error(`current change selection contains invalid JSON: ${i instanceof Error?i.message:String(i)}`,{cause:i})}if(!Pw(e))throw new Error("current change selection must be a JSON object");if(e.version===1){if(typeof e.change!="string")throw new Error("legacy current change selection change must be a string");if(e.branch!==void 0&&!du(e.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:Pa,workflow:"classic",change:e.change,branch:e.branch??null},legacy:!0}}if(e.schema!==Pa)throw new Error(`current change selection schema must be ${Pa}`);if(e.workflow!=="native"&&e.workflow!=="classic")throw new Error("current change selection workflow must be native or classic");if(typeof e.change!="string")throw new Error("current change selection change must be a string");if(!du(e.branch))throw new Error("current change selection branch must be a string or null");if(e.workflow==="native"&&e.branch!==null)throw new Error("Native current change selection branch must be null");return{selection:e,legacy:!1}}async function Nt(t){let e;try{let r=xa(t),{bytes:n}=await hi(r,Cw,{label:"current change selection"});e=n.toString("utf8")}catch(r){if(r.code==="ENOENT")return{status:"missing"};throw new Error(`cannot read current change selection: ${r instanceof Error?r.message:String(r)}`,{cause:r})}return{status:"selected",...xw(e)}}var tn=xt(mt(),1);Ge();we();import en from"path";Ei();var Ia=["full","hotfix","tweak"],Ru=1,Au=["open","design","build","verify","archive"],Ww=["en","zh-CN"],qw=["off","beta"],Hw=["subagent-driven-development","executing-plans","direct"],Gw=["plan-ready"],zw=["confirmed"],Vw=["tdd","direct"],Kw=["off","standard","thorough"],Jw=["current","branch","worktree"],Uw=["light","full"],Yw=["pending","pass","fail"],Xw=["pending","handled"],Qw=["pending","confirmed"],ja=["workflow","language","phase","context_compression","build_mode","build_pause","subagent_dispatch","tdd_mode","review_mode","isolation","bound_branch","verify_mode","auto_transition","base_ref","design_doc","plan","verify_result","verify_failures","verification_report","branch_status","created_at","verified_at","archive_confirmation","archived","direct_override","handoff_context","handoff_hash","classic_profile","classic_migration"],Zw=["run_id"],Tu=new Set([...ja,...Zw]),ev=["workflow","phase","design_doc","plan","build_mode","isolation","verify_mode","verify_result","verified_at","archived"];function _u(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function kt(t,e){let i=t[e];if(i==null||i==="")return null;if(typeof i!="string")throw new Error(`Invalid Classic state: ${e} must be a string or null`);return i}function F(t,e,i,r=!0){let n=t[e];if(n==null||n===""){if(r)return null;throw new Error(`Invalid Classic state: ${e} is required`)}if(typeof n!="string"||!i.includes(n))throw new Error(`Invalid Classic state: ${e} must be one of ${i.join(", ")}${r?" or null":""}`);return n}function Oa(t,e,i=!0){let r=t[e];if(r==null||r===""){if(i)return null;throw new Error(`Invalid Classic state: ${e} is required`)}if(typeof r!="boolean")throw new Error(`Invalid Classic state: ${e} must be true or false`);return r}function tv(t,e,i=0){let r=t[e];if(r==null||r==="")return i;if(typeof r!="number"||!Number.isInteger(r)||r<0)throw new Error(`Invalid Classic state: ${e} must be a non-negative integer`);return r}function Zr(t,e){let i=kt(t,e);if(i===null)return null;if(/^(?:[A-Za-z]:|[\\/]|~)/u.test(i)||i.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Classic state: ${e} must be a relative repository path`);return i}function iv(t,e){let i=kt(t,e);if(i!==null&&!/^[a-f0-9]{64}$/u.test(i))throw new Error(`Invalid Classic state: ${e} must be a sha256 hex digest`);return i}function rv(t){let e=t.classic_migration;if(e==null||e==="")return null;if(e!==Ru)throw new Error(`Invalid Classic state: classic_migration must be ${Ru}`);return e}function nv(t){if(!ja.some(i=>_u(t,i)))return null;for(let i of ev)if(!_u(t,i))return null;return{workflow:F(t,"workflow",Ia,!1),language:F(t,"language",Ww),phase:F(t,"phase",Au,!1),contextCompression:F(t,"context_compression",qw),buildMode:F(t,"build_mode",Hw),buildPause:F(t,"build_pause",Gw),subagentDispatch:F(t,"subagent_dispatch",zw),tddMode:F(t,"tdd_mode",Vw),reviewMode:F(t,"review_mode",Kw),isolation:F(t,"isolation",Jw),boundBranch:kt(t,"bound_branch"),verifyMode:F(t,"verify_mode",Uw),autoTransition:Oa(t,"auto_transition"),baseRef:kt(t,"base_ref"),designDoc:Zr(t,"design_doc"),plan:Zr(t,"plan"),verifyResult:F(t,"verify_result",Yw,!1),verifyFailures:tv(t,"verify_failures"),verificationReport:Zr(t,"verification_report"),branchStatus:F(t,"branch_status",Xw),createdAt:kt(t,"created_at"),verifiedAt:kt(t,"verified_at"),archiveConfirmation:F(t,"archive_confirmation",Qw),archived:Oa(t,"archived",!1),directOverride:Oa(t,"direct_override"),handoffContext:Zr(t,"handoff_context"),handoffHash:iv(t,"handoff_hash"),classicProfile:F(t,"classic_profile",Ia),classicMigration:rv(t)}}function Ou(t,e){let i=e??null;if(i===null&&e===void 0&&t.run_id&&t.skill)try{i=Si(t)}catch(r){let n=r instanceof Error?r.message:String(r);throw new Error(n.replace(/^Invalid Run state:/u,"Invalid Classic state:"),{cause:r})}return{classic:nv(t),run:i,unknownKeys:Object.keys(t).filter(r=>!Tu.has(r))}}function Iu(t){let e=t.workflow,i=t.phase,r=t.archived,n=t.design_doc;return{workflow:typeof e=="string"&&Ia.includes(e)?e:null,phase:typeof i=="string"&&Au.includes(i)?i:null,archived:r===!0,designDoc:typeof n=="string"&&n!==""?n:null,unknownKeys:Object.keys(t).filter(o=>!Tu.has(o))}}Ei();var ov=2*1024*1024;function Ci(t){let e=t.toJS();if(e===null)return{};if(typeof e!="object"||Array.isArray(e))throw new Error("Invalid Classic state document: root must be a mapping");return e}function av(t){let e=["skill","skill_version","skill_hash","orchestration","current_step","iteration","pending","pending_ref","trajectory_ref","context_ref","artifacts_ref","checkpoint_ref","run_status","run_retries"];for(let i of e)t.delete(i)}function sv(t){let e=!1;for(let i of["build_command","verify_command"])t.has(i)&&(t.delete(i),e=!0);return e}async function ju(t){let e;try{e=(await te(en.dirname(t),en.basename(t),ov,{label:"Classic state document"})).bytes.toString("utf8")}catch(r){if(r.code!=="ENOENT")throw r;return new tn.Document({})}let i=(0,tn.parseDocument)(e);if(i.errors.length>0)throw new Error(`Invalid Classic state document: ${i.errors[0].message}`);return Ci(i),i}async function rn(t,e={}){let i=e.migrate!==!1,r=en.join(t,".comet.yaml"),n=await ju(r),o=Ci(n),a=sv(n);a&&(o=Ci(n));let s=await Aa(t);if(!s&&o.run_id&&o.skill){let{runStateFromDocument:c}=await Promise.resolve().then(()=>(Ei(),xu));s=c(o),s&&i&&(await Ta(t,s),av(n),a=!0)}return a&&i&&await ve(r,n.toString(),{containedRoot:t}),Ou(Ci(n),s)}async function Lu(t){let e=await ju(en.join(t,".comet.yaml"));return Iu(Ci(e))}var fv=K("readCometCurrentSelection",t=>Nt(t));async function dv(t,e){Sa(e);let i=await yi(e,t);if(!i.stateExists)throw new Error(`Cannot select current change '${e}': active change state not found`);let r=await rn(i.directory,{migrate:!1});if(!r.classic)throw new Error(`Cannot select current change '${e}': Classic state is incomplete`);if(r.classic.archived)throw new Error(`Cannot select current change '${e}': change is archived`);return i.directory}async function nn(t){let e;try{e=await fv(t)}catch(o){return{status:"stale",reason:o instanceof Error?o.message:String(o)}}if(e.status==="missing")return{status:"missing"};if(e.selection.workflow!=="classic")return{status:"stale",reason:`current change '${e.selection.change}' belongs to Native, not Classic`};let i=e.selection,r;try{r=await dv(t,i.change)}catch(o){return{status:"stale",reason:o instanceof Error?o.message:String(o)}}let n=await Jr(r,{heal:!1,cwd:t});return n.status==="drift"?{status:"stale",reason:Ur(i.change,n.boundBranch,n.currentBranch)}:n.status==="unbound-detached"?{status:"stale",reason:Yr(i.change)}:n.status==="ok"?{status:"selected",selection:i}:i.branch!==null&&n.currentBranch!==i.branch?{status:"stale",reason:`current change '${i.change}' was selected on branch '${i.branch}', current branch is '${n.currentBranch??"detached HEAD"}'`}:{status:"selected",selection:i}}import Ke from"node:path";async function $u(t,e){if(!e||e==="null")return{status:"missing",recordedPath:null};let i=await ye(t),r=Ke.resolve(t,e),n=Ke.relative(i.superpowersPlansDir,r);return Ke.isAbsolute(e)||!n||n.startsWith(`..${Ke.sep}`)||Ke.isAbsolute(n)||n.includes(Ke.sep)||Ke.extname(n).toLowerCase()!==".md"?{status:"broken",recordedPath:e}:await au(t,e,{label:`Classic build plan ${e}`,expected:"file"})?{status:"ready",recordedPath:e}:{status:"broken",recordedPath:e}}function ie(t,e){return{exitCode:t,stderr:e+` +`}}function be(t){return ie(0,`[COMET-HOOK] allowed: ${t}`)}function xi(t){return t.replaceAll("\\","/").replace(/\/+/gu,"/")}function Je(t){let e=xi(t);return process.platform==="win32"?e.toLowerCase():e}function Du(t,e){let i=xi(J.relative(e,t));return i===""?"":i.startsWith("../")||i===".."||J.isAbsolute(i)?null:i}async function hv(t){let e=J.resolve(t),i=J.parse(e).root,r=[],n=e;for(;n&&n!==i;)try{let o=await on.realpath(n);return J.join(o,...r.reverse())}catch(o){let a=o.code;if(a!=="ENOENT"&&a!=="ENOTDIR")throw o;r.push(J.basename(n)),n=J.dirname(n)}try{let o=await on.realpath(i);return J.join(o,...r.reverse())}catch{return null}}async function mv(t,e){let i=J.isAbsolute(t)?t:J.resolve(e,t),r=xi(i),n=Du(i,e);if(n!==null)return n;try{let o=await hv(i),a=await on.realpath(e);if(o){let s=Du(o,a);if(s!==null)return s;r=xi(o)}}catch{if(!J.isAbsolute(t))return xi(t).replace(/^\.\//u,"")}return r.replace(/^\.\//u,"")}async function Wu(t){try{let e=await rn(t,{migrate:!1}),i=Array.from(new Set(e.unknownKeys)).sort();if(i.length>0)throw new Error(`Invalid Classic state: unknown field(s): ${i.join(", ")}`);if(!e.classic)throw new Error("Classic state projection is unavailable");return{changeDir:t,phase:e.classic.phase,classic:e.classic,archived:e.classic.archived}}catch(e){let i=await Lu(t);return i.phase?{changeDir:t,phase:i.phase,classic:null,archived:i.archived,invalidState:e instanceof Error&&e.message.includes("unknown field")}:null}}async function pv(t){let e=(await ye(t)).changesDir,i=[];if(!(await bt(t,e,{label:"Classic changes directory",expected:"directory"})).exists)return i;for(let n of(await on.readdir(e,{withFileTypes:!0})).sort((o,a)=>o.name.localeCompare(a.name))){if(n.name==="archive"||ka(n.name))continue;let o=await yi(n.name,t);if(!o.exists||!o.stateExists)continue;let a=await Wu(o.directory);!a||a.archived||i.push(a)}return i}var Ri=K("classicActiveChanges",t=>pv(t)),qu=K("classicPlanReadiness",$u);async function Hu(t){return(await Ri(t)).map(e=>({workflow:"classic",name:re(e),phase:e.phase}))}function Gu(t,e){return`${M(t,e.superpowersRoot)}/`}function zu(t,e){return Je(t).startsWith(Je(e))}function gv(t,e){return[{prefix:`${M(t,e.superpowersSpecsDir)}/`,field:"designDoc",wireField:"design_doc",phase:"design"},{prefix:`${M(t,e.superpowersPlansDir)}/`,field:"plan",wireField:"plan",phase:"build"},{prefix:`${M(t,e.superpowersReportsDir)}/`,field:"verificationReport",wireField:"verification_report",phase:"verify"}]}function wv(t,e){let i=Je(t),r=e.find(o=>i.startsWith(Je(o.prefix)));if(!r)return null;let n=i.slice(Je(r.prefix).length);return!n||n.includes("/")||!n.endsWith(".md")?null:r}function Vu(t,e){return t.classic?.[e.field]??null}function vv(t,e){return t.classic!==null&&t.phase===e.phase&&!Vu(t,e)}async function Bu(t,e,i){return vv(e,i)?!0:i.field!=="plan"||e.phase!=="build"?!1:(await qu(t,e.classic?.plan??null)).status==="broken"}function Ku(t){return t.phase==="design"||t.phase==="build"||t.phase==="verify"}function re(t){return t.changeDir?J.basename(t.changeDir):null}var yv=new Set(["design","plan","verify","verification","verification-report","report"]);function Mu(t){return t.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}function bv(t,e){return[e.classic?.designDoc,e.classic?.plan,e.classic?.verificationReport].some(r=>r&&Je(r)===Je(t))}function Nv(t,e){let r=(t.split("/").at(-1)??t).replace(/\.[^.]+$/u,"");if(r===e)return!0;let n=[...yv].map(Mu).join("|");return new RegExp(`(^|[-_.])${Mu(e)}[-_.](${n})$`,"u").test(r)}async function kv(t,e){let i=await Ri(e),r=i.find(a=>bv(t,a));if(r)return{governing:r,match:"recorded"};let o=i.filter(Ku).filter(a=>{let s=re(a);return s!==null&&Nv(t,s)}).sort((a,s)=>(re(s)?.length??0)-(re(a)?.length??0))[0];return o?{governing:o,match:"named"}:null}async function Fu(t,e,i){let r=await Ri(t);if(r.length===0)return null;if(i)return r.find(a=>re(a)===i)??{blockedResult:Pi(e,`selected change '${i}' is no longer active`)};let n=await nn(t);if(n.status==="stale")return{blockedResult:Pi(e,n.reason)};if(n.status==="selected"){let o=r.find(a=>re(a)===n.selection.change);return o||{blockedResult:Pi(e,`selected change '${n.selection.change}' is no longer active`)}}if(r.length===1){let o=r[0];if(o.changeDir!==null){let a=await Jr(o.changeDir,{heal:!1,cwd:t}),s=re(o)??"unknown";if(a.status==="drift")return{blockedResult:Pi(e,Ur(s,a.boundBranch,a.currentBranch))};if(a.status==="unbound-detached")return{blockedResult:Pi(e,Yr(s))}}return o}return{blockedResult:Ov(e,r.map(o=>re(o)).filter(Boolean))}}async function Sv(t,e,i,r){let n=`${M(e,i.changesDir)}/`;if(t.startsWith(n)){let o=t.slice(n.length),[a]=o.split("/");if(a&&a!=="archive"){let s=await yi(a,e);if(s.stateExists){let c=await Wu(s.directory);return c||{changeDir:s.directory,phase:"open",classic:null,archived:!1}}return{changeDir:s.directory,phase:"open",classic:null,archived:!1}}}if(zu(t,Gu(e,i))){let o=await kv(t,e);if(o?.match==="recorded")return{...o.governing,superpowersArtifact:"matched"};let a=wv(t,gv(e,i));if(o)return a?{...o.governing,superpowersArtifact:await Bu(e,o.governing,a)?"matched":"unmatched",superpowersSlot:a}:{...o.governing,superpowersArtifact:"matched"};if(a){let l=await Fu(e,t,r);return!l||"blockedResult"in l?l:{...l,superpowersArtifact:await Bu(e,l,a)?"matched":"unmatched",superpowersSlot:a}}let s=await Ri(e),c=r?s.find(l=>re(l)===r)??null:s[0]??null;return c?{...c,superpowersArtifact:"unmatched"}:null}return Fu(e,t,r)}function Ev(t){return!t.includes("/")&&t.endsWith(".md")}function Cv(t){return t.startsWith(".comet/")||t.includes("/.comet/")}function Pv(t){return t===".superpowers"||t.startsWith(".superpowers/")}function xv(t,e,i){if(!t.startsWith(i))return null;let r=t.endsWith("/.comet.yaml")||t.endsWith("/.openspec.yaml"),n=t.endsWith("/proposal.md")||t.endsWith("/design.md")||t.endsWith("/tasks.md"),o=t.includes("/.comet/"),a=t.includes("/specs/");return e==="open"&&(n||r||o||a)?`${t} (phase: open, openspec artifacts)`:e==="design"&&(n||r||o||a)?`${t} (phase: design, handoff/spec)`:e==="build"&&(t.endsWith("/tasks.md")||r||a)?`${t} (phase: build, spec/tasks)`:e==="verify"&&(t.endsWith("/tasks.md")||r)?`${t} (phase: verify, tasks/state)`:e==="archive"&&r?`${t} (phase: archive, state)`:null}function Rv(t,e){let i=e==="open"?[" BLOCKED: source writes are not allowed during open"," This phase does not allow source writes"," ALLOWED: create proposal/design/tasks artifacts and run guard"," NEXT: finish clarification and artifacts, then run guard --apply"]:e==="design"?[" BLOCKED: source writes are not allowed during design"," This phase does not allow source writes"," ALLOWED: run brainstorming, create the Design Doc, and run guard"," NEXT: finish the Design Doc, then run comet guard design --apply to enter build"]:[" BLOCKED: source writes are not allowed during archive"," This phase does not allow source writes"," ALLOWED: confirm archive state and run the archive script"];return ie(2,["","╔══════════════════════════════════════════╗","║ COMET PHASE GUARD — WRITE BLOCKED ║","╚══════════════════════════════════════════╝","",` Current phase: ${e}`,` Target file: ${t}`,"",...i,""].join(` `))}function _v(t){return ie(2,["","╔══════════════════════════════════════════╗","║ COMET PHASE GUARD — WRITE BLOCKED ║","╚══════════════════════════════════════════╝",""," Current phase: build (workflow: full), but design_doc is empty",` Target file: ${t}`,""," BLOCKED: full workflow source writes require a recorded Design Doc"," This phase does not allow source writes until design_doc is recorded"," NEXT: return to design, create/link the Design Doc, then run guard again",""].join(` -`))}function Av(t,e,i,r,n){let o=re(e)??"",a=i.status==="missing",s=a?"classic-build-plan-missing":"classic-build-plan-broken",c=a?"plan is not recorded":"the recorded plan path does not resolve to a file",l=a?[]:[`RECORDED_PLAN: ${i.recordedPath}`],f=e.changeDir?$(r,e.changeDir):"",u=$(r,n.superpowersPlansDir),d=a?`comet state set ${o} plan `:`comet state set ${o} plan `,m=a?["2. Load the Superpowers writing-plans Skill.",`3. Read the Design Doc path from "comet state get ${o} design_doc" and read ${f}/tasks.md.`,`4. Create the implementation plan under ${u}/.`,"5. Record the plan path:",` ${d}`]:[`2. Restore the plan file at ${i.recordedPath}, or load the Superpowers writing-plans Skill and create a replacement under ${u}/.`,"3. When creating a replacement, record its path:",` ${d}`];return ie(2,["","╔══════════════════════════════════════════╗","║ COMET PHASE GUARD — WRITE BLOCKED ║","╚══════════════════════════════════════════╝","",`ERROR_CODE: ${s}`,`CHANGE: ${o}`,"WORKFLOW: full","PHASE: build",`TARGET: ${t}`,`STATE: ${c}`,...l,"","BLOCKED: project source writes require a ready Superpowers implementation plan.","","ALLOWED_RECOVERY_WRITES:",`- ${u}/.md`,"- Comet state updates performed by the comet CLI",`- ${f} artifacts allowed by the build phase`,"","RECOVERY:",`1. Invoke /comet-build for ${o} and resume Step 1.`,...m,`${a?"6":"4"}. Verify recovery:`,` comet state check ${o} build --recover`,"","SUCCESS: plan is reported as DONE and recovery advances beyond plan creation.",`RETRY: retry the original Write/Edit for ${t} only after SUCCESS.`,"PROHIBITED: do not treat tasks.md as the implementation plan or write project source before SUCCESS.","If writing-plans is unavailable, stop and report the missing Skill instead of bypassing this check.",""].join(` -`))}function Tv(t,e){let i=e.superpowersSlot,r=i?zu(e,i):null,n=i?e.phase!==i.phase?[` BLOCKED: ${i.wireField} cannot be first-written in phase ${e.phase}`,` Expected phase: ${i.phase}`," NEXT: resume the matching Comet phase or use an already recorded artifact path"]:r?[` BLOCKED: ${i.wireField} is already recorded for this change`,` Recorded path: ${r}`," NEXT: write the recorded artifact or explicitly correct the state path"]:[" BLOCKED: standard Superpowers artifact state is incomplete"," NEXT: validate the active change state, then retry the matching phase"]:[" BLOCKED: unmatched Superpowers artifact"," This docs/superpowers/ path does not match any active change artifact"," NEXT: use a recorded artifact path or a standard phase artifact directory"];return ie(2,["","╔══════════════════════════════════════════╗","║ COMET PHASE GUARD — WRITE BLOCKED ║","╚══════════════════════════════════════════╝","",` Current phase: ${e.phase}`,` Target file: ${t}`,"",...n,""].join(` +`))}function Av(t,e,i,r,n){let o=re(e)??"",a=i.status==="missing",s=a?"classic-build-plan-missing":"classic-build-plan-broken",c=a?"plan is not recorded":"the recorded plan path does not resolve to a file",l=a?[]:[`RECORDED_PLAN: ${i.recordedPath}`],f=e.changeDir?M(r,e.changeDir):"",u=M(r,n.superpowersPlansDir),d=a?`comet state set ${o} plan `:`comet state set ${o} plan `,m=a?["2. Load the Superpowers writing-plans Skill.",`3. Read the Design Doc path from "comet state get ${o} design_doc" and read ${f}/tasks.md.`,`4. Create the implementation plan under ${u}/.`,"5. Record the plan path:",` ${d}`]:[`2. Restore the plan file at ${i.recordedPath}, or load the Superpowers writing-plans Skill and create a replacement under ${u}/.`,"3. When creating a replacement, record its path:",` ${d}`];return ie(2,["","╔══════════════════════════════════════════╗","║ COMET PHASE GUARD — WRITE BLOCKED ║","╚══════════════════════════════════════════╝","",`ERROR_CODE: ${s}`,`CHANGE: ${o}`,"WORKFLOW: full","PHASE: build",`TARGET: ${t}`,`STATE: ${c}`,...l,"","BLOCKED: project source writes require a ready Superpowers implementation plan.","","ALLOWED_RECOVERY_WRITES:",`- ${u}/.md`,"- Comet state updates performed by the comet CLI",`- ${f} artifacts allowed by the build phase`,"","RECOVERY:",`1. Invoke /comet-build for ${o} and resume Step 1.`,...m,`${a?"6":"4"}. Verify recovery:`,` comet state check ${o} build --recover`,"","SUCCESS: plan is reported as DONE and recovery advances beyond plan creation.",`RETRY: retry the original Write/Edit for ${t} only after SUCCESS.`,"PROHIBITED: do not treat tasks.md as the implementation plan or write project source before SUCCESS.","If writing-plans is unavailable, stop and report the missing Skill instead of bypassing this check.",""].join(` +`))}function Tv(t,e){let i=e.superpowersSlot,r=i?Vu(e,i):null,n=i?e.phase!==i.phase?[` BLOCKED: ${i.wireField} cannot be first-written in phase ${e.phase}`,` Expected phase: ${i.phase}`," NEXT: resume the matching Comet phase or use an already recorded artifact path"]:r?[` BLOCKED: ${i.wireField} is already recorded for this change`,` Recorded path: ${r}`," NEXT: write the recorded artifact or explicitly correct the state path"]:[" BLOCKED: standard Superpowers artifact state is incomplete"," NEXT: validate the active change state, then retry the matching phase"]:[" BLOCKED: unmatched Superpowers artifact"," This docs/superpowers/ path does not match any active change artifact"," NEXT: use a recorded artifact path or a standard phase artifact directory"];return ie(2,["","╔══════════════════════════════════════════╗","║ COMET PHASE GUARD — WRITE BLOCKED ║","╚══════════════════════════════════════════╝","",` Current phase: ${e.phase}`,` Target file: ${t}`,"",...n,""].join(` `))}function Ov(t,e){return ie(2,["","╔══════════════════════════════════════════╗","║ COMET PHASE GUARD — WRITE BLOCKED ║","╚══════════════════════════════════════════╝",""," BLOCKED: multiple active changes require a current change",` Target file: ${t}`,` Active changes: ${e.join(", ")}`,""," NEXT: run comet state select , then retry the source write",""].join(` `))}function Pi(t,e){return ie(2,["","╔══════════════════════════════════════════╗","║ COMET PHASE GUARD — WRITE BLOCKED ║","╚══════════════════════════════════════════╝",""," BLOCKED: current change selection is stale or invalid",` Target file: ${t}`,` Reason: ${e}`,""," NEXT: run comet state select , then retry the source write",""].join(` `))}async function Iv(t,e,i,r=Kr){try{if((await r(t,[e])).projectTargets.length===0)return be(`${e} (outside guarded project)`)}catch(l){return ie(2,[`[COMET-HOOK] blocked: scope could not be determined safely for ${e}.`,`REASON: ${l instanceof Error?l.message:String(l)}`,"NEXT: verify that the project root is accessible, then retry the write."].join(` -`))}let n=await mv(e,t),o;try{o=await Vr(t)}catch(l){return ie(2,`[COMET-HOOK] blocked: ${l instanceof Error?l.message:String(l)}`)}if(Cv(n))return be(`${n} (whitelist: comet config)`);if(Pv(n))return be(`${n} (whitelist: superpowers workspace)`);if(n==="CLAUDE.md"||n==="CHANGELOG.md"||n==="README.md"||Ev(n))return be(`${n} (whitelist: root markdown)`);let a;try{a=await Sv(n,t,o,i)}catch(l){return ie(2,`[COMET-HOOK] blocked: ${l instanceof Error?l.message:String(l)}`)}if(!a)return be("no active comet change");if("blockedResult"in a)return a.blockedResult;if(a.archived)return be(`${n} (own change archived)`);let s=a.phase,c=xv(n,s,`${$(t,o.openSpecRoot)}/`);if(c)return be(c);if(Gu(n,Hu(t,o))){if(a.superpowersArtifact==="matched"&&Vu(a))return be(`${n} (phase: ${s}, superpowers)`);if(a.superpowersArtifact==="unmatched")return Tv(n,a)}if(a.invalidState)return ie(2,`[COMET-HOOK] blocked: active Classic state is invalid; repair .comet.yaml before writing ${n}`);if(s==="build"&&a.classic?.workflow==="full"&&!a.classic.designDoc)return _v(n);if(s==="build"&&a.classic?.workflow==="full"){let l=await Wu(t,a.classic.plan);if(l.status!=="ready")return Av(n,a,l,t,o)}return s==="build"||s==="verify"?be(`${n} (phase: ${s})`):Rv(n,s)}async function Ku(t,e,i,r={}){if(i.intent!=="non-write")try{await Vr(t)}catch(a){return{allowed:!1,reason:a instanceof Error?a.message:String(a),workflow:"classic",change:e}}let n;try{n=await Ri(t)}catch(a){return{allowed:!1,reason:a instanceof Error?a.message:String(a),workflow:"classic",change:e}}let o=n.find(a=>re(a)===e);if(!o)return{allowed:!1,reason:`Selected Classic change ${e} is missing or archived; resume /comet-classic before retrying`,workflow:"classic",change:e};if(i.intent==="non-write")return{allowed:!0,reason:"Hook event is not a write"};if(i.intent==="unknown"||i.targets.length===0)return{allowed:!0,reason:"Hook write target was not attributed to the guarded project",workflow:"classic",change:e,phase:o.phase};for(let a of i.targets){let s=await Iv(t,a,e,r.scopeTargets);if(s.exitCode!==0)return{allowed:!1,reason:s.stderr?.trim()||"Classic phase guard blocked the write",workflow:"classic",change:e,phase:o.phase}}return{allowed:!0,reason:`Classic write allowed in ${o.phase}`,workflow:"classic",change:e,phase:o.phase}}import{promises as lb}from"fs";import Pt from"path";var za=xt(mt(),1);import{promises as qy}from"fs";import et from"path";import{createHash as Dv}from"node:crypto";import{promises as ne}from"node:fs";import U from"node:path";import{TextDecoder as Bv}from"node:util";var jv=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),Lv=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function $v(t){return t.toLowerCase().startsWith(".env")}function La(t){let i=t.replaceAll("\\","/").split("/").filter(Boolean).map(r=>r.toLowerCase());return i.some(r=>$v(r))?"environment-file":i.some(r=>Lv.has(r))?"credential-config":i.includes(".git")?"git-metadata":i.some(r=>jv.has(r))?"dependency-or-cache":i.join("/")===".comet/config.yaml"?"comet-config":i.join("/")===".comet/current-change.json"?"comet-selection":null}fi();var Mv=1024*1024;function $a(t,e){let i=U.relative(t,e);return i===""||!U.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${U.sep}`)}function Fv(t){let e=U.posix.normalize(t);if(t.length===0||t!==t.trim()||t.includes("\\")||Array.from(t).some(n=>{let o=n.codePointAt(0)??0;return o<=31||o===127})||U.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes("..")||e!==t||e==="."||t.endsWith("/"))throw new Error(`Native artifact ref must be normalized and relative: ${t}`);let i=t.toLowerCase(),r=La(t);if(r||i==="runtime"||i.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${r??"native-runtime"}): ${t}`);return t}function Wv(t){if(!Number.isSafeInteger(t)||t<1)throw new Error("Native artifact byte limit must be a positive integer");return t}function qv(t,e){return T({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function an(t,e){let i={...t,birthtime:t.birthtimeMs},r={...e,birthtime:e.birthtimeMs};return fe(i,r)?T(i,r):T(i,r)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.size===e.size}async function Ju(t){let e=await ne.lstat(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${t}`);return{path:t,realPath:await ne.realpath(t),dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}async function Hv(t,e){let i=U.resolve(t),r=U.resolve(e);if(!$a(i,r))throw new Error("Native artifact path is outside its root");let n=[await Ju(i)],o=i;for(let a of U.relative(i,r).split(U.sep).filter(Boolean)){o=U.join(o,a);let s=await Ju(o);if(!$a(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${o}`);n.push(s)}return n}async function Uu(t){for(let e of t){let i=await ne.lstat(e.path);if(!i.isDirectory()||i.isSymbolicLink()||!qv(e,i)||await ne.realpath(e.path)!==e.realPath)throw new Error(`Native artifact parent changed while reading: ${e.path}`)}}async function sn(t){let e=Fv(t.ref),i=Wv(t.maxBytes??Mv),r=U.resolve(t.root,...e.split("/")),n=await Hv(t.root,U.dirname(r));await t.hooks?.afterParentChainCaptured?.();let o=await ne.lstat(r);if(!o.isFile()||o.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${e}`);if(o.size>i)throw new Error(`Native artifact exceeds ${i} bytes: ${e}`);let a=await ne.realpath(r);if(!$a(n[0].realPath,a))throw new Error(`Native artifact resolves outside its root: ${e}`);let s=await ne.open(r,"r");try{let[c,l,f]=await Promise.all([s.stat(),ne.lstat(r),ne.realpath(r)]);if(await Uu(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||f!==a||!an(o,c)||!an(c,l))throw new Error(`Native artifact changed while opening: ${e}`);await t.hooks?.afterOpen?.();let u=[],d=0,m=Buffer.allocUnsafe(Math.min(64*1024,i+1));for(;;){let k=i+1-d,S=await s.read(m,0,Math.min(m.length,k),null);if(S.bytesRead===0)break;if(d+=S.bytesRead,d>i)throw new Error(`Native artifact exceeds ${i} bytes: ${e}`);u.push(Buffer.from(m.subarray(0,S.bytesRead)))}await t.hooks?.beforeFinalCheck?.();let[w,h,p]=await Promise.all([s.stat(),ne.lstat(r),ne.realpath(r)]);if(await Uu(n),!h.isFile()||h.isSymbolicLink()||p!==a||!an(c,w)||!an(c,h))throw new Error(`Native artifact changed while reading: ${e}`);let y=Buffer.concat(u,d),b;try{b=new Bv("utf-8",{fatal:!0}).decode(y)}catch(k){throw new Error(`Native artifact is not valid UTF-8: ${e}`,{cause:k})}return{ref:e,size:d,hash:Dv("sha256").update(y).digest("hex"),text:b}}finally{await s.close()}}ue();He();zr();var cn=$r;async function ln(t){let e=(await qe(t))?.config??null;return e?.native?e:null}import{AsyncLocalStorage as Gv}from"async_hooks";Mr();var nC=16*1024;var oC=new Gv;import{TextDecoder as Zv}from"util";import{createHash as zv}from"node:crypto";import{constants as un,promises as oe}from"node:fs";import ae from"node:path";import{TextDecoder as Vv}from"node:util";function dn(t,e){let i=ae.relative(t,e);return i===""||!ae.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${ae.sep}`)}function Kv(t){if(!Number.isSafeInteger(t)||t<1)throw new Error("Native protected file byte limit must be a positive integer");return t}function Jv(t,e){return T({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function Uv(t){return{dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs,ctimeMs:t.ctimeMs,mtimeMs:t.mtimeMs,size:t.size}}function fn(t,e){return T({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.mtimeMs===e.mtimeMs&&t.size===e.size}async function Ba(t,e){let i=await oe.lstat(t);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${e} parent must be a real directory: ${t}`);return{path:t,realPath:await oe.realpath(t),dev:i.dev,ino:i.ino,birthtimeMs:i.birthtimeMs}}async function Yv(t,e,i){let r=ae.resolve(t),n=ae.resolve(e);if(!dn(r,n))throw new Error(`${i} is outside its managed root`);let o=[await Ba(r,i)],a=r;for(let s of ae.relative(r,n).split(ae.sep).filter(Boolean)){await Ue(o,i),a=ae.join(a,s);let c=await Ba(a,i);if(!dn(o[0].realPath,c.realPath))throw new Error(`${i} parent resolves outside its managed root: ${a}`);o.push(c)}return await Ue(o,i),o}async function Ue(t,e){for(let i of t){let r=await oe.lstat(i.path);if(!r.isDirectory()||r.isSymbolicLink()||!Jv(i,r)||await oe.realpath(i.path)!==i.realPath)throw new Error(`${e} parent changed during I/O: ${i.path}`)}}async function Xv(t,e,i){let r=[],n=0,o=Buffer.allocUnsafe(Math.min(64*1024,e+1));for(;;){let a=e+1-n,{bytesRead:s}=await t.read(o,0,Math.min(o.length,a),null);if(s===0)break;if(n+=s,n>e)throw new Error(`${i} exceeds ${e} bytes`);r.push(Buffer.from(o.subarray(0,s)))}return Buffer.concat(r,n)}async function Yu(t){let e=Kv(t.maxBytes),i=ae.resolve(t.file),r=await Yv(t.root,ae.dirname(i),t.label),n=await Promise.all((t.forbiddenRoots??[]).map(f=>Ba(ae.resolve(f),t.label)));await t.hooks?.afterParentChainCaptured?.(),await Ue(r,t.label);let o=await oe.lstat(i);if(!o.isFile()||o.isSymbolicLink())throw new Error(`${t.label} must be a regular file`);if(o.size>e)throw new Error(`${t.label} exceeds ${e} bytes`);let a=Uv(o),s=await oe.realpath(i);if(!dn(r[0].realPath,s))throw new Error(`${t.label} resolves outside its managed root`);if(n.some(f=>dn(f.realPath,s)))throw new Error(`${t.label} resolves inside an excluded root`);let c=process.platform==="win32"?un.O_RDONLY:un.O_RDONLY|un.O_NOFOLLOW|un.O_NONBLOCK,l=await oe.open(i,c);try{let f=await l.stat();await t.hooks?.afterOpen?.();let[u,d]=await Promise.all([oe.lstat(i),oe.realpath(i)]);if(await Ue(r,t.label),await Ue(n,t.label),!f.isFile()||!u.isFile()||u.isSymbolicLink()||d!==s||!fn(a,f)||!fn(a,u))throw new Error(`${t.label} changed while opening`);await t.hooks?.beforeRead?.();let m=await Xv(l,e,t.label);await t.hooks?.beforeFinalCheck?.();let[w,h,p]=await Promise.all([l.stat(),oe.lstat(i),oe.realpath(i)]);if(await Ue(r,t.label),await Ue(n,t.label),!h.isFile()||h.isSymbolicLink()||p!==s||!fn(a,w)||!fn(a,h))throw new Error(`${t.label} changed while reading`);return{bytes:m,hash:zv("sha256").update(m).digest("hex"),size:m.length}}finally{await l.close()}}async function Xu(t){let e=await Yu(t),i;try{i=new Vv("utf-8",{fatal:!0}).decode(e.bytes)}catch(r){throw new Error(`${t.label} is not valid UTF-8`,{cause:r})}return{...e,text:i}}var SC=256*1024,EC=1024*1024,CC=16*1024;var PC=64*1024*1024;var xC=new Zv("utf-8",{fatal:!0});import mn from"path";import{createHash as ey}from"crypto";function ef(t){return ey("sha256").update(t).digest("hex")}var JC={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},iy=1e3,ry=8*1024*1024,ny=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,oy=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),ay=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),sy=new Set(["schema","include","exclude","hash"]),cy=new Set(["provider","gitSelection","physicalSelection","projection"]),ly=new Set(["provider","selection"]),uy=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),fy=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),dy=new Set(["schema","status","before","after"]),hy=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),my=new Set(["path","hash","size","type","gitObjectId"]),py=new Set(["path","size","type","reason"]),gy=new Set(["ref","hash","count"]),wy=new Set(["change-created","legacy-migration","explicit"]),vy=new Set(["file","directory","other"]),yy=new Set(["file-size","file-count","total-size","manifest-size","changed-during-read","unreadable","gitlink-unavailable","gitlink-dirty","gitlink-changed","legacy-gitlink-boundary","git-enumeration-limit","git-selection-changed","physical-enumeration-limit","physical-selection-changed"]),pn=/^[a-f0-9]{64}$/u,by=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;var UC=64*1024,YC=64*1024;var XC={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},QC={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};function hn(t,e){return t.hash===e.hash&&t.recordCount===e.recordCount&&t.storedRecordCount===e.storedRecordCount&&t.stdoutBytes===e.stdoutBytes&&t.overflow===e.overflow}var ZC=(1n<<256n)-1n;function Ny(t,e){return t.hash===e.hash&&t.visitedNodeCount===e.visitedNodeCount&&t.recordCount===e.recordCount&&t.storedRecordCount===e.storedRecordCount&&t.encodedBytes===e.encodedBytes&&t.overflow===e.overflow&&t.unstable===e.unstable}function ky(t){return Buffer.byteLength(JSON.stringify(t,null,2)+` -`)}function Sy(t,e){return ef(`comet.native.snapshot-policy.v1 -${JSON.stringify({include:t,exclude:e,hash:"sha256"})}`)}function Ma(t,e,i){let r=new Set(e),n=[...e];for(;n.length>0;){if(i&&!i())return null;let o=n.pop(),a=t[o];a&&(a.kind==="star"||a.kind==="globstar"||a.kind==="globstar-slash")&&!r.has(o+1)&&(r.add(o+1),n.push(o+1))}return r}function Ey(t){let e=0;return()=>e>0?(e-=1,!0):t()?(e=63,!0):!1}function tf(t){let e=cn(t,"Native snapshot pattern"),i=[];for(let r=0;r{let o=n?Ey(n):void 0;if(o&&!o())return!1;let a=Ma(i,new Set([0]),o);if(a===null)return!1;for(let s of r){if(o&&!o())return!1;let c=new Set;for(let l of a){if(o&&!o())return!1;let f=i[l];f&&(f.kind==="literal"&&f.value===s||f.kind==="question"&&s!=="/"?c.add(l+1):f.kind==="star"&&s!=="/"||f.kind==="globstar"?c.add(l):f.kind==="globstar-slash"&&(c.add(l),s==="/"&&c.add(l+1)))}if(a=Ma(i,c,o),a===null||a.size===0)return!1}return Ma(i,a,o)?.has(i.length)??!1}}function Cy(t){if(t===void 0)return;let e=[...new Set(t.include.map(n=>cn(n,"include")))].sort((n,o)=>n.localeCompare(o,"en")),i=[...new Set(t.exclude.map(n=>cn(n,"exclude")))].sort((n,o)=>n.localeCompare(o,"en"));if(e.length===0)throw new Error("Native snapshot policy include must not be empty");let r=Sy(e,i);if("hash"in t&&t.hash!==r)throw new Error("Native snapshot policy hash is invalid");return{manifest:{schema:"comet.native.snapshot-policy.v1",include:e,exclude:i,hash:r},includeMatchers:e.map(tf),excludeMatchers:i.map(tf),excludedDirectoryPrefixes:i.flatMap(n=>{if(!n.endsWith("/**"))return[];let o=n.slice(0,-3);return/[*?]/u.test(o)?[]:[o]}).sort((n,o)=>n.localeCompare(o,"en"))}}function Y(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function X(t,e,i){let r=Object.keys(t).find(n=>!e.has(n));if(r)throw new Error(`${i} contains unknown field: ${r}`)}function Et(t,e){if(!Number.isSafeInteger(t)||t<1)throw new Error(`${e} must be a positive integer`);return t}function de(t,e){if(!Number.isSafeInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return t}function of(t,e){if(typeof t!="string"||t.length===0||t.includes("\\")||t.includes("\0"))throw new Error(`${e} must be a normalized project-relative path`);let i=mn.posix.normalize(t);if(i!==t||mn.posix.isAbsolute(t)||i===".."||i.startsWith("../"))throw new Error(`${e} must stay inside the project root`);return t}function Py(t,e){let i=Y(t,`Native snapshot entry ${e}`);X(i,my,`Native snapshot entry ${e}`);let r=of(i.path,`Native snapshot entry ${e} path`);if(typeof i.hash!="string"||!pn.test(i.hash))throw new Error(`Native snapshot entry ${e} hash is invalid`);if(i.type!=="file")throw new Error(`Native snapshot entry ${e} type is invalid`);let n={path:r,hash:i.hash,size:de(i.size,`Native snapshot entry ${e} size`),type:"file"};if(i.gitObjectId!==void 0){if(typeof i.gitObjectId!="string"||!by.test(i.gitObjectId))throw new Error(`Native snapshot entry ${e} gitObjectId is invalid`);n.gitObjectId=i.gitObjectId}return n}function xy(t,e){let i=Y(t,`Native snapshot omission ${e}`);if(X(i,py,`Native snapshot omission ${e}`),!vy.has(i.type))throw new Error(`Native snapshot omission ${e} type is invalid`);if(!yy.has(i.reason))throw new Error(`Native snapshot omission ${e} reason is invalid`);return{path:of(i.path,`Native snapshot omission ${e} path`),size:i.size===null?null:de(i.size,`Native snapshot omission ${e} size`),type:i.type,reason:i.reason}}function Ry(t){let e=Y(t,"Native snapshot omission overflow");if(X(e,gy,"Native snapshot omission overflow"),typeof e.hash!="string"||!pn.test(e.hash))throw new Error("Native snapshot omission overflow hash is invalid");let i=`native-snapshot://omitted-overflow/${e.hash}`;if(e.ref!==i)throw new Error("Native snapshot omission overflow ref is invalid");return{ref:i,hash:e.hash,count:Et(e.count,"Native snapshot omission overflow count")}}function St(t,e){let i=Y(t,e);if(X(i,fy,e),typeof i.hash!="string"||!pn.test(i.hash))throw new Error(`${e} hash is invalid`);if(typeof i.overflow!="boolean")throw new Error(`${e} overflow flag is invalid`);let r=de(i.recordCount,`${e} recordCount`),n=de(i.storedRecordCount,`${e} storedRecordCount`),o=de(i.stdoutBytes,`${e} stdoutBytes`);if(n>r||!i.overflow&&n!==r)throw new Error(`${e} stored record count is inconsistent`);return{hash:i.hash,recordCount:r,storedRecordCount:n,stdoutBytes:o,overflow:i.overflow}}function rf(t){let e=Y(t,"Native Git selection evidence");if(X(e,uy,"Native Git selection evidence"),e.schema!=="comet.native.git-selection.v1")throw new Error("Native Git selection evidence schema is invalid");if(e.status!=="overflow"&&e.status!=="changed"&&e.status!=="overflow-and-changed")throw new Error("Native Git selection evidence status is invalid");let i=St(e.stageBefore,"Native Git selection stageBefore"),r=St(e.combined,"Native Git selection combined"),n=St(e.stageAfter,"Native Git selection stageAfter"),o=St(e.finalStageBefore,"Native Git selection finalStageBefore"),a=St(e.finalCombined,"Native Git selection finalCombined"),s=St(e.finalStageAfter,"Native Git selection finalStageAfter"),c=[i,r,n,o,a,s].some(u=>u.overflow),l=!hn(i,n)||!hn(n,o)||!hn(r,a)||!hn(o,s),f=c&&l?"overflow-and-changed":c?"overflow":"changed";if(!c&&!l)throw new Error("Native Git selection evidence must describe an exceptional selection");if(e.status!==f)throw new Error("Native Git selection evidence status is inconsistent");return{schema:"comet.native.git-selection.v1",status:f,stageBefore:i,combined:r,stageAfter:n,finalStageBefore:o,finalCombined:a,finalStageAfter:s}}function nf(t,e){let i=Y(t,e);if(X(i,hy,e),typeof i.hash!="string"||!pn.test(i.hash))throw new Error(`${e} hash is invalid`);if(typeof i.overflow!="boolean"||typeof i.unstable!="boolean")throw new Error(`${e} flags are invalid`);let r=de(i.visitedNodeCount,`${e} visitedNodeCount`),n=de(i.recordCount,`${e} recordCount`),o=de(i.storedRecordCount,`${e} storedRecordCount`),a=de(i.encodedBytes,`${e} encodedBytes`);if(o>n||!i.overflow&&o!==n)throw new Error(`${e} stored record count is inconsistent`);return{hash:i.hash,visitedNodeCount:r,recordCount:n,storedRecordCount:o,encodedBytes:a,overflow:i.overflow,unstable:i.unstable}}function _y(t){let e=Y(t,"Native physical selection evidence");if(X(e,dy,"Native physical selection evidence"),e.schema!=="comet.native.physical-selection.v1")throw new Error("Native physical selection evidence schema is invalid");if(e.status!=="overflow"&&e.status!=="changed"&&e.status!=="overflow-and-changed")throw new Error("Native physical selection evidence status is invalid");let i=nf(e.before,"Native physical selection before"),r=nf(e.after,"Native physical selection after"),n=i.overflow||r.overflow,o=i.unstable||r.unstable||!Ny(i,r);if(!n&&!o)throw new Error("Native physical selection evidence must describe an exceptional selection");let a=n&&o?"overflow-and-changed":n?"overflow":"changed";if(e.status!==a)throw new Error("Native physical selection evidence status is inconsistent");return{schema:"comet.native.physical-selection.v1",status:a,before:i,after:r}}function Ay(t){let e=Y(t,"Native content snapshot manifest");if(X(e,oy,"Native content snapshot manifest"),e.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!wy.has(e.origin))throw new Error("Native content snapshot origin is invalid");let i;if(e.capture!==void 0){let g=Y(e.capture,"Native content snapshot capture");if(X(g,cy,"Native content snapshot capture"),g.provider!=="git"&&g.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let P=g.gitSelection===void 0?void 0:rf(g.gitSelection),N=g.physicalSelection===void 0?void 0:_y(g.physicalSelection),_=null;if(g.projection!==void 0){let G=Y(g.projection,"Native content snapshot projection");if(X(G,ly,"Native content snapshot projection"),G.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");_={provider:"git",...G.selection===void 0?{}:{selection:rf(G.selection)}}}if(g.provider==="git"){if(N||_)throw new Error("Native Git capture cannot include physical or projection evidence");i={provider:"git",...P?{gitSelection:P}:{}}}else{if(P)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(N&&_)throw new Error("Native physical-tree capture cannot combine selection and projection");i=_?{provider:"physical-tree",projection:_}:{provider:"physical-tree",...N?{physicalSelection:N}:{}}}}if(typeof e.createdAt!="string"||Number.isNaN(Date.parse(e.createdAt)))throw new Error("Native content snapshot timestamp is invalid");if(typeof e.complete!="boolean")throw new Error("Native content snapshot complete flag is invalid");let r=Y(e.limits,"Native content snapshot limits");X(r,ay,"Native content snapshot limits");let n={maxFiles:Et(r.maxFiles,"Native snapshot maxFiles"),maxFileBytes:Et(r.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:Et(r.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:Et(r.maxManifestBytes,"Native snapshot maxManifestBytes"),...r.maxDurationMs===void 0?{}:{maxDurationMs:Et(r.maxDurationMs,"Native snapshot maxDurationMs")}},o;if(e.policy!==void 0){let g=Y(e.policy,"Native snapshot policy");if(X(g,sy,"Native snapshot policy"),g.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(g.include)||!Array.isArray(g.exclude))throw new Error("Native snapshot policy patterns must be arrays");o=Cy({include:g.include,exclude:g.exclude,hash:g.hash,schema:"comet.native.snapshot-policy.v1"}).manifest}if(!Array.isArray(e.entries)||!Array.isArray(e.omitted))throw new Error("Native content snapshot entries and omissions must be arrays");let a=e.entries.map(Py),s=e.omitted.map(xy),c=de(e.omittedCount,"Native content snapshot omittedCount"),l=e.omissionOverflow===void 0?void 0:Ry(e.omissionOverflow);if(a.length>n.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(a.some(g=>g.size>n.maxFileBytes)||a.reduce((g,P)=>g+P.size,0)>n.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(a.map(g=>g.path)).size!==a.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>iy||c0&&l?.count!==f)throw new Error("Native content snapshot omission overflow is inconsistent");if(e.complete!==(c===0))throw new Error("Native content snapshot completeness is inconsistent");let u=s.filter(g=>g.reason==="git-enumeration-limit"),d=s.filter(g=>g.reason==="git-selection-changed");for(let g of[...u,...d])if(g.path!=="."||g.size!==null||g.type!=="directory")throw new Error("Native Git selection omission must use the project-root sentinel");if(u.length>1||d.length>1)throw new Error("Native Git selection omissions must not be duplicated");let m=i?.provider==="git"?i.gitSelection:i?.projection?.selection,w=m?.status==="overflow"||m?.status==="overflow-and-changed",h=m?.status==="changed"||m?.status==="overflow-and-changed";if(w!==(u.length===1))throw new Error("Native Git enumeration omission and selection evidence are inconsistent");if(h!==(d.length===1))throw new Error("Native Git selection-change omission and selection evidence are inconsistent");let p=s.filter(g=>g.reason==="physical-enumeration-limit"),y=s.filter(g=>g.reason==="physical-selection-changed");for(let g of[...p,...y])if(g.path!=="."||g.size!==null||g.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(p.length>1||y.length>1)throw new Error("Native physical selection omissions must not be duplicated");let b=i?.physicalSelection,k=b?.status==="overflow"||b?.status==="overflow-and-changed",S=b?.status==="changed"||b?.status==="overflow-and-changed";if(k!==(p.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(S!==(y.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");let E={schema:"comet.native.content-snapshot.v1",origin:e.origin,...i?{capture:i}:{},createdAt:e.createdAt,complete:e.complete,limits:n,...o?{policy:o}:{},entries:a,omitted:s,omittedCount:c,...l?{omissionOverflow:l}:{}};if(ky(E)>n.maxManifestBytes)throw new Error("Native content snapshot exceeds its manifest byte limit");return E}function Ty(t,e){if(!ny.test(e))throw new Error(`Invalid Native change name: ${e}`);let i=mn.join(t.changesDir,e);if(!vt(t.changesDir,i))throw new Error("Native change path escaped");return mn.join(i,"runtime","baseline-manifest.json")}async function af(t,e){let i=Ty(t,e);await pe(t.nativeRoot,i);try{let r=await Xu({root:t.nativeRoot,file:i,maxBytes:ry,label:"Native baseline snapshot manifest"});return Ay(JSON.parse(r.text))}catch(r){if(r.code==="ENOENT")return null;throw r}}Ei();var dP={runStateBytes:256*1024,trajectoryBytes:8*1024*1024,trajectoryEvents:4096,trajectoryEventBytes:256*1024,checkpointBytes:256*1024,pendingActionBytes:256*1024,contextBytes:1024*1024,artifactsBytes:1024*1024};import{createHash as Ly}from"node:crypto";import{promises as gn}from"node:fs";import je from"node:path";import{execFileSync as Iy}from"child_process";import Ai from"path";function _i(t,e){return Iy("git",["-C",t,...e],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function jy(t,e){let i=Ai.normalize(t),r=Ai.normalize(e);return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function sf(t){try{let e=Ai.resolve(_i(t,["rev-parse","--show-toplevel"])),r=_i(t,["worktree","list","--porcelain","-z"]).split("\0").find(a=>a.startsWith("worktree ")),n=r?Ai.resolve(r.slice(9)):e,o=null;try{o=_i(t,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!jy(e,n),currentWorktreeRoot:e,primaryWorktreeRoot:n,currentBranch:o}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function cf(t){try{_i(t,["rev-parse","--is-inside-work-tree"])}catch{return[]}return _i(t,["worktree","list","--porcelain","-z"]).split("\0").filter(i=>i.startsWith("worktree ")).map(i=>Ai.resolve(i.slice(9)))}var Ti=/^[a-f0-9]{64}$/u,$y=16*1024,Wa=process.platform;function df(t,e){let i=je.relative(t,e);return je.isAbsolute(i)||i===".."||i.startsWith(`..${je.sep}`)?null:i.replaceAll("\\","/")||"."}function hf(t){return Array.from(t).some(e=>{let i=e.codePointAt(0)??0;return i<=31||i===127})}function mf(t,e){if(t.length===0||hf(t)||t.includes("\\")||je.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes(".."))throw new Error(`${e} must be a portable project-relative path`);let i=je.posix.normalize(t);if(i!==t||i===".."||i.startsWith("../"))throw new Error(`${e} must be a normalized project-relative path`);return i}function qa(t,e){return Ly("sha256").update(`${t} -${e}`).digest("hex")}async function lf(t,e){let i=await gn.realpath(e),r=await gn.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=Wa==="win32"?je.normalize(i).toLowerCase():i;return qa(t,`${n} +`))}let n=await mv(e,t),o;try{o=await Vr(t)}catch(l){return ie(2,`[COMET-HOOK] blocked: ${l instanceof Error?l.message:String(l)}`)}if(Cv(n))return be(`${n} (whitelist: comet config)`);if(Pv(n))return be(`${n} (whitelist: superpowers workspace)`);if(n==="CLAUDE.md"||n==="CHANGELOG.md"||n==="README.md"||Ev(n))return be(`${n} (whitelist: root markdown)`);let a;try{a=await Sv(n,t,o,i)}catch(l){return ie(2,`[COMET-HOOK] blocked: ${l instanceof Error?l.message:String(l)}`)}if(!a)return be("no active comet change");if("blockedResult"in a)return a.blockedResult;if(a.archived)return be(`${n} (own change archived)`);let s=a.phase,c=xv(n,s,`${M(t,o.openSpecRoot)}/`);if(c)return be(c);if(zu(n,Gu(t,o))){if(a.superpowersArtifact==="matched"&&Ku(a))return be(`${n} (phase: ${s}, superpowers)`);if(a.superpowersArtifact==="unmatched")return Tv(n,a)}if(a.invalidState)return ie(2,`[COMET-HOOK] blocked: active Classic state is invalid; repair .comet.yaml before writing ${n}`);if(s==="build"&&a.classic?.workflow==="full"&&!a.classic.designDoc)return _v(n);if(s==="build"&&a.classic?.workflow==="full"){let l=await qu(t,a.classic.plan);if(l.status!=="ready")return Av(n,a,l,t,o)}return s==="build"||s==="verify"?be(`${n} (phase: ${s})`):Rv(n,s)}async function Ju(t,e,i,r={}){if(i.intent!=="non-write")try{await Vr(t)}catch(a){return{allowed:!1,reason:a instanceof Error?a.message:String(a),workflow:"classic",change:e}}let n;try{n=await Ri(t)}catch(a){return{allowed:!1,reason:a instanceof Error?a.message:String(a),workflow:"classic",change:e}}let o=n.find(a=>re(a)===e);if(!o)return{allowed:!1,reason:`Selected Classic change ${e} is missing or archived; resume /comet-classic before retrying`,workflow:"classic",change:e};if(i.intent==="non-write")return{allowed:!0,reason:"Hook event is not a write"};if(i.intent==="unknown"||i.targets.length===0)return{allowed:!0,reason:"Hook write target was not attributed to the guarded project",workflow:"classic",change:e,phase:o.phase};for(let a of i.targets){let s=await Iv(t,a,e,r.scopeTargets);if(s.exitCode!==0)return{allowed:!1,reason:s.stderr?.trim()||"Classic phase guard blocked the write",workflow:"classic",change:e,phase:o.phase}}return{allowed:!0,reason:`Classic write allowed in ${o.phase}`,workflow:"classic",change:e,phase:o.phase}}import{promises as lb}from"fs";import Pt from"path";var za=xt(mt(),1);import{promises as qy}from"fs";import et from"path";import{createHash as Dv}from"node:crypto";import{promises as ne}from"node:fs";import U from"node:path";import{TextDecoder as Bv}from"node:util";var jv=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),Lv=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function $v(t){return t.toLowerCase().startsWith(".env")}function La(t){let i=t.replaceAll("\\","/").split("/").filter(Boolean).map(r=>r.toLowerCase());return i.some(r=>$v(r))?"environment-file":i.some(r=>Lv.has(r))?"credential-config":i.includes(".git")?"git-metadata":i.some(r=>jv.has(r))?"dependency-or-cache":i.join("/")===".comet/config.yaml"?"comet-config":i.join("/")===".comet/current-change.json"?"comet-selection":null}fi();var Mv=1024*1024;function $a(t,e){let i=U.relative(t,e);return i===""||!U.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${U.sep}`)}function Fv(t){let e=U.posix.normalize(t);if(t.length===0||t!==t.trim()||t.includes("\\")||Array.from(t).some(n=>{let o=n.codePointAt(0)??0;return o<=31||o===127})||U.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes("..")||e!==t||e==="."||t.endsWith("/"))throw new Error(`Native artifact ref must be normalized and relative: ${t}`);let i=t.toLowerCase(),r=La(t);if(r||i==="runtime"||i.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${r??"native-runtime"}): ${t}`);return t}function Wv(t){if(!Number.isSafeInteger(t)||t<1)throw new Error("Native artifact byte limit must be a positive integer");return t}function qv(t,e){return T({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function an(t,e){let i={...t,birthtime:t.birthtimeMs},r={...e,birthtime:e.birthtimeMs};return fe(i,r)?T(i,r):T(i,r)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.size===e.size}async function Uu(t){let e=await ne.lstat(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${t}`);return{path:t,realPath:await ne.realpath(t),dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}async function Hv(t,e){let i=U.resolve(t),r=U.resolve(e);if(!$a(i,r))throw new Error("Native artifact path is outside its root");let n=[await Uu(i)],o=i;for(let a of U.relative(i,r).split(U.sep).filter(Boolean)){o=U.join(o,a);let s=await Uu(o);if(!$a(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${o}`);n.push(s)}return n}async function Yu(t){for(let e of t){let i=await ne.lstat(e.path);if(!i.isDirectory()||i.isSymbolicLink()||!qv(e,i)||await ne.realpath(e.path)!==e.realPath)throw new Error(`Native artifact parent changed while reading: ${e.path}`)}}async function sn(t){let e=Fv(t.ref),i=Wv(t.maxBytes??Mv),r=U.resolve(t.root,...e.split("/")),n=await Hv(t.root,U.dirname(r));await t.hooks?.afterParentChainCaptured?.();let o=await ne.lstat(r);if(!o.isFile()||o.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${e}`);if(o.size>i)throw new Error(`Native artifact exceeds ${i} bytes: ${e}`);let a=await ne.realpath(r);if(!$a(n[0].realPath,a))throw new Error(`Native artifact resolves outside its root: ${e}`);let s=await ne.open(r,"r");try{let[c,l,f]=await Promise.all([s.stat(),ne.lstat(r),ne.realpath(r)]);if(await Yu(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||f!==a||!an(o,c)||!an(c,l))throw new Error(`Native artifact changed while opening: ${e}`);await t.hooks?.afterOpen?.();let u=[],d=0,m=Buffer.allocUnsafe(Math.min(64*1024,i+1));for(;;){let k=i+1-d,S=await s.read(m,0,Math.min(m.length,k),null);if(S.bytesRead===0)break;if(d+=S.bytesRead,d>i)throw new Error(`Native artifact exceeds ${i} bytes: ${e}`);u.push(Buffer.from(m.subarray(0,S.bytesRead)))}await t.hooks?.beforeFinalCheck?.();let[w,h,p]=await Promise.all([s.stat(),ne.lstat(r),ne.realpath(r)]);if(await Yu(n),!h.isFile()||h.isSymbolicLink()||p!==a||!an(c,w)||!an(c,h))throw new Error(`Native artifact changed while reading: ${e}`);let y=Buffer.concat(u,d),b;try{b=new Bv("utf-8",{fatal:!0}).decode(y)}catch(k){throw new Error(`Native artifact is not valid UTF-8: ${e}`,{cause:k})}return{ref:e,size:d,hash:Dv("sha256").update(y).digest("hex"),text:b}}finally{await s.close()}}ue();He();zr();var cn=$r;async function ln(t){let e=(await qe(t))?.config??null;return e?.native?e:null}import{AsyncLocalStorage as Gv}from"async_hooks";Mr();var nC=16*1024;var oC=new Gv;import{TextDecoder as Zv}from"util";import{createHash as zv}from"node:crypto";import{constants as un,promises as oe}from"node:fs";import ae from"node:path";import{TextDecoder as Vv}from"node:util";function dn(t,e){let i=ae.relative(t,e);return i===""||!ae.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${ae.sep}`)}function Kv(t){if(!Number.isSafeInteger(t)||t<1)throw new Error("Native protected file byte limit must be a positive integer");return t}function Jv(t,e){return T({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function Uv(t){return{dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs,ctimeMs:t.ctimeMs,mtimeMs:t.mtimeMs,size:t.size}}function fn(t,e){return T({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.mtimeMs===e.mtimeMs&&t.size===e.size}async function Ba(t,e){let i=await oe.lstat(t);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${e} parent must be a real directory: ${t}`);return{path:t,realPath:await oe.realpath(t),dev:i.dev,ino:i.ino,birthtimeMs:i.birthtimeMs}}async function Yv(t,e,i){let r=ae.resolve(t),n=ae.resolve(e);if(!dn(r,n))throw new Error(`${i} is outside its managed root`);let o=[await Ba(r,i)],a=r;for(let s of ae.relative(r,n).split(ae.sep).filter(Boolean)){await Ue(o,i),a=ae.join(a,s);let c=await Ba(a,i);if(!dn(o[0].realPath,c.realPath))throw new Error(`${i} parent resolves outside its managed root: ${a}`);o.push(c)}return await Ue(o,i),o}async function Ue(t,e){for(let i of t){let r=await oe.lstat(i.path);if(!r.isDirectory()||r.isSymbolicLink()||!Jv(i,r)||await oe.realpath(i.path)!==i.realPath)throw new Error(`${e} parent changed during I/O: ${i.path}`)}}async function Xv(t,e,i){let r=[],n=0,o=Buffer.allocUnsafe(Math.min(64*1024,e+1));for(;;){let a=e+1-n,{bytesRead:s}=await t.read(o,0,Math.min(o.length,a),null);if(s===0)break;if(n+=s,n>e)throw new Error(`${i} exceeds ${e} bytes`);r.push(Buffer.from(o.subarray(0,s)))}return Buffer.concat(r,n)}async function Xu(t){let e=Kv(t.maxBytes),i=ae.resolve(t.file),r=await Yv(t.root,ae.dirname(i),t.label),n=await Promise.all((t.forbiddenRoots??[]).map(f=>Ba(ae.resolve(f),t.label)));await t.hooks?.afterParentChainCaptured?.(),await Ue(r,t.label);let o=await oe.lstat(i);if(!o.isFile()||o.isSymbolicLink())throw new Error(`${t.label} must be a regular file`);if(o.size>e)throw new Error(`${t.label} exceeds ${e} bytes`);let a=Uv(o),s=await oe.realpath(i);if(!dn(r[0].realPath,s))throw new Error(`${t.label} resolves outside its managed root`);if(n.some(f=>dn(f.realPath,s)))throw new Error(`${t.label} resolves inside an excluded root`);let c=process.platform==="win32"?un.O_RDONLY:un.O_RDONLY|un.O_NOFOLLOW|un.O_NONBLOCK,l=await oe.open(i,c);try{let f=await l.stat();await t.hooks?.afterOpen?.();let[u,d]=await Promise.all([oe.lstat(i),oe.realpath(i)]);if(await Ue(r,t.label),await Ue(n,t.label),!f.isFile()||!u.isFile()||u.isSymbolicLink()||d!==s||!fn(a,f)||!fn(a,u))throw new Error(`${t.label} changed while opening`);await t.hooks?.beforeRead?.();let m=await Xv(l,e,t.label);await t.hooks?.beforeFinalCheck?.();let[w,h,p]=await Promise.all([l.stat(),oe.lstat(i),oe.realpath(i)]);if(await Ue(r,t.label),await Ue(n,t.label),!h.isFile()||h.isSymbolicLink()||p!==s||!fn(a,w)||!fn(a,h))throw new Error(`${t.label} changed while reading`);return{bytes:m,hash:zv("sha256").update(m).digest("hex"),size:m.length}}finally{await l.close()}}async function Qu(t){let e=await Xu(t),i;try{i=new Vv("utf-8",{fatal:!0}).decode(e.bytes)}catch(r){throw new Error(`${t.label} is not valid UTF-8`,{cause:r})}return{...e,text:i}}var SC=256*1024,EC=1024*1024,CC=16*1024;var PC=64*1024*1024;var xC=new Zv("utf-8",{fatal:!0});import mn from"path";import{createHash as ey}from"crypto";function tf(t){return ey("sha256").update(t).digest("hex")}var JC={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},iy=1e3,ry=8*1024*1024,ny=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,oy=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),ay=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),sy=new Set(["schema","include","exclude","hash"]),cy=new Set(["provider","gitSelection","physicalSelection","projection"]),ly=new Set(["provider","selection"]),uy=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),fy=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),dy=new Set(["schema","status","before","after"]),hy=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),my=new Set(["path","hash","size","type","gitObjectId"]),py=new Set(["path","size","type","reason"]),gy=new Set(["ref","hash","count"]),wy=new Set(["change-created","legacy-migration","explicit"]),vy=new Set(["file","directory","other"]),yy=new Set(["file-size","file-count","total-size","manifest-size","changed-during-read","unreadable","gitlink-unavailable","gitlink-dirty","gitlink-changed","legacy-gitlink-boundary","git-enumeration-limit","git-selection-changed","physical-enumeration-limit","physical-selection-changed"]),pn=/^[a-f0-9]{64}$/u,by=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;var UC=64*1024,YC=64*1024;var XC={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},QC={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};function hn(t,e){return t.hash===e.hash&&t.recordCount===e.recordCount&&t.storedRecordCount===e.storedRecordCount&&t.stdoutBytes===e.stdoutBytes&&t.overflow===e.overflow}var ZC=(1n<<256n)-1n;function Ny(t,e){return t.hash===e.hash&&t.visitedNodeCount===e.visitedNodeCount&&t.recordCount===e.recordCount&&t.storedRecordCount===e.storedRecordCount&&t.encodedBytes===e.encodedBytes&&t.overflow===e.overflow&&t.unstable===e.unstable}function ky(t){return Buffer.byteLength(JSON.stringify(t,null,2)+` +`)}function Sy(t,e){return tf(`comet.native.snapshot-policy.v1 +${JSON.stringify({include:t,exclude:e,hash:"sha256"})}`)}function Ma(t,e,i){let r=new Set(e),n=[...e];for(;n.length>0;){if(i&&!i())return null;let o=n.pop(),a=t[o];a&&(a.kind==="star"||a.kind==="globstar"||a.kind==="globstar-slash")&&!r.has(o+1)&&(r.add(o+1),n.push(o+1))}return r}function Ey(t){let e=0;return()=>e>0?(e-=1,!0):t()?(e=63,!0):!1}function rf(t){let e=cn(t,"Native snapshot pattern"),i=[];for(let r=0;r{let o=n?Ey(n):void 0;if(o&&!o())return!1;let a=Ma(i,new Set([0]),o);if(a===null)return!1;for(let s of r){if(o&&!o())return!1;let c=new Set;for(let l of a){if(o&&!o())return!1;let f=i[l];f&&(f.kind==="literal"&&f.value===s||f.kind==="question"&&s!=="/"?c.add(l+1):f.kind==="star"&&s!=="/"||f.kind==="globstar"?c.add(l):f.kind==="globstar-slash"&&(c.add(l),s==="/"&&c.add(l+1)))}if(a=Ma(i,c,o),a===null||a.size===0)return!1}return Ma(i,a,o)?.has(i.length)??!1}}function Cy(t){if(t===void 0)return;let e=[...new Set(t.include.map(n=>cn(n,"include")))].sort((n,o)=>n.localeCompare(o,"en")),i=[...new Set(t.exclude.map(n=>cn(n,"exclude")))].sort((n,o)=>n.localeCompare(o,"en"));if(e.length===0)throw new Error("Native snapshot policy include must not be empty");let r=Sy(e,i);if("hash"in t&&t.hash!==r)throw new Error("Native snapshot policy hash is invalid");return{manifest:{schema:"comet.native.snapshot-policy.v1",include:e,exclude:i,hash:r},includeMatchers:e.map(rf),excludeMatchers:i.map(rf),excludedDirectoryPrefixes:i.flatMap(n=>{if(!n.endsWith("/**"))return[];let o=n.slice(0,-3);return/[*?]/u.test(o)?[]:[o]}).sort((n,o)=>n.localeCompare(o,"en"))}}function Y(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function X(t,e,i){let r=Object.keys(t).find(n=>!e.has(n));if(r)throw new Error(`${i} contains unknown field: ${r}`)}function Et(t,e){if(!Number.isSafeInteger(t)||t<1)throw new Error(`${e} must be a positive integer`);return t}function de(t,e){if(!Number.isSafeInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return t}function af(t,e){if(typeof t!="string"||t.length===0||t.includes("\\")||t.includes("\0"))throw new Error(`${e} must be a normalized project-relative path`);let i=mn.posix.normalize(t);if(i!==t||mn.posix.isAbsolute(t)||i===".."||i.startsWith("../"))throw new Error(`${e} must stay inside the project root`);return t}function Py(t,e){let i=Y(t,`Native snapshot entry ${e}`);X(i,my,`Native snapshot entry ${e}`);let r=af(i.path,`Native snapshot entry ${e} path`);if(typeof i.hash!="string"||!pn.test(i.hash))throw new Error(`Native snapshot entry ${e} hash is invalid`);if(i.type!=="file")throw new Error(`Native snapshot entry ${e} type is invalid`);let n={path:r,hash:i.hash,size:de(i.size,`Native snapshot entry ${e} size`),type:"file"};if(i.gitObjectId!==void 0){if(typeof i.gitObjectId!="string"||!by.test(i.gitObjectId))throw new Error(`Native snapshot entry ${e} gitObjectId is invalid`);n.gitObjectId=i.gitObjectId}return n}function xy(t,e){let i=Y(t,`Native snapshot omission ${e}`);if(X(i,py,`Native snapshot omission ${e}`),!vy.has(i.type))throw new Error(`Native snapshot omission ${e} type is invalid`);if(!yy.has(i.reason))throw new Error(`Native snapshot omission ${e} reason is invalid`);return{path:af(i.path,`Native snapshot omission ${e} path`),size:i.size===null?null:de(i.size,`Native snapshot omission ${e} size`),type:i.type,reason:i.reason}}function Ry(t){let e=Y(t,"Native snapshot omission overflow");if(X(e,gy,"Native snapshot omission overflow"),typeof e.hash!="string"||!pn.test(e.hash))throw new Error("Native snapshot omission overflow hash is invalid");let i=`native-snapshot://omitted-overflow/${e.hash}`;if(e.ref!==i)throw new Error("Native snapshot omission overflow ref is invalid");return{ref:i,hash:e.hash,count:Et(e.count,"Native snapshot omission overflow count")}}function St(t,e){let i=Y(t,e);if(X(i,fy,e),typeof i.hash!="string"||!pn.test(i.hash))throw new Error(`${e} hash is invalid`);if(typeof i.overflow!="boolean")throw new Error(`${e} overflow flag is invalid`);let r=de(i.recordCount,`${e} recordCount`),n=de(i.storedRecordCount,`${e} storedRecordCount`),o=de(i.stdoutBytes,`${e} stdoutBytes`);if(n>r||!i.overflow&&n!==r)throw new Error(`${e} stored record count is inconsistent`);return{hash:i.hash,recordCount:r,storedRecordCount:n,stdoutBytes:o,overflow:i.overflow}}function nf(t){let e=Y(t,"Native Git selection evidence");if(X(e,uy,"Native Git selection evidence"),e.schema!=="comet.native.git-selection.v1")throw new Error("Native Git selection evidence schema is invalid");if(e.status!=="overflow"&&e.status!=="changed"&&e.status!=="overflow-and-changed")throw new Error("Native Git selection evidence status is invalid");let i=St(e.stageBefore,"Native Git selection stageBefore"),r=St(e.combined,"Native Git selection combined"),n=St(e.stageAfter,"Native Git selection stageAfter"),o=St(e.finalStageBefore,"Native Git selection finalStageBefore"),a=St(e.finalCombined,"Native Git selection finalCombined"),s=St(e.finalStageAfter,"Native Git selection finalStageAfter"),c=[i,r,n,o,a,s].some(u=>u.overflow),l=!hn(i,n)||!hn(n,o)||!hn(r,a)||!hn(o,s),f=c&&l?"overflow-and-changed":c?"overflow":"changed";if(!c&&!l)throw new Error("Native Git selection evidence must describe an exceptional selection");if(e.status!==f)throw new Error("Native Git selection evidence status is inconsistent");return{schema:"comet.native.git-selection.v1",status:f,stageBefore:i,combined:r,stageAfter:n,finalStageBefore:o,finalCombined:a,finalStageAfter:s}}function of(t,e){let i=Y(t,e);if(X(i,hy,e),typeof i.hash!="string"||!pn.test(i.hash))throw new Error(`${e} hash is invalid`);if(typeof i.overflow!="boolean"||typeof i.unstable!="boolean")throw new Error(`${e} flags are invalid`);let r=de(i.visitedNodeCount,`${e} visitedNodeCount`),n=de(i.recordCount,`${e} recordCount`),o=de(i.storedRecordCount,`${e} storedRecordCount`),a=de(i.encodedBytes,`${e} encodedBytes`);if(o>n||!i.overflow&&o!==n)throw new Error(`${e} stored record count is inconsistent`);return{hash:i.hash,visitedNodeCount:r,recordCount:n,storedRecordCount:o,encodedBytes:a,overflow:i.overflow,unstable:i.unstable}}function _y(t){let e=Y(t,"Native physical selection evidence");if(X(e,dy,"Native physical selection evidence"),e.schema!=="comet.native.physical-selection.v1")throw new Error("Native physical selection evidence schema is invalid");if(e.status!=="overflow"&&e.status!=="changed"&&e.status!=="overflow-and-changed")throw new Error("Native physical selection evidence status is invalid");let i=of(e.before,"Native physical selection before"),r=of(e.after,"Native physical selection after"),n=i.overflow||r.overflow,o=i.unstable||r.unstable||!Ny(i,r);if(!n&&!o)throw new Error("Native physical selection evidence must describe an exceptional selection");let a=n&&o?"overflow-and-changed":n?"overflow":"changed";if(e.status!==a)throw new Error("Native physical selection evidence status is inconsistent");return{schema:"comet.native.physical-selection.v1",status:a,before:i,after:r}}function Ay(t){let e=Y(t,"Native content snapshot manifest");if(X(e,oy,"Native content snapshot manifest"),e.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!wy.has(e.origin))throw new Error("Native content snapshot origin is invalid");let i;if(e.capture!==void 0){let g=Y(e.capture,"Native content snapshot capture");if(X(g,cy,"Native content snapshot capture"),g.provider!=="git"&&g.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let P=g.gitSelection===void 0?void 0:nf(g.gitSelection),N=g.physicalSelection===void 0?void 0:_y(g.physicalSelection),_=null;if(g.projection!==void 0){let H=Y(g.projection,"Native content snapshot projection");if(X(H,ly,"Native content snapshot projection"),H.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");_={provider:"git",...H.selection===void 0?{}:{selection:nf(H.selection)}}}if(g.provider==="git"){if(N||_)throw new Error("Native Git capture cannot include physical or projection evidence");i={provider:"git",...P?{gitSelection:P}:{}}}else{if(P)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(N&&_)throw new Error("Native physical-tree capture cannot combine selection and projection");i=_?{provider:"physical-tree",projection:_}:{provider:"physical-tree",...N?{physicalSelection:N}:{}}}}if(typeof e.createdAt!="string"||Number.isNaN(Date.parse(e.createdAt)))throw new Error("Native content snapshot timestamp is invalid");if(typeof e.complete!="boolean")throw new Error("Native content snapshot complete flag is invalid");let r=Y(e.limits,"Native content snapshot limits");X(r,ay,"Native content snapshot limits");let n={maxFiles:Et(r.maxFiles,"Native snapshot maxFiles"),maxFileBytes:Et(r.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:Et(r.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:Et(r.maxManifestBytes,"Native snapshot maxManifestBytes"),...r.maxDurationMs===void 0?{}:{maxDurationMs:Et(r.maxDurationMs,"Native snapshot maxDurationMs")}},o;if(e.policy!==void 0){let g=Y(e.policy,"Native snapshot policy");if(X(g,sy,"Native snapshot policy"),g.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(g.include)||!Array.isArray(g.exclude))throw new Error("Native snapshot policy patterns must be arrays");o=Cy({include:g.include,exclude:g.exclude,hash:g.hash,schema:"comet.native.snapshot-policy.v1"}).manifest}if(!Array.isArray(e.entries)||!Array.isArray(e.omitted))throw new Error("Native content snapshot entries and omissions must be arrays");let a=e.entries.map(Py),s=e.omitted.map(xy),c=de(e.omittedCount,"Native content snapshot omittedCount"),l=e.omissionOverflow===void 0?void 0:Ry(e.omissionOverflow);if(a.length>n.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(a.some(g=>g.size>n.maxFileBytes)||a.reduce((g,P)=>g+P.size,0)>n.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(a.map(g=>g.path)).size!==a.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>iy||c0&&l?.count!==f)throw new Error("Native content snapshot omission overflow is inconsistent");if(e.complete!==(c===0))throw new Error("Native content snapshot completeness is inconsistent");let u=s.filter(g=>g.reason==="git-enumeration-limit"),d=s.filter(g=>g.reason==="git-selection-changed");for(let g of[...u,...d])if(g.path!=="."||g.size!==null||g.type!=="directory")throw new Error("Native Git selection omission must use the project-root sentinel");if(u.length>1||d.length>1)throw new Error("Native Git selection omissions must not be duplicated");let m=i?.provider==="git"?i.gitSelection:i?.projection?.selection,w=m?.status==="overflow"||m?.status==="overflow-and-changed",h=m?.status==="changed"||m?.status==="overflow-and-changed";if(w!==(u.length===1))throw new Error("Native Git enumeration omission and selection evidence are inconsistent");if(h!==(d.length===1))throw new Error("Native Git selection-change omission and selection evidence are inconsistent");let p=s.filter(g=>g.reason==="physical-enumeration-limit"),y=s.filter(g=>g.reason==="physical-selection-changed");for(let g of[...p,...y])if(g.path!=="."||g.size!==null||g.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(p.length>1||y.length>1)throw new Error("Native physical selection omissions must not be duplicated");let b=i?.physicalSelection,k=b?.status==="overflow"||b?.status==="overflow-and-changed",S=b?.status==="changed"||b?.status==="overflow-and-changed";if(k!==(p.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(S!==(y.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");let E={schema:"comet.native.content-snapshot.v1",origin:e.origin,...i?{capture:i}:{},createdAt:e.createdAt,complete:e.complete,limits:n,...o?{policy:o}:{},entries:a,omitted:s,omittedCount:c,...l?{omissionOverflow:l}:{}};if(ky(E)>n.maxManifestBytes)throw new Error("Native content snapshot exceeds its manifest byte limit");return E}function Ty(t,e){if(!ny.test(e))throw new Error(`Invalid Native change name: ${e}`);let i=mn.join(t.changesDir,e);if(!vt(t.changesDir,i))throw new Error("Native change path escaped");return mn.join(i,"runtime","baseline-manifest.json")}async function sf(t,e){let i=Ty(t,e);await pe(t.nativeRoot,i);try{let r=await Qu({root:t.nativeRoot,file:i,maxBytes:ry,label:"Native baseline snapshot manifest"});return Ay(JSON.parse(r.text))}catch(r){if(r.code==="ENOENT")return null;throw r}}Ei();var dP={runStateBytes:256*1024,trajectoryBytes:8*1024*1024,trajectoryEvents:4096,trajectoryEventBytes:256*1024,checkpointBytes:256*1024,pendingActionBytes:256*1024,contextBytes:1024*1024,artifactsBytes:1024*1024};import{createHash as Ly}from"node:crypto";import{promises as gn}from"node:fs";import je from"node:path";import{execFileSync as Iy}from"child_process";import Ai from"path";function _i(t,e){return Iy("git",["-C",t,...e],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function jy(t,e){let i=Ai.normalize(t),r=Ai.normalize(e);return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function cf(t){try{let e=Ai.resolve(_i(t,["rev-parse","--show-toplevel"])),r=_i(t,["worktree","list","--porcelain","-z"]).split("\0").find(a=>a.startsWith("worktree ")),n=r?Ai.resolve(r.slice(9)):e,o=null;try{o=_i(t,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!jy(e,n),currentWorktreeRoot:e,primaryWorktreeRoot:n,currentBranch:o}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function lf(t){try{_i(t,["rev-parse","--is-inside-work-tree"])}catch{return[]}return _i(t,["worktree","list","--porcelain","-z"]).split("\0").filter(i=>i.startsWith("worktree ")).map(i=>Ai.resolve(i.slice(9)))}var Ti=/^[a-f0-9]{64}$/u,$y=16*1024,Wa=process.platform;function hf(t,e){let i=je.relative(t,e);return je.isAbsolute(i)||i===".."||i.startsWith(`..${je.sep}`)?null:i.replaceAll("\\","/")||"."}function mf(t){return Array.from(t).some(e=>{let i=e.codePointAt(0)??0;return i<=31||i===127})}function pf(t,e){if(t.length===0||mf(t)||t.includes("\\")||je.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes(".."))throw new Error(`${e} must be a portable project-relative path`);let i=je.posix.normalize(t);if(i!==t||i===".."||i.startsWith("../"))throw new Error(`${e} must be a normalized project-relative path`);return i}function qa(t,e){return Ly("sha256").update(`${t} +${e}`).digest("hex")}async function uf(t,e){let i=await gn.realpath(e),r=await gn.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=Wa==="win32"?je.normalize(i).toLowerCase():i;return qa(t,`${n} ${r.dev} ${r.ino} -${r.birthtimeMs}`)}async function uf(t,e){let i=await gn.realpath(e),r=await gn.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=Wa==="win32"?je.normalize(i).toLowerCase():i;return qa(t,n)}function Dy(t){if(typeof t!="string")throw new Error("Native workspace capturedAt is invalid");let e=new Date(t);if(!Number.isFinite(e.getTime())||e.toISOString()!==t)throw new Error("Native workspace capturedAt is invalid");return t}function ff(t,e){if(t===null)return null;if(typeof t!="string"||t.length===0||t.trim()!==t||hf(t))throw new Error(`${e} must be a non-empty branch name or null`);return t}function pf(t){if(!new Set(["current","branch","worktree"]).has(t.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(ff(t.changeBranch,"Native workspace change branch"),ff(t.targetBranch,"Native workspace target branch"),(t.isolation==="branch"||t.isolation==="worktree")&&(t.changeBranch===null||t.targetBranch===null))throw new Error("Native isolated workspace requires change and target branches")}function wn(t){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Native workspace identity must be an object");let e=t,i=new Set(["schema","capturedAt","capturedRevision","nativeRootRef","projectRootId","nativeRootId","projectRootPathId","nativeRootPathId","sessionHash","isolation","changeBranch","targetBranch","finish"]),r=Object.keys(e).filter(a=>!i.has(a));if(r.length>0)throw new Error(`Native workspace identity has unknown field(s): ${r.join(", ")}`);if(e.schema!=="comet.native.workspace.v2"&&e.schema!=="comet.native.workspace.v3")throw new Error("Unsupported Native workspace identity");if(!Number.isSafeInteger(e.capturedRevision)||e.capturedRevision<1||typeof e.nativeRootRef!="string"||!Ti.test(String(e.projectRootId))||!Ti.test(String(e.nativeRootId)))throw new Error("Native workspace identity is invalid");Dy(e.capturedAt),mf(e.nativeRootRef,"Native workspace root ref");let n=e.projectRootPathId!==void 0,o=e.nativeRootPathId!==void 0;if(n!==o)throw new Error("Native workspace path identities must be provided together");if(n&&!Ti.test(String(e.projectRootPathId))||o&&!Ti.test(String(e.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(e.sessionHash!==void 0&&!Ti.test(String(e.sessionHash)))throw new Error("Native workspace session hash is invalid");if(e.schema==="comet.native.workspace.v2"){if(e.isolation!==void 0||e.changeBranch!==void 0||e.targetBranch!==void 0||e.finish!==void 0)throw new Error("Native workspace v2 identity cannot contain a workspace binding");return}if(typeof e.isolation!="string"||e.changeBranch===void 0||e.targetBranch===void 0||e.finish===void 0)throw new Error("Native workspace v3 identity requires a workspace binding");if(pf(e),e.finish!==null&&!new Set(["merge","push","pull-request","keep"]).has(e.finish))throw new Error("Native workspace finish must be merge, push, pull-request, keep, or null")}function By(t,e){return je.join(t.changesDir,e,"runtime","workspace.json")}function My(t,e){let i=df(t.nativeRoot,By(t,e));if(!i||i===".")throw new Error("Native workspace file escaped its root");return mf(i,"Native workspace file ref")}async function Fy(t,e){try{let i=await sn({root:t.nativeRoot,ref:My(t,e),maxBytes:$y});return JSON.parse(i.text)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function Wy(t){if(!Number.isSafeInteger(t.revision)||t.revision<1)throw new Error("Native workspace revision must be a positive integer");let e=df(t.paths.projectRoot,t.paths.nativeRoot);if(!e)throw new Error("Native root is outside the project root");let[i,r,n,o]=await Promise.all([lf("comet.native.workspace-project-root.v2",t.paths.projectRoot),lf("comet.native.workspace-native-root.v2",t.paths.nativeRoot),uf("comet.native.workspace-project-root-path.v2",t.paths.projectRoot),uf("comet.native.workspace-native-root-path.v2",t.paths.nativeRoot)]),a=(t.now??new Date).toISOString();if(t.finish&&!t.binding)throw new Error("Native workspace finish requires a workspace binding");t.binding&&pf(t.binding);let s={capturedAt:a,capturedRevision:t.revision,nativeRootRef:e,projectRootId:i,nativeRootId:r,projectRootPathId:n,nativeRootPathId:o,...t.sessionId?{sessionHash:qa("comet.native.workspace-session.v2",`${i} +${r.birthtimeMs}`)}async function ff(t,e){let i=await gn.realpath(e),r=await gn.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=Wa==="win32"?je.normalize(i).toLowerCase():i;return qa(t,n)}function Dy(t){if(typeof t!="string")throw new Error("Native workspace capturedAt is invalid");let e=new Date(t);if(!Number.isFinite(e.getTime())||e.toISOString()!==t)throw new Error("Native workspace capturedAt is invalid");return t}function df(t,e){if(t===null)return null;if(typeof t!="string"||t.length===0||t.trim()!==t||mf(t))throw new Error(`${e} must be a non-empty branch name or null`);return t}function gf(t){if(!new Set(["current","branch","worktree"]).has(t.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(df(t.changeBranch,"Native workspace change branch"),df(t.targetBranch,"Native workspace target branch"),(t.isolation==="branch"||t.isolation==="worktree")&&(t.changeBranch===null||t.targetBranch===null))throw new Error("Native isolated workspace requires change and target branches")}function wn(t){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Native workspace identity must be an object");let e=t,i=new Set(["schema","capturedAt","capturedRevision","nativeRootRef","projectRootId","nativeRootId","projectRootPathId","nativeRootPathId","sessionHash","isolation","changeBranch","targetBranch","finish"]),r=Object.keys(e).filter(a=>!i.has(a));if(r.length>0)throw new Error(`Native workspace identity has unknown field(s): ${r.join(", ")}`);if(e.schema!=="comet.native.workspace.v2"&&e.schema!=="comet.native.workspace.v3")throw new Error("Unsupported Native workspace identity");if(!Number.isSafeInteger(e.capturedRevision)||e.capturedRevision<1||typeof e.nativeRootRef!="string"||!Ti.test(String(e.projectRootId))||!Ti.test(String(e.nativeRootId)))throw new Error("Native workspace identity is invalid");Dy(e.capturedAt),pf(e.nativeRootRef,"Native workspace root ref");let n=e.projectRootPathId!==void 0,o=e.nativeRootPathId!==void 0;if(n!==o)throw new Error("Native workspace path identities must be provided together");if(n&&!Ti.test(String(e.projectRootPathId))||o&&!Ti.test(String(e.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(e.sessionHash!==void 0&&!Ti.test(String(e.sessionHash)))throw new Error("Native workspace session hash is invalid");if(e.schema==="comet.native.workspace.v2"){if(e.isolation!==void 0||e.changeBranch!==void 0||e.targetBranch!==void 0||e.finish!==void 0)throw new Error("Native workspace v2 identity cannot contain a workspace binding");return}if(typeof e.isolation!="string"||e.changeBranch===void 0||e.targetBranch===void 0||e.finish===void 0)throw new Error("Native workspace v3 identity requires a workspace binding");if(gf(e),e.finish!==null&&!new Set(["merge","push","pull-request","keep"]).has(e.finish))throw new Error("Native workspace finish must be merge, push, pull-request, keep, or null")}function By(t,e){return je.join(t.changesDir,e,"runtime","workspace.json")}function My(t,e){let i=hf(t.nativeRoot,By(t,e));if(!i||i===".")throw new Error("Native workspace file escaped its root");return pf(i,"Native workspace file ref")}async function Fy(t,e){try{let i=await sn({root:t.nativeRoot,ref:My(t,e),maxBytes:$y});return JSON.parse(i.text)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function Wy(t){if(!Number.isSafeInteger(t.revision)||t.revision<1)throw new Error("Native workspace revision must be a positive integer");let e=hf(t.paths.projectRoot,t.paths.nativeRoot);if(!e)throw new Error("Native root is outside the project root");let[i,r,n,o]=await Promise.all([uf("comet.native.workspace-project-root.v2",t.paths.projectRoot),uf("comet.native.workspace-native-root.v2",t.paths.nativeRoot),ff("comet.native.workspace-project-root-path.v2",t.paths.projectRoot),ff("comet.native.workspace-native-root-path.v2",t.paths.nativeRoot)]),a=(t.now??new Date).toISOString();if(t.finish&&!t.binding)throw new Error("Native workspace finish requires a workspace binding");t.binding&&gf(t.binding);let s={capturedAt:a,capturedRevision:t.revision,nativeRootRef:e,projectRootId:i,nativeRootId:r,projectRootPathId:n,nativeRootPathId:o,...t.sessionId?{sessionHash:qa("comet.native.workspace-session.v2",`${i} ${r} -${t.sessionId}`)}:{}},c=t.binding?{schema:"comet.native.workspace.v3",...s,...t.binding,finish:t.finish??null}:{schema:"comet.native.workspace.v2",...s};return wn(c),c}async function gf(t,e){let i=await Fy(t,e);return i===null||i&&typeof i=="object"&&!Array.isArray(i)&&i.schema==="comet.native.workspace.v1"?null:(wn(i),i)}async function wf(t){wn(t.identity);let e=await Wy({paths:t.paths,name:"workspace-advisory",revision:t.identity.capturedRevision}),i=[],r=[];return e.nativeRootRef!==t.identity.nativeRootRef&&i.push("native-root-ref"),t.identity.projectRootPathId&&t.identity.nativeRootPathId?(e.projectRootPathId!==t.identity.projectRootPathId&&i.push("project-root-path"),e.nativeRootPathId!==t.identity.nativeRootPathId&&i.push("native-root-path")):(e.projectRootId!==t.identity.projectRootId&&i.push("project-root-legacy-identity"),e.nativeRootId!==t.identity.nativeRootId&&i.push("native-root-legacy-identity")),Wa==="win32"&&i.length>0&&i.every(o=>o==="project-root-legacy-identity"||o==="native-root-legacy-identity")?r.push("workspace-inspection-unavailable"):i.length>0&&r.push("workspace-root-changed"),{state:r.length===0?"aligned":r.includes("workspace-root-changed")?"drifted":"unknown",findingCodes:r,driftComponents:i}}async function vf(t){if(wn(t.identity),t.identity.schema==="comet.native.workspace.v2")return{state:"legacy",code:"workspace-binding-legacy",message:"Legacy Native workspace metadata has no isolation binding"};if((await wf(t)).state==="drifted")return{state:"drifted",code:"workspace-binding-root-changed",message:"Native change is being accessed from a different working directory"};let i=sf(t.paths.projectRoot);return t.identity.changeBranch===null?i.isGitWorktree?{state:"drifted",code:"workspace-branch-changed",message:"Native change was created outside Git but is now being accessed inside Git"}:{state:"aligned",code:null,message:null}:i.isGitWorktree?i.currentBranch!==t.identity.changeBranch?{state:"drifted",code:"workspace-branch-changed",message:`Native change is bound to branch ${t.identity.changeBranch}, but the current branch is ${i.currentBranch??"detached HEAD"}`}:t.identity.isolation==="worktree"&&!i.isSecondaryWorktree?{state:"drifted",code:"workspace-kind-changed",message:"Native change is bound to a linked Git worktree"}:{state:"aligned",code:null,message:null}:{state:"drifted",code:"workspace-vcs-unavailable",message:"Native change requires its bound Git working directory"}}async function yf(t,e){let i=await gf(t,e);if(i===null)return null;let r=await vf({paths:t,identity:i});if(r.state==="drifted")throw new Error(`${r.code}: ${r.message}`);return i}var Ye="comet.native.v3",Xe="comet.native.v2",Qe="comet.native.v1";var bf=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],Hy=new Set(bf),Nf=new Set([...bf,"minimum_runtime_version","revision"]),Gy=new Set([...Nf,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),zy=new Set(["capability","operation","source","base_hash"]),Vy=new Set(["shape","build","verify","archive"]),Ky=new Set(["implicit","confirmed"]),Jy=new Set(["pending","pass","fail"]),Ct="comet-state.yaml",Ga=/^[a-f0-9]{64}$/u,kf=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Uy=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,vn=class extends Error{constructor(i,r){super(`Native change ${i} uses ${r}; run comet native doctor ${i} --repair before mutating it`);this.change=i;this.schema=r;this.name="NativeSchemaMigrationRequiredError"}change;schema;code="native-schema-migration-required"},tt=class extends Error{constructor(i,r){super(i!==Ye||r===null?`Unsupported Native change schema ${i} for runtime protocol ${3}`:`Native change ${i} requires runtime protocol ${r}; current protocol is ${3}`);this.schema=i;this.minimumRuntimeVersion=r;this.name="NativeRuntimeCompatibilityError"}schema;minimumRuntimeVersion;code="native-runtime-incompatible"};var ix=["# Outcome","","# Scope","","# Non-goals","","# Acceptance examples","","# Constraints and invariants","","# Decisions","","# Open questions","","# Verification expectations",""].join(` -`);function Ii(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function Sf(t,e,i){let r=Object.keys(t).filter(n=>!e.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function yn(t){if(!kf.test(t))throw new Error(`Invalid Native change name: ${t}`)}function Yy(t){if(!kf.test(t))throw new Error(`Invalid Native capability id: ${t}`)}function Ef(t,e){if(t.length===0||et.isAbsolute(t)||/^(?:[A-Za-z]:|~|[\\/])/u.test(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`${e} must stay inside the Native change`)}function Xy(t,e){let i=Ii(t,`spec_changes[${e}]`);if(Sf(i,zy,`spec_changes[${e}]`),typeof i.capability!="string")throw new Error("spec change capability is required");if(Yy(i.capability),i.operation!=="create"&&i.operation!=="replace"&&i.operation!=="remove")throw new Error(`Invalid spec operation for ${i.capability}`);let r=i.source,n=i.base_hash;if(r!==void 0&&typeof r!="string")throw new Error(`Spec source for ${i.capability} must be a string`);if(typeof r=="string"&&Ef(r,`Spec source for ${i.capability}`),i.operation==="create"){if(!r)throw new Error(`Create spec ${i.capability} requires source`);if(n!==null)throw new Error(`Create spec ${i.capability} requires null base_hash`)}else if(i.operation==="replace"){if(!r)throw new Error(`Replace spec ${i.capability} requires source`);if(typeof n!="string"||!Ga.test(n))throw new Error(`Replace spec ${i.capability} requires a SHA-256 base_hash`)}else{if(r!==void 0)throw new Error(`Remove spec ${i.capability} forbids source`);if(typeof n!="string"||!Ga.test(n))throw new Error(`Remove spec ${i.capability} requires a SHA-256 base_hash`)}return{capability:i.capability,operation:i.operation,...typeof r=="string"?{source:r}:{},base_hash:n}}function Qy(t){return/^\d{4}-\d{2}-\d{2}$/u.test(t)?new Date(`${t}T00:00:00.000Z`).toISOString().slice(0,10)===t:!1}function Va(t,e){if(Sf(t,e,Ct),typeof t.name!="string")throw new Error("Native change name is required");if(yn(t.name),t.language!=="en"&&t.language!=="zh-CN")throw new Error("Native change language must be en or zh-CN");if(typeof t.phase!="string"||!Vy.has(t.phase))throw new Error("Native change phase is invalid");if(t.brief!=="brief.md")throw new Error("Native change brief must be brief.md");if(t.approval!==null&&!Ky.has(t.approval))throw new Error("Native change approval is invalid");if(!Array.isArray(t.spec_changes))throw new Error("Native spec_changes must be an array");let i=t.spec_changes.map(Xy),r=i.map(n=>n.capability).filter((n,o,a)=>a.indexOf(n)!==o);if(r.length>0)throw new Error(`Duplicate Native capability operation: ${[...new Set(r)].join(", ")}`);if(typeof t.verification_result!="string"||!Jy.has(t.verification_result))throw new Error("Native verification_result is invalid");if(t.verification_report!==null&&typeof t.verification_report!="string")throw new Error("Native verification_report must be a string or null");if(typeof t.verification_report=="string"&&Ef(t.verification_report,"Native verification_report"),typeof t.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof t.created_at!="string"||!Qy(t.created_at))throw new Error("Native created_at must be a valid YYYY-MM-DD date");if(t.run_id!==null&&(typeof t.run_id!="string"||t.run_id.length===0))throw new Error("Native run_id must be a non-empty string or null");return{name:t.name,language:t.language,phase:t.phase,brief:"brief.md",approval:t.approval,spec_changes:i,verification_result:t.verification_result,verification_report:t.verification_report,archived:t.archived,created_at:t.created_at,run_id:t.run_id}}function Cf(t){let e=Ii(t,Ct);if(e.schema!==Qe)throw new Error(`Expected ${Qe}`);return{schema:Qe,...Va(e,Hy)}}function Oi(t,e){if(!Number.isSafeInteger(t)||t<1)throw new Error(`${e} must be a positive integer`);return t}function Ha(t,e,i){if(t===null)return null;let r=typeof t=="string"?Uy.exec(t):null;if(!r||r[1]!==i)throw new Error(`${e} must be null or runtime/evidence/${i}/.json relative to the Native change`);return t}function Zy(t){if(t==null)return null;if(typeof t!="string"||!Ga.test(t))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return t}function eb(t){if(t===void 0)return"legacy-v1";if(t!=="legacy-v1")throw new Error("Native verification_protocol must be legacy-v1");return t}function Pf(t){let e=Ii(t,Ct);if(e.schema!==Xe)throw new Error(`Expected ${Xe}`);if(Oi(e.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${Xe} minimum_runtime_version must be 2`);return{schema:Xe,minimum_runtime_version:2,revision:Oi(e.revision,"Native v2 revision"),...Va(e,Nf)}}function tb(t){let e=Ii(t,Ct);if(e.schema!==Ye){if(e.schema===Qe||e.schema===Xe){let a=e.schema===Qe?Cf(e):Pf(e);throw new vn(a.name,a.schema)}throw new tt(typeof e.schema=="string"?e.schema:"(missing)",typeof e.minimum_runtime_version=="number"?e.minimum_runtime_version:null)}let i=Oi(e.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)throw new tt(e.schema,i);if(i!==3)throw new Error(`Native ${e.schema} minimum_runtime_version must be ${3}`);let r=Oi(e.revision,"Native revision"),n=Va(e,Gy),o=Zy(e.approved_contract_hash);if(n.approval===null&&o!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:Ye,minimum_runtime_version:3,revision:r,verification_protocol:eb(e.verification_protocol),...n,approved_contract_hash:o,implementation_scope:Ha(e.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:Ha(e.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:Ha(e.partial_allowance,"Native partial_allowance","allowances")}}function ib(t){let e=Ii(t,Ct);if(e.schema===Qe){let n=Cf(e);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${Ye}`}}if(e.schema===Xe){let n=Pf(e);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${Ye}`}}if(e.schema!==Ye){let n=typeof e.minimum_runtime_version=="number"&&Number.isSafeInteger(e.minimum_runtime_version)?e.minimum_runtime_version:null;return{status:"runtime-incompatible",schema:typeof e.schema=="string"?e.schema:"(missing)",minimumRuntimeVersion:n,state:null,message:new tt(typeof e.schema=="string"?e.schema:"(missing)",n).message}}let i=Oi(e.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)return{status:"runtime-incompatible",schema:e.schema,minimumRuntimeVersion:i,state:null,message:new tt(e.schema,i).message};let r=tb(e);return{status:"current",schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,state:r}}function xf(t,e){yn(e);let i=et.join(t.changesDir,e);if(!vt(t.changesDir,i))throw new Error("Native change path escaped");return i}async function rb(t,e){let i=et.join(xf(t,e),"runtime","schema-migration.json");await pe(t.nativeRoot,i);try{return await qy.lstat(i),!0}catch(r){if(r.code==="ENOENT")return!1;throw r}}var nb=256*1024;async function ob(t,e=et.dirname(t)){let i=et.relative(e,t).split(et.sep).join("/"),r=await sn({root:e,ref:i,maxBytes:nb}),n=(0,za.parseDocument)(r.text,{uniqueKeys:!0});if(n.errors.length>0)throw new Error(`Invalid Native change file ${t}: ${n.errors[0].message}`);return n.toJS()}async function ab(t,e){let i=et.join(xf(t,e),Ct);await pe(t.nativeRoot,i);let r=ib(await ob(i,t.nativeRoot));if(r.state&&r.state.name!==e)throw new Error(`Native change directory/name mismatch: ${e}`);return await rb(t,e)?{status:"migration-required",schema:r.schema,minimumRuntimeVersion:r.minimumRuntimeVersion,state:r.state,message:`Native schema migration is incomplete for ${e}; run doctor --repair`}:(r.status==="current"&&r.state&&await sb(t,r.state),r)}async function sb(t,e){if(await af(t,e.name)!==null&&e.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${e.verification_protocol}`)}async function bn(t,e){let i=await ab(t,e);if(i.status==="migration-required")throw new vn(e,i.schema);if(i.status==="runtime-incompatible"||!i.state)throw new tt(i.schema,i.minimumRuntimeVersion);return await yf(t,e),i.state}var cx=16*1024;async function cb(t){let e=await Nt(t.projectRoot);return e.status==="missing"||e.selection.workflow!=="native"?null:(yn(e.selection.change),e.selection)}async function Rf(t){let e=await cb(t);return e?(await bn(t,e.change),e.change):null}function Nn(t,e){let i=Pt.relative(t,e);return i===""||!i.startsWith("..")&&!Pt.isAbsolute(i)}function ub(t,e,i){return i.targets.length>0&&i.targets.every(r=>{let n=Pt.resolve(t,r);return Nn(t,n)?Pt.relative(t,n).replaceAll("\\","/")===".comet/config.yaml"||Nn(e,n):!0})}async function fb(t){let e=await ln(t);if(!e||!(e.workflows??[e.default_workflow]).includes("native"))return null;let i=await la(t,e.native.artifact_root),r;try{r=await lb.readdir(i.changesDir,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")return{paths:i,changes:[]};throw o}let n=[];for(let o of r.sort((a,s)=>a.name.localeCompare(s.name))){if(!o.isDirectory()||o.isSymbolicLink())continue;let a=await bn(i,o.name);a.archived||n.push(a)}return{paths:i,changes:n}}var _f=K("nativeActiveContext",t=>fb(t));async function Af(t){return((await _f(t))?.changes??[]).map(i=>({workflow:"native",name:i.name,phase:i.phase}))}async function Tf(t,e,i){let r=await _f(t);if(!r)return{allowed:!0,reason:"Native workflow is not enabled"};if(e.intent==="non-write")return{allowed:!0,reason:"Hook event is not a write"};if(r.changes.length===0)return{allowed:!0,reason:ub(t,r.paths.nativeRoot,e)?"Native control artifact write":"No Native changes exist"};let n;if(i){if(n=r.changes.find(s=>s.name===i),!n)return{allowed:!1,reason:`Selected Native change ${i} is missing or archived; resume /comet-native before retrying`,workflow:"native",change:i}}else if(r.changes.length===1)n=r.changes[0];else{let s=await Rf(r.paths);if(n=r.changes.find(c=>c.name===s),!n)return{allowed:!1,reason:"Multiple Native changes are active; select the change to resume before writing code",workflow:"native"}}if(n.phase==="build")return{allowed:!0,reason:"Native change is in Build",workflow:"native",phase:n.phase,change:n.name};if(e.intent==="unknown"||e.targets.length===0)return{allowed:!0,reason:"Hook write target was not attributed to the guarded project",workflow:"native",phase:n.phase,change:n.name};let o=!1,a=!1;for(let s of e.targets){let c=Pt.resolve(t,s);if(!Nn(t,c)){a=!0;continue}if(Pt.relative(t,c).replaceAll("\\","/")===".comet/config.yaml"||Nn(r.paths.nativeRoot,c)){o=!0;continue}return{allowed:!1,reason:`Native change ${n.name} is in ${n.phase}; implementation writes are only allowed in build. Resume /comet-native to continue safely`,workflow:"native",phase:n.phase,change:n.name}}return{allowed:!0,reason:o?"Native control artifact write":a?"Write target is outside the guarded project":"No guarded write target was provided",workflow:"native",phase:n.phase,change:n.name}}He();var Of=K("readWorkflowProjectConfig",t=>da(t)),kx=K("discoverNativeProject",t=>li(t));var db=K("readCometCurrentSelection",t=>Nt(t)),Lf={listNative:Af,listClassic:qu,inspectNative:Tf,inspectClassic:Ku};function hb(t){return t?t.workflows??[t.default_workflow]:["classic"]}async function If(t,e,i,r,n={}){let o=async()=>{if(!e.includes("classic"))return[];if(r?.workflow==="classic")return r.candidates;try{return await i.listClassic(t)}catch(c){if(n.tolerateUnavailableClassic&&c instanceof ze)return[];throw c}},[a,s]=await Promise.all([e.includes("native")?r?.workflow==="native"?r.candidates:i.listNative(t):[],o()]);return[...a,...s]}function jf(t,e){return t.length===0?{status:"none",staleSelection:e}:t.length===1?{status:"inferred",owner:t[0],staleSelection:e}:{status:"ambiguous",candidates:t,staleSelection:e}}async function mb(t,e=Lf){let i=await Of(t),r=hb(i),n;try{n=await db(t)}catch(o){return{status:"stale",code:"selection-unreadable",reason:o instanceof Error?o.message:String(o)}}if(n.status==="selected"){let o=n.selection;if(!r.includes(o.workflow))return{status:"stale",code:"workflow-disabled",reason:`selected workflow '${o.workflow}' is not enabled for this project`};let a;try{a=o.workflow==="native"?await e.listNative(t):await e.listClassic(t)}catch(c){return{status:"stale",code:"change-state-unreadable",reason:`cannot safely enumerate active Comet changes: ${c instanceof Error?c.message:String(c)}`}}let s=a.find(c=>c.name===o.change);if(!s){let c={code:"target-missing",reason:`selected ${o.workflow} change '${o.change}' is missing or archived`};try{let l=await If(t,r,e,{workflow:o.workflow,candidates:a});return jf(l,c)}catch(l){return{status:"stale",code:"change-state-unreadable",reason:`cannot safely enumerate active Comet changes: ${l instanceof Error?l.message:String(l)}`}}}if(o.workflow==="classic"){let c=await nn(t);if(c.status!=="selected")return{status:"stale",code:"classic-selection-invalid",reason:c.status==="stale"?c.reason:`selected Classic change '${o.change}' is no longer active`}}return{status:"owned",owner:s}}try{let o=await If(t,r,e,void 0,{tolerateUnavailableClassic:!0});return jf(o)}catch(o){return{status:"stale",code:"change-state-unreadable",reason:`cannot safely enumerate active Comet changes: ${o instanceof Error?o.message:String(o)}`}}}async function $f(t,e,i=Lf){if(e.intent==="non-write")return{allowed:!0,reason:"Hook event is not a write"};if(e.intent==="unknown"||e.targets.length===0)return{allowed:!0,reason:"Hook write target is outside Comet attribution"};let r;try{let n=await(i.scopeTargets??Kr)(t,e.targets);if(n.projectTargets.length===0)return{allowed:!0,reason:"Write targets are outside the guarded project"};r={...e,targets:n.projectTargets}}catch(n){return{allowed:!1,reason:["Comet Hook Router scope could not be determined safely.",`Reason: ${n instanceof Error?n.message:String(n)}`,"Next: verify that the project root is accessible, then retry the write."].join(" ")}}try{let n=await mb(t,i);if(n.status==="none")return{allowed:!0,reason:"No active Comet change"};if(n.status==="stale")return{allowed:!1,reason:`${n.reason}. Resume /comet-native or /comet-classic and select the current change before retrying`};if(n.status==="ambiguous")return{allowed:!1,reason:`Multiple active Comet changes require one current selection: ${n.candidates.map(a=>`${a.workflow}:${a.name}`).join(", ")}`};let o=n.owner;return o.workflow==="native"?i.inspectNative(t,r,o.name):i.inspectClassic(t,o.name,r)}catch(n){return{allowed:!1,reason:`Comet Hook Router failed closed: ${n instanceof Error?n.message:String(n)}`}}}import{promises as pb}from"fs";import Q from"path";function gb(t,e){let i=Q.resolve(t),r=Q.resolve(e);return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function wb(t,e){let i=Q.relative(t,e);return i===""||i!==".."&&!i.startsWith(`..${Q.sep}`)&&!Q.isAbsolute(i)}function Df(t,e){return[...e].sort((i,r)=>r.length-i.length).find(i=>wb(i,t))??null}async function vb(t){for(let e of[".git",Q.join(".comet","config.yaml")])try{await pb.lstat(Q.join(t,e))}catch(i){throw i.code!=="ENOENT"?i:new Error(`linked worktree ${t} is not initialized for Comet: missing ${e.replaceAll("\\","/")}`,{cause:i})}}async function Bf(t,e){let i=Q.resolve(t),r=cf(i);if(r.length<2||e.targets.length===0)return i;let o=(e.cwd?Df(Q.resolve(e.cwd),r):null)??i,a=new Map;for(let c of e.targets){let l=Q.isAbsolute(c)?Q.resolve(c):Q.resolve(o,c),f=Df(l,r);if(!f)continue;let u=process.platform==="win32"?f.toLowerCase():f;a.set(u,f)}if(a.size===0)return i;if(a.size>1)throw new Error("one Hook request cannot write across multiple Git worktrees");let[s]=a.values();return gb(s,i)||await vb(s),s}var yb="Usage: comet-hook-router --platform [--project-root ]";function bb(t){let e,i;for(let r=0;r0&&i.every(o=>o==="project-root-legacy-identity"||o==="native-root-legacy-identity")?r.push("workspace-inspection-unavailable"):i.length>0&&r.push("workspace-root-changed"),{state:r.length===0?"aligned":r.includes("workspace-root-changed")?"drifted":"unknown",findingCodes:r,driftComponents:i}}async function yf(t){if(wn(t.identity),t.identity.schema==="comet.native.workspace.v2")return{state:"legacy",code:"workspace-binding-legacy",message:"Legacy Native workspace metadata has no isolation binding"};if((await vf(t)).state==="drifted")return{state:"drifted",code:"workspace-binding-root-changed",message:"Native change is being accessed from a different working directory"};let i=cf(t.paths.projectRoot);return t.identity.changeBranch===null?i.isGitWorktree?{state:"drifted",code:"workspace-branch-changed",message:"Native change was created outside Git but is now being accessed inside Git"}:{state:"aligned",code:null,message:null}:i.isGitWorktree?i.currentBranch!==t.identity.changeBranch?{state:"drifted",code:"workspace-branch-changed",message:`Native change is bound to branch ${t.identity.changeBranch}, but the current branch is ${i.currentBranch??"detached HEAD"}`}:t.identity.isolation==="worktree"&&!i.isSecondaryWorktree?{state:"drifted",code:"workspace-kind-changed",message:"Native change is bound to a linked Git worktree"}:{state:"aligned",code:null,message:null}:{state:"drifted",code:"workspace-vcs-unavailable",message:"Native change requires its bound Git working directory"}}async function bf(t,e){let i=await wf(t,e);if(i===null)return null;let r=await yf({paths:t,identity:i});if(r.state==="drifted")throw new Error(`${r.code}: ${r.message}`);return i}var Ye="comet.native.v3",Xe="comet.native.v2",Qe="comet.native.v1";var Nf=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],Hy=new Set(Nf),kf=new Set([...Nf,"minimum_runtime_version","revision"]),Gy=new Set([...kf,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),zy=new Set(["capability","operation","source","base_hash"]),Vy=new Set(["shape","build","verify","archive"]),Ky=new Set(["implicit","confirmed"]),Jy=new Set(["pending","pass","fail"]),Ct="comet-state.yaml",Ga=/^[a-f0-9]{64}$/u,Sf=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Uy=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,vn=class extends Error{constructor(i,r){super(`Native change ${i} uses ${r}; run comet native doctor ${i} --repair before mutating it`);this.change=i;this.schema=r;this.name="NativeSchemaMigrationRequiredError"}change;schema;code="native-schema-migration-required"},tt=class extends Error{constructor(i,r){super(i!==Ye||r===null?`Unsupported Native change schema ${i} for runtime protocol ${3}`:`Native change ${i} requires runtime protocol ${r}; current protocol is ${3}`);this.schema=i;this.minimumRuntimeVersion=r;this.name="NativeRuntimeCompatibilityError"}schema;minimumRuntimeVersion;code="native-runtime-incompatible"};var ix=["# Outcome","","# Scope","","# Non-goals","","# Acceptance examples","","# Constraints and invariants","","# Decisions","","# Open questions","","# Verification expectations",""].join(` +`);function Ii(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function Ef(t,e,i){let r=Object.keys(t).filter(n=>!e.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function yn(t){if(!Sf.test(t))throw new Error(`Invalid Native change name: ${t}`)}function Yy(t){if(!Sf.test(t))throw new Error(`Invalid Native capability id: ${t}`)}function Cf(t,e){if(t.length===0||et.isAbsolute(t)||/^(?:[A-Za-z]:|~|[\\/])/u.test(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`${e} must stay inside the Native change`)}function Xy(t,e){let i=Ii(t,`spec_changes[${e}]`);if(Ef(i,zy,`spec_changes[${e}]`),typeof i.capability!="string")throw new Error("spec change capability is required");if(Yy(i.capability),i.operation!=="create"&&i.operation!=="replace"&&i.operation!=="remove")throw new Error(`Invalid spec operation for ${i.capability}`);let r=i.source,n=i.base_hash;if(r!==void 0&&typeof r!="string")throw new Error(`Spec source for ${i.capability} must be a string`);if(typeof r=="string"&&Cf(r,`Spec source for ${i.capability}`),i.operation==="create"){if(!r)throw new Error(`Create spec ${i.capability} requires source`);if(n!==null)throw new Error(`Create spec ${i.capability} requires null base_hash`)}else if(i.operation==="replace"){if(!r)throw new Error(`Replace spec ${i.capability} requires source`);if(typeof n!="string"||!Ga.test(n))throw new Error(`Replace spec ${i.capability} requires a SHA-256 base_hash`)}else{if(r!==void 0)throw new Error(`Remove spec ${i.capability} forbids source`);if(typeof n!="string"||!Ga.test(n))throw new Error(`Remove spec ${i.capability} requires a SHA-256 base_hash`)}return{capability:i.capability,operation:i.operation,...typeof r=="string"?{source:r}:{},base_hash:n}}function Qy(t){return/^\d{4}-\d{2}-\d{2}$/u.test(t)?new Date(`${t}T00:00:00.000Z`).toISOString().slice(0,10)===t:!1}function Va(t,e){if(Ef(t,e,Ct),typeof t.name!="string")throw new Error("Native change name is required");if(yn(t.name),t.language!=="en"&&t.language!=="zh-CN")throw new Error("Native change language must be en or zh-CN");if(typeof t.phase!="string"||!Vy.has(t.phase))throw new Error("Native change phase is invalid");if(t.brief!=="brief.md")throw new Error("Native change brief must be brief.md");if(t.approval!==null&&!Ky.has(t.approval))throw new Error("Native change approval is invalid");if(!Array.isArray(t.spec_changes))throw new Error("Native spec_changes must be an array");let i=t.spec_changes.map(Xy),r=i.map(n=>n.capability).filter((n,o,a)=>a.indexOf(n)!==o);if(r.length>0)throw new Error(`Duplicate Native capability operation: ${[...new Set(r)].join(", ")}`);if(typeof t.verification_result!="string"||!Jy.has(t.verification_result))throw new Error("Native verification_result is invalid");if(t.verification_report!==null&&typeof t.verification_report!="string")throw new Error("Native verification_report must be a string or null");if(typeof t.verification_report=="string"&&Cf(t.verification_report,"Native verification_report"),typeof t.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof t.created_at!="string"||!Qy(t.created_at))throw new Error("Native created_at must be a valid YYYY-MM-DD date");if(t.run_id!==null&&(typeof t.run_id!="string"||t.run_id.length===0))throw new Error("Native run_id must be a non-empty string or null");return{name:t.name,language:t.language,phase:t.phase,brief:"brief.md",approval:t.approval,spec_changes:i,verification_result:t.verification_result,verification_report:t.verification_report,archived:t.archived,created_at:t.created_at,run_id:t.run_id}}function Pf(t){let e=Ii(t,Ct);if(e.schema!==Qe)throw new Error(`Expected ${Qe}`);return{schema:Qe,...Va(e,Hy)}}function Oi(t,e){if(!Number.isSafeInteger(t)||t<1)throw new Error(`${e} must be a positive integer`);return t}function Ha(t,e,i){if(t===null)return null;let r=typeof t=="string"?Uy.exec(t):null;if(!r||r[1]!==i)throw new Error(`${e} must be null or runtime/evidence/${i}/.json relative to the Native change`);return t}function Zy(t){if(t==null)return null;if(typeof t!="string"||!Ga.test(t))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return t}function eb(t){if(t===void 0)return"legacy-v1";if(t!=="legacy-v1")throw new Error("Native verification_protocol must be legacy-v1");return t}function xf(t){let e=Ii(t,Ct);if(e.schema!==Xe)throw new Error(`Expected ${Xe}`);if(Oi(e.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${Xe} minimum_runtime_version must be 2`);return{schema:Xe,minimum_runtime_version:2,revision:Oi(e.revision,"Native v2 revision"),...Va(e,kf)}}function tb(t){let e=Ii(t,Ct);if(e.schema!==Ye){if(e.schema===Qe||e.schema===Xe){let a=e.schema===Qe?Pf(e):xf(e);throw new vn(a.name,a.schema)}throw new tt(typeof e.schema=="string"?e.schema:"(missing)",typeof e.minimum_runtime_version=="number"?e.minimum_runtime_version:null)}let i=Oi(e.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)throw new tt(e.schema,i);if(i!==3)throw new Error(`Native ${e.schema} minimum_runtime_version must be ${3}`);let r=Oi(e.revision,"Native revision"),n=Va(e,Gy),o=Zy(e.approved_contract_hash);if(n.approval===null&&o!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:Ye,minimum_runtime_version:3,revision:r,verification_protocol:eb(e.verification_protocol),...n,approved_contract_hash:o,implementation_scope:Ha(e.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:Ha(e.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:Ha(e.partial_allowance,"Native partial_allowance","allowances")}}function ib(t){let e=Ii(t,Ct);if(e.schema===Qe){let n=Pf(e);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${Ye}`}}if(e.schema===Xe){let n=xf(e);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${Ye}`}}if(e.schema!==Ye){let n=typeof e.minimum_runtime_version=="number"&&Number.isSafeInteger(e.minimum_runtime_version)?e.minimum_runtime_version:null;return{status:"runtime-incompatible",schema:typeof e.schema=="string"?e.schema:"(missing)",minimumRuntimeVersion:n,state:null,message:new tt(typeof e.schema=="string"?e.schema:"(missing)",n).message}}let i=Oi(e.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)return{status:"runtime-incompatible",schema:e.schema,minimumRuntimeVersion:i,state:null,message:new tt(e.schema,i).message};let r=tb(e);return{status:"current",schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,state:r}}function Rf(t,e){yn(e);let i=et.join(t.changesDir,e);if(!vt(t.changesDir,i))throw new Error("Native change path escaped");return i}async function rb(t,e){let i=et.join(Rf(t,e),"runtime","schema-migration.json");await pe(t.nativeRoot,i);try{return await qy.lstat(i),!0}catch(r){if(r.code==="ENOENT")return!1;throw r}}var nb=256*1024;async function ob(t,e=et.dirname(t)){let i=et.relative(e,t).split(et.sep).join("/"),r=await sn({root:e,ref:i,maxBytes:nb}),n=(0,za.parseDocument)(r.text,{uniqueKeys:!0});if(n.errors.length>0)throw new Error(`Invalid Native change file ${t}: ${n.errors[0].message}`);return n.toJS()}async function ab(t,e){let i=et.join(Rf(t,e),Ct);await pe(t.nativeRoot,i);let r=ib(await ob(i,t.nativeRoot));if(r.state&&r.state.name!==e)throw new Error(`Native change directory/name mismatch: ${e}`);return await rb(t,e)?{status:"migration-required",schema:r.schema,minimumRuntimeVersion:r.minimumRuntimeVersion,state:r.state,message:`Native schema migration is incomplete for ${e}; run doctor --repair`}:(r.status==="current"&&r.state&&await sb(t,r.state),r)}async function sb(t,e){if(await sf(t,e.name)!==null&&e.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${e.verification_protocol}`)}async function bn(t,e){let i=await ab(t,e);if(i.status==="migration-required")throw new vn(e,i.schema);if(i.status==="runtime-incompatible"||!i.state)throw new tt(i.schema,i.minimumRuntimeVersion);return await bf(t,e),i.state}var cx=16*1024;async function cb(t){let e=await Nt(t.projectRoot);return e.status==="missing"||e.selection.workflow!=="native"?null:(yn(e.selection.change),e.selection)}async function _f(t){let e=await cb(t);return e?(await bn(t,e.change),e.change):null}function Nn(t,e){let i=Pt.relative(t,e);return i===""||!i.startsWith("..")&&!Pt.isAbsolute(i)}function ub(t,e,i){return i.targets.length>0&&i.targets.every(r=>{let n=Pt.resolve(t,r);return Nn(t,n)?Pt.relative(t,n).replaceAll("\\","/")===".comet/config.yaml"||Nn(e,n):!0})}async function fb(t){let e=await ln(t);if(!e||!(e.workflows??[e.default_workflow]).includes("native"))return null;let i=await la(t,e.native.artifact_root),r;try{r=await lb.readdir(i.changesDir,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")return{paths:i,changes:[]};throw o}let n=[];for(let o of r.sort((a,s)=>a.name.localeCompare(s.name))){if(!o.isDirectory()||o.isSymbolicLink())continue;let a=await bn(i,o.name);a.archived||n.push(a)}return{paths:i,changes:n}}var Af=K("nativeActiveContext",t=>fb(t));async function Tf(t){return((await Af(t))?.changes??[]).map(i=>({workflow:"native",name:i.name,phase:i.phase}))}async function Of(t,e,i){let r=await Af(t);if(!r)return{allowed:!0,reason:"Native workflow is not enabled"};if(e.intent==="non-write")return{allowed:!0,reason:"Hook event is not a write"};if(r.changes.length===0)return{allowed:!0,reason:ub(t,r.paths.nativeRoot,e)?"Native control artifact write":"No Native changes exist"};let n;if(i){if(n=r.changes.find(s=>s.name===i),!n)return{allowed:!1,reason:`Selected Native change ${i} is missing or archived; resume /comet-native before retrying`,workflow:"native",change:i}}else if(r.changes.length===1)n=r.changes[0];else{let s=await _f(r.paths);if(n=r.changes.find(c=>c.name===s),!n)return{allowed:!1,reason:"Multiple Native changes are active; select the change to resume before writing code",workflow:"native"}}if(n.phase==="build")return{allowed:!0,reason:"Native change is in Build",workflow:"native",phase:n.phase,change:n.name};if(e.intent==="unknown"||e.targets.length===0)return{allowed:!0,reason:"Hook write target was not attributed to the guarded project",workflow:"native",phase:n.phase,change:n.name};let o=!1,a=!1;for(let s of e.targets){let c=Pt.resolve(t,s);if(!Nn(t,c)){a=!0;continue}if(Pt.relative(t,c).replaceAll("\\","/")===".comet/config.yaml"||Nn(r.paths.nativeRoot,c)){o=!0;continue}return{allowed:!1,reason:`Native change ${n.name} is in ${n.phase}; implementation writes are only allowed in build. Resume /comet-native to continue safely`,workflow:"native",phase:n.phase,change:n.name}}return{allowed:!0,reason:o?"Native control artifact write":a?"Write target is outside the guarded project":"No guarded write target was provided",workflow:"native",phase:n.phase,change:n.name}}He();var If=K("readWorkflowProjectConfig",t=>da(t)),kx=K("discoverNativeProject",t=>li(t));var db=K("readCometCurrentSelection",t=>Nt(t)),$f={listNative:Tf,listClassic:Hu,inspectNative:Of,inspectClassic:Ju};function hb(t){return t?t.workflows??[t.default_workflow]:["classic"]}async function jf(t,e,i,r,n={}){let o=async()=>{if(!e.includes("classic"))return[];if(r?.workflow==="classic")return r.candidates;try{return await i.listClassic(t)}catch(c){if(n.tolerateUnavailableClassic&&c instanceof ze)return[];throw c}},[a,s]=await Promise.all([e.includes("native")?r?.workflow==="native"?r.candidates:i.listNative(t):[],o()]);return[...a,...s]}function Lf(t,e){return t.length===0?{status:"none",staleSelection:e}:t.length===1?{status:"inferred",owner:t[0],staleSelection:e}:{status:"ambiguous",candidates:t,staleSelection:e}}async function mb(t,e=$f){let i=await If(t),r=hb(i),n;try{n=await db(t)}catch(o){return{status:"stale",code:"selection-unreadable",reason:o instanceof Error?o.message:String(o)}}if(n.status==="selected"){let o=n.selection;if(!r.includes(o.workflow))return{status:"stale",code:"workflow-disabled",reason:`selected workflow '${o.workflow}' is not enabled for this project`};let a;try{a=o.workflow==="native"?await e.listNative(t):await e.listClassic(t)}catch(c){return{status:"stale",code:"change-state-unreadable",reason:`cannot safely enumerate active Comet changes: ${c instanceof Error?c.message:String(c)}`}}let s=a.find(c=>c.name===o.change);if(!s){let c={code:"target-missing",reason:`selected ${o.workflow} change '${o.change}' is missing or archived`};try{let l=await jf(t,r,e,{workflow:o.workflow,candidates:a});return Lf(l,c)}catch(l){return{status:"stale",code:"change-state-unreadable",reason:`cannot safely enumerate active Comet changes: ${l instanceof Error?l.message:String(l)}`}}}if(o.workflow==="classic"){let c=await nn(t);if(c.status!=="selected")return{status:"stale",code:"classic-selection-invalid",reason:c.status==="stale"?c.reason:`selected Classic change '${o.change}' is no longer active`}}return{status:"owned",owner:s}}try{let o=await jf(t,r,e,void 0,{tolerateUnavailableClassic:!0});return Lf(o)}catch(o){return{status:"stale",code:"change-state-unreadable",reason:`cannot safely enumerate active Comet changes: ${o instanceof Error?o.message:String(o)}`}}}async function Df(t,e,i=$f){if(e.intent==="non-write")return{allowed:!0,reason:"Hook event is not a write"};if(e.intent==="unknown"||e.targets.length===0)return{allowed:!0,reason:"Hook write target is outside Comet attribution"};let r;try{let n=await(i.scopeTargets??Kr)(t,e.targets);if(n.projectTargets.length===0)return{allowed:!0,reason:"Write targets are outside the guarded project"};r={...e,targets:n.projectTargets}}catch(n){return{allowed:!1,reason:["Comet Hook Router scope could not be determined safely.",`Reason: ${n instanceof Error?n.message:String(n)}`,"Next: verify that the project root is accessible, then retry the write."].join(" ")}}try{let n=await mb(t,i);if(n.status==="none")return{allowed:!0,reason:"No active Comet change"};if(n.status==="stale")return{allowed:!1,reason:`${n.reason}. Resume /comet-native or /comet-classic and select the current change before retrying`};if(n.status==="ambiguous")return{allowed:!1,reason:`Multiple active Comet changes require one current selection: ${n.candidates.map(a=>`${a.workflow}:${a.name}`).join(", ")}`};let o=n.owner;return o.workflow==="native"?i.inspectNative(t,r,o.name):i.inspectClassic(t,o.name,r)}catch(n){return{allowed:!1,reason:`Comet Hook Router failed closed: ${n instanceof Error?n.message:String(n)}`}}}import{promises as pb}from"fs";import Q from"path";function gb(t,e){let i=Q.resolve(t),r=Q.resolve(e);return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function wb(t,e){let i=Q.relative(t,e);return i===""||i!==".."&&!i.startsWith(`..${Q.sep}`)&&!Q.isAbsolute(i)}function Bf(t,e){return[...e].sort((i,r)=>r.length-i.length).find(i=>wb(i,t))??null}async function vb(t){for(let e of[".git",Q.join(".comet","config.yaml")])try{await pb.lstat(Q.join(t,e))}catch(i){throw i.code!=="ENOENT"?i:new Error(`linked worktree ${t} is not initialized for Comet: missing ${e.replaceAll("\\","/")}`,{cause:i})}}async function Mf(t,e){let i=Q.resolve(t),r=lf(i);if(r.length<2||e.targets.length===0)return i;let o=(e.cwd?Bf(Q.resolve(e.cwd),r):null)??i,a=new Map;for(let c of e.targets){let l=Q.isAbsolute(c)?Q.resolve(c):Q.resolve(o,c),f=Bf(l,r);if(!f)continue;let u=process.platform==="win32"?f.toLowerCase():f;a.set(u,f)}if(a.size===0)return i;if(a.size>1)throw new Error("one Hook request cannot write across multiple Git worktrees");let[s]=a.values();return gb(s,i)||await vb(s),s}var yb="Usage: comet-hook-router --platform [--project-root ]";function bb(t){let e,i;for(let r=0;r$f(o,n)):{allowed:!0,reason:"No Comet project discovered"}}catch(n){i={allowed:!1,reason:`Comet Hook Router failed closed during project discovery: ${n instanceof Error?n.message:String(n)}`}}let r=iu(e.platformId,i);return r.stdout&&process.stdout.write(r.stdout),r.stderr&&process.stderr.write(r.stderr),r.exitCode}process.exitCode=await kb(process.argv.slice(2));export{Nb as projectRootFrom,kb as runCometHookRouter}; +`),64}let i;try{let n=ba(),o=await Nb(e,n);i=o?await nu(()=>Df(o,n)):{allowed:!0,reason:"No Comet project discovered"}}catch(n){i={allowed:!1,reason:`Comet Hook Router failed closed during project discovery: ${n instanceof Error?n.message:String(n)}`}}let r=ru(e.platformId,i);return r.stdout&&process.stdout.write(r.stdout),r.stderr&&process.stderr.write(r.stderr),r.exitCode}process.exitCode=await kb(process.argv.slice(2));export{Nb as projectRootFrom,kb as runCometHookRouter}; diff --git a/assets/skills/comet/scripts/comet-resume-probe.mjs b/assets/skills/comet/scripts/comet-resume-probe.mjs index 71b52182f..4a5a411d3 100644 --- a/assets/skills/comet/scripts/comet-resume-probe.mjs +++ b/assets/skills/comet/scripts/comet-resume-probe.mjs @@ -1,75 +1,75 @@ #!/usr/bin/env node import { createRequire as __cometCreateRequire } from 'module'; const require = __cometCreateRequire(import.meta.url); -var Yc=Object.create;var Xn=Object.defineProperty;var Uc=Object.getOwnPropertyDescriptor;var Jc=Object.getOwnPropertyNames;var Vc=Object.getPrototypeOf,Hc=Object.prototype.hasOwnProperty;var At=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var L=(t,e,n)=>()=>{if(n)throw n[0];try{return t&&(e=t(t=0)),e}catch(i){throw n=[i],i}};var g=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(n){throw e=0,n}},Gc=(t,e)=>{for(var n in e)Xn(t,n,{get:e[n],enumerable:!0})},zc=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Jc(e))!Hc.call(t,r)&&r!==n&&Xn(t,r,{get:()=>e[r],enumerable:!(i=Uc(e,r))||i.enumerable});return t};var Zn=(t,e,n)=>(n=t!=null?Yc(Vc(t)):{},zc(e||!t||!t.__esModule?Xn(n,"default",{value:t,enumerable:!0}):n,t));var E=g(j=>{"use strict";var ti=Symbol.for("yaml.alias"),os=Symbol.for("yaml.document"),Rt=Symbol.for("yaml.map"),as=Symbol.for("yaml.pair"),ni=Symbol.for("yaml.scalar"),It=Symbol.for("yaml.seq"),H=Symbol.for("yaml.node.type"),Xc=t=>!!t&&typeof t=="object"&&t[H]===ti,Zc=t=>!!t&&typeof t=="object"&&t[H]===os,el=t=>!!t&&typeof t=="object"&&t[H]===Rt,tl=t=>!!t&&typeof t=="object"&&t[H]===as,cs=t=>!!t&&typeof t=="object"&&t[H]===ni,nl=t=>!!t&&typeof t=="object"&&t[H]===It;function ls(t){if(t&&typeof t=="object")switch(t[H]){case Rt:case It:return!0}return!1}function il(t){if(t&&typeof t=="object")switch(t[H]){case ti:case Rt:case ni:case It:return!0}return!1}var rl=t=>(cs(t)||ls(t))&&!!t.anchor;j.ALIAS=ti;j.DOC=os;j.MAP=Rt;j.NODE_TYPE=H;j.PAIR=as;j.SCALAR=ni;j.SEQ=It;j.hasAnchor=rl;j.isAlias=Xc;j.isCollection=ls;j.isDocument=Zc;j.isMap=el;j.isNode=il;j.isPair=tl;j.isScalar=cs;j.isSeq=nl});var Be=g(ii=>{"use strict";var T=E(),M=Symbol("break visit"),us=Symbol("skip children"),J=Symbol("remove node");function Tt(t,e){let n=fs(e);T.isDocument(t)?Pe(null,t.contents,n,Object.freeze([t]))===J&&(t.contents=null):Pe(null,t,n,Object.freeze([]))}Tt.BREAK=M;Tt.SKIP=us;Tt.REMOVE=J;function Pe(t,e,n,i){let r=ds(t,e,n,i);if(T.isNode(r)||T.isPair(r))return ms(t,i,r),Pe(t,r,n,i);if(typeof r!="symbol"){if(T.isCollection(e)){i=Object.freeze(i.concat(e));for(let s=0;s{"use strict";var ps=E(),sl=Be(),ol={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},al=t=>t.replace(/[!,[\]{}]/g,e=>ol[e]),Ke=class t{constructor(e,n){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},t.defaultYaml,e),this.tags=Object.assign({},t.defaultTags,n)}clone(){let e=new t(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){let e=new t(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:t.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},t.defaultTags);break}return e}add(e,n){this.atNextDocument&&(this.yaml={explicit:t.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},t.defaultTags),this.atNextDocument=!1);let i=e.trim().split(/[ \t]+/),r=i.shift();switch(r){case"%TAG":{if(i.length!==2&&(n(0,"%TAG directive should contain exactly two parts"),i.length<2))return!1;let[s,o]=i;return this.tags[s]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,i.length!==1)return n(0,"%YAML directive should contain exactly one part"),!1;let[s]=i;if(s==="1.1"||s==="1.2")return this.yaml.version=s,!0;{let o=/^\d+\.\d+$/.test(s);return n(6,`Unsupported YAML version ${s}`,o),!1}}default:return n(0,`Unknown directive ${r}`,!0),!1}}tagName(e,n){if(e==="!")return"!";if(e[0]!=="!")return n(`Not a valid tag: ${e}`),null;if(e[1]==="<"){let o=e.slice(2,-1);return o==="!"||o==="!!"?(n(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&n("Verbatim tags must end with a >"),o)}let[,i,r]=e.match(/^(.*!)([^!]*)$/s);r||n(`The ${e} tag has no suffix`);let s=this.tags[i];if(s)try{return s+decodeURIComponent(r)}catch(o){return n(String(o)),null}return i==="!"?e:(n(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[n,i]of Object.entries(this.tags))if(e.startsWith(i))return n+al(e.substring(i.length));return e[0]==="!"?e:`!<${e}>`}toString(e){let n=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],i=Object.entries(this.tags),r;if(e&&i.length>0&&ps.isNode(e.contents)){let s={};sl.visit(e.contents,(o,a)=>{ps.isNode(a)&&a.tag&&(s[a.tag]=!0)}),r=Object.keys(s)}else r=[];for(let[s,o]of i)s==="!!"&&o==="tag:yaml.org,2002:"||(!e||r.some(a=>a.startsWith(o)))&&n.push(`%TAG ${s} ${o}`);return n.join(` -`)}};Ke.defaultYaml={explicit:!1,version:"1.2"};Ke.defaultTags={"!!":"tag:yaml.org,2002:"};hs.Directives=Ke});var qt=g(Ye=>{"use strict";var gs=E(),cl=Be();function ll(t){if(/[\x00-\x19\s,[\]{}]/.test(t)){let n=`Anchor must not contain whitespace or control characters: ${JSON.stringify(t)}`;throw new Error(n)}return!0}function ws(t){let e=new Set;return cl.visit(t,{Value(n,i){i.anchor&&e.add(i.anchor)}}),e}function ys(t,e){for(let n=1;;++n){let i=`${t}${n}`;if(!e.has(i))return i}}function ul(t,e){let n=[],i=new Map,r=null;return{onAnchor:s=>{n.push(s),r??(r=ws(t));let o=ys(e,r);return r.add(o),o},setAnchors:()=>{for(let s of n){let o=i.get(s);if(typeof o=="object"&&o.anchor&&(gs.isScalar(o.node)||gs.isCollection(o.node)))o.node.anchor=o.anchor;else{let a=new Error("Failed to resolve repeated object (this should not happen)");throw a.source=s,a}}},sourceObjects:i}}Ye.anchorIsValid=ll;Ye.anchorNames=ws;Ye.createNodeAnchors=ul;Ye.findNewAnchor=ys});var si=g(vs=>{"use strict";function Ue(t,e,n,i){if(i&&typeof i=="object")if(Array.isArray(i))for(let r=0,s=i.length;r{"use strict";var fl=E();function bs(t,e,n){if(Array.isArray(t))return t.map((i,r)=>bs(i,String(r),n));if(t&&typeof t.toJSON=="function"){if(!n||!fl.hasAnchor(t))return t.toJSON(e,n);let i={aliasCount:0,count:1,res:void 0};n.anchors.set(t,i),n.onCreate=s=>{i.res=s,delete n.onCreate};let r=t.toJSON(e,n);return n.onCreate&&n.onCreate(r),r}return typeof t=="bigint"&&!n?.keep?Number(t):t}ks.toJS=bs});var Lt=g(Cs=>{"use strict";var dl=si(),Ss=E(),ml=ne(),oi=class{constructor(e){Object.defineProperty(this,Ss.NODE_TYPE,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:n,maxAliasCount:i,onAnchor:r,reviver:s}={}){if(!Ss.isDocument(e))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:e,keep:!0,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},a=ml.toJS(this,"",o);if(typeof r=="function")for(let{count:c,res:l}of o.anchors.values())r(l,c);return typeof s=="function"?dl.applyReviver(s,{"":a},"",a):a}};Cs.NodeBase=oi});var Je=g(_s=>{"use strict";var pl=qt(),hl=Be(),xe=E(),gl=Lt(),wl=ne(),ai=class extends gl.NodeBase{constructor(e){super(xe.ALIAS),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,n){if(n?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let i;n?.aliasResolveCache?i=n.aliasResolveCache:(i=[],hl.visit(e,{Node:(s,o)=>{(xe.isAlias(o)||xe.hasAnchor(o))&&i.push(o)}}),n&&(n.aliasResolveCache=i));let r;for(let s of i){if(s===this)break;s.anchor===this.source&&(r=s)}return r}toJSON(e,n){if(!n)return{source:this.source};let{anchors:i,doc:r,maxAliasCount:s}=n,o=this.resolve(r,n);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let a=i.get(o);if(a||(wl.toJS(o,null,n),a=i.get(o)),a?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(s>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=Dt(r,o,i)),a.count*a.aliasCount>s)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return a.res}toString(e,n,i){let r=`*${this.source}`;if(e){if(pl.anchorIsValid(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let s=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(s)}if(e.implicitKey)return`${r} `}return r}};function Dt(t,e,n){if(xe.isAlias(e)){let i=e.resolve(t),r=n&&i&&n.get(i);return r?r.count*r.aliasCount:0}else if(xe.isCollection(e)){let i=0;for(let r of e.items){let s=Dt(t,r,n);s>i&&(i=s)}return i}else if(xe.isPair(e)){let i=Dt(t,e.key,n),r=Dt(t,e.value,n);return Math.max(i,r)}return 1}_s.Alias=ai});var x=g(ci=>{"use strict";var yl=E(),vl=Lt(),bl=ne(),kl=t=>!t||typeof t!="function"&&typeof t!="object",ie=class extends vl.NodeBase{constructor(e){super(yl.SCALAR),this.value=e}toJSON(e,n){return n?.keep?this.value:bl.toJS(this.value,e,n)}toString(){return String(this.value)}};ie.BLOCK_FOLDED="BLOCK_FOLDED";ie.BLOCK_LITERAL="BLOCK_LITERAL";ie.PLAIN="PLAIN";ie.QUOTE_DOUBLE="QUOTE_DOUBLE";ie.QUOTE_SINGLE="QUOTE_SINGLE";ci.Scalar=ie;ci.isScalarValue=kl});var Ve=g(Ps=>{"use strict";var Sl=Je(),we=E(),Es=x(),Cl="tag:yaml.org,2002:";function _l(t,e,n){if(e){let i=n.filter(s=>s.tag===e),r=i.find(s=>!s.format)??i[0];if(!r)throw new Error(`Tag ${e} not found`);return r}return n.find(i=>i.identify?.(t)&&!i.format)}function El(t,e,n){if(we.isDocument(t)&&(t=t.contents),we.isNode(t))return t;if(we.isPair(t)){let u=n.schema[we.MAP].createNode?.(n.schema,null,n);return u.items.push(t),u}(t instanceof String||t instanceof Number||t instanceof Boolean||typeof BigInt<"u"&&t instanceof BigInt)&&(t=t.valueOf());let{aliasDuplicateObjects:i,onAnchor:r,onTagObj:s,schema:o,sourceObjects:a}=n,c;if(i&&t&&typeof t=="object"){if(c=a.get(t),c)return c.anchor??(c.anchor=r(t)),new Sl.Alias(c.anchor);c={anchor:null,node:null},a.set(t,c)}e?.startsWith("!!")&&(e=Cl+e.slice(2));let l=_l(t,e,o.tags);if(!l){if(t&&typeof t.toJSON=="function"&&(t=t.toJSON()),!t||typeof t!="object"){let u=new Es.Scalar(t);return c&&(c.node=u),u}l=t instanceof Map?o[we.MAP]:Symbol.iterator in Object(t)?o[we.SEQ]:o[we.MAP]}s&&(s(l),delete n.onTagObj);let m=l?.createNode?l.createNode(n.schema,t,n):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(n.schema,t,n):new Es.Scalar(t);return e?m.tag=e:l.default||(m.tag=l.tag),c&&(c.node=m),m}Ps.createNode=El});var Wt=g(Mt=>{"use strict";var Pl=Ve(),V=E(),Nl=Lt();function li(t,e,n){let i=n;for(let r=e.length-1;r>=0;--r){let s=e[r];if(typeof s=="number"&&Number.isInteger(s)&&s>=0){let o=[];o[s]=i,i=o}else i=new Map([[s,i]])}return Pl.createNode(i,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:t,sourceObjects:new Map})}var Ns=t=>t==null||typeof t=="object"&&!!t[Symbol.iterator]().next().done,ui=class extends Nl.NodeBase{constructor(e,n){super(e),Object.defineProperty(this,"schema",{value:n,configurable:!0,enumerable:!1,writable:!0})}clone(e){let n=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(n.schema=e),n.items=n.items.map(i=>V.isNode(i)||V.isPair(i)?i.clone(e):i),this.range&&(n.range=this.range.slice()),n}addIn(e,n){if(Ns(e))this.add(n);else{let[i,...r]=e,s=this.get(i,!0);if(V.isCollection(s))s.addIn(r,n);else if(s===void 0&&this.schema)this.set(i,li(this.schema,r,n));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${r}`)}}deleteIn(e){let[n,...i]=e;if(i.length===0)return this.delete(n);let r=this.get(n,!0);if(V.isCollection(r))return r.deleteIn(i);throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}getIn(e,n){let[i,...r]=e,s=this.get(i,!0);return r.length===0?!n&&V.isScalar(s)?s.value:s:V.isCollection(s)?s.getIn(r,n):void 0}hasAllNullValues(e){return this.items.every(n=>{if(!V.isPair(n))return!1;let i=n.value;return i==null||e&&V.isScalar(i)&&i.value==null&&!i.commentBefore&&!i.comment&&!i.tag})}hasIn(e){let[n,...i]=e;if(i.length===0)return this.has(n);let r=this.get(n,!0);return V.isCollection(r)?r.hasIn(i):!1}setIn(e,n){let[i,...r]=e;if(r.length===0)this.set(i,n);else{let s=this.get(i,!0);if(V.isCollection(s))s.setIn(r,n);else if(s===void 0&&this.schema)this.set(i,li(this.schema,r,n));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${r}`)}}};Mt.Collection=ui;Mt.collectionFromPath=li;Mt.isEmptyPath=Ns});var He=g($t=>{"use strict";var xl=t=>t.replace(/^(?!$)(?: $)?/gm,"#");function fi(t,e){return/^\n+$/.test(t)?t.substring(1):e?t.replace(/^(?! *$)/gm,e):t}var Ol=(t,e,n)=>t.endsWith(` +var Uc=Object.create;var Xn=Object.defineProperty;var Jc=Object.getOwnPropertyDescriptor;var Vc=Object.getOwnPropertyNames;var Hc=Object.getPrototypeOf,Gc=Object.prototype.hasOwnProperty;var At=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var L=(t,e,n)=>()=>{if(n)throw n[0];try{return t&&(e=t(t=0)),e}catch(i){throw n=[i],i}};var g=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(n){throw e=0,n}},zc=(t,e)=>{for(var n in e)Xn(t,n,{get:e[n],enumerable:!0})},Qc=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Vc(e))!Gc.call(t,r)&&r!==n&&Xn(t,r,{get:()=>e[r],enumerable:!(i=Jc(e,r))||i.enumerable});return t};var Zn=(t,e,n)=>(n=t!=null?Uc(Hc(t)):{},Qc(e||!t||!t.__esModule?Xn(n,"default",{value:t,enumerable:!0}):n,t));var E=g(j=>{"use strict";var ti=Symbol.for("yaml.alias"),ss=Symbol.for("yaml.document"),Rt=Symbol.for("yaml.map"),os=Symbol.for("yaml.pair"),ni=Symbol.for("yaml.scalar"),It=Symbol.for("yaml.seq"),H=Symbol.for("yaml.node.type"),Zc=t=>!!t&&typeof t=="object"&&t[H]===ti,el=t=>!!t&&typeof t=="object"&&t[H]===ss,tl=t=>!!t&&typeof t=="object"&&t[H]===Rt,nl=t=>!!t&&typeof t=="object"&&t[H]===os,as=t=>!!t&&typeof t=="object"&&t[H]===ni,il=t=>!!t&&typeof t=="object"&&t[H]===It;function cs(t){if(t&&typeof t=="object")switch(t[H]){case Rt:case It:return!0}return!1}function rl(t){if(t&&typeof t=="object")switch(t[H]){case ti:case Rt:case ni:case It:return!0}return!1}var sl=t=>(as(t)||cs(t))&&!!t.anchor;j.ALIAS=ti;j.DOC=ss;j.MAP=Rt;j.NODE_TYPE=H;j.PAIR=os;j.SCALAR=ni;j.SEQ=It;j.hasAnchor=sl;j.isAlias=Zc;j.isCollection=cs;j.isDocument=el;j.isMap=tl;j.isNode=rl;j.isPair=nl;j.isScalar=as;j.isSeq=il});var Be=g(ii=>{"use strict";var T=E(),M=Symbol("break visit"),ls=Symbol("skip children"),J=Symbol("remove node");function Tt(t,e){let n=us(e);T.isDocument(t)?Ee(null,t.contents,n,Object.freeze([t]))===J&&(t.contents=null):Ee(null,t,n,Object.freeze([]))}Tt.BREAK=M;Tt.SKIP=ls;Tt.REMOVE=J;function Ee(t,e,n,i){let r=fs(t,e,n,i);if(T.isNode(r)||T.isPair(r))return ds(t,i,r),Ee(t,r,n,i);if(typeof r!="symbol"){if(T.isCollection(e)){i=Object.freeze(i.concat(e));for(let s=0;s{"use strict";var ms=E(),ol=Be(),al={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},cl=t=>t.replace(/[!,[\]{}]/g,e=>al[e]),Ke=class t{constructor(e,n){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},t.defaultYaml,e),this.tags=Object.assign({},t.defaultTags,n)}clone(){let e=new t(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){let e=new t(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:t.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},t.defaultTags);break}return e}add(e,n){this.atNextDocument&&(this.yaml={explicit:t.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},t.defaultTags),this.atNextDocument=!1);let i=e.trim().split(/[ \t]+/),r=i.shift();switch(r){case"%TAG":{if(i.length!==2&&(n(0,"%TAG directive should contain exactly two parts"),i.length<2))return!1;let[s,o]=i;return this.tags[s]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,i.length!==1)return n(0,"%YAML directive should contain exactly one part"),!1;let[s]=i;if(s==="1.1"||s==="1.2")return this.yaml.version=s,!0;{let o=/^\d+\.\d+$/.test(s);return n(6,`Unsupported YAML version ${s}`,o),!1}}default:return n(0,`Unknown directive ${r}`,!0),!1}}tagName(e,n){if(e==="!")return"!";if(e[0]!=="!")return n(`Not a valid tag: ${e}`),null;if(e[1]==="<"){let o=e.slice(2,-1);return o==="!"||o==="!!"?(n(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&n("Verbatim tags must end with a >"),o)}let[,i,r]=e.match(/^(.*!)([^!]*)$/s);r||n(`The ${e} tag has no suffix`);let s=this.tags[i];if(s)try{return s+decodeURIComponent(r)}catch(o){return n(String(o)),null}return i==="!"?e:(n(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[n,i]of Object.entries(this.tags))if(e.startsWith(i))return n+cl(e.substring(i.length));return e[0]==="!"?e:`!<${e}>`}toString(e){let n=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],i=Object.entries(this.tags),r;if(e&&i.length>0&&ms.isNode(e.contents)){let s={};ol.visit(e.contents,(o,a)=>{ms.isNode(a)&&a.tag&&(s[a.tag]=!0)}),r=Object.keys(s)}else r=[];for(let[s,o]of i)s==="!!"&&o==="tag:yaml.org,2002:"||(!e||r.some(a=>a.startsWith(o)))&&n.push(`%TAG ${s} ${o}`);return n.join(` +`)}};Ke.defaultYaml={explicit:!1,version:"1.2"};Ke.defaultTags={"!!":"tag:yaml.org,2002:"};ps.Directives=Ke});var qt=g(Ye=>{"use strict";var hs=E(),ll=Be();function ul(t){if(/[\x00-\x19\s,[\]{}]/.test(t)){let n=`Anchor must not contain whitespace or control characters: ${JSON.stringify(t)}`;throw new Error(n)}return!0}function gs(t){let e=new Set;return ll.visit(t,{Value(n,i){i.anchor&&e.add(i.anchor)}}),e}function ws(t,e){for(let n=1;;++n){let i=`${t}${n}`;if(!e.has(i))return i}}function fl(t,e){let n=[],i=new Map,r=null;return{onAnchor:s=>{n.push(s),r??(r=gs(t));let o=ws(e,r);return r.add(o),o},setAnchors:()=>{for(let s of n){let o=i.get(s);if(typeof o=="object"&&o.anchor&&(hs.isScalar(o.node)||hs.isCollection(o.node)))o.node.anchor=o.anchor;else{let a=new Error("Failed to resolve repeated object (this should not happen)");throw a.source=s,a}}},sourceObjects:i}}Ye.anchorIsValid=ul;Ye.anchorNames=gs;Ye.createNodeAnchors=fl;Ye.findNewAnchor=ws});var si=g(ys=>{"use strict";function Ue(t,e,n,i){if(i&&typeof i=="object")if(Array.isArray(i))for(let r=0,s=i.length;r{"use strict";var dl=E();function vs(t,e,n){if(Array.isArray(t))return t.map((i,r)=>vs(i,String(r),n));if(t&&typeof t.toJSON=="function"){if(!n||!dl.hasAnchor(t))return t.toJSON(e,n);let i={aliasCount:0,count:1,res:void 0};n.anchors.set(t,i),n.onCreate=s=>{i.res=s,delete n.onCreate};let r=t.toJSON(e,n);return n.onCreate&&n.onCreate(r),r}return typeof t=="bigint"&&!n?.keep?Number(t):t}bs.toJS=vs});var Lt=g(Ss=>{"use strict";var ml=si(),ks=E(),pl=te(),oi=class{constructor(e){Object.defineProperty(this,ks.NODE_TYPE,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:n,maxAliasCount:i,onAnchor:r,reviver:s}={}){if(!ks.isDocument(e))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:e,keep:!0,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},a=pl.toJS(this,"",o);if(typeof r=="function")for(let{count:c,res:l}of o.anchors.values())r(l,c);return typeof s=="function"?ml.applyReviver(s,{"":a},"",a):a}};Ss.NodeBase=oi});var Je=g(Cs=>{"use strict";var hl=qt(),gl=Be(),Ne=E(),wl=Lt(),yl=te(),ai=class extends wl.NodeBase{constructor(e){super(Ne.ALIAS),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,n){if(n?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let i;n?.aliasResolveCache?i=n.aliasResolveCache:(i=[],gl.visit(e,{Node:(s,o)=>{(Ne.isAlias(o)||Ne.hasAnchor(o))&&i.push(o)}}),n&&(n.aliasResolveCache=i));let r;for(let s of i){if(s===this)break;s.anchor===this.source&&(r=s)}return r}toJSON(e,n){if(!n)return{source:this.source};let{anchors:i,doc:r,maxAliasCount:s}=n,o=this.resolve(r,n);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let a=i.get(o);if(a||(yl.toJS(o,null,n),a=i.get(o)),a?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(s>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=Dt(r,o,i)),a.count*a.aliasCount>s)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return a.res}toString(e,n,i){let r=`*${this.source}`;if(e){if(hl.anchorIsValid(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let s=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(s)}if(e.implicitKey)return`${r} `}return r}};function Dt(t,e,n){if(Ne.isAlias(e)){let i=e.resolve(t),r=n&&i&&n.get(i);return r?r.count*r.aliasCount:0}else if(Ne.isCollection(e)){let i=0;for(let r of e.items){let s=Dt(t,r,n);s>i&&(i=s)}return i}else if(Ne.isPair(e)){let i=Dt(t,e.key,n),r=Dt(t,e.value,n);return Math.max(i,r)}return 1}Cs.Alias=ai});var x=g(ci=>{"use strict";var vl=E(),bl=Lt(),kl=te(),Sl=t=>!t||typeof t!="function"&&typeof t!="object",ne=class extends bl.NodeBase{constructor(e){super(vl.SCALAR),this.value=e}toJSON(e,n){return n?.keep?this.value:kl.toJS(this.value,e,n)}toString(){return String(this.value)}};ne.BLOCK_FOLDED="BLOCK_FOLDED";ne.BLOCK_LITERAL="BLOCK_LITERAL";ne.PLAIN="PLAIN";ne.QUOTE_DOUBLE="QUOTE_DOUBLE";ne.QUOTE_SINGLE="QUOTE_SINGLE";ci.Scalar=ne;ci.isScalarValue=Sl});var Ve=g(Es=>{"use strict";var Cl=Je(),ge=E(),_s=x(),_l="tag:yaml.org,2002:";function El(t,e,n){if(e){let i=n.filter(s=>s.tag===e),r=i.find(s=>!s.format)??i[0];if(!r)throw new Error(`Tag ${e} not found`);return r}return n.find(i=>i.identify?.(t)&&!i.format)}function Pl(t,e,n){if(ge.isDocument(t)&&(t=t.contents),ge.isNode(t))return t;if(ge.isPair(t)){let u=n.schema[ge.MAP].createNode?.(n.schema,null,n);return u.items.push(t),u}(t instanceof String||t instanceof Number||t instanceof Boolean||typeof BigInt<"u"&&t instanceof BigInt)&&(t=t.valueOf());let{aliasDuplicateObjects:i,onAnchor:r,onTagObj:s,schema:o,sourceObjects:a}=n,c;if(i&&t&&typeof t=="object"){if(c=a.get(t),c)return c.anchor??(c.anchor=r(t)),new Cl.Alias(c.anchor);c={anchor:null,node:null},a.set(t,c)}e?.startsWith("!!")&&(e=_l+e.slice(2));let l=El(t,e,o.tags);if(!l){if(t&&typeof t.toJSON=="function"&&(t=t.toJSON()),!t||typeof t!="object"){let u=new _s.Scalar(t);return c&&(c.node=u),u}l=t instanceof Map?o[ge.MAP]:Symbol.iterator in Object(t)?o[ge.SEQ]:o[ge.MAP]}s&&(s(l),delete n.onTagObj);let m=l?.createNode?l.createNode(n.schema,t,n):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(n.schema,t,n):new _s.Scalar(t);return e?m.tag=e:l.default||(m.tag=l.tag),c&&(c.node=m),m}Es.createNode=Pl});var Wt=g(Mt=>{"use strict";var Nl=Ve(),V=E(),xl=Lt();function li(t,e,n){let i=n;for(let r=e.length-1;r>=0;--r){let s=e[r];if(typeof s=="number"&&Number.isInteger(s)&&s>=0){let o=[];o[s]=i,i=o}else i=new Map([[s,i]])}return Nl.createNode(i,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:t,sourceObjects:new Map})}var Ps=t=>t==null||typeof t=="object"&&!!t[Symbol.iterator]().next().done,ui=class extends xl.NodeBase{constructor(e,n){super(e),Object.defineProperty(this,"schema",{value:n,configurable:!0,enumerable:!1,writable:!0})}clone(e){let n=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(n.schema=e),n.items=n.items.map(i=>V.isNode(i)||V.isPair(i)?i.clone(e):i),this.range&&(n.range=this.range.slice()),n}addIn(e,n){if(Ps(e))this.add(n);else{let[i,...r]=e,s=this.get(i,!0);if(V.isCollection(s))s.addIn(r,n);else if(s===void 0&&this.schema)this.set(i,li(this.schema,r,n));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${r}`)}}deleteIn(e){let[n,...i]=e;if(i.length===0)return this.delete(n);let r=this.get(n,!0);if(V.isCollection(r))return r.deleteIn(i);throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}getIn(e,n){let[i,...r]=e,s=this.get(i,!0);return r.length===0?!n&&V.isScalar(s)?s.value:s:V.isCollection(s)?s.getIn(r,n):void 0}hasAllNullValues(e){return this.items.every(n=>{if(!V.isPair(n))return!1;let i=n.value;return i==null||e&&V.isScalar(i)&&i.value==null&&!i.commentBefore&&!i.comment&&!i.tag})}hasIn(e){let[n,...i]=e;if(i.length===0)return this.has(n);let r=this.get(n,!0);return V.isCollection(r)?r.hasIn(i):!1}setIn(e,n){let[i,...r]=e;if(r.length===0)this.set(i,n);else{let s=this.get(i,!0);if(V.isCollection(s))s.setIn(r,n);else if(s===void 0&&this.schema)this.set(i,li(this.schema,r,n));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${r}`)}}};Mt.Collection=ui;Mt.collectionFromPath=li;Mt.isEmptyPath=Ps});var He=g($t=>{"use strict";var Ol=t=>t.replace(/^(?!$)(?: $)?/gm,"#");function fi(t,e){return/^\n+$/.test(t)?t.substring(1):e?t.replace(/^(?! *$)/gm,e):t}var Al=(t,e,n)=>t.endsWith(` `)?fi(n,e):n.includes(` `)?` -`+fi(n,e):(t.endsWith(" ")?"":" ")+n;$t.indentComment=fi;$t.lineComment=Ol;$t.stringifyComment=xl});var Os=g(Ge=>{"use strict";var Al="flow",di="block",Ft="quoted";function Rl(t,e,n="flow",{indentAtStart:i,lineWidth:r=80,minContentWidth:s=20,onFold:o,onOverflow:a}={}){if(!r||r<0)return t;rr-Math.max(2,s)?l.push(0):u=r-i);let f,h,w=!1,d=-1,p=-1,y=-1;n===di&&(d=xs(t,d,e.length),d!==-1&&(u=d+c));for(let k;k=t[d+=1];){if(n===Ft&&k==="\\"){switch(p=d,t[d+1]){case"x":d+=3;break;case"u":d+=5;break;case"U":d+=9;break;default:d+=1}y=d}if(k===` -`)n===di&&(d=xs(t,d,e.length)),u=d+e.length+c,f=void 0;else{if(k===" "&&h&&h!==" "&&h!==` +`+fi(n,e):(t.endsWith(" ")?"":" ")+n;$t.indentComment=fi;$t.lineComment=Al;$t.stringifyComment=Ol});var xs=g(Ge=>{"use strict";var Rl="flow",di="block",Ft="quoted";function Il(t,e,n="flow",{indentAtStart:i,lineWidth:r=80,minContentWidth:s=20,onFold:o,onOverflow:a}={}){if(!r||r<0)return t;rr-Math.max(2,s)?l.push(0):u=r-i);let f,h,w=!1,d=-1,p=-1,y=-1;n===di&&(d=Ns(t,d,e.length),d!==-1&&(u=d+c));for(let k;k=t[d+=1];){if(n===Ft&&k==="\\"){switch(p=d,t[d+1]){case"x":d+=3;break;case"u":d+=5;break;case"U":d+=9;break;default:d+=1}y=d}if(k===` +`)n===di&&(d=Ns(t,d,e.length)),u=d+e.length+c,f=void 0;else{if(k===" "&&h&&h!==" "&&h!==` `&&h!==" "){let S=t[d+1];S&&S!==" "&&S!==` `&&S!==" "&&(f=d)}if(d>=u)if(f)l.push(f),u=f+c,f=void 0;else if(n===Ft){for(;h===" "||h===" ";)h=k,k=t[d+=1],w=!0;let S=d>y+1?d-2:p-1;if(m[S])return t;l.push(S),m[S]=!0,u=S+c,f=void 0}else w=!0}h=k}if(w&&a&&a(),l.length===0)return t;o&&o();let b=t.slice(0,l[0]);for(let k=0;k{"use strict";var Y=x(),re=Os(),Kt=(t,e)=>({indentAtStart:e?t.indent.length:t.indentAtStart,lineWidth:t.options.lineWidth,minContentWidth:t.options.minContentWidth}),Yt=t=>/^(%|---|\.\.\.)/m.test(t);function Il(t,e,n){if(!e||e<0)return!1;let i=e-n,r=t.length;if(r<=i)return!1;for(let s=0,o=0;s{"use strict";var Y=x(),ie=xs(),Kt=(t,e)=>({indentAtStart:e?t.indent.length:t.indentAtStart,lineWidth:t.options.lineWidth,minContentWidth:t.options.minContentWidth}),Yt=t=>/^(%|---|\.\.\.)/m.test(t);function Tl(t,e,n){if(!e||e<0)return!1;let i=e-n,r=t.length;if(r<=i)return!1;for(let s=0,o=0;si)return!0;if(o=s+1,r-o<=i)return!1}return!0}function ze(t,e){let n=JSON.stringify(t);if(e.options.doubleQuotedAsJSON)return n;let{implicitKey:i}=e,r=e.options.doubleQuotedMinMultiLineLength,s=e.indent||(Yt(t)?" ":""),o="",a=0;for(let c=0,l=n[c];l;l=n[++c])if(l===" "&&n[c+1]==="\\"&&n[c+2]==="n"&&(o+=n.slice(a,c)+"\\ ",c+=1,a=c,l="\\"),l==="\\")switch(n[c+1]){case"u":{o+=n.slice(a,c);let m=n.substr(c+2,4);switch(m){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:m.substr(0,2)==="00"?o+="\\x"+m.substr(2):o+=n.substr(c,6)}c+=5,a=c+1}break;case"n":if(i||n[c+2]==='"'||n.length `;let u,f;for(f=n.length;f>0;--f){let C=n[f-1];if(C!==` `&&C!==" "&&C!==" ")break}let h=n.substring(f),w=h.indexOf(` `);w===-1?u="-":n===h||w!==h.length-1?(u="+",s&&s()):u="",h&&(n=n.slice(0,-h.length),h[h.length-1]===` `&&(h=h.slice(0,-1)),h=h.replace(pi,`$&${l}`));let d=!1,p,y=-1;for(p=0;p{_=!0});let v=re.foldFlowLines(`${b}${C}${h}`,l,re.FOLD_BLOCK,N);if(!_)return`>${S} +$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),_=!1,N=Kt(i,!0);o!=="folded"&&e!==Y.Scalar.BLOCK_FOLDED&&(N.onOverflow=()=>{_=!0});let v=ie.foldFlowLines(`${b}${C}${h}`,l,ie.FOLD_BLOCK,N);if(!_)return`>${S} ${l}${v}`}return n=n.replace(/\n+/g,`$&${l}`),`|${S} -${l}${b}${n}${h}`}function Tl(t,e,n,i){let{type:r,value:s}=t,{actualString:o,implicitKey:a,indent:c,indentStep:l,inFlow:m}=e;if(a&&s.includes(` -`)||m&&/[[\]{},]/.test(s))return Oe(s,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(s))return a||m||!s.includes(` -`)?Oe(s,e):Bt(t,e,n,i);if(!a&&!m&&r!==Y.Scalar.PLAIN&&s.includes(` -`))return Bt(t,e,n,i);if(Yt(s)){if(c==="")return e.forceBlockIndent=!0,Bt(t,e,n,i);if(a&&c===l)return Oe(s,e)}let u=s.replace(/\n+/g,`$& -${c}`);if(o){let f=d=>d.default&&d.tag!=="tag:yaml.org,2002:str"&&d.test?.test(u),{compat:h,tags:w}=e.doc.schema;if(w.some(f)||h?.some(f))return Oe(s,e)}return a?u:re.foldFlowLines(u,c,re.FOLD_FLOW,Kt(e,!1))}function jl(t,e,n,i){let{implicitKey:r,inFlow:s}=e,o=typeof t.value=="string"?t:Object.assign({},t,{value:String(t.value)}),{type:a}=t;a!==Y.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=Y.Scalar.QUOTE_DOUBLE);let c=m=>{switch(m){case Y.Scalar.BLOCK_FOLDED:case Y.Scalar.BLOCK_LITERAL:return r||s?Oe(o.value,e):Bt(o,e,n,i);case Y.Scalar.QUOTE_DOUBLE:return ze(o.value,e);case Y.Scalar.QUOTE_SINGLE:return mi(o.value,e);case Y.Scalar.PLAIN:return Tl(o,e,n,i);default:return null}},l=c(a);if(l===null){let{defaultKeyType:m,defaultStringType:u}=e.options,f=r&&m||u;if(l=c(f),l===null)throw new Error(`Unsupported default string type ${f}`)}return l}As.stringifyString=jl});var Xe=g(hi=>{"use strict";var ql=qt(),se=E(),Ll=He(),Dl=Qe();function Ml(t,e){let n=Object.assign({blockQuote:!0,commentString:Ll.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},t.schema.toStringOptions,e),i;switch(n.collectionStyle){case"block":i=!1;break;case"flow":i=!0;break;default:i=null}return{anchors:new Set,doc:t,flowCollectionPadding:n.flowCollectionPadding?" ":"",indent:"",indentStep:typeof n.indent=="number"?" ".repeat(n.indent):" ",inFlow:i,options:n}}function Wl(t,e){if(e.tag){let r=t.filter(s=>s.tag===e.tag);if(r.length>0)return r.find(s=>s.format===e.format)??r[0]}let n,i;if(se.isScalar(e)){i=e.value;let r=t.filter(s=>s.identify?.(i));if(r.length>1){let s=r.filter(o=>o.test);s.length>0&&(r=s)}n=r.find(s=>s.format===e.format)??r.find(s=>!s.format)}else i=e,n=t.find(r=>r.nodeClass&&i instanceof r.nodeClass);if(!n){let r=i?.constructor?.name??(i===null?"null":typeof i);throw new Error(`Tag not resolved for ${r} value`)}return n}function $l(t,e,{anchors:n,doc:i}){if(!i.directives)return"";let r=[],s=(se.isScalar(t)||se.isCollection(t))&&t.anchor;s&&ql.anchorIsValid(s)&&(n.add(s),r.push(`&${s}`));let o=t.tag??(e.default?null:e.tag);return o&&r.push(i.directives.tagString(o)),r.join(" ")}function Fl(t,e,n,i){if(se.isPair(t))return t.toString(e,n,i);if(se.isAlias(t)){if(e.doc.directives)return t.toString(e);if(e.resolvedAliases?.has(t))throw new TypeError("Cannot stringify circular structure without alias nodes");e.resolvedAliases?e.resolvedAliases.add(t):e.resolvedAliases=new Set([t]),t=t.resolve(e.doc)}let r,s=se.isNode(t)?t:e.doc.createNode(t,{onTagObj:c=>r=c});r??(r=Wl(e.doc.schema.tags,s));let o=$l(s,r,e);o.length>0&&(e.indentAtStart=(e.indentAtStart??0)+o.length+1);let a=typeof r.stringify=="function"?r.stringify(s,e,n,i):se.isScalar(s)?Dl.stringifyString(s,e,n,i):s.toString(e,n,i);return o?se.isScalar(s)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o} -${e.indent}${a}`:a}hi.createStringifyContext=Ml;hi.stringify=Fl});var js=g(Ts=>{"use strict";var G=E(),Rs=x(),Is=Xe(),Ze=He();function Bl({key:t,value:e},n,i,r){let{allNullValues:s,doc:o,indent:a,indentStep:c,options:{commentString:l,indentSeq:m,simpleKeys:u}}=n,f=G.isNode(t)&&t.comment||null;if(u){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(G.isCollection(t)||!G.isNode(t)&&typeof t=="object"){let N="With simple keys, collection cannot be used as a key value";throw new Error(N)}}let h=!u&&(!t||f&&e==null&&!n.inFlow||G.isCollection(t)||(G.isScalar(t)?t.type===Rs.Scalar.BLOCK_FOLDED||t.type===Rs.Scalar.BLOCK_LITERAL:typeof t=="object"));n=Object.assign({},n,{allNullValues:!1,implicitKey:!h&&(u||!s),indent:a+c});let w=!1,d=!1,p=Is.stringify(t,n,()=>w=!0,()=>d=!0);if(!h&&!n.inFlow&&p.length>1024){if(u)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");h=!0}if(n.inFlow){if(s||e==null)return w&&i&&i(),p===""?"?":h?`? ${p}`:p}else if(s&&!u||e==null&&h)return p=`? ${p}`,f&&!w?p+=Ze.lineComment(p,n.indent,l(f)):d&&r&&r(),p;w&&(f=null),h?(f&&(p+=Ze.lineComment(p,n.indent,l(f))),p=`? ${p} -${a}:`):(p=`${p}:`,f&&(p+=Ze.lineComment(p,n.indent,l(f))));let y,b,k;G.isNode(e)?(y=!!e.spaceBefore,b=e.commentBefore,k=e.comment):(y=!1,b=null,k=null,e&&typeof e=="object"&&(e=o.createNode(e))),n.implicitKey=!1,!h&&!f&&G.isScalar(e)&&(n.indentAtStart=p.length+1),d=!1,!m&&c.length>=2&&!n.inFlow&&!h&&G.isSeq(e)&&!e.flow&&!e.tag&&!e.anchor&&(n.indent=n.indent.substring(2));let S=!1,C=Is.stringify(e,n,()=>S=!0,()=>d=!0),_=" ";if(f||y||b){if(_=y?` +${l}${b}${n}${h}`}function jl(t,e,n,i){let{type:r,value:s}=t,{actualString:o,implicitKey:a,indent:c,indentStep:l,inFlow:m}=e;if(a&&s.includes(` +`)||m&&/[[\]{},]/.test(s))return xe(s,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(s))return a||m||!s.includes(` +`)?xe(s,e):Bt(t,e,n,i);if(!a&&!m&&r!==Y.Scalar.PLAIN&&s.includes(` +`))return Bt(t,e,n,i);if(Yt(s)){if(c==="")return e.forceBlockIndent=!0,Bt(t,e,n,i);if(a&&c===l)return xe(s,e)}let u=s.replace(/\n+/g,`$& +${c}`);if(o){let f=d=>d.default&&d.tag!=="tag:yaml.org,2002:str"&&d.test?.test(u),{compat:h,tags:w}=e.doc.schema;if(w.some(f)||h?.some(f))return xe(s,e)}return a?u:ie.foldFlowLines(u,c,ie.FOLD_FLOW,Kt(e,!1))}function ql(t,e,n,i){let{implicitKey:r,inFlow:s}=e,o=typeof t.value=="string"?t:Object.assign({},t,{value:String(t.value)}),{type:a}=t;a!==Y.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=Y.Scalar.QUOTE_DOUBLE);let c=m=>{switch(m){case Y.Scalar.BLOCK_FOLDED:case Y.Scalar.BLOCK_LITERAL:return r||s?xe(o.value,e):Bt(o,e,n,i);case Y.Scalar.QUOTE_DOUBLE:return ze(o.value,e);case Y.Scalar.QUOTE_SINGLE:return mi(o.value,e);case Y.Scalar.PLAIN:return jl(o,e,n,i);default:return null}},l=c(a);if(l===null){let{defaultKeyType:m,defaultStringType:u}=e.options,f=r&&m||u;if(l=c(f),l===null)throw new Error(`Unsupported default string type ${f}`)}return l}Os.stringifyString=ql});var Xe=g(hi=>{"use strict";var Ll=qt(),re=E(),Dl=He(),Ml=Qe();function Wl(t,e){let n=Object.assign({blockQuote:!0,commentString:Dl.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},t.schema.toStringOptions,e),i;switch(n.collectionStyle){case"block":i=!1;break;case"flow":i=!0;break;default:i=null}return{anchors:new Set,doc:t,flowCollectionPadding:n.flowCollectionPadding?" ":"",indent:"",indentStep:typeof n.indent=="number"?" ".repeat(n.indent):" ",inFlow:i,options:n}}function $l(t,e){if(e.tag){let r=t.filter(s=>s.tag===e.tag);if(r.length>0)return r.find(s=>s.format===e.format)??r[0]}let n,i;if(re.isScalar(e)){i=e.value;let r=t.filter(s=>s.identify?.(i));if(r.length>1){let s=r.filter(o=>o.test);s.length>0&&(r=s)}n=r.find(s=>s.format===e.format)??r.find(s=>!s.format)}else i=e,n=t.find(r=>r.nodeClass&&i instanceof r.nodeClass);if(!n){let r=i?.constructor?.name??(i===null?"null":typeof i);throw new Error(`Tag not resolved for ${r} value`)}return n}function Fl(t,e,{anchors:n,doc:i}){if(!i.directives)return"";let r=[],s=(re.isScalar(t)||re.isCollection(t))&&t.anchor;s&&Ll.anchorIsValid(s)&&(n.add(s),r.push(`&${s}`));let o=t.tag??(e.default?null:e.tag);return o&&r.push(i.directives.tagString(o)),r.join(" ")}function Bl(t,e,n,i){if(re.isPair(t))return t.toString(e,n,i);if(re.isAlias(t)){if(e.doc.directives)return t.toString(e);if(e.resolvedAliases?.has(t))throw new TypeError("Cannot stringify circular structure without alias nodes");e.resolvedAliases?e.resolvedAliases.add(t):e.resolvedAliases=new Set([t]),t=t.resolve(e.doc)}let r,s=re.isNode(t)?t:e.doc.createNode(t,{onTagObj:c=>r=c});r??(r=$l(e.doc.schema.tags,s));let o=Fl(s,r,e);o.length>0&&(e.indentAtStart=(e.indentAtStart??0)+o.length+1);let a=typeof r.stringify=="function"?r.stringify(s,e,n,i):re.isScalar(s)?Ml.stringifyString(s,e,n,i):s.toString(e,n,i);return o?re.isScalar(s)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o} +${e.indent}${a}`:a}hi.createStringifyContext=Wl;hi.stringify=Bl});var Ts=g(Is=>{"use strict";var G=E(),As=x(),Rs=Xe(),Ze=He();function Kl({key:t,value:e},n,i,r){let{allNullValues:s,doc:o,indent:a,indentStep:c,options:{commentString:l,indentSeq:m,simpleKeys:u}}=n,f=G.isNode(t)&&t.comment||null;if(u){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(G.isCollection(t)||!G.isNode(t)&&typeof t=="object"){let N="With simple keys, collection cannot be used as a key value";throw new Error(N)}}let h=!u&&(!t||f&&e==null&&!n.inFlow||G.isCollection(t)||(G.isScalar(t)?t.type===As.Scalar.BLOCK_FOLDED||t.type===As.Scalar.BLOCK_LITERAL:typeof t=="object"));n=Object.assign({},n,{allNullValues:!1,implicitKey:!h&&(u||!s),indent:a+c});let w=!1,d=!1,p=Rs.stringify(t,n,()=>w=!0,()=>d=!0);if(!h&&!n.inFlow&&p.length>1024){if(u)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");h=!0}if(n.inFlow){if(s||e==null)return w&&i&&i(),p===""?"?":h?`? ${p}`:p}else if(s&&!u||e==null&&h)return p=`? ${p}`,f&&!w?p+=Ze.lineComment(p,n.indent,l(f)):d&&r&&r(),p;w&&(f=null),h?(f&&(p+=Ze.lineComment(p,n.indent,l(f))),p=`? ${p} +${a}:`):(p=`${p}:`,f&&(p+=Ze.lineComment(p,n.indent,l(f))));let y,b,k;G.isNode(e)?(y=!!e.spaceBefore,b=e.commentBefore,k=e.comment):(y=!1,b=null,k=null,e&&typeof e=="object"&&(e=o.createNode(e))),n.implicitKey=!1,!h&&!f&&G.isScalar(e)&&(n.indentAtStart=p.length+1),d=!1,!m&&c.length>=2&&!n.inFlow&&!h&&G.isSeq(e)&&!e.flow&&!e.tag&&!e.anchor&&(n.indent=n.indent.substring(2));let S=!1,C=Rs.stringify(e,n,()=>S=!0,()=>d=!0),_=" ";if(f||y||b){if(_=y?` `:"",b){let N=l(b);_+=` ${Ze.indentComment(N,n.indent)}`}C===""&&!n.inFlow?_===` `&&k&&(_=` `):_+=` ${n.indent}`}else if(!h&&G.isCollection(e)){let N=C[0],v=C.indexOf(` -`),R=v!==-1,te=n.inFlow??e.flow??e.items.length===0;if(R||!te){let Ee=!1;if(R&&(N==="&"||N==="!")){let I=C.indexOf(" ");N==="&"&&I!==-1&&I{"use strict";var qs=At("process");function Kl(t,...e){t==="debug"&&console.log(...e)}function Yl(t,e){(t==="debug"||t==="warn")&&(typeof qs.emitWarning=="function"?qs.emitWarning(e):console.warn(e))}gi.debug=Kl;gi.warn=Yl});var Gt=g(Ht=>{"use strict";var Vt=E(),Ls=x(),Ut="<<",Jt={identify:t=>t===Ut||typeof t=="symbol"&&t.description===Ut,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new Ls.Scalar(Symbol(Ut)),{addToJSMap:Ds}),stringify:()=>Ut},Ul=(t,e)=>(Jt.identify(e)||Vt.isScalar(e)&&(!e.type||e.type===Ls.Scalar.PLAIN)&&Jt.identify(e.value))&&t?.doc.schema.tags.some(n=>n.tag===Jt.tag&&n.default);function Ds(t,e,n){let i=Ms(t,n);if(Vt.isSeq(i))for(let r of i.items)yi(t,e,r);else if(Array.isArray(i))for(let r of i)yi(t,e,r);else yi(t,e,i)}function yi(t,e,n){let i=Ms(t,n);if(!Vt.isMap(i))throw new Error("Merge sources must be maps or map aliases");let r=i.toJSON(null,t,Map);for(let[s,o]of r)e instanceof Map?e.has(s)||e.set(s,o):e instanceof Set?e.add(s):Object.prototype.hasOwnProperty.call(e,s)||Object.defineProperty(e,s,{value:o,writable:!0,enumerable:!0,configurable:!0});return e}function Ms(t,e){return t&&Vt.isAlias(e)?e.resolve(t.doc,t):e}Ht.addMergeToJSMap=Ds;Ht.isMergeKey=Ul;Ht.merge=Jt});var bi=g(Fs=>{"use strict";var Jl=wi(),Ws=Gt(),Vl=Xe(),$s=E(),vi=ne();function Hl(t,e,{key:n,value:i}){if($s.isNode(n)&&n.addToJSMap)n.addToJSMap(t,e,i);else if(Ws.isMergeKey(t,n))Ws.addMergeToJSMap(t,e,i);else{let r=vi.toJS(n,"",t);if(e instanceof Map)e.set(r,vi.toJS(i,r,t));else if(e instanceof Set)e.add(r);else{let s=Gl(n,r,t),o=vi.toJS(i,s,t);s in e?Object.defineProperty(e,s,{value:o,writable:!0,enumerable:!0,configurable:!0}):e[s]=o}}return e}function Gl(t,e,n){if(e===null)return"";if(typeof e!="object")return String(e);if($s.isNode(t)&&n?.doc){let i=Vl.createStringifyContext(n.doc,{});i.anchors=new Set;for(let s of n.anchors.keys())i.anchors.add(s.anchor);i.inFlow=!0,i.inStringifyKey=!0;let r=t.toString(i);if(!n.mapKeyWarned){let s=JSON.stringify(r);s.length>40&&(s=s.substring(0,36)+'..."'),Jl.warn(n.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${s}. Set mapAsMap: true to use object keys.`),n.mapKeyWarned=!0}return r}return JSON.stringify(e)}Fs.addPairToJSMap=Hl});var oe=g(ki=>{"use strict";var Bs=Ve(),zl=js(),Ql=bi(),zt=E();function Xl(t,e,n){let i=Bs.createNode(t,void 0,n),r=Bs.createNode(e,void 0,n);return new Qt(i,r)}var Qt=class t{constructor(e,n=null){Object.defineProperty(this,zt.NODE_TYPE,{value:zt.PAIR}),this.key=e,this.value=n}clone(e){let{key:n,value:i}=this;return zt.isNode(n)&&(n=n.clone(e)),zt.isNode(i)&&(i=i.clone(e)),new t(n,i)}toJSON(e,n){let i=n?.mapAsMap?new Map:{};return Ql.addPairToJSMap(n,i,this)}toString(e,n,i){return e?.doc?zl.stringifyPair(this,e,n,i):JSON.stringify(this)}};ki.Pair=Qt;ki.createPair=Xl});var Si=g(Ys=>{"use strict";var ye=E(),Ks=Xe(),Xt=He();function Zl(t,e,n){return(e.inFlow??t.flow?tu:eu)(t,e,n)}function eu({comment:t,items:e},n,{blockItemPrefix:i,flowChars:r,itemIndent:s,onChompKeep:o,onComment:a}){let{indent:c,options:{commentString:l}}=n,m=Object.assign({},n,{indent:s,type:null}),u=!1,f=[];for(let w=0;wp=null,()=>u=!0);p&&(y+=Xt.lineComment(y,s,l(p))),u&&p&&(u=!1),f.push(i+y)}let h;if(f.length===0)h=r.start+r.end;else{h=f[0];for(let w=1;w{"use strict";var js=At("process");function Yl(t,...e){t==="debug"&&console.log(...e)}function Ul(t,e){(t==="debug"||t==="warn")&&(typeof js.emitWarning=="function"?js.emitWarning(e):console.warn(e))}gi.debug=Yl;gi.warn=Ul});var Gt=g(Ht=>{"use strict";var Vt=E(),qs=x(),Ut="<<",Jt={identify:t=>t===Ut||typeof t=="symbol"&&t.description===Ut,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new qs.Scalar(Symbol(Ut)),{addToJSMap:Ls}),stringify:()=>Ut},Jl=(t,e)=>(Jt.identify(e)||Vt.isScalar(e)&&(!e.type||e.type===qs.Scalar.PLAIN)&&Jt.identify(e.value))&&t?.doc.schema.tags.some(n=>n.tag===Jt.tag&&n.default);function Ls(t,e,n){let i=Ds(t,n);if(Vt.isSeq(i))for(let r of i.items)yi(t,e,r);else if(Array.isArray(i))for(let r of i)yi(t,e,r);else yi(t,e,i)}function yi(t,e,n){let i=Ds(t,n);if(!Vt.isMap(i))throw new Error("Merge sources must be maps or map aliases");let r=i.toJSON(null,t,Map);for(let[s,o]of r)e instanceof Map?e.has(s)||e.set(s,o):e instanceof Set?e.add(s):Object.prototype.hasOwnProperty.call(e,s)||Object.defineProperty(e,s,{value:o,writable:!0,enumerable:!0,configurable:!0});return e}function Ds(t,e){return t&&Vt.isAlias(e)?e.resolve(t.doc,t):e}Ht.addMergeToJSMap=Ls;Ht.isMergeKey=Jl;Ht.merge=Jt});var bi=g($s=>{"use strict";var Vl=wi(),Ms=Gt(),Hl=Xe(),Ws=E(),vi=te();function Gl(t,e,{key:n,value:i}){if(Ws.isNode(n)&&n.addToJSMap)n.addToJSMap(t,e,i);else if(Ms.isMergeKey(t,n))Ms.addMergeToJSMap(t,e,i);else{let r=vi.toJS(n,"",t);if(e instanceof Map)e.set(r,vi.toJS(i,r,t));else if(e instanceof Set)e.add(r);else{let s=zl(n,r,t),o=vi.toJS(i,s,t);s in e?Object.defineProperty(e,s,{value:o,writable:!0,enumerable:!0,configurable:!0}):e[s]=o}}return e}function zl(t,e,n){if(e===null)return"";if(typeof e!="object")return String(e);if(Ws.isNode(t)&&n?.doc){let i=Hl.createStringifyContext(n.doc,{});i.anchors=new Set;for(let s of n.anchors.keys())i.anchors.add(s.anchor);i.inFlow=!0,i.inStringifyKey=!0;let r=t.toString(i);if(!n.mapKeyWarned){let s=JSON.stringify(r);s.length>40&&(s=s.substring(0,36)+'..."'),Vl.warn(n.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${s}. Set mapAsMap: true to use object keys.`),n.mapKeyWarned=!0}return r}return JSON.stringify(e)}$s.addPairToJSMap=Gl});var se=g(ki=>{"use strict";var Fs=Ve(),Ql=Ts(),Xl=bi(),zt=E();function Zl(t,e,n){let i=Fs.createNode(t,void 0,n),r=Fs.createNode(e,void 0,n);return new Qt(i,r)}var Qt=class t{constructor(e,n=null){Object.defineProperty(this,zt.NODE_TYPE,{value:zt.PAIR}),this.key=e,this.value=n}clone(e){let{key:n,value:i}=this;return zt.isNode(n)&&(n=n.clone(e)),zt.isNode(i)&&(i=i.clone(e)),new t(n,i)}toJSON(e,n){let i=n?.mapAsMap?new Map:{};return Xl.addPairToJSMap(n,i,this)}toString(e,n,i){return e?.doc?Ql.stringifyPair(this,e,n,i):JSON.stringify(this)}};ki.Pair=Qt;ki.createPair=Zl});var Si=g(Ks=>{"use strict";var we=E(),Bs=Xe(),Xt=He();function eu(t,e,n){return(e.inFlow??t.flow?nu:tu)(t,e,n)}function tu({comment:t,items:e},n,{blockItemPrefix:i,flowChars:r,itemIndent:s,onChompKeep:o,onComment:a}){let{indent:c,options:{commentString:l}}=n,m=Object.assign({},n,{indent:s,type:null}),u=!1,f=[];for(let w=0;wp=null,()=>u=!0);p&&(y+=Xt.lineComment(y,s,l(p))),u&&p&&(u=!1),f.push(i+y)}let h;if(f.length===0)h=r.start+r.end;else{h=f[0];for(let w=1;wp=null);l||(l=u.length>m||y.includes(` +`+Xt.indentComment(l(t),c),a&&a()):u&&o&&o(),h}function nu({items:t},e,{flowChars:n,itemIndent:i}){let{indent:r,indentStep:s,flowCollectionPadding:o,options:{commentString:a}}=e;i+=s;let c=Object.assign({},e,{indent:i,inFlow:!0,type:null}),l=!1,m=0,u=[];for(let w=0;wp=null);l||(l=u.length>m||y.includes(` `)),w0&&(l||(l=u.reduce((b,k)=>b+k.length+2,2)+(y.length+2)>e.options.lineWidth)),l&&(y+=",")),p&&(y+=Xt.lineComment(y,i,a(p))),u.push(y),m=u.length}let{start:f,end:h}=n;if(u.length===0)return f+h;if(!l){let w=u.reduce((d,p)=>d+p.length+2,2);l=e.options.lineWidth>0&&w>e.options.lineWidth}if(l){let w=f;for(let d of u)w+=d?` ${s}${r}${d}`:` `;return`${w} -${r}${h}`}else return`${f}${o}${u.join(" ")}${o}${h}`}function Zt({indent:t,options:{commentString:e}},n,i,r){if(i&&r&&(i=i.replace(/^\n+/,"")),i){let s=Xt.indentComment(e(i),t);n.push(s.trimStart())}}Ys.stringifyCollection=Zl});var ce=g(_i=>{"use strict";var nu=Si(),iu=bi(),ru=Wt(),ae=E(),en=oe(),su=x();function et(t,e){let n=ae.isScalar(e)?e.value:e;for(let i of t)if(ae.isPair(i)&&(i.key===e||i.key===n||ae.isScalar(i.key)&&i.key.value===n))return i}var Ci=class extends ru.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(ae.MAP,e),this.items=[]}static from(e,n,i){let{keepUndefined:r,replacer:s}=i,o=new this(e),a=(c,l)=>{if(typeof s=="function")l=s.call(n,c,l);else if(Array.isArray(s)&&!s.includes(c))return;(l!==void 0||r)&&o.items.push(en.createPair(c,l,i))};if(n instanceof Map)for(let[c,l]of n)a(c,l);else if(n&&typeof n=="object")for(let c of Object.keys(n))a(c,n[c]);return typeof e.sortMapEntries=="function"&&o.items.sort(e.sortMapEntries),o}add(e,n){let i;ae.isPair(e)?i=e:!e||typeof e!="object"||!("key"in e)?i=new en.Pair(e,e?.value):i=new en.Pair(e.key,e.value);let r=et(this.items,i.key),s=this.schema?.sortMapEntries;if(r){if(!n)throw new Error(`Key ${i.key} already set`);ae.isScalar(r.value)&&su.isScalarValue(i.value)?r.value.value=i.value:r.value=i.value}else if(s){let o=this.items.findIndex(a=>s(i,a)<0);o===-1?this.items.push(i):this.items.splice(o,0,i)}else this.items.push(i)}delete(e){let n=et(this.items,e);return n?this.items.splice(this.items.indexOf(n),1).length>0:!1}get(e,n){let r=et(this.items,e)?.value;return(!n&&ae.isScalar(r)?r.value:r)??void 0}has(e){return!!et(this.items,e)}set(e,n){this.add(new en.Pair(e,n),!0)}toJSON(e,n,i){let r=i?new i:n?.mapAsMap?new Map:{};n?.onCreate&&n.onCreate(r);for(let s of this.items)iu.addPairToJSMap(n,r,s);return r}toString(e,n,i){if(!e)return JSON.stringify(this);for(let r of this.items)if(!ae.isPair(r))throw new Error(`Map items must all be pairs; found ${JSON.stringify(r)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),nu.stringifyCollection(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:i,onComment:n})}};_i.YAMLMap=Ci;_i.findPair=et});var Ae=g(Js=>{"use strict";var ou=E(),Us=ce(),au={collection:"map",default:!0,nodeClass:Us.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(t,e){return ou.isMap(t)||e("Expected a mapping for this tag"),t},createNode:(t,e,n)=>Us.YAMLMap.from(t,e,n)};Js.map=au});var le=g(Vs=>{"use strict";var cu=Ve(),lu=Si(),uu=Wt(),nn=E(),fu=x(),du=ne(),Ei=class extends uu.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(nn.SEQ,e),this.items=[]}add(e){this.items.push(e)}delete(e){let n=tn(e);return typeof n!="number"?!1:this.items.splice(n,1).length>0}get(e,n){let i=tn(e);if(typeof i!="number")return;let r=this.items[i];return!n&&nn.isScalar(r)?r.value:r}has(e){let n=tn(e);return typeof n=="number"&&n=0?e:null}Vs.YAMLSeq=Ei});var Re=g(Gs=>{"use strict";var mu=E(),Hs=le(),pu={collection:"seq",default:!0,nodeClass:Hs.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(t,e){return mu.isSeq(t)||e("Expected a sequence for this tag"),t},createNode:(t,e,n)=>Hs.YAMLSeq.from(t,e,n)};Gs.seq=pu});var tt=g(zs=>{"use strict";var hu=Qe(),gu={identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify(t,e,n,i){return e=Object.assign({actualString:!0},e),hu.stringifyString(t,e,n,i)}};zs.string=gu});var rn=g(Zs=>{"use strict";var Qs=x(),Xs={identify:t=>t==null,createNode:()=>new Qs.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Qs.Scalar(null),stringify:({source:t},e)=>typeof t=="string"&&Xs.test.test(t)?t:e.options.nullStr};Zs.nullTag=Xs});var Pi=g(to=>{"use strict";var wu=x(),eo={identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:t=>new wu.Scalar(t[0]==="t"||t[0]==="T"),stringify({source:t,value:e},n){if(t&&eo.test.test(t)){let i=t[0]==="t"||t[0]==="T";if(e===i)return t}return e?n.options.trueStr:n.options.falseStr}};to.boolTag=eo});var Ie=g(no=>{"use strict";function yu({format:t,minFractionDigits:e,tag:n,value:i}){if(typeof i=="bigint")return String(i);let r=typeof i=="number"?i:Number(i);if(!isFinite(r))return isNaN(r)?".nan":r<0?"-.inf":".inf";let s=Object.is(i,-0)?"-0":JSON.stringify(i);if(!t&&e&&(!n||n==="tag:yaml.org,2002:float")&&/^-?\d/.test(s)&&!s.includes("e")){let o=s.indexOf(".");o<0&&(o=s.length,s+=".");let a=e-(s.length-o-1);for(;a-- >0;)s+="0"}return s}no.stringifyNumber=yu});var xi=g(sn=>{"use strict";var vu=x(),Ni=Ie(),bu={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:t=>t.slice(-3).toLowerCase()==="nan"?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Ni.stringifyNumber},ku={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t),stringify(t){let e=Number(t.value);return isFinite(e)?e.toExponential():Ni.stringifyNumber(t)}},Su={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(t){let e=new vu.Scalar(parseFloat(t)),n=t.indexOf(".");return n!==-1&&t[t.length-1]==="0"&&(e.minFractionDigits=t.length-n-1),e},stringify:Ni.stringifyNumber};sn.float=Su;sn.floatExp=ku;sn.floatNaN=bu});var Ai=g(an=>{"use strict";var io=Ie(),on=t=>typeof t=="bigint"||Number.isInteger(t),Oi=(t,e,n,{intAsBigInt:i})=>i?BigInt(t):parseInt(t.substring(e),n);function ro(t,e,n){let{value:i}=t;return on(i)&&i>=0?n+i.toString(e):io.stringifyNumber(t)}var Cu={identify:t=>on(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(t,e,n)=>Oi(t,2,8,n),stringify:t=>ro(t,8,"0o")},_u={identify:on,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(t,e,n)=>Oi(t,0,10,n),stringify:io.stringifyNumber},Eu={identify:t=>on(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(t,e,n)=>Oi(t,2,16,n),stringify:t=>ro(t,16,"0x")};an.int=_u;an.intHex=Eu;an.intOct=Cu});var oo=g(so=>{"use strict";var Pu=Ae(),Nu=rn(),xu=Re(),Ou=tt(),Au=Pi(),Ri=xi(),Ii=Ai(),Ru=[Pu.map,xu.seq,Ou.string,Nu.nullTag,Au.boolTag,Ii.intOct,Ii.int,Ii.intHex,Ri.floatNaN,Ri.floatExp,Ri.float];so.schema=Ru});var lo=g(co=>{"use strict";var Iu=x(),Tu=Ae(),ju=Re();function ao(t){return typeof t=="bigint"||Number.isInteger(t)}var cn=({value:t})=>JSON.stringify(t),qu=[{identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify:cn},{identify:t=>t==null,createNode:()=>new Iu.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:cn},{identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:t=>t==="true",stringify:cn},{identify:ao,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(t,e,{intAsBigInt:n})=>n?BigInt(t):parseInt(t,10),stringify:({value:t})=>ao(t)?t.toString():JSON.stringify(t)},{identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:t=>parseFloat(t),stringify:cn}],Lu={default:!0,tag:"",test:/^/,resolve(t,e){return e(`Unresolved plain scalar ${JSON.stringify(t)}`),t}},Du=[Tu.map,ju.seq].concat(qu,Lu);co.schema=Du});var ji=g(uo=>{"use strict";var nt=At("buffer"),Ti=x(),Mu=Qe(),Wu={identify:t=>t instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(t,e){if(typeof nt.Buffer=="function")return nt.Buffer.from(t,"base64");if(typeof atob=="function"){let n=atob(t.replace(/[\n\r]/g,"")),i=new Uint8Array(n.length);for(let r=0;r{"use strict";var ln=E(),qi=oe(),$u=x(),Fu=le();function fo(t,e){if(ln.isSeq(t))for(let n=0;n1&&e("Each pair must have its own sequence indicator");let r=i.items[0]||new qi.Pair(new $u.Scalar(null));if(i.commentBefore&&(r.key.commentBefore=r.key.commentBefore?`${i.commentBefore} +${r}${h}`}else return`${f}${o}${u.join(" ")}${o}${h}`}function Zt({indent:t,options:{commentString:e}},n,i,r){if(i&&r&&(i=i.replace(/^\n+/,"")),i){let s=Xt.indentComment(e(i),t);n.push(s.trimStart())}}Ks.stringifyCollection=eu});var ae=g(_i=>{"use strict";var iu=Si(),ru=bi(),su=Wt(),oe=E(),en=se(),ou=x();function et(t,e){let n=oe.isScalar(e)?e.value:e;for(let i of t)if(oe.isPair(i)&&(i.key===e||i.key===n||oe.isScalar(i.key)&&i.key.value===n))return i}var Ci=class extends su.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(oe.MAP,e),this.items=[]}static from(e,n,i){let{keepUndefined:r,replacer:s}=i,o=new this(e),a=(c,l)=>{if(typeof s=="function")l=s.call(n,c,l);else if(Array.isArray(s)&&!s.includes(c))return;(l!==void 0||r)&&o.items.push(en.createPair(c,l,i))};if(n instanceof Map)for(let[c,l]of n)a(c,l);else if(n&&typeof n=="object")for(let c of Object.keys(n))a(c,n[c]);return typeof e.sortMapEntries=="function"&&o.items.sort(e.sortMapEntries),o}add(e,n){let i;oe.isPair(e)?i=e:!e||typeof e!="object"||!("key"in e)?i=new en.Pair(e,e?.value):i=new en.Pair(e.key,e.value);let r=et(this.items,i.key),s=this.schema?.sortMapEntries;if(r){if(!n)throw new Error(`Key ${i.key} already set`);oe.isScalar(r.value)&&ou.isScalarValue(i.value)?r.value.value=i.value:r.value=i.value}else if(s){let o=this.items.findIndex(a=>s(i,a)<0);o===-1?this.items.push(i):this.items.splice(o,0,i)}else this.items.push(i)}delete(e){let n=et(this.items,e);return n?this.items.splice(this.items.indexOf(n),1).length>0:!1}get(e,n){let r=et(this.items,e)?.value;return(!n&&oe.isScalar(r)?r.value:r)??void 0}has(e){return!!et(this.items,e)}set(e,n){this.add(new en.Pair(e,n),!0)}toJSON(e,n,i){let r=i?new i:n?.mapAsMap?new Map:{};n?.onCreate&&n.onCreate(r);for(let s of this.items)ru.addPairToJSMap(n,r,s);return r}toString(e,n,i){if(!e)return JSON.stringify(this);for(let r of this.items)if(!oe.isPair(r))throw new Error(`Map items must all be pairs; found ${JSON.stringify(r)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),iu.stringifyCollection(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:i,onComment:n})}};_i.YAMLMap=Ci;_i.findPair=et});var Oe=g(Us=>{"use strict";var au=E(),Ys=ae(),cu={collection:"map",default:!0,nodeClass:Ys.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(t,e){return au.isMap(t)||e("Expected a mapping for this tag"),t},createNode:(t,e,n)=>Ys.YAMLMap.from(t,e,n)};Us.map=cu});var ce=g(Js=>{"use strict";var lu=Ve(),uu=Si(),fu=Wt(),nn=E(),du=x(),mu=te(),Ei=class extends fu.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(nn.SEQ,e),this.items=[]}add(e){this.items.push(e)}delete(e){let n=tn(e);return typeof n!="number"?!1:this.items.splice(n,1).length>0}get(e,n){let i=tn(e);if(typeof i!="number")return;let r=this.items[i];return!n&&nn.isScalar(r)?r.value:r}has(e){let n=tn(e);return typeof n=="number"&&n=0?e:null}Js.YAMLSeq=Ei});var Ae=g(Hs=>{"use strict";var pu=E(),Vs=ce(),hu={collection:"seq",default:!0,nodeClass:Vs.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(t,e){return pu.isSeq(t)||e("Expected a sequence for this tag"),t},createNode:(t,e,n)=>Vs.YAMLSeq.from(t,e,n)};Hs.seq=hu});var tt=g(Gs=>{"use strict";var gu=Qe(),wu={identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify(t,e,n,i){return e=Object.assign({actualString:!0},e),gu.stringifyString(t,e,n,i)}};Gs.string=wu});var rn=g(Xs=>{"use strict";var zs=x(),Qs={identify:t=>t==null,createNode:()=>new zs.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new zs.Scalar(null),stringify:({source:t},e)=>typeof t=="string"&&Qs.test.test(t)?t:e.options.nullStr};Xs.nullTag=Qs});var Pi=g(eo=>{"use strict";var yu=x(),Zs={identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:t=>new yu.Scalar(t[0]==="t"||t[0]==="T"),stringify({source:t,value:e},n){if(t&&Zs.test.test(t)){let i=t[0]==="t"||t[0]==="T";if(e===i)return t}return e?n.options.trueStr:n.options.falseStr}};eo.boolTag=Zs});var Re=g(to=>{"use strict";function vu({format:t,minFractionDigits:e,tag:n,value:i}){if(typeof i=="bigint")return String(i);let r=typeof i=="number"?i:Number(i);if(!isFinite(r))return isNaN(r)?".nan":r<0?"-.inf":".inf";let s=Object.is(i,-0)?"-0":JSON.stringify(i);if(!t&&e&&(!n||n==="tag:yaml.org,2002:float")&&/^-?\d/.test(s)&&!s.includes("e")){let o=s.indexOf(".");o<0&&(o=s.length,s+=".");let a=e-(s.length-o-1);for(;a-- >0;)s+="0"}return s}to.stringifyNumber=vu});var xi=g(sn=>{"use strict";var bu=x(),Ni=Re(),ku={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:t=>t.slice(-3).toLowerCase()==="nan"?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Ni.stringifyNumber},Su={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t),stringify(t){let e=Number(t.value);return isFinite(e)?e.toExponential():Ni.stringifyNumber(t)}},Cu={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(t){let e=new bu.Scalar(parseFloat(t)),n=t.indexOf(".");return n!==-1&&t[t.length-1]==="0"&&(e.minFractionDigits=t.length-n-1),e},stringify:Ni.stringifyNumber};sn.float=Cu;sn.floatExp=Su;sn.floatNaN=ku});var Ai=g(an=>{"use strict";var no=Re(),on=t=>typeof t=="bigint"||Number.isInteger(t),Oi=(t,e,n,{intAsBigInt:i})=>i?BigInt(t):parseInt(t.substring(e),n);function io(t,e,n){let{value:i}=t;return on(i)&&i>=0?n+i.toString(e):no.stringifyNumber(t)}var _u={identify:t=>on(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(t,e,n)=>Oi(t,2,8,n),stringify:t=>io(t,8,"0o")},Eu={identify:on,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(t,e,n)=>Oi(t,0,10,n),stringify:no.stringifyNumber},Pu={identify:t=>on(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(t,e,n)=>Oi(t,2,16,n),stringify:t=>io(t,16,"0x")};an.int=Eu;an.intHex=Pu;an.intOct=_u});var so=g(ro=>{"use strict";var Nu=Oe(),xu=rn(),Ou=Ae(),Au=tt(),Ru=Pi(),Ri=xi(),Ii=Ai(),Iu=[Nu.map,Ou.seq,Au.string,xu.nullTag,Ru.boolTag,Ii.intOct,Ii.int,Ii.intHex,Ri.floatNaN,Ri.floatExp,Ri.float];ro.schema=Iu});var co=g(ao=>{"use strict";var Tu=x(),ju=Oe(),qu=Ae();function oo(t){return typeof t=="bigint"||Number.isInteger(t)}var cn=({value:t})=>JSON.stringify(t),Lu=[{identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify:cn},{identify:t=>t==null,createNode:()=>new Tu.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:cn},{identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:t=>t==="true",stringify:cn},{identify:oo,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(t,e,{intAsBigInt:n})=>n?BigInt(t):parseInt(t,10),stringify:({value:t})=>oo(t)?t.toString():JSON.stringify(t)},{identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:t=>parseFloat(t),stringify:cn}],Du={default:!0,tag:"",test:/^/,resolve(t,e){return e(`Unresolved plain scalar ${JSON.stringify(t)}`),t}},Mu=[ju.map,qu.seq].concat(Lu,Du);ao.schema=Mu});var ji=g(lo=>{"use strict";var nt=At("buffer"),Ti=x(),Wu=Qe(),$u={identify:t=>t instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(t,e){if(typeof nt.Buffer=="function")return nt.Buffer.from(t,"base64");if(typeof atob=="function"){let n=atob(t.replace(/[\n\r]/g,"")),i=new Uint8Array(n.length);for(let r=0;r{"use strict";var ln=E(),qi=se(),Fu=x(),Bu=ce();function uo(t,e){if(ln.isSeq(t))for(let n=0;n1&&e("Each pair must have its own sequence indicator");let r=i.items[0]||new qi.Pair(new Fu.Scalar(null));if(i.commentBefore&&(r.key.commentBefore=r.key.commentBefore?`${i.commentBefore} ${r.key.commentBefore}`:i.commentBefore),i.comment){let s=r.value??r.key;s.comment=s.comment?`${i.comment} -${s.comment}`:i.comment}i=r}t.items[n]=ln.isPair(i)?i:new qi.Pair(i)}}else e("Expected a sequence for this tag");return t}function mo(t,e,n){let{replacer:i}=n,r=new Fu.YAMLSeq(t);r.tag="tag:yaml.org,2002:pairs";let s=0;if(e&&Symbol.iterator in Object(e))for(let o of e){typeof i=="function"&&(o=i.call(e,String(s++),o));let a,c;if(Array.isArray(o))if(o.length===2)a=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)a=l[0],c=o[a];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else a=o;r.items.push(qi.createPair(a,c,n))}return r}var Bu={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:fo,createNode:mo};un.createPairs=mo;un.pairs=Bu;un.resolvePairs=fo});var Mi=g(Di=>{"use strict";var po=E(),Li=ne(),it=ce(),Ku=le(),ho=fn(),ve=class t extends Ku.YAMLSeq{constructor(){super(),this.add=it.YAMLMap.prototype.add.bind(this),this.delete=it.YAMLMap.prototype.delete.bind(this),this.get=it.YAMLMap.prototype.get.bind(this),this.has=it.YAMLMap.prototype.has.bind(this),this.set=it.YAMLMap.prototype.set.bind(this),this.tag=t.tag}toJSON(e,n){if(!n)return super.toJSON(e);let i=new Map;n?.onCreate&&n.onCreate(i);for(let r of this.items){let s,o;if(po.isPair(r)?(s=Li.toJS(r.key,"",n),o=Li.toJS(r.value,s,n)):s=Li.toJS(r,"",n),i.has(s))throw new Error("Ordered maps must not include duplicate keys");i.set(s,o)}return i}static from(e,n,i){let r=ho.createPairs(e,n,i),s=new this;return s.items=r.items,s}};ve.tag="tag:yaml.org,2002:omap";var Yu={collection:"seq",identify:t=>t instanceof Map,nodeClass:ve,default:!1,tag:"tag:yaml.org,2002:omap",resolve(t,e){let n=ho.resolvePairs(t,e),i=[];for(let{key:r}of n.items)po.isScalar(r)&&(i.includes(r.value)?e(`Ordered maps must not include duplicate keys: ${r.value}`):i.push(r.value));return Object.assign(new ve,n)},createNode:(t,e,n)=>ve.from(t,e,n)};Di.YAMLOMap=ve;Di.omap=Yu});var bo=g(Wi=>{"use strict";var go=x();function wo({value:t,source:e},n){return e&&(t?yo:vo).test.test(e)?e:t?n.options.trueStr:n.options.falseStr}var yo={identify:t=>t===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new go.Scalar(!0),stringify:wo},vo={identify:t=>t===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new go.Scalar(!1),stringify:wo};Wi.falseTag=vo;Wi.trueTag=yo});var ko=g(dn=>{"use strict";var Uu=x(),$i=Ie(),Ju={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:t=>t.slice(-3).toLowerCase()==="nan"?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:$i.stringifyNumber},Vu={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t.replace(/_/g,"")),stringify(t){let e=Number(t.value);return isFinite(e)?e.toExponential():$i.stringifyNumber(t)}},Hu={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(t){let e=new Uu.Scalar(parseFloat(t.replace(/_/g,""))),n=t.indexOf(".");if(n!==-1){let i=t.substring(n+1).replace(/_/g,"");i[i.length-1]==="0"&&(e.minFractionDigits=i.length)}return e},stringify:$i.stringifyNumber};dn.float=Hu;dn.floatExp=Vu;dn.floatNaN=Ju});var Co=g(st=>{"use strict";var So=Ie(),rt=t=>typeof t=="bigint"||Number.isInteger(t);function mn(t,e,n,{intAsBigInt:i}){let r=t[0];if((r==="-"||r==="+")&&(e+=1),t=t.substring(e).replace(/_/g,""),i){switch(n){case 2:t=`0b${t}`;break;case 8:t=`0o${t}`;break;case 16:t=`0x${t}`;break}let o=BigInt(t);return r==="-"?BigInt(-1)*o:o}let s=parseInt(t,n);return r==="-"?-1*s:s}function Fi(t,e,n){let{value:i}=t;if(rt(i)){let r=i.toString(e);return i<0?"-"+n+r.substr(1):n+r}return So.stringifyNumber(t)}var Gu={identify:rt,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(t,e,n)=>mn(t,2,2,n),stringify:t=>Fi(t,2,"0b")},zu={identify:rt,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(t,e,n)=>mn(t,1,8,n),stringify:t=>Fi(t,8,"0")},Qu={identify:rt,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(t,e,n)=>mn(t,0,10,n),stringify:So.stringifyNumber},Xu={identify:rt,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(t,e,n)=>mn(t,2,16,n),stringify:t=>Fi(t,16,"0x")};st.int=Qu;st.intBin=Gu;st.intHex=Xu;st.intOct=zu});var Ki=g(Bi=>{"use strict";var gn=E(),pn=oe(),hn=ce(),be=class t extends hn.YAMLMap{constructor(e){super(e),this.tag=t.tag}add(e){let n;gn.isPair(e)?n=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?n=new pn.Pair(e.key,null):n=new pn.Pair(e,null),hn.findPair(this.items,n.key)||this.items.push(n)}get(e,n){let i=hn.findPair(this.items,e);return!n&&gn.isPair(i)?gn.isScalar(i.key)?i.key.value:i.key:i}set(e,n){if(typeof n!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof n}`);let i=hn.findPair(this.items,e);i&&!n?this.items.splice(this.items.indexOf(i),1):!i&&n&&this.items.push(new pn.Pair(e))}toJSON(e,n){return super.toJSON(e,n,Set)}toString(e,n,i){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),n,i);throw new Error("Set items must all have null values")}static from(e,n,i){let{replacer:r}=i,s=new this(e);if(n&&Symbol.iterator in Object(n))for(let o of n)typeof r=="function"&&(o=r.call(n,o,o)),s.items.push(pn.createPair(o,null,i));return s}};be.tag="tag:yaml.org,2002:set";var Zu={collection:"map",identify:t=>t instanceof Set,nodeClass:be,default:!1,tag:"tag:yaml.org,2002:set",createNode:(t,e,n)=>be.from(t,e,n),resolve(t,e){if(gn.isMap(t)){if(t.hasAllNullValues(!0))return Object.assign(new be,t);e("Set items must all have null values")}else e("Expected a mapping for this tag");return t}};Bi.YAMLSet=be;Bi.set=Zu});var Ui=g(wn=>{"use strict";var ef=Ie();function Yi(t,e){let n=t[0],i=n==="-"||n==="+"?t.substring(1):t,r=o=>e?BigInt(o):Number(o),s=i.replace(/_/g,"").split(":").reduce((o,a)=>o*r(60)+r(a),r(0));return n==="-"?r(-1)*s:s}function _o(t){let{value:e}=t,n=o=>o;if(typeof e=="bigint")n=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return ef.stringifyNumber(t);let i="";e<0&&(i="-",e*=n(-1));let r=n(60),s=[e%r];return e<60?s.unshift(0):(e=(e-s[0])/r,s.unshift(e%r),e>=60&&(e=(e-s[0])/r,s.unshift(e))),i+s.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var tf={identify:t=>typeof t=="bigint"||Number.isInteger(t),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(t,e,{intAsBigInt:n})=>Yi(t,n),stringify:_o},nf={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:t=>Yi(t,!1),stringify:_o},Eo={identify:t=>t instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(t){let e=t.match(Eo.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,n,i,r,s,o,a]=e.map(Number),c=e[7]?Number((e[7]+"00").substr(1,3)):0,l=Date.UTC(n,i-1,r,s||0,o||0,a||0,c),m=e[8];if(m&&m!=="Z"){let u=Yi(m,!1);Math.abs(u)<30&&(u*=60),l-=6e4*u}return new Date(l)},stringify:({value:t})=>t?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};wn.floatTime=nf;wn.intTime=tf;wn.timestamp=Eo});var xo=g(No=>{"use strict";var rf=Ae(),sf=rn(),of=Re(),af=tt(),cf=ji(),Po=bo(),Ji=ko(),yn=Co(),lf=Gt(),uf=Mi(),ff=fn(),df=Ki(),Vi=Ui(),mf=[rf.map,of.seq,af.string,sf.nullTag,Po.trueTag,Po.falseTag,yn.intBin,yn.intOct,yn.int,yn.intHex,Ji.floatNaN,Ji.floatExp,Ji.float,cf.binary,lf.merge,uf.omap,ff.pairs,df.set,Vi.intTime,Vi.floatTime,Vi.timestamp];No.schema=mf});var Mo=g(zi=>{"use strict";var Io=Ae(),pf=rn(),To=Re(),hf=tt(),gf=Pi(),Hi=xi(),Gi=Ai(),wf=oo(),yf=lo(),jo=ji(),ot=Gt(),qo=Mi(),Lo=fn(),Oo=xo(),Do=Ki(),vn=Ui(),Ao=new Map([["core",wf.schema],["failsafe",[Io.map,To.seq,hf.string]],["json",yf.schema],["yaml11",Oo.schema],["yaml-1.1",Oo.schema]]),Ro={binary:jo.binary,bool:gf.boolTag,float:Hi.float,floatExp:Hi.floatExp,floatNaN:Hi.floatNaN,floatTime:vn.floatTime,int:Gi.int,intHex:Gi.intHex,intOct:Gi.intOct,intTime:vn.intTime,map:Io.map,merge:ot.merge,null:pf.nullTag,omap:qo.omap,pairs:Lo.pairs,seq:To.seq,set:Do.set,timestamp:vn.timestamp},vf={"tag:yaml.org,2002:binary":jo.binary,"tag:yaml.org,2002:merge":ot.merge,"tag:yaml.org,2002:omap":qo.omap,"tag:yaml.org,2002:pairs":Lo.pairs,"tag:yaml.org,2002:set":Do.set,"tag:yaml.org,2002:timestamp":vn.timestamp};function bf(t,e,n){let i=Ao.get(e);if(i&&!t)return n&&!i.includes(ot.merge)?i.concat(ot.merge):i.slice();let r=i;if(!r)if(Array.isArray(t))r=[];else{let s=Array.from(Ao.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${e}"; use one of ${s} or define customTags array`)}if(Array.isArray(t))for(let s of t)r=r.concat(s);else typeof t=="function"&&(r=t(r.slice()));return n&&(r=r.concat(ot.merge)),r.reduce((s,o)=>{let a=typeof o=="string"?Ro[o]:o;if(!a){let c=JSON.stringify(o),l=Object.keys(Ro).map(m=>JSON.stringify(m)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return s.includes(a)||s.push(a),s},[])}zi.coreKnownTags=vf;zi.getTags=bf});var Zi=g(Wo=>{"use strict";var Qi=E(),kf=Ae(),Sf=Re(),Cf=tt(),bn=Mo(),_f=(t,e)=>t.keye.key?1:0,Xi=class t{constructor({compat:e,customTags:n,merge:i,resolveKnownTags:r,schema:s,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?bn.getTags(e,"compat"):e?bn.getTags(null,e):null,this.name=typeof s=="string"&&s||"core",this.knownTags=r?bn.coreKnownTags:{},this.tags=bn.getTags(n,this.name,i),this.toStringOptions=a??null,Object.defineProperty(this,Qi.MAP,{value:kf.map}),Object.defineProperty(this,Qi.SCALAR,{value:Cf.string}),Object.defineProperty(this,Qi.SEQ,{value:Sf.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?_f:null}clone(){let e=Object.create(t.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};Wo.Schema=Xi});var Fo=g($o=>{"use strict";var Ef=E(),er=Xe(),at=He();function Pf(t,e){let n=[],i=e.directives===!0;if(e.directives!==!1&&t.directives){let c=t.directives.toString(t);c?(n.push(c),i=!0):t.directives.docStart&&(i=!0)}i&&n.push("---");let r=er.createStringifyContext(t,e),{commentString:s}=r.options;if(t.commentBefore){n.length!==1&&n.unshift("");let c=s(t.commentBefore);n.unshift(at.indentComment(c,""))}let o=!1,a=null;if(t.contents){if(Ef.isNode(t.contents)){if(t.contents.spaceBefore&&i&&n.push(""),t.contents.commentBefore){let m=s(t.contents.commentBefore);n.push(at.indentComment(m,""))}r.forceBlockIndent=!!t.comment,a=t.contents.comment}let c=a?void 0:()=>o=!0,l=er.stringify(t.contents,r,()=>a=null,c);a&&(l+=at.lineComment(l,"",s(a))),(l[0]==="|"||l[0]===">")&&n[n.length-1]==="---"?n[n.length-1]=`--- ${l}`:n.push(l)}else n.push(er.stringify(t.contents,r));if(t.directives?.docEnd)if(t.comment){let c=s(t.comment);c.includes(` +${s.comment}`:i.comment}i=r}t.items[n]=ln.isPair(i)?i:new qi.Pair(i)}}else e("Expected a sequence for this tag");return t}function fo(t,e,n){let{replacer:i}=n,r=new Bu.YAMLSeq(t);r.tag="tag:yaml.org,2002:pairs";let s=0;if(e&&Symbol.iterator in Object(e))for(let o of e){typeof i=="function"&&(o=i.call(e,String(s++),o));let a,c;if(Array.isArray(o))if(o.length===2)a=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)a=l[0],c=o[a];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else a=o;r.items.push(qi.createPair(a,c,n))}return r}var Ku={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:uo,createNode:fo};un.createPairs=fo;un.pairs=Ku;un.resolvePairs=uo});var Mi=g(Di=>{"use strict";var mo=E(),Li=te(),it=ae(),Yu=ce(),po=fn(),ye=class t extends Yu.YAMLSeq{constructor(){super(),this.add=it.YAMLMap.prototype.add.bind(this),this.delete=it.YAMLMap.prototype.delete.bind(this),this.get=it.YAMLMap.prototype.get.bind(this),this.has=it.YAMLMap.prototype.has.bind(this),this.set=it.YAMLMap.prototype.set.bind(this),this.tag=t.tag}toJSON(e,n){if(!n)return super.toJSON(e);let i=new Map;n?.onCreate&&n.onCreate(i);for(let r of this.items){let s,o;if(mo.isPair(r)?(s=Li.toJS(r.key,"",n),o=Li.toJS(r.value,s,n)):s=Li.toJS(r,"",n),i.has(s))throw new Error("Ordered maps must not include duplicate keys");i.set(s,o)}return i}static from(e,n,i){let r=po.createPairs(e,n,i),s=new this;return s.items=r.items,s}};ye.tag="tag:yaml.org,2002:omap";var Uu={collection:"seq",identify:t=>t instanceof Map,nodeClass:ye,default:!1,tag:"tag:yaml.org,2002:omap",resolve(t,e){let n=po.resolvePairs(t,e),i=[];for(let{key:r}of n.items)mo.isScalar(r)&&(i.includes(r.value)?e(`Ordered maps must not include duplicate keys: ${r.value}`):i.push(r.value));return Object.assign(new ye,n)},createNode:(t,e,n)=>ye.from(t,e,n)};Di.YAMLOMap=ye;Di.omap=Uu});var vo=g(Wi=>{"use strict";var ho=x();function go({value:t,source:e},n){return e&&(t?wo:yo).test.test(e)?e:t?n.options.trueStr:n.options.falseStr}var wo={identify:t=>t===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new ho.Scalar(!0),stringify:go},yo={identify:t=>t===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new ho.Scalar(!1),stringify:go};Wi.falseTag=yo;Wi.trueTag=wo});var bo=g(dn=>{"use strict";var Ju=x(),$i=Re(),Vu={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:t=>t.slice(-3).toLowerCase()==="nan"?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:$i.stringifyNumber},Hu={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t.replace(/_/g,"")),stringify(t){let e=Number(t.value);return isFinite(e)?e.toExponential():$i.stringifyNumber(t)}},Gu={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(t){let e=new Ju.Scalar(parseFloat(t.replace(/_/g,""))),n=t.indexOf(".");if(n!==-1){let i=t.substring(n+1).replace(/_/g,"");i[i.length-1]==="0"&&(e.minFractionDigits=i.length)}return e},stringify:$i.stringifyNumber};dn.float=Gu;dn.floatExp=Hu;dn.floatNaN=Vu});var So=g(st=>{"use strict";var ko=Re(),rt=t=>typeof t=="bigint"||Number.isInteger(t);function mn(t,e,n,{intAsBigInt:i}){let r=t[0];if((r==="-"||r==="+")&&(e+=1),t=t.substring(e).replace(/_/g,""),i){switch(n){case 2:t=`0b${t}`;break;case 8:t=`0o${t}`;break;case 16:t=`0x${t}`;break}let o=BigInt(t);return r==="-"?BigInt(-1)*o:o}let s=parseInt(t,n);return r==="-"?-1*s:s}function Fi(t,e,n){let{value:i}=t;if(rt(i)){let r=i.toString(e);return i<0?"-"+n+r.substr(1):n+r}return ko.stringifyNumber(t)}var zu={identify:rt,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(t,e,n)=>mn(t,2,2,n),stringify:t=>Fi(t,2,"0b")},Qu={identify:rt,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(t,e,n)=>mn(t,1,8,n),stringify:t=>Fi(t,8,"0")},Xu={identify:rt,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(t,e,n)=>mn(t,0,10,n),stringify:ko.stringifyNumber},Zu={identify:rt,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(t,e,n)=>mn(t,2,16,n),stringify:t=>Fi(t,16,"0x")};st.int=Xu;st.intBin=zu;st.intHex=Zu;st.intOct=Qu});var Ki=g(Bi=>{"use strict";var gn=E(),pn=se(),hn=ae(),ve=class t extends hn.YAMLMap{constructor(e){super(e),this.tag=t.tag}add(e){let n;gn.isPair(e)?n=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?n=new pn.Pair(e.key,null):n=new pn.Pair(e,null),hn.findPair(this.items,n.key)||this.items.push(n)}get(e,n){let i=hn.findPair(this.items,e);return!n&&gn.isPair(i)?gn.isScalar(i.key)?i.key.value:i.key:i}set(e,n){if(typeof n!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof n}`);let i=hn.findPair(this.items,e);i&&!n?this.items.splice(this.items.indexOf(i),1):!i&&n&&this.items.push(new pn.Pair(e))}toJSON(e,n){return super.toJSON(e,n,Set)}toString(e,n,i){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),n,i);throw new Error("Set items must all have null values")}static from(e,n,i){let{replacer:r}=i,s=new this(e);if(n&&Symbol.iterator in Object(n))for(let o of n)typeof r=="function"&&(o=r.call(n,o,o)),s.items.push(pn.createPair(o,null,i));return s}};ve.tag="tag:yaml.org,2002:set";var ef={collection:"map",identify:t=>t instanceof Set,nodeClass:ve,default:!1,tag:"tag:yaml.org,2002:set",createNode:(t,e,n)=>ve.from(t,e,n),resolve(t,e){if(gn.isMap(t)){if(t.hasAllNullValues(!0))return Object.assign(new ve,t);e("Set items must all have null values")}else e("Expected a mapping for this tag");return t}};Bi.YAMLSet=ve;Bi.set=ef});var Ui=g(wn=>{"use strict";var tf=Re();function Yi(t,e){let n=t[0],i=n==="-"||n==="+"?t.substring(1):t,r=o=>e?BigInt(o):Number(o),s=i.replace(/_/g,"").split(":").reduce((o,a)=>o*r(60)+r(a),r(0));return n==="-"?r(-1)*s:s}function Co(t){let{value:e}=t,n=o=>o;if(typeof e=="bigint")n=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return tf.stringifyNumber(t);let i="";e<0&&(i="-",e*=n(-1));let r=n(60),s=[e%r];return e<60?s.unshift(0):(e=(e-s[0])/r,s.unshift(e%r),e>=60&&(e=(e-s[0])/r,s.unshift(e))),i+s.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var nf={identify:t=>typeof t=="bigint"||Number.isInteger(t),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(t,e,{intAsBigInt:n})=>Yi(t,n),stringify:Co},rf={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:t=>Yi(t,!1),stringify:Co},_o={identify:t=>t instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(t){let e=t.match(_o.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,n,i,r,s,o,a]=e.map(Number),c=e[7]?Number((e[7]+"00").substr(1,3)):0,l=Date.UTC(n,i-1,r,s||0,o||0,a||0,c),m=e[8];if(m&&m!=="Z"){let u=Yi(m,!1);Math.abs(u)<30&&(u*=60),l-=6e4*u}return new Date(l)},stringify:({value:t})=>t?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};wn.floatTime=rf;wn.intTime=nf;wn.timestamp=_o});var No=g(Po=>{"use strict";var sf=Oe(),of=rn(),af=Ae(),cf=tt(),lf=ji(),Eo=vo(),Ji=bo(),yn=So(),uf=Gt(),ff=Mi(),df=fn(),mf=Ki(),Vi=Ui(),pf=[sf.map,af.seq,cf.string,of.nullTag,Eo.trueTag,Eo.falseTag,yn.intBin,yn.intOct,yn.int,yn.intHex,Ji.floatNaN,Ji.floatExp,Ji.float,lf.binary,uf.merge,ff.omap,df.pairs,mf.set,Vi.intTime,Vi.floatTime,Vi.timestamp];Po.schema=pf});var Do=g(zi=>{"use strict";var Ro=Oe(),hf=rn(),Io=Ae(),gf=tt(),wf=Pi(),Hi=xi(),Gi=Ai(),yf=so(),vf=co(),To=ji(),ot=Gt(),jo=Mi(),qo=fn(),xo=No(),Lo=Ki(),vn=Ui(),Oo=new Map([["core",yf.schema],["failsafe",[Ro.map,Io.seq,gf.string]],["json",vf.schema],["yaml11",xo.schema],["yaml-1.1",xo.schema]]),Ao={binary:To.binary,bool:wf.boolTag,float:Hi.float,floatExp:Hi.floatExp,floatNaN:Hi.floatNaN,floatTime:vn.floatTime,int:Gi.int,intHex:Gi.intHex,intOct:Gi.intOct,intTime:vn.intTime,map:Ro.map,merge:ot.merge,null:hf.nullTag,omap:jo.omap,pairs:qo.pairs,seq:Io.seq,set:Lo.set,timestamp:vn.timestamp},bf={"tag:yaml.org,2002:binary":To.binary,"tag:yaml.org,2002:merge":ot.merge,"tag:yaml.org,2002:omap":jo.omap,"tag:yaml.org,2002:pairs":qo.pairs,"tag:yaml.org,2002:set":Lo.set,"tag:yaml.org,2002:timestamp":vn.timestamp};function kf(t,e,n){let i=Oo.get(e);if(i&&!t)return n&&!i.includes(ot.merge)?i.concat(ot.merge):i.slice();let r=i;if(!r)if(Array.isArray(t))r=[];else{let s=Array.from(Oo.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${e}"; use one of ${s} or define customTags array`)}if(Array.isArray(t))for(let s of t)r=r.concat(s);else typeof t=="function"&&(r=t(r.slice()));return n&&(r=r.concat(ot.merge)),r.reduce((s,o)=>{let a=typeof o=="string"?Ao[o]:o;if(!a){let c=JSON.stringify(o),l=Object.keys(Ao).map(m=>JSON.stringify(m)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return s.includes(a)||s.push(a),s},[])}zi.coreKnownTags=bf;zi.getTags=kf});var Zi=g(Mo=>{"use strict";var Qi=E(),Sf=Oe(),Cf=Ae(),_f=tt(),bn=Do(),Ef=(t,e)=>t.keye.key?1:0,Xi=class t{constructor({compat:e,customTags:n,merge:i,resolveKnownTags:r,schema:s,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?bn.getTags(e,"compat"):e?bn.getTags(null,e):null,this.name=typeof s=="string"&&s||"core",this.knownTags=r?bn.coreKnownTags:{},this.tags=bn.getTags(n,this.name,i),this.toStringOptions=a??null,Object.defineProperty(this,Qi.MAP,{value:Sf.map}),Object.defineProperty(this,Qi.SCALAR,{value:_f.string}),Object.defineProperty(this,Qi.SEQ,{value:Cf.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?Ef:null}clone(){let e=Object.create(t.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};Mo.Schema=Xi});var $o=g(Wo=>{"use strict";var Pf=E(),er=Xe(),at=He();function Nf(t,e){let n=[],i=e.directives===!0;if(e.directives!==!1&&t.directives){let c=t.directives.toString(t);c?(n.push(c),i=!0):t.directives.docStart&&(i=!0)}i&&n.push("---");let r=er.createStringifyContext(t,e),{commentString:s}=r.options;if(t.commentBefore){n.length!==1&&n.unshift("");let c=s(t.commentBefore);n.unshift(at.indentComment(c,""))}let o=!1,a=null;if(t.contents){if(Pf.isNode(t.contents)){if(t.contents.spaceBefore&&i&&n.push(""),t.contents.commentBefore){let m=s(t.contents.commentBefore);n.push(at.indentComment(m,""))}r.forceBlockIndent=!!t.comment,a=t.contents.comment}let c=a?void 0:()=>o=!0,l=er.stringify(t.contents,r,()=>a=null,c);a&&(l+=at.lineComment(l,"",s(a))),(l[0]==="|"||l[0]===">")&&n[n.length-1]==="---"?n[n.length-1]=`--- ${l}`:n.push(l)}else n.push(er.stringify(t.contents,r));if(t.directives?.docEnd)if(t.comment){let c=s(t.comment);c.includes(` `)?(n.push("..."),n.push(at.indentComment(c,""))):n.push(`... ${c}`)}else n.push("...");else{let c=t.comment;c&&o&&(c=c.replace(/^\n+/,"")),c&&((!o||a)&&n[n.length-1]!==""&&n.push(""),n.push(at.indentComment(s(c),"")))}return n.join(` `)+` -`}$o.stringifyDocument=Pf});var ct=g(Bo=>{"use strict";var Nf=Je(),Te=Wt(),B=E(),xf=oe(),Of=ne(),Af=Zi(),Rf=Fo(),tr=qt(),If=si(),Tf=Ve(),nr=ri(),ir=class t{constructor(e,n,i){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,B.NODE_TYPE,{value:B.DOC});let r=null;typeof n=="function"||Array.isArray(n)?r=n:i===void 0&&n&&(i=n,n=void 0);let s=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},i);this.options=s;let{version:o}=s;i?._directives?(this.directives=i._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new nr.Directives({version:o}),this.setSchema(o,i),this.contents=e===void 0?null:this.createNode(e,r,i)}clone(){let e=Object.create(t.prototype,{[B.NODE_TYPE]:{value:B.DOC}});return e.commentBefore=this.commentBefore,e.comment=this.comment,e.errors=this.errors.slice(),e.warnings=this.warnings.slice(),e.options=Object.assign({},this.options),this.directives&&(e.directives=this.directives.clone()),e.schema=this.schema.clone(),e.contents=B.isNode(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){je(this.contents)&&this.contents.add(e)}addIn(e,n){je(this.contents)&&this.contents.addIn(e,n)}createAlias(e,n){if(!e.anchor){let i=tr.anchorNames(this);e.anchor=!n||i.has(n)?tr.findNewAnchor(n||"a",i):n}return new Nf.Alias(e.anchor)}createNode(e,n,i){let r;if(typeof n=="function")e=n.call({"":e},"",e),r=n;else if(Array.isArray(n)){let p=b=>typeof b=="number"||b instanceof String||b instanceof Number,y=n.filter(p).map(String);y.length>0&&(n=n.concat(y)),r=n}else i===void 0&&n&&(i=n,n=void 0);let{aliasDuplicateObjects:s,anchorPrefix:o,flow:a,keepUndefined:c,onTagObj:l,tag:m}=i??{},{onAnchor:u,setAnchors:f,sourceObjects:h}=tr.createNodeAnchors(this,o||"a"),w={aliasDuplicateObjects:s??!0,keepUndefined:c??!1,onAnchor:u,onTagObj:l,replacer:r,schema:this.schema,sourceObjects:h},d=Tf.createNode(e,m,w);return a&&B.isCollection(d)&&(d.flow=!0),f(),d}createPair(e,n,i={}){let r=this.createNode(e,null,i),s=this.createNode(n,null,i);return new xf.Pair(r,s)}delete(e){return je(this.contents)?this.contents.delete(e):!1}deleteIn(e){return Te.isEmptyPath(e)?this.contents==null?!1:(this.contents=null,!0):je(this.contents)?this.contents.deleteIn(e):!1}get(e,n){return B.isCollection(this.contents)?this.contents.get(e,n):void 0}getIn(e,n){return Te.isEmptyPath(e)?!n&&B.isScalar(this.contents)?this.contents.value:this.contents:B.isCollection(this.contents)?this.contents.getIn(e,n):void 0}has(e){return B.isCollection(this.contents)?this.contents.has(e):!1}hasIn(e){return Te.isEmptyPath(e)?this.contents!==void 0:B.isCollection(this.contents)?this.contents.hasIn(e):!1}set(e,n){this.contents==null?this.contents=Te.collectionFromPath(this.schema,[e],n):je(this.contents)&&this.contents.set(e,n)}setIn(e,n){Te.isEmptyPath(e)?this.contents=n:this.contents==null?this.contents=Te.collectionFromPath(this.schema,Array.from(e),n):je(this.contents)&&this.contents.setIn(e,n)}setSchema(e,n={}){typeof e=="number"&&(e=String(e));let i;switch(e){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new nr.Directives({version:"1.1"}),i={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=e:this.directives=new nr.Directives({version:e}),i={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,i=null;break;default:{let r=JSON.stringify(e);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${r}`)}}if(n.schema instanceof Object)this.schema=n.schema;else if(i)this.schema=new Af.Schema(Object.assign(i,n));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:e,jsonArg:n,mapAsMap:i,maxAliasCount:r,onAnchor:s,reviver:o}={}){let a={anchors:new Map,doc:this,keep:!e,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},c=Of.toJS(this.contents,n??"",a);if(typeof s=="function")for(let{count:l,res:m}of a.anchors.values())s(m,l);return typeof o=="function"?If.applyReviver(o,{"":c},"",c):c}toJSON(e,n){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:n})}toString(e={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let n=JSON.stringify(e.indent);throw new Error(`"indent" option must be a positive integer, not ${n}`)}return Rf.stringifyDocument(this,e)}};function je(t){if(B.isCollection(t))return!0;throw new Error("Expected a YAML collection as document contents")}Bo.Document=ir});var ft=g(ut=>{"use strict";var lt=class extends Error{constructor(e,n,i,r){super(),this.name=e,this.code=i,this.message=r,this.pos=n}},rr=class extends lt{constructor(e,n,i){super("YAMLParseError",e,n,i)}},sr=class extends lt{constructor(e,n,i){super("YAMLWarning",e,n,i)}},jf=(t,e)=>n=>{if(n.pos[0]===-1)return;n.linePos=n.pos.map(a=>e.linePos(a));let{line:i,col:r}=n.linePos[0];n.message+=` at line ${i}, column ${r}`;let s=r-1,o=t.substring(e.lineStarts[i-1],e.lineStarts[i]).replace(/[\n\r]+$/,"");if(s>=60&&o.length>80){let a=Math.min(s-39,o.length-79);o="…"+o.substring(a),s-=a-1}if(o.length>80&&(o=o.substring(0,79)+"…"),i>1&&/^ *$/.test(o.substring(0,s))){let a=t.substring(e.lineStarts[i-2],e.lineStarts[i-1]);a.length>80&&(a=a.substring(0,79)+`… +`}Wo.stringifyDocument=Nf});var ct=g(Fo=>{"use strict";var xf=Je(),Ie=Wt(),B=E(),Of=se(),Af=te(),Rf=Zi(),If=$o(),tr=qt(),Tf=si(),jf=Ve(),nr=ri(),ir=class t{constructor(e,n,i){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,B.NODE_TYPE,{value:B.DOC});let r=null;typeof n=="function"||Array.isArray(n)?r=n:i===void 0&&n&&(i=n,n=void 0);let s=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},i);this.options=s;let{version:o}=s;i?._directives?(this.directives=i._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new nr.Directives({version:o}),this.setSchema(o,i),this.contents=e===void 0?null:this.createNode(e,r,i)}clone(){let e=Object.create(t.prototype,{[B.NODE_TYPE]:{value:B.DOC}});return e.commentBefore=this.commentBefore,e.comment=this.comment,e.errors=this.errors.slice(),e.warnings=this.warnings.slice(),e.options=Object.assign({},this.options),this.directives&&(e.directives=this.directives.clone()),e.schema=this.schema.clone(),e.contents=B.isNode(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){Te(this.contents)&&this.contents.add(e)}addIn(e,n){Te(this.contents)&&this.contents.addIn(e,n)}createAlias(e,n){if(!e.anchor){let i=tr.anchorNames(this);e.anchor=!n||i.has(n)?tr.findNewAnchor(n||"a",i):n}return new xf.Alias(e.anchor)}createNode(e,n,i){let r;if(typeof n=="function")e=n.call({"":e},"",e),r=n;else if(Array.isArray(n)){let p=b=>typeof b=="number"||b instanceof String||b instanceof Number,y=n.filter(p).map(String);y.length>0&&(n=n.concat(y)),r=n}else i===void 0&&n&&(i=n,n=void 0);let{aliasDuplicateObjects:s,anchorPrefix:o,flow:a,keepUndefined:c,onTagObj:l,tag:m}=i??{},{onAnchor:u,setAnchors:f,sourceObjects:h}=tr.createNodeAnchors(this,o||"a"),w={aliasDuplicateObjects:s??!0,keepUndefined:c??!1,onAnchor:u,onTagObj:l,replacer:r,schema:this.schema,sourceObjects:h},d=jf.createNode(e,m,w);return a&&B.isCollection(d)&&(d.flow=!0),f(),d}createPair(e,n,i={}){let r=this.createNode(e,null,i),s=this.createNode(n,null,i);return new Of.Pair(r,s)}delete(e){return Te(this.contents)?this.contents.delete(e):!1}deleteIn(e){return Ie.isEmptyPath(e)?this.contents==null?!1:(this.contents=null,!0):Te(this.contents)?this.contents.deleteIn(e):!1}get(e,n){return B.isCollection(this.contents)?this.contents.get(e,n):void 0}getIn(e,n){return Ie.isEmptyPath(e)?!n&&B.isScalar(this.contents)?this.contents.value:this.contents:B.isCollection(this.contents)?this.contents.getIn(e,n):void 0}has(e){return B.isCollection(this.contents)?this.contents.has(e):!1}hasIn(e){return Ie.isEmptyPath(e)?this.contents!==void 0:B.isCollection(this.contents)?this.contents.hasIn(e):!1}set(e,n){this.contents==null?this.contents=Ie.collectionFromPath(this.schema,[e],n):Te(this.contents)&&this.contents.set(e,n)}setIn(e,n){Ie.isEmptyPath(e)?this.contents=n:this.contents==null?this.contents=Ie.collectionFromPath(this.schema,Array.from(e),n):Te(this.contents)&&this.contents.setIn(e,n)}setSchema(e,n={}){typeof e=="number"&&(e=String(e));let i;switch(e){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new nr.Directives({version:"1.1"}),i={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=e:this.directives=new nr.Directives({version:e}),i={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,i=null;break;default:{let r=JSON.stringify(e);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${r}`)}}if(n.schema instanceof Object)this.schema=n.schema;else if(i)this.schema=new Rf.Schema(Object.assign(i,n));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:e,jsonArg:n,mapAsMap:i,maxAliasCount:r,onAnchor:s,reviver:o}={}){let a={anchors:new Map,doc:this,keep:!e,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},c=Af.toJS(this.contents,n??"",a);if(typeof s=="function")for(let{count:l,res:m}of a.anchors.values())s(m,l);return typeof o=="function"?Tf.applyReviver(o,{"":c},"",c):c}toJSON(e,n){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:n})}toString(e={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let n=JSON.stringify(e.indent);throw new Error(`"indent" option must be a positive integer, not ${n}`)}return If.stringifyDocument(this,e)}};function Te(t){if(B.isCollection(t))return!0;throw new Error("Expected a YAML collection as document contents")}Fo.Document=ir});var ft=g(ut=>{"use strict";var lt=class extends Error{constructor(e,n,i,r){super(),this.name=e,this.code=i,this.message=r,this.pos=n}},rr=class extends lt{constructor(e,n,i){super("YAMLParseError",e,n,i)}},sr=class extends lt{constructor(e,n,i){super("YAMLWarning",e,n,i)}},qf=(t,e)=>n=>{if(n.pos[0]===-1)return;n.linePos=n.pos.map(a=>e.linePos(a));let{line:i,col:r}=n.linePos[0];n.message+=` at line ${i}, column ${r}`;let s=r-1,o=t.substring(e.lineStarts[i-1],e.lineStarts[i]).replace(/[\n\r]+$/,"");if(s>=60&&o.length>80){let a=Math.min(s-39,o.length-79);o="…"+o.substring(a),s-=a-1}if(o.length>80&&(o=o.substring(0,79)+"…"),i>1&&/^ *$/.test(o.substring(0,s))){let a=t.substring(e.lineStarts[i-2],e.lineStarts[i-1]);a.length>80&&(a=a.substring(0,79)+`… `),o=a+o}if(/[^ ]/.test(o)){let a=1,c=n.linePos[1];c?.line===i&&c.col>r&&(a=Math.max(1,Math.min(c.col-r,80-s)));let l=" ".repeat(s)+"^".repeat(a);n.message+=`: ${o} ${l} -`}};ut.YAMLError=lt;ut.YAMLParseError=rr;ut.YAMLWarning=sr;ut.prettifyError=jf});var dt=g(Ko=>{"use strict";function qf(t,{flow:e,indicator:n,next:i,offset:r,onError:s,parentIndent:o,startOnNewline:a}){let c=!1,l=a,m=a,u="",f="",h=!1,w=!1,d=null,p=null,y=null,b=null,k=null,S=null,C=null;for(let v of t)switch(w&&(v.type!=="space"&&v.type!=="newline"&&v.type!=="comma"&&s(v.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),w=!1),d&&(l&&v.type!=="comment"&&v.type!=="newline"&&s(d,"TAB_AS_INDENT","Tabs are not allowed as indentation"),d=null),v.type){case"space":!e&&(n!=="doc-start"||i?.type!=="flow-collection")&&v.source.includes(" ")&&(d=v),m=!0;break;case"comment":{m||s(v,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let R=v.source.substring(1)||" ";u?u+=f+R:u=R,f="",l=!1;break}case"newline":l?u?u+=v.source:(!S||n!=="seq-item-ind")&&(c=!0):f+=v.source,l=!0,h=!0,(p||y)&&(b=v),m=!0;break;case"anchor":p&&s(v,"MULTIPLE_ANCHORS","A node can have at most one anchor"),v.source.endsWith(":")&&s(v.offset+v.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),p=v,C??(C=v.offset),l=!1,m=!1,w=!0;break;case"tag":{y&&s(v,"MULTIPLE_TAGS","A node can have at most one tag"),y=v,C??(C=v.offset),l=!1,m=!1,w=!0;break}case n:(p||y)&&s(v,"BAD_PROP_ORDER",`Anchors and tags must be after the ${v.source} indicator`),S&&s(v,"UNEXPECTED_TOKEN",`Unexpected ${v.source} in ${e??"collection"}`),S=v,l=n==="seq-item-ind"||n==="explicit-key-ind",m=!1;break;case"comma":if(e){k&&s(v,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),k=v,l=!1,m=!1;break}default:s(v,"UNEXPECTED_TOKEN",`Unexpected ${v.type} token`),l=!1,m=!1}let _=t[t.length-1],N=_?_.offset+_.source.length:r;return w&&i&&i.type!=="space"&&i.type!=="newline"&&i.type!=="comma"&&(i.type!=="scalar"||i.source!=="")&&s(i.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),d&&(l&&d.indent<=o||i?.type==="block-map"||i?.type==="block-seq")&&s(d,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:k,found:S,spaceBefore:c,comment:u,hasNewline:h,anchor:p,tag:y,newlineAfterProp:b,end:N,start:C??N}}Ko.resolveProps=qf});var kn=g(Yo=>{"use strict";function or(t){if(!t)return null;switch(t.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(t.source.includes(` -`))return!0;if(t.end){for(let e of t.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(let e of t.items){for(let n of e.start)if(n.type==="newline")return!0;if(e.sep){for(let n of e.sep)if(n.type==="newline")return!0}if(or(e.key)||or(e.value))return!0}return!1;default:return!0}}Yo.containsNewline=or});var ar=g(Uo=>{"use strict";var Lf=kn();function Df(t,e,n){if(e?.type==="flow-collection"){let i=e.end[0];i.indent===t&&(i.source==="]"||i.source==="}")&&Lf.containsNewline(e)&&n(i,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Uo.flowIndentCheck=Df});var cr=g(Vo=>{"use strict";var Jo=E();function Mf(t,e,n){let{uniqueKeys:i}=t.options;if(i===!1)return!1;let r=typeof i=="function"?i:(s,o)=>s===o||Jo.isScalar(s)&&Jo.isScalar(o)&&s.value===o.value;return e.some(s=>r(s.key,n))}Vo.mapIncludes=Mf});var Zo=g(Xo=>{"use strict";var Ho=oe(),Wf=ce(),Go=dt(),$f=kn(),zo=ar(),Ff=cr(),Qo="All mapping items must start at the same column";function Bf({composeNode:t,composeEmptyNode:e},n,i,r,s){let o=s?.nodeClass??Wf.YAMLMap,a=new o(n.schema);n.atRoot&&(n.atRoot=!1);let c=i.offset,l=null;for(let m of i.items){let{start:u,key:f,sep:h,value:w}=m,d=Go.resolveProps(u,{indicator:"explicit-key-ind",next:f??h?.[0],offset:c,onError:r,parentIndent:i.indent,startOnNewline:!0}),p=!d.found;if(p){if(f&&(f.type==="block-seq"?r(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in f&&f.indent!==i.indent&&r(c,"BAD_INDENT",Qo)),!d.anchor&&!d.tag&&!h){l=d.end,d.comment&&(a.comment?a.comment+=` -`+d.comment:a.comment=d.comment);continue}(d.newlineAfterProp||$f.containsNewline(f))&&r(f??u[u.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else d.found?.indent!==i.indent&&r(c,"BAD_INDENT",Qo);n.atKey=!0;let y=d.end,b=f?t(n,f,d,r):e(n,y,u,null,d,r);n.schema.compat&&zo.flowIndentCheck(i.indent,f,r),n.atKey=!1,Ff.mapIncludes(n,a.items,b)&&r(y,"DUPLICATE_KEY","Map keys must be unique");let k=Go.resolveProps(h??[],{indicator:"map-value-ind",next:w,offset:b.range[2],onError:r,parentIndent:i.indent,startOnNewline:!f||f.type==="block-scalar"});if(c=k.end,k.found){p&&(w?.type==="block-map"&&!k.hasNewline&&r(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),n.options.strict&&d.start{"use strict";var Kf=le(),Yf=dt(),Uf=ar();function Jf({composeNode:t,composeEmptyNode:e},n,i,r,s){let o=s?.nodeClass??Kf.YAMLSeq,a=new o(n.schema);n.atRoot&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let c=i.offset,l=null;for(let{start:m,value:u}of i.items){let f=Yf.resolveProps(m,{indicator:"seq-item-ind",next:u,offset:c,onError:r,parentIndent:i.indent,startOnNewline:!0});if(!f.found)if(f.anchor||f.tag||u)u?.type==="block-seq"?r(f.end,"BAD_INDENT","All sequence items must start at the same column"):r(c,"MISSING_CHAR","Sequence item without - indicator");else{l=f.end,f.comment&&(a.comment=f.comment);continue}let h=u?t(n,u,f,r):e(n,f.end,m,null,f,r);n.schema.compat&&Uf.flowIndentCheck(i.indent,u,r),c=h.range[2],a.items.push(h)}return a.range=[i.offset,c,l??c],a}ea.resolveBlockSeq=Jf});var qe=g(na=>{"use strict";function Vf(t,e,n,i){let r="";if(t){let s=!1,o="";for(let a of t){let{source:c,type:l}=a;switch(l){case"space":s=!0;break;case"comment":{n&&!s&&i(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let m=c.substring(1)||" ";r?r+=o+m:r=m,o="";break}case"newline":r&&(o+=c),s=!0;break;default:i(a,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}e+=c.length}}return{comment:r,offset:e}}na.resolveEnd=Vf});var oa=g(sa=>{"use strict";var Hf=E(),Gf=oe(),ia=ce(),zf=le(),Qf=qe(),ra=dt(),Xf=kn(),Zf=cr(),lr="Block collections are not allowed within flow collections",ur=t=>t&&(t.type==="block-map"||t.type==="block-seq");function ed({composeNode:t,composeEmptyNode:e},n,i,r,s){let o=i.start.source==="{",a=o?"flow map":"flow sequence",c=s?.nodeClass??(o?ia.YAMLMap:zf.YAMLSeq),l=new c(n.schema);l.flow=!0;let m=n.atRoot;m&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let u=i.offset+i.start.source.length;for(let p=0;p0){let p=Qf.resolveEnd(w,d,n.options.strict,r);p.comment&&(l.comment?l.comment+=` -`+p.comment:l.comment=p.comment),l.range=[i.offset,d,p.offset]}else l.range=[i.offset,d,d];return l}sa.resolveFlowCollection=ed});var ca=g(aa=>{"use strict";var td=E(),nd=x(),id=ce(),rd=le(),sd=Zo(),od=ta(),ad=oa();function fr(t,e,n,i,r,s){let o=n.type==="block-map"?sd.resolveBlockMap(t,e,n,i,s):n.type==="block-seq"?od.resolveBlockSeq(t,e,n,i,s):ad.resolveFlowCollection(t,e,n,i,s),a=o.constructor;return r==="!"||r===a.tagName?(o.tag=a.tagName,o):(r&&(o.tag=r),o)}function cd(t,e,n,i,r){let s=i.tag,o=s?e.directives.tagName(s.source,f=>r(s,"TAG_RESOLVE_FAILED",f)):null;if(n.type==="block-seq"){let{anchor:f,newlineAfterProp:h}=i,w=f&&s?f.offset>s.offset?f:s:f??s;w&&(!h||h.offsetf.tag===o&&f.collection===a);if(!c){let f=e.schema.knownTags[o];if(f?.collection===a)e.schema.tags.push(Object.assign({},f,{default:!1})),c=f;else return f?r(s,"BAD_COLLECTION_TYPE",`${f.tag} used for ${a} collection, but expects ${f.collection??"scalar"}`,!0):r(s,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),fr(t,e,n,r,o)}let l=fr(t,e,n,r,o,c),m=c.resolve?.(l,f=>r(s,"TAG_RESOLVE_FAILED",f),e.options)??l,u=td.isNode(m)?m:new nd.Scalar(m);return u.range=l.range,u.tag=o,c?.format&&(u.format=c.format),u}aa.composeCollection=cd});var mr=g(la=>{"use strict";var dr=x();function ld(t,e,n){let i=e.offset,r=ud(e,t.options.strict,n);if(!r)return{value:"",type:null,comment:"",range:[i,i,i]};let s=r.mode===">"?dr.Scalar.BLOCK_FOLDED:dr.Scalar.BLOCK_LITERAL,o=e.source?fd(e.source):[],a=o.length;for(let d=o.length-1;d>=0;--d){let p=o[d][1];if(p===""||p==="\r")a=d;else break}if(a===0){let d=r.chomp==="+"&&o.length>0?` +`}};ut.YAMLError=lt;ut.YAMLParseError=rr;ut.YAMLWarning=sr;ut.prettifyError=qf});var dt=g(Bo=>{"use strict";function Lf(t,{flow:e,indicator:n,next:i,offset:r,onError:s,parentIndent:o,startOnNewline:a}){let c=!1,l=a,m=a,u="",f="",h=!1,w=!1,d=null,p=null,y=null,b=null,k=null,S=null,C=null;for(let v of t)switch(w&&(v.type!=="space"&&v.type!=="newline"&&v.type!=="comma"&&s(v.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),w=!1),d&&(l&&v.type!=="comment"&&v.type!=="newline"&&s(d,"TAB_AS_INDENT","Tabs are not allowed as indentation"),d=null),v.type){case"space":!e&&(n!=="doc-start"||i?.type!=="flow-collection")&&v.source.includes(" ")&&(d=v),m=!0;break;case"comment":{m||s(v,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let R=v.source.substring(1)||" ";u?u+=f+R:u=R,f="",l=!1;break}case"newline":l?u?u+=v.source:(!S||n!=="seq-item-ind")&&(c=!0):f+=v.source,l=!0,h=!0,(p||y)&&(b=v),m=!0;break;case"anchor":p&&s(v,"MULTIPLE_ANCHORS","A node can have at most one anchor"),v.source.endsWith(":")&&s(v.offset+v.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),p=v,C??(C=v.offset),l=!1,m=!1,w=!0;break;case"tag":{y&&s(v,"MULTIPLE_TAGS","A node can have at most one tag"),y=v,C??(C=v.offset),l=!1,m=!1,w=!0;break}case n:(p||y)&&s(v,"BAD_PROP_ORDER",`Anchors and tags must be after the ${v.source} indicator`),S&&s(v,"UNEXPECTED_TOKEN",`Unexpected ${v.source} in ${e??"collection"}`),S=v,l=n==="seq-item-ind"||n==="explicit-key-ind",m=!1;break;case"comma":if(e){k&&s(v,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),k=v,l=!1,m=!1;break}default:s(v,"UNEXPECTED_TOKEN",`Unexpected ${v.type} token`),l=!1,m=!1}let _=t[t.length-1],N=_?_.offset+_.source.length:r;return w&&i&&i.type!=="space"&&i.type!=="newline"&&i.type!=="comma"&&(i.type!=="scalar"||i.source!=="")&&s(i.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),d&&(l&&d.indent<=o||i?.type==="block-map"||i?.type==="block-seq")&&s(d,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:k,found:S,spaceBefore:c,comment:u,hasNewline:h,anchor:p,tag:y,newlineAfterProp:b,end:N,start:C??N}}Bo.resolveProps=Lf});var kn=g(Ko=>{"use strict";function or(t){if(!t)return null;switch(t.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(t.source.includes(` +`))return!0;if(t.end){for(let e of t.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(let e of t.items){for(let n of e.start)if(n.type==="newline")return!0;if(e.sep){for(let n of e.sep)if(n.type==="newline")return!0}if(or(e.key)||or(e.value))return!0}return!1;default:return!0}}Ko.containsNewline=or});var ar=g(Yo=>{"use strict";var Df=kn();function Mf(t,e,n){if(e?.type==="flow-collection"){let i=e.end[0];i.indent===t&&(i.source==="]"||i.source==="}")&&Df.containsNewline(e)&&n(i,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Yo.flowIndentCheck=Mf});var cr=g(Jo=>{"use strict";var Uo=E();function Wf(t,e,n){let{uniqueKeys:i}=t.options;if(i===!1)return!1;let r=typeof i=="function"?i:(s,o)=>s===o||Uo.isScalar(s)&&Uo.isScalar(o)&&s.value===o.value;return e.some(s=>r(s.key,n))}Jo.mapIncludes=Wf});var Xo=g(Qo=>{"use strict";var Vo=se(),$f=ae(),Ho=dt(),Ff=kn(),Go=ar(),Bf=cr(),zo="All mapping items must start at the same column";function Kf({composeNode:t,composeEmptyNode:e},n,i,r,s){let o=s?.nodeClass??$f.YAMLMap,a=new o(n.schema);n.atRoot&&(n.atRoot=!1);let c=i.offset,l=null;for(let m of i.items){let{start:u,key:f,sep:h,value:w}=m,d=Ho.resolveProps(u,{indicator:"explicit-key-ind",next:f??h?.[0],offset:c,onError:r,parentIndent:i.indent,startOnNewline:!0}),p=!d.found;if(p){if(f&&(f.type==="block-seq"?r(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in f&&f.indent!==i.indent&&r(c,"BAD_INDENT",zo)),!d.anchor&&!d.tag&&!h){l=d.end,d.comment&&(a.comment?a.comment+=` +`+d.comment:a.comment=d.comment);continue}(d.newlineAfterProp||Ff.containsNewline(f))&&r(f??u[u.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else d.found?.indent!==i.indent&&r(c,"BAD_INDENT",zo);n.atKey=!0;let y=d.end,b=f?t(n,f,d,r):e(n,y,u,null,d,r);n.schema.compat&&Go.flowIndentCheck(i.indent,f,r),n.atKey=!1,Bf.mapIncludes(n,a.items,b)&&r(y,"DUPLICATE_KEY","Map keys must be unique");let k=Ho.resolveProps(h??[],{indicator:"map-value-ind",next:w,offset:b.range[2],onError:r,parentIndent:i.indent,startOnNewline:!f||f.type==="block-scalar"});if(c=k.end,k.found){p&&(w?.type==="block-map"&&!k.hasNewline&&r(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),n.options.strict&&d.start{"use strict";var Yf=ce(),Uf=dt(),Jf=ar();function Vf({composeNode:t,composeEmptyNode:e},n,i,r,s){let o=s?.nodeClass??Yf.YAMLSeq,a=new o(n.schema);n.atRoot&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let c=i.offset,l=null;for(let{start:m,value:u}of i.items){let f=Uf.resolveProps(m,{indicator:"seq-item-ind",next:u,offset:c,onError:r,parentIndent:i.indent,startOnNewline:!0});if(!f.found)if(f.anchor||f.tag||u)u?.type==="block-seq"?r(f.end,"BAD_INDENT","All sequence items must start at the same column"):r(c,"MISSING_CHAR","Sequence item without - indicator");else{l=f.end,f.comment&&(a.comment=f.comment);continue}let h=u?t(n,u,f,r):e(n,f.end,m,null,f,r);n.schema.compat&&Jf.flowIndentCheck(i.indent,u,r),c=h.range[2],a.items.push(h)}return a.range=[i.offset,c,l??c],a}Zo.resolveBlockSeq=Vf});var je=g(ta=>{"use strict";function Hf(t,e,n,i){let r="";if(t){let s=!1,o="";for(let a of t){let{source:c,type:l}=a;switch(l){case"space":s=!0;break;case"comment":{n&&!s&&i(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let m=c.substring(1)||" ";r?r+=o+m:r=m,o="";break}case"newline":r&&(o+=c),s=!0;break;default:i(a,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}e+=c.length}}return{comment:r,offset:e}}ta.resolveEnd=Hf});var sa=g(ra=>{"use strict";var Gf=E(),zf=se(),na=ae(),Qf=ce(),Xf=je(),ia=dt(),Zf=kn(),ed=cr(),lr="Block collections are not allowed within flow collections",ur=t=>t&&(t.type==="block-map"||t.type==="block-seq");function td({composeNode:t,composeEmptyNode:e},n,i,r,s){let o=i.start.source==="{",a=o?"flow map":"flow sequence",c=s?.nodeClass??(o?na.YAMLMap:Qf.YAMLSeq),l=new c(n.schema);l.flow=!0;let m=n.atRoot;m&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let u=i.offset+i.start.source.length;for(let p=0;p0){let p=Xf.resolveEnd(w,d,n.options.strict,r);p.comment&&(l.comment?l.comment+=` +`+p.comment:l.comment=p.comment),l.range=[i.offset,d,p.offset]}else l.range=[i.offset,d,d];return l}ra.resolveFlowCollection=td});var aa=g(oa=>{"use strict";var nd=E(),id=x(),rd=ae(),sd=ce(),od=Xo(),ad=ea(),cd=sa();function fr(t,e,n,i,r,s){let o=n.type==="block-map"?od.resolveBlockMap(t,e,n,i,s):n.type==="block-seq"?ad.resolveBlockSeq(t,e,n,i,s):cd.resolveFlowCollection(t,e,n,i,s),a=o.constructor;return r==="!"||r===a.tagName?(o.tag=a.tagName,o):(r&&(o.tag=r),o)}function ld(t,e,n,i,r){let s=i.tag,o=s?e.directives.tagName(s.source,f=>r(s,"TAG_RESOLVE_FAILED",f)):null;if(n.type==="block-seq"){let{anchor:f,newlineAfterProp:h}=i,w=f&&s?f.offset>s.offset?f:s:f??s;w&&(!h||h.offsetf.tag===o&&f.collection===a);if(!c){let f=e.schema.knownTags[o];if(f?.collection===a)e.schema.tags.push(Object.assign({},f,{default:!1})),c=f;else return f?r(s,"BAD_COLLECTION_TYPE",`${f.tag} used for ${a} collection, but expects ${f.collection??"scalar"}`,!0):r(s,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),fr(t,e,n,r,o)}let l=fr(t,e,n,r,o,c),m=c.resolve?.(l,f=>r(s,"TAG_RESOLVE_FAILED",f),e.options)??l,u=nd.isNode(m)?m:new id.Scalar(m);return u.range=l.range,u.tag=o,c?.format&&(u.format=c.format),u}oa.composeCollection=ld});var mr=g(ca=>{"use strict";var dr=x();function ud(t,e,n){let i=e.offset,r=fd(e,t.options.strict,n);if(!r)return{value:"",type:null,comment:"",range:[i,i,i]};let s=r.mode===">"?dr.Scalar.BLOCK_FOLDED:dr.Scalar.BLOCK_LITERAL,o=e.source?dd(e.source):[],a=o.length;for(let d=o.length-1;d>=0;--d){let p=o[d][1];if(p===""||p==="\r")a=d;else break}if(a===0){let d=r.chomp==="+"&&o.length>0?` `.repeat(Math.max(1,o.length-1)):"",p=i+r.length;return e.source&&(p+=e.source.length),{value:d,type:s,comment:r.comment,range:[i,p,p]}}let c=e.indent+r.indent,l=e.offset+r.length,m=0;for(let d=0;dc&&(c=p.length);else{p.length=a;--d)o[d][0].length>c&&(a=d+1);let u="",f="",h=!1;for(let d=0;dc||y[0]===" "?(f===" "?f=` @@ -84,41 +84,41 @@ ${l} `+o[d][0].slice(c);u[u.length-1]!==` `&&(u+=` `);break;default:u+=` -`}let w=i+r.length+e.source.length;return{value:u,type:s,comment:r.comment,range:[i,w,w]}}function ud({offset:t,props:e},n,i){if(e[0].type!=="block-scalar-header")return i(e[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:r}=e[0],s=r[0],o=0,a="",c=-1;for(let f=1;f{"use strict";var pr=x(),dd=qe();function md(t,e,n){let{offset:i,type:r,source:s,end:o}=t,a,c,l=(f,h,w)=>n(i+f,h,w);switch(r){case"scalar":a=pr.Scalar.PLAIN,c=pd(s,l);break;case"single-quoted-scalar":a=pr.Scalar.QUOTE_SINGLE,c=hd(s,l);break;case"double-quoted-scalar":a=pr.Scalar.QUOTE_DOUBLE,c=gd(s,l);break;default:return n(t,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${r}`),{value:"",type:null,comment:"",range:[i,i+s.length,i+s.length]}}let m=i+s.length,u=dd.resolveEnd(o,m,e,n);return{value:c,type:a,comment:u.comment,range:[i,m,u.offset]}}function pd(t,e){let n="";switch(t[0]){case" ":n="a tab character";break;case",":n="flow indicator character ,";break;case"%":n="directive indicator character %";break;case"|":case">":{n=`block scalar indicator ${t[0]}`;break}case"@":case"`":{n=`reserved character ${t[0]}`;break}}return n&&e(0,"BAD_SCALAR_START",`Plain value cannot start with ${n}`),ua(t)}function hd(t,e){return(t[t.length-1]!=="'"||t.length===1)&&e(t.length,"MISSING_CHAR","Missing closing 'quote"),ua(t.slice(1,-1)).replace(/''/g,"'")}function ua(t){let e,n;try{e=new RegExp(`(.*?)(?{"use strict";var pr=x(),md=je();function pd(t,e,n){let{offset:i,type:r,source:s,end:o}=t,a,c,l=(f,h,w)=>n(i+f,h,w);switch(r){case"scalar":a=pr.Scalar.PLAIN,c=hd(s,l);break;case"single-quoted-scalar":a=pr.Scalar.QUOTE_SINGLE,c=gd(s,l);break;case"double-quoted-scalar":a=pr.Scalar.QUOTE_DOUBLE,c=wd(s,l);break;default:return n(t,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${r}`),{value:"",type:null,comment:"",range:[i,i+s.length,i+s.length]}}let m=i+s.length,u=md.resolveEnd(o,m,e,n);return{value:c,type:a,comment:u.comment,range:[i,m,u.offset]}}function hd(t,e){let n="";switch(t[0]){case" ":n="a tab character";break;case",":n="flow indicator character ,";break;case"%":n="directive indicator character %";break;case"|":case">":{n=`block scalar indicator ${t[0]}`;break}case"@":case"`":{n=`reserved character ${t[0]}`;break}}return n&&e(0,"BAD_SCALAR_START",`Plain value cannot start with ${n}`),la(t)}function gd(t,e){return(t[t.length-1]!=="'"||t.length===1)&&e(t.length,"MISSING_CHAR","Missing closing 'quote"),la(t.slice(1,-1)).replace(/''/g,"'")}function la(t){let e,n;try{e=new RegExp(`(.*?)(?s?t.slice(s,i+1):r)}else n+=r}return(t[t.length-1]!=='"'||t.length===1)&&e(t.length,"MISSING_CHAR",'Missing closing "quote'),n}function wd(t,e){let n="",i=t[e+1];for(;(i===" "||i===" "||i===` +`)&&(n+=i>s?t.slice(s,i+1):r)}else n+=r}return(t[t.length-1]!=='"'||t.length===1)&&e(t.length,"MISSING_CHAR",'Missing closing "quote'),n}function yd(t,e){let n="",i=t[e+1];for(;(i===" "||i===" "||i===` `||i==="\r")&&!(i==="\r"&&t[e+2]!==` `);)i===` `&&(n+=` -`),e+=1,i=t[e+1];return n||(n=" "),{fold:n,offset:e}}var yd={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:` -`,r:"\r",t:" ",v:"\v",N:"…",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function vd(t,e,n,i){let r=t.substr(e,n),o=r.length===n&&/^[0-9a-fA-F]+$/.test(r)?parseInt(r,16):NaN;try{return String.fromCodePoint(o)}catch{let a=t.substr(e-2,n+2);return i(e-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),a}}fa.resolveFlowScalar=md});var pa=g(ma=>{"use strict";var ke=E(),da=x(),bd=mr(),kd=hr();function Sd(t,e,n,i){let{value:r,type:s,comment:o,range:a}=e.type==="block-scalar"?bd.resolveBlockScalar(t,e,i):kd.resolveFlowScalar(e,t.options.strict,i),c=n?t.directives.tagName(n.source,u=>i(n,"TAG_RESOLVE_FAILED",u)):null,l;t.options.stringKeys&&t.atKey?l=t.schema[ke.SCALAR]:c?l=Cd(t.schema,r,c,n,i):e.type==="scalar"?l=_d(t,r,e,i):l=t.schema[ke.SCALAR];let m;try{let u=l.resolve(r,f=>i(n??e,"TAG_RESOLVE_FAILED",f),t.options);m=ke.isScalar(u)?u:new da.Scalar(u)}catch(u){let f=u instanceof Error?u.message:String(u);i(n??e,"TAG_RESOLVE_FAILED",f),m=new da.Scalar(r)}return m.range=a,m.source=r,s&&(m.type=s),c&&(m.tag=c),l.format&&(m.format=l.format),o&&(m.comment=o),m}function Cd(t,e,n,i,r){if(n==="!")return t[ke.SCALAR];let s=[];for(let a of t.tags)if(!a.collection&&a.tag===n)if(a.default&&a.test)s.push(a);else return a;for(let a of s)if(a.test?.test(e))return a;let o=t.knownTags[n];return o&&!o.collection?(t.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(r(i,"TAG_RESOLVE_FAILED",`Unresolved tag: ${n}`,n!=="tag:yaml.org,2002:str"),t[ke.SCALAR])}function _d({atKey:t,directives:e,schema:n},i,r,s){let o=n.tags.find(a=>(a.default===!0||t&&a.default==="key")&&a.test?.test(i))||n[ke.SCALAR];if(n.compat){let a=n.compat.find(c=>c.default&&c.test?.test(i))??n[ke.SCALAR];if(o.tag!==a.tag){let c=e.tagString(o.tag),l=e.tagString(a.tag),m=`Value may be parsed as either ${c} or ${l}`;s(r,"TAG_RESOLVE_FAILED",m,!0)}}return o}ma.composeScalar=Sd});var ga=g(ha=>{"use strict";function Ed(t,e,n){if(e){n??(n=e.length);for(let i=n-1;i>=0;--i){let r=e[i];switch(r.type){case"space":case"comment":case"newline":t-=r.source.length;continue}for(r=e[++i];r?.type==="space";)t+=r.source.length,r=e[++i];break}}return t}ha.emptyScalarPosition=Ed});var va=g(wr=>{"use strict";var Pd=Je(),Nd=E(),xd=ca(),wa=pa(),Od=qe(),Ad=ga(),Rd={composeNode:ya,composeEmptyNode:gr};function ya(t,e,n,i){let r=t.atKey,{spaceBefore:s,comment:o,anchor:a,tag:c}=n,l,m=!0;switch(e.type){case"alias":l=Id(t,e,i),(a||c)&&i(e,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=wa.composeScalar(t,e,c,i),a&&(l.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=xd.composeCollection(Rd,t,e,n,i),a&&(l.anchor=a.source.substring(1))}catch(u){let f=u instanceof Error?u.message:String(u);i(e,"RESOURCE_EXHAUSTION",f)}break;default:{let u=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;i(e,"UNEXPECTED_TOKEN",u),m=!1}}return l??(l=gr(t,e.offset,void 0,null,n,i)),a&&l.anchor===""&&i(a,"BAD_ALIAS","Anchor cannot be an empty string"),r&&t.options.stringKeys&&(!Nd.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&i(c??e,"NON_STRING_KEY","With stringKeys, all keys must be strings"),s&&(l.spaceBefore=!0),o&&(e.type==="scalar"&&e.source===""?l.comment=o:l.commentBefore=o),t.options.keepSourceTokens&&m&&(l.srcToken=e),l}function gr(t,e,n,i,{spaceBefore:r,comment:s,anchor:o,tag:a,end:c},l){let m={type:"scalar",offset:Ad.emptyScalarPosition(e,n,i),indent:-1,source:""},u=wa.composeScalar(t,m,a,l);return o&&(u.anchor=o.source.substring(1),u.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),r&&(u.spaceBefore=!0),s&&(u.comment=s,u.range[2]=c),u}function Id({options:t},{offset:e,source:n,end:i},r){let s=new Pd.Alias(n.substring(1));s.source===""&&r(e,"BAD_ALIAS","Alias cannot be an empty string"),s.source.endsWith(":")&&r(e+n.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=e+n.length,a=Od.resolveEnd(i,o,t.strict,r);return s.range=[e,o,a.offset],a.comment&&(s.comment=a.comment),s}wr.composeEmptyNode=gr;wr.composeNode=ya});var Sa=g(ka=>{"use strict";var Td=ct(),ba=va(),jd=qe(),qd=dt();function Ld(t,e,{offset:n,start:i,value:r,end:s},o){let a=Object.assign({_directives:e},t),c=new Td.Document(void 0,a),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},m=qd.resolveProps(i,{indicator:"doc-start",next:r??s?.[0],offset:n,onError:o,parentIndent:0,startOnNewline:!0});m.found&&(c.directives.docStart=!0,r&&(r.type==="block-map"||r.type==="block-seq")&&!m.hasNewline&&o(m.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=r?ba.composeNode(l,r,m,o):ba.composeEmptyNode(l,m.end,i,null,m,o);let u=c.contents.range[2],f=jd.resolveEnd(s,u,!1,o);return f.comment&&(c.comment=f.comment),c.range=[n,u,f.offset],c}ka.composeDoc=Ld});var vr=g(Ea=>{"use strict";var Dd=At("process"),Md=ri(),Wd=ct(),mt=ft(),Ca=E(),$d=Sa(),Fd=qe();function pt(t){if(typeof t=="number")return[t,t+1];if(Array.isArray(t))return t.length===2?t:[t[0],t[1]];let{offset:e,source:n}=t;return[e,e+(typeof n=="string"?n.length:1)]}function _a(t){let e="",n=!1,i=!1;for(let r=0;r{"use strict";var be=E(),fa=x(),kd=mr(),Sd=hr();function Cd(t,e,n,i){let{value:r,type:s,comment:o,range:a}=e.type==="block-scalar"?kd.resolveBlockScalar(t,e,i):Sd.resolveFlowScalar(e,t.options.strict,i),c=n?t.directives.tagName(n.source,u=>i(n,"TAG_RESOLVE_FAILED",u)):null,l;t.options.stringKeys&&t.atKey?l=t.schema[be.SCALAR]:c?l=_d(t.schema,r,c,n,i):e.type==="scalar"?l=Ed(t,r,e,i):l=t.schema[be.SCALAR];let m;try{let u=l.resolve(r,f=>i(n??e,"TAG_RESOLVE_FAILED",f),t.options);m=be.isScalar(u)?u:new fa.Scalar(u)}catch(u){let f=u instanceof Error?u.message:String(u);i(n??e,"TAG_RESOLVE_FAILED",f),m=new fa.Scalar(r)}return m.range=a,m.source=r,s&&(m.type=s),c&&(m.tag=c),l.format&&(m.format=l.format),o&&(m.comment=o),m}function _d(t,e,n,i,r){if(n==="!")return t[be.SCALAR];let s=[];for(let a of t.tags)if(!a.collection&&a.tag===n)if(a.default&&a.test)s.push(a);else return a;for(let a of s)if(a.test?.test(e))return a;let o=t.knownTags[n];return o&&!o.collection?(t.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(r(i,"TAG_RESOLVE_FAILED",`Unresolved tag: ${n}`,n!=="tag:yaml.org,2002:str"),t[be.SCALAR])}function Ed({atKey:t,directives:e,schema:n},i,r,s){let o=n.tags.find(a=>(a.default===!0||t&&a.default==="key")&&a.test?.test(i))||n[be.SCALAR];if(n.compat){let a=n.compat.find(c=>c.default&&c.test?.test(i))??n[be.SCALAR];if(o.tag!==a.tag){let c=e.tagString(o.tag),l=e.tagString(a.tag),m=`Value may be parsed as either ${c} or ${l}`;s(r,"TAG_RESOLVE_FAILED",m,!0)}}return o}da.composeScalar=Cd});var ha=g(pa=>{"use strict";function Pd(t,e,n){if(e){n??(n=e.length);for(let i=n-1;i>=0;--i){let r=e[i];switch(r.type){case"space":case"comment":case"newline":t-=r.source.length;continue}for(r=e[++i];r?.type==="space";)t+=r.source.length,r=e[++i];break}}return t}pa.emptyScalarPosition=Pd});var ya=g(wr=>{"use strict";var Nd=Je(),xd=E(),Od=aa(),ga=ma(),Ad=je(),Rd=ha(),Id={composeNode:wa,composeEmptyNode:gr};function wa(t,e,n,i){let r=t.atKey,{spaceBefore:s,comment:o,anchor:a,tag:c}=n,l,m=!0;switch(e.type){case"alias":l=Td(t,e,i),(a||c)&&i(e,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=ga.composeScalar(t,e,c,i),a&&(l.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=Od.composeCollection(Id,t,e,n,i),a&&(l.anchor=a.source.substring(1))}catch(u){let f=u instanceof Error?u.message:String(u);i(e,"RESOURCE_EXHAUSTION",f)}break;default:{let u=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;i(e,"UNEXPECTED_TOKEN",u),m=!1}}return l??(l=gr(t,e.offset,void 0,null,n,i)),a&&l.anchor===""&&i(a,"BAD_ALIAS","Anchor cannot be an empty string"),r&&t.options.stringKeys&&(!xd.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&i(c??e,"NON_STRING_KEY","With stringKeys, all keys must be strings"),s&&(l.spaceBefore=!0),o&&(e.type==="scalar"&&e.source===""?l.comment=o:l.commentBefore=o),t.options.keepSourceTokens&&m&&(l.srcToken=e),l}function gr(t,e,n,i,{spaceBefore:r,comment:s,anchor:o,tag:a,end:c},l){let m={type:"scalar",offset:Rd.emptyScalarPosition(e,n,i),indent:-1,source:""},u=ga.composeScalar(t,m,a,l);return o&&(u.anchor=o.source.substring(1),u.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),r&&(u.spaceBefore=!0),s&&(u.comment=s,u.range[2]=c),u}function Td({options:t},{offset:e,source:n,end:i},r){let s=new Nd.Alias(n.substring(1));s.source===""&&r(e,"BAD_ALIAS","Alias cannot be an empty string"),s.source.endsWith(":")&&r(e+n.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=e+n.length,a=Ad.resolveEnd(i,o,t.strict,r);return s.range=[e,o,a.offset],a.comment&&(s.comment=a.comment),s}wr.composeEmptyNode=gr;wr.composeNode=wa});var ka=g(ba=>{"use strict";var jd=ct(),va=ya(),qd=je(),Ld=dt();function Dd(t,e,{offset:n,start:i,value:r,end:s},o){let a=Object.assign({_directives:e},t),c=new jd.Document(void 0,a),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},m=Ld.resolveProps(i,{indicator:"doc-start",next:r??s?.[0],offset:n,onError:o,parentIndent:0,startOnNewline:!0});m.found&&(c.directives.docStart=!0,r&&(r.type==="block-map"||r.type==="block-seq")&&!m.hasNewline&&o(m.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=r?va.composeNode(l,r,m,o):va.composeEmptyNode(l,m.end,i,null,m,o);let u=c.contents.range[2],f=qd.resolveEnd(s,u,!1,o);return f.comment&&(c.comment=f.comment),c.range=[n,u,f.offset],c}ba.composeDoc=Dd});var vr=g(_a=>{"use strict";var Md=At("process"),Wd=ri(),$d=ct(),mt=ft(),Sa=E(),Fd=ka(),Bd=je();function pt(t){if(typeof t=="number")return[t,t+1];if(Array.isArray(t))return t.length===2?t:[t[0],t[1]];let{offset:e,source:n}=t;return[e,e+(typeof n=="string"?n.length:1)]}function Ca(t){let e="",n=!1,i=!1;for(let r=0;r{let o=pt(n);s?this.warnings.push(new mt.YAMLWarning(o,i,r)):this.errors.push(new mt.YAMLParseError(o,i,r))},this.directives=new Md.Directives({version:e.version||"1.2"}),this.options=e}decorate(e,n){let{comment:i,afterEmptyLine:r}=_a(this.prelude);if(i){let s=e.contents;if(n)e.comment=e.comment?`${e.comment} -${i}`:i;else if(r||e.directives.docStart||!s)e.commentBefore=i;else if(Ca.isCollection(s)&&!s.flow&&s.items.length>0){let o=s.items[0];Ca.isPair(o)&&(o=o.key);let a=o.commentBefore;o.commentBefore=a?`${i} +`)+(s.substring(1)||" "),n=!0,i=!1;break;case"%":t[r+1]?.[0]!=="#"&&(r+=1),n=!1;break;default:n||(i=!0),n=!1}}return{comment:e,afterEmptyLine:i}}var yr=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(n,i,r,s)=>{let o=pt(n);s?this.warnings.push(new mt.YAMLWarning(o,i,r)):this.errors.push(new mt.YAMLParseError(o,i,r))},this.directives=new Wd.Directives({version:e.version||"1.2"}),this.options=e}decorate(e,n){let{comment:i,afterEmptyLine:r}=Ca(this.prelude);if(i){let s=e.contents;if(n)e.comment=e.comment?`${e.comment} +${i}`:i;else if(r||e.directives.docStart||!s)e.commentBefore=i;else if(Sa.isCollection(s)&&!s.flow&&s.items.length>0){let o=s.items[0];Sa.isPair(o)&&(o=o.key);let a=o.commentBefore;o.commentBefore=a?`${i} ${a}`:i}else{let o=s.commentBefore;s.commentBefore=o?`${i} -${o}`:i}}if(n){for(let s=0;s{let s=pt(e);s[0]+=n,this.onError(s,"BAD_DIRECTIVE",i,r)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let n=$d.composeDoc(this.options,this.directives,e,this.onError);this.atDirectives&&!n.directives.docStart&&this.onError(e,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(n,!1),this.doc&&(yield this.doc),this.doc=n,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(e.source);break;case"error":{let n=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,i=new mt.YAMLParseError(pt(e),"UNEXPECTED_TOKEN",n);this.atDirectives||!this.doc?this.errors.push(i):this.doc.errors.push(i);break}case"doc-end":{if(!this.doc){let i="Unexpected doc-end without preceding document";this.errors.push(new mt.YAMLParseError(pt(e),"UNEXPECTED_TOKEN",i));break}this.doc.directives.docEnd=!0;let n=Fd.resolveEnd(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),n.comment){let i=this.doc.comment;this.doc.comment=i?`${i} -${n.comment}`:n.comment}this.doc.range[2]=n.offset;break}default:this.errors.push(new mt.YAMLParseError(pt(e),"UNEXPECTED_TOKEN",`Unsupported token ${e.type}`))}}*end(e=!1,n=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let i=Object.assign({_directives:this.directives},this.options),r=new Wd.Document(void 0,i);this.atDirectives&&this.onError(n,"MISSING_CHAR","Missing directives-end indicator line"),r.range=[0,n,n],this.decorate(r,!1),yield r}}};Ea.Composer=yr});var xa=g(Sn=>{"use strict";var Bd=mr(),Kd=hr(),Yd=ft(),Pa=Qe();function Ud(t,e=!0,n){if(t){let i=(r,s,o)=>{let a=typeof r=="number"?r:Array.isArray(r)?r[0]:r.offset;if(n)n(a,s,o);else throw new Yd.YAMLParseError([a,a+1],s,o)};switch(t.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return Kd.resolveFlowScalar(t,e,i);case"block-scalar":return Bd.resolveBlockScalar({options:{strict:e}},t,i)}}return null}function Jd(t,e){let{implicitKey:n=!1,indent:i,inFlow:r=!1,offset:s=-1,type:o="PLAIN"}=e,a=Pa.stringifyString({type:o,value:t},{implicitKey:n,indent:i>0?" ".repeat(i):"",inFlow:r,options:{blockQuote:!0,lineWidth:-1}}),c=e.end??[{type:"newline",offset:-1,indent:i,source:` +${o}`:i}}if(n){for(let s=0;s{let s=pt(e);s[0]+=n,this.onError(s,"BAD_DIRECTIVE",i,r)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let n=Fd.composeDoc(this.options,this.directives,e,this.onError);this.atDirectives&&!n.directives.docStart&&this.onError(e,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(n,!1),this.doc&&(yield this.doc),this.doc=n,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(e.source);break;case"error":{let n=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,i=new mt.YAMLParseError(pt(e),"UNEXPECTED_TOKEN",n);this.atDirectives||!this.doc?this.errors.push(i):this.doc.errors.push(i);break}case"doc-end":{if(!this.doc){let i="Unexpected doc-end without preceding document";this.errors.push(new mt.YAMLParseError(pt(e),"UNEXPECTED_TOKEN",i));break}this.doc.directives.docEnd=!0;let n=Bd.resolveEnd(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),n.comment){let i=this.doc.comment;this.doc.comment=i?`${i} +${n.comment}`:n.comment}this.doc.range[2]=n.offset;break}default:this.errors.push(new mt.YAMLParseError(pt(e),"UNEXPECTED_TOKEN",`Unsupported token ${e.type}`))}}*end(e=!1,n=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let i=Object.assign({_directives:this.directives},this.options),r=new $d.Document(void 0,i);this.atDirectives&&this.onError(n,"MISSING_CHAR","Missing directives-end indicator line"),r.range=[0,n,n],this.decorate(r,!1),yield r}}};_a.Composer=yr});var Na=g(Sn=>{"use strict";var Kd=mr(),Yd=hr(),Ud=ft(),Ea=Qe();function Jd(t,e=!0,n){if(t){let i=(r,s,o)=>{let a=typeof r=="number"?r:Array.isArray(r)?r[0]:r.offset;if(n)n(a,s,o);else throw new Ud.YAMLParseError([a,a+1],s,o)};switch(t.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return Yd.resolveFlowScalar(t,e,i);case"block-scalar":return Kd.resolveBlockScalar({options:{strict:e}},t,i)}}return null}function Vd(t,e){let{implicitKey:n=!1,indent:i,inFlow:r=!1,offset:s=-1,type:o="PLAIN"}=e,a=Ea.stringifyString({type:o,value:t},{implicitKey:n,indent:i>0?" ".repeat(i):"",inFlow:r,options:{blockQuote:!0,lineWidth:-1}}),c=e.end??[{type:"newline",offset:-1,indent:i,source:` `}];switch(a[0]){case"|":case">":{let l=a.indexOf(` `),m=a.substring(0,l),u=a.substring(l+1)+` -`,f=[{type:"block-scalar-header",offset:s,indent:i,source:m}];return Na(f,c)||f.push({type:"newline",offset:-1,indent:i,source:` -`}),{type:"block-scalar",offset:s,indent:i,props:f,source:u}}case'"':return{type:"double-quoted-scalar",offset:s,indent:i,source:a,end:c};case"'":return{type:"single-quoted-scalar",offset:s,indent:i,source:a,end:c};default:return{type:"scalar",offset:s,indent:i,source:a,end:c}}}function Vd(t,e,n={}){let{afterKey:i=!1,implicitKey:r=!1,inFlow:s=!1,type:o}=n,a="indent"in t?t.indent:null;if(i&&typeof a=="number"&&(a+=2),!o)switch(t.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let l=t.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let c=Pa.stringifyString({type:o,value:e},{implicitKey:r||a===null,indent:a!==null&&a>0?" ".repeat(a):"",inFlow:s,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":Hd(t,c);break;case'"':br(t,c,"double-quoted-scalar");break;case"'":br(t,c,"single-quoted-scalar");break;default:br(t,c,"scalar")}}function Hd(t,e){let n=e.indexOf(` +`,f=[{type:"block-scalar-header",offset:s,indent:i,source:m}];return Pa(f,c)||f.push({type:"newline",offset:-1,indent:i,source:` +`}),{type:"block-scalar",offset:s,indent:i,props:f,source:u}}case'"':return{type:"double-quoted-scalar",offset:s,indent:i,source:a,end:c};case"'":return{type:"single-quoted-scalar",offset:s,indent:i,source:a,end:c};default:return{type:"scalar",offset:s,indent:i,source:a,end:c}}}function Hd(t,e,n={}){let{afterKey:i=!1,implicitKey:r=!1,inFlow:s=!1,type:o}=n,a="indent"in t?t.indent:null;if(i&&typeof a=="number"&&(a+=2),!o)switch(t.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let l=t.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let c=Ea.stringifyString({type:o,value:e},{implicitKey:r||a===null,indent:a!==null&&a>0?" ".repeat(a):"",inFlow:s,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":Gd(t,c);break;case'"':br(t,c,"double-quoted-scalar");break;case"'":br(t,c,"single-quoted-scalar");break;default:br(t,c,"scalar")}}function Gd(t,e){let n=e.indexOf(` `),i=e.substring(0,n),r=e.substring(n+1)+` -`;if(t.type==="block-scalar"){let s=t.props[0];if(s.type!=="block-scalar-header")throw new Error("Invalid block scalar header");s.source=i,t.source=r}else{let{offset:s}=t,o="indent"in t?t.indent:-1,a=[{type:"block-scalar-header",offset:s,indent:o,source:i}];Na(a,"end"in t?t.end:void 0)||a.push({type:"newline",offset:-1,indent:o,source:` -`});for(let c of Object.keys(t))c!=="type"&&c!=="offset"&&delete t[c];Object.assign(t,{type:"block-scalar",indent:o,props:a,source:r})}}function Na(t,e){if(e)for(let n of e)switch(n.type){case"space":case"comment":t.push(n);break;case"newline":return t.push(n),!0}return!1}function br(t,e,n){switch(t.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":t.type=n,t.source=e;break;case"block-scalar":{let i=t.props.slice(1),r=e.length;t.props[0].type==="block-scalar-header"&&(r-=t.props[0].source.length);for(let s of i)s.offset+=r;delete t.props,Object.assign(t,{type:n,source:e,end:i});break}case"block-map":case"block-seq":{let r={type:"newline",offset:t.offset+e.length,indent:t.indent,source:` -`};delete t.items,Object.assign(t,{type:n,source:e,end:[r]});break}default:{let i="indent"in t?t.indent:-1,r="end"in t&&Array.isArray(t.end)?t.end.filter(s=>s.type==="space"||s.type==="comment"||s.type==="newline"):[];for(let s of Object.keys(t))s!=="type"&&s!=="offset"&&delete t[s];Object.assign(t,{type:n,indent:i,source:e,end:r})}}}Sn.createScalarToken=Jd;Sn.resolveAsScalar=Ud;Sn.setScalarValue=Vd});var Aa=g(Oa=>{"use strict";var Gd=t=>"type"in t?_n(t):Cn(t);function _n(t){switch(t.type){case"block-scalar":{let e="";for(let n of t.props)e+=_n(n);return e+t.source}case"block-map":case"block-seq":{let e="";for(let n of t.items)e+=Cn(n);return e}case"flow-collection":{let e=t.start.source;for(let n of t.items)e+=Cn(n);for(let n of t.end)e+=n.source;return e}case"document":{let e=Cn(t);if(t.end)for(let n of t.end)e+=n.source;return e}default:{let e=t.source;if("end"in t&&t.end)for(let n of t.end)e+=n.source;return e}}}function Cn({start:t,key:e,sep:n,value:i}){let r="";for(let s of t)r+=s.source;if(e&&(r+=_n(e)),n)for(let s of n)r+=s.source;return i&&(r+=_n(i)),r}Oa.stringify=Gd});var ja=g(Ta=>{"use strict";var kr=Symbol("break visit"),zd=Symbol("skip children"),Ra=Symbol("remove item");function Se(t,e){"type"in t&&t.type==="document"&&(t={start:t.start,value:t.value}),Ia(Object.freeze([]),t,e)}Se.BREAK=kr;Se.SKIP=zd;Se.REMOVE=Ra;Se.itemAtPath=(t,e)=>{let n=t;for(let[i,r]of e){let s=n?.[i];if(s&&"items"in s)n=s.items[r];else return}return n};Se.parentCollection=(t,e)=>{let n=Se.itemAtPath(t,e.slice(0,-1)),i=e[e.length-1][0],r=n?.[i];if(r&&"items"in r)return r;throw new Error("Parent collection not found")};function Ia(t,e,n){let i=n(e,t);if(typeof i=="symbol")return i;for(let r of["key","value"]){let s=e[r];if(s&&"items"in s){for(let o=0;o{"use strict";var Sr=xa(),Qd=Aa(),Xd=ja(),Cr="\uFEFF",_r="",Er="",Pr="",Zd=t=>!!t&&"items"in t,em=t=>!!t&&(t.type==="scalar"||t.type==="single-quoted-scalar"||t.type==="double-quoted-scalar"||t.type==="block-scalar");function tm(t){switch(t){case Cr:return"";case _r:return"";case Er:return"";case Pr:return"";default:return JSON.stringify(t)}}function nm(t){switch(t){case Cr:return"byte-order-mark";case _r:return"doc-mode";case Er:return"flow-error-end";case Pr:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case` +`;if(t.type==="block-scalar"){let s=t.props[0];if(s.type!=="block-scalar-header")throw new Error("Invalid block scalar header");s.source=i,t.source=r}else{let{offset:s}=t,o="indent"in t?t.indent:-1,a=[{type:"block-scalar-header",offset:s,indent:o,source:i}];Pa(a,"end"in t?t.end:void 0)||a.push({type:"newline",offset:-1,indent:o,source:` +`});for(let c of Object.keys(t))c!=="type"&&c!=="offset"&&delete t[c];Object.assign(t,{type:"block-scalar",indent:o,props:a,source:r})}}function Pa(t,e){if(e)for(let n of e)switch(n.type){case"space":case"comment":t.push(n);break;case"newline":return t.push(n),!0}return!1}function br(t,e,n){switch(t.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":t.type=n,t.source=e;break;case"block-scalar":{let i=t.props.slice(1),r=e.length;t.props[0].type==="block-scalar-header"&&(r-=t.props[0].source.length);for(let s of i)s.offset+=r;delete t.props,Object.assign(t,{type:n,source:e,end:i});break}case"block-map":case"block-seq":{let r={type:"newline",offset:t.offset+e.length,indent:t.indent,source:` +`};delete t.items,Object.assign(t,{type:n,source:e,end:[r]});break}default:{let i="indent"in t?t.indent:-1,r="end"in t&&Array.isArray(t.end)?t.end.filter(s=>s.type==="space"||s.type==="comment"||s.type==="newline"):[];for(let s of Object.keys(t))s!=="type"&&s!=="offset"&&delete t[s];Object.assign(t,{type:n,indent:i,source:e,end:r})}}}Sn.createScalarToken=Vd;Sn.resolveAsScalar=Jd;Sn.setScalarValue=Hd});var Oa=g(xa=>{"use strict";var zd=t=>"type"in t?_n(t):Cn(t);function _n(t){switch(t.type){case"block-scalar":{let e="";for(let n of t.props)e+=_n(n);return e+t.source}case"block-map":case"block-seq":{let e="";for(let n of t.items)e+=Cn(n);return e}case"flow-collection":{let e=t.start.source;for(let n of t.items)e+=Cn(n);for(let n of t.end)e+=n.source;return e}case"document":{let e=Cn(t);if(t.end)for(let n of t.end)e+=n.source;return e}default:{let e=t.source;if("end"in t&&t.end)for(let n of t.end)e+=n.source;return e}}}function Cn({start:t,key:e,sep:n,value:i}){let r="";for(let s of t)r+=s.source;if(e&&(r+=_n(e)),n)for(let s of n)r+=s.source;return i&&(r+=_n(i)),r}xa.stringify=zd});var Ta=g(Ia=>{"use strict";var kr=Symbol("break visit"),Qd=Symbol("skip children"),Aa=Symbol("remove item");function ke(t,e){"type"in t&&t.type==="document"&&(t={start:t.start,value:t.value}),Ra(Object.freeze([]),t,e)}ke.BREAK=kr;ke.SKIP=Qd;ke.REMOVE=Aa;ke.itemAtPath=(t,e)=>{let n=t;for(let[i,r]of e){let s=n?.[i];if(s&&"items"in s)n=s.items[r];else return}return n};ke.parentCollection=(t,e)=>{let n=ke.itemAtPath(t,e.slice(0,-1)),i=e[e.length-1][0],r=n?.[i];if(r&&"items"in r)return r;throw new Error("Parent collection not found")};function Ra(t,e,n){let i=n(e,t);if(typeof i=="symbol")return i;for(let r of["key","value"]){let s=e[r];if(s&&"items"in s){for(let o=0;o{"use strict";var Sr=Na(),Xd=Oa(),Zd=Ta(),Cr="\uFEFF",_r="",Er="",Pr="",em=t=>!!t&&"items"in t,tm=t=>!!t&&(t.type==="scalar"||t.type==="single-quoted-scalar"||t.type==="double-quoted-scalar"||t.type==="block-scalar");function nm(t){switch(t){case Cr:return"";case _r:return"";case Er:return"";case Pr:return"";default:return JSON.stringify(t)}}function im(t){switch(t){case Cr:return"byte-order-mark";case _r:return"doc-mode";case Er:return"flow-error-end";case Pr:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case` `:case`\r -`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(t[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}W.createScalarToken=Sr.createScalarToken;W.resolveAsScalar=Sr.resolveAsScalar;W.setScalarValue=Sr.setScalarValue;W.stringify=Qd.stringify;W.visit=Xd.visit;W.BOM=Cr;W.DOCUMENT=_r;W.FLOW_END=Er;W.SCALAR=Pr;W.isCollection=Zd;W.isScalar=em;W.prettyToken=tm;W.tokenType=nm});var Or=g(La=>{"use strict";var ht=En();function U(t){switch(t){case void 0:case" ":case` -`:case"\r":case" ":return!0;default:return!1}}var qa=new Set("0123456789ABCDEFabcdef"),im=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Pn=new Set(",[]{}"),rm=new Set(` ,[]{} -\r `),Nr=t=>!t||rm.has(t),xr=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,n=!1){if(e){if(typeof e!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!n;let i=this.next??"stream";for(;i&&(n||this.hasChars(1));)i=yield*this.parseNext(i)}atLineEnd(){let e=this.pos,n=this.buffer[e];for(;n===" "||n===" ";)n=this.buffer[++e];return!n||n==="#"||n===` +`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(t[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}W.createScalarToken=Sr.createScalarToken;W.resolveAsScalar=Sr.resolveAsScalar;W.setScalarValue=Sr.setScalarValue;W.stringify=Xd.stringify;W.visit=Zd.visit;W.BOM=Cr;W.DOCUMENT=_r;W.FLOW_END=Er;W.SCALAR=Pr;W.isCollection=em;W.isScalar=tm;W.prettyToken=nm;W.tokenType=im});var Or=g(qa=>{"use strict";var ht=En();function U(t){switch(t){case void 0:case" ":case` +`:case"\r":case" ":return!0;default:return!1}}var ja=new Set("0123456789ABCDEFabcdef"),rm=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Pn=new Set(",[]{}"),sm=new Set(` ,[]{} +\r `),Nr=t=>!t||sm.has(t),xr=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,n=!1){if(e){if(typeof e!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!n;let i=this.next??"stream";for(;i&&(n||this.hasChars(1));)i=yield*this.parseNext(i)}atLineEnd(){let e=this.pos,n=this.buffer[e];for(;n===" "||n===" ";)n=this.buffer[++e];return!n||n==="#"||n===` `?!0:n==="\r"?this.buffer[e+1]===` `:!1}charAt(e){return this.buffer[this.pos+e]}continueScalar(e){let n=this.buffer[e];if(this.indentNext>0){let i=0;for(;n===" ";)n=this.buffer[++i+e];if(n==="\r"){let r=this.buffer[i+e+1];if(r===` `||!r&&!this.atEnd)return e+i+1}return n===` @@ -133,17 +133,17 @@ ${n.comment}`:n.comment}this.doc.range[2]=n.offset;break}default:this.errors.pus `&&s>=this.pos&&s+1+n>a)e=s;else break}while(!0);return yield ht.SCALAR,yield*this.pushToIndex(e+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let e=this.flowLevel>0,n=this.pos-1,i=this.pos-1,r;for(;r=this.buffer[++i];)if(r===":"){let s=this.buffer[i+1];if(U(s)||e&&Pn.has(s))break;n=i}else if(U(r)){let s=this.buffer[i+1];if(r==="\r"&&(s===` `?(i+=1,r=` `,s=this.buffer[i+1]):n=i),s==="#"||e&&Pn.has(s))break;if(r===` -`){let o=this.continueScalar(i+1);if(o===-1)break;i=Math.max(i,o-2)}}else{if(e&&Pn.has(r))break;n=i}return!r&&!this.atEnd?this.setNext("plain-scalar"):(yield ht.SCALAR,yield*this.pushToIndex(n+1,!0),e?"flow":"doc")}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,n){let i=this.buffer.slice(this.pos,e);return i?(yield i,this.pos+=i.length,i.length):(n&&(yield""),0)}*pushIndicators(){let e=0;e:for(;;){switch(this.charAt(0)){case"!":e+=yield*this.pushTag(),e+=yield*this.pushSpaces(!0);continue e;case"&":e+=yield*this.pushUntil(Nr),e+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let n=this.flowLevel>0,i=this.charAt(1);if(U(i)||n&&Pn.has(i)){n?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,e+=yield*this.pushCount(1),e+=yield*this.pushSpaces(!0);continue e}}}break e}return e}*pushTag(){if(this.charAt(1)==="<"){let e=this.pos+2,n=this.buffer[e];for(;!U(n)&&n!==">";)n=this.buffer[++e];return yield*this.pushToIndex(n===">"?e+1:e,!1)}else{let e=this.pos+1,n=this.buffer[e];for(;n;)if(im.has(n))n=this.buffer[++e];else if(n==="%"&&qa.has(this.buffer[e+1])&&qa.has(this.buffer[e+2]))n=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];return e===` +`){let o=this.continueScalar(i+1);if(o===-1)break;i=Math.max(i,o-2)}}else{if(e&&Pn.has(r))break;n=i}return!r&&!this.atEnd?this.setNext("plain-scalar"):(yield ht.SCALAR,yield*this.pushToIndex(n+1,!0),e?"flow":"doc")}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,n){let i=this.buffer.slice(this.pos,e);return i?(yield i,this.pos+=i.length,i.length):(n&&(yield""),0)}*pushIndicators(){let e=0;e:for(;;){switch(this.charAt(0)){case"!":e+=yield*this.pushTag(),e+=yield*this.pushSpaces(!0);continue e;case"&":e+=yield*this.pushUntil(Nr),e+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let n=this.flowLevel>0,i=this.charAt(1);if(U(i)||n&&Pn.has(i)){n?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,e+=yield*this.pushCount(1),e+=yield*this.pushSpaces(!0);continue e}}}break e}return e}*pushTag(){if(this.charAt(1)==="<"){let e=this.pos+2,n=this.buffer[e];for(;!U(n)&&n!==">";)n=this.buffer[++e];return yield*this.pushToIndex(n===">"?e+1:e,!1)}else{let e=this.pos+1,n=this.buffer[e];for(;n;)if(rm.has(n))n=this.buffer[++e];else if(n==="%"&&ja.has(this.buffer[e+1])&&ja.has(this.buffer[e+2]))n=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];return e===` `?yield*this.pushCount(1):e==="\r"&&this.charAt(1)===` -`?yield*this.pushCount(2):0}*pushSpaces(e){let n=this.pos-1,i;do i=this.buffer[++n];while(i===" "||e&&i===" ");let r=n-this.pos;return r>0&&(yield this.buffer.substr(this.pos,r),this.pos=n),r}*pushUntil(e){let n=this.pos,i=this.buffer[n];for(;!e(i);)i=this.buffer[++n];return yield*this.pushToIndex(n,!1)}};La.Lexer=xr});var Rr=g(Da=>{"use strict";var Ar=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let n=0,i=this.lineStarts.length;for(;n>1;this.lineStarts[s]{"use strict";var sm=At("process"),Ma=En(),om=Or();function ue(t,e){for(let n=0;n=0;)switch(t[e].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;t[++e]?.type==="space";);return t.splice(e,t.length)}function xn(t,e){if(e.length<1e5)Array.prototype.push.apply(t,e);else for(let n=0;n0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let e=this.peek(1);if(this.type==="doc-end"&&e?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!e)return yield*this.stream();switch(e.type){case"document":return yield*this.document(e);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(e);case"block-scalar":return yield*this.blockScalar(e);case"block-map":return yield*this.blockMap(e);case"block-seq":return yield*this.blockSequence(e);case"flow-collection":return yield*this.flowCollection(e);case"doc-end":return yield*this.documentEnd(e)}yield*this.pop()}peek(e){return this.stack[this.stack.length-e]}*pop(e){let n=e??this.stack.pop();if(!n)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield n;else{let i=this.peek(1);switch(n.type==="block-scalar"?n.indent="indent"in i?i.indent:0:n.type==="flow-collection"&&i.type==="document"&&(n.indent=0),n.type==="flow-collection"&&$a(n),i.type){case"document":i.value=n;break;case"block-scalar":i.props.push(n);break;case"block-map":{let r=i.items[i.items.length-1];if(r.value){i.items.push({start:[],key:n,sep:[]}),this.onKeyLine=!0;return}else if(r.sep)r.value=n;else{Object.assign(r,{key:n,sep:[]}),this.onKeyLine=!r.explicitKey;return}break}case"block-seq":{let r=i.items[i.items.length-1];r.value?i.items.push({start:[],value:n}):r.value=n;break}case"flow-collection":{let r=i.items[i.items.length-1];!r||r.value?i.items.push({start:[],key:n,sep:[]}):r.sep?r.value=n:Object.assign(r,{key:n,sep:[]});return}default:yield*this.pop(),yield*this.pop(n)}if((i.type==="document"||i.type==="block-map"||i.type==="block-seq")&&(n.type==="block-map"||n.type==="block-seq")){let r=n.items[n.items.length-1];r&&!r.sep&&!r.value&&r.start.length>0&&Wa(r.start)===-1&&(n.indent===0||r.start.every(s=>s.type!=="comment"||s.indent0&&(yield this.buffer.substr(this.pos,r),this.pos=n),r}*pushUntil(e){let n=this.pos,i=this.buffer[n];for(;!e(i);)i=this.buffer[++n];return yield*this.pushToIndex(n,!1)}};qa.Lexer=xr});var Rr=g(La=>{"use strict";var Ar=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let n=0,i=this.lineStarts.length;for(;n>1;this.lineStarts[s]{"use strict";var om=At("process"),Da=En(),am=Or();function le(t,e){for(let n=0;n=0;)switch(t[e].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;t[++e]?.type==="space";);return t.splice(e,t.length)}function xn(t,e){if(e.length<1e5)Array.prototype.push.apply(t,e);else for(let n=0;n0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let e=this.peek(1);if(this.type==="doc-end"&&e?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!e)return yield*this.stream();switch(e.type){case"document":return yield*this.document(e);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(e);case"block-scalar":return yield*this.blockScalar(e);case"block-map":return yield*this.blockMap(e);case"block-seq":return yield*this.blockSequence(e);case"flow-collection":return yield*this.flowCollection(e);case"doc-end":return yield*this.documentEnd(e)}yield*this.pop()}peek(e){return this.stack[this.stack.length-e]}*pop(e){let n=e??this.stack.pop();if(!n)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield n;else{let i=this.peek(1);switch(n.type==="block-scalar"?n.indent="indent"in i?i.indent:0:n.type==="flow-collection"&&i.type==="document"&&(n.indent=0),n.type==="flow-collection"&&Wa(n),i.type){case"document":i.value=n;break;case"block-scalar":i.props.push(n);break;case"block-map":{let r=i.items[i.items.length-1];if(r.value){i.items.push({start:[],key:n,sep:[]}),this.onKeyLine=!0;return}else if(r.sep)r.value=n;else{Object.assign(r,{key:n,sep:[]}),this.onKeyLine=!r.explicitKey;return}break}case"block-seq":{let r=i.items[i.items.length-1];r.value?i.items.push({start:[],value:n}):r.value=n;break}case"flow-collection":{let r=i.items[i.items.length-1];!r||r.value?i.items.push({start:[],key:n,sep:[]}):r.sep?r.value=n:Object.assign(r,{key:n,sep:[]});return}default:yield*this.pop(),yield*this.pop(n)}if((i.type==="document"||i.type==="block-map"||i.type==="block-seq")&&(n.type==="block-map"||n.type==="block-seq")){let r=n.items[n.items.length-1];r&&!r.sep&&!r.value&&r.start.length>0&&Ma(r.start)===-1&&(n.indent===0||r.start.every(s=>s.type!=="comment"||s.indent=e.indent){let i=!this.onKeyLine&&this.indent===e.indent,r=i&&(n.sep||n.explicitKey)&&this.type!=="seq-item-ind",s=[];if(r&&n.sep&&!n.value){let o=[];for(let a=0;ae.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(s=n.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":r||n.value?(s.push(this.sourceToken),e.items.push({start:s}),this.onKeyLine=!0):n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"explicit-key-ind":!n.sep&&!n.explicitKey?(n.start.push(this.sourceToken),n.explicitKey=!0):r||n.value?(s.push(this.sourceToken),e.items.push({start:s,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(n.explicitKey)if(n.sep)if(n.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(ue(n.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:s,key:null,sep:[this.sourceToken]}]});else if(Fa(n.key)&&!ue(n.sep,"newline")){let o=Le(n.start),a=n.key,c=n.sep;c.push(this.sourceToken),delete n.key,delete n.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:a,sep:c}]})}else s.length>0?n.sep=n.sep.concat(s,this.sourceToken):n.sep.push(this.sourceToken);else if(ue(n.start,"newline"))Object.assign(n,{key:null,sep:[this.sourceToken]});else{let o=Le(n.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else n.sep?n.value||r?e.items.push({start:s,key:null,sep:[this.sourceToken]}):ue(n.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):n.sep.push(this.sourceToken):Object.assign(n,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);r||n.value?(e.items.push({start:s,key:o,sep:[]}),this.onKeyLine=!0):n.sep?this.stack.push(o):(Object.assign(n,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(e);if(o){if(o.type==="block-seq"){if(!n.explicitKey&&n.sep&&!ue(n.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else i&&e.items.push({start:s});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let n=e.items[e.items.length-1];switch(this.type){case"newline":if(n.value){let i="end"in n.value?n.value.end:void 0;(Array.isArray(i)?i[i.length-1]:void 0)?.type==="comment"?i?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else n.start.push(this.sourceToken);return;case"space":case"comment":if(n.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(n.start,e.indent)){let r=e.items[e.items.length-2]?.value?.end;if(Array.isArray(r)){xn(r,n.start),r.push(this.sourceToken),e.items.pop();return}}n.start.push(this.sourceToken)}return;case"anchor":case"tag":if(n.value||this.indent<=e.indent)break;n.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;n.value||ue(n.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):n.start.push(this.sourceToken);return}if(this.indent>e.indent){let i=this.startBlockValue(e);if(i){this.stack.push(i);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let n=e.items[e.items.length-1];if(this.type==="flow-error-end"){let i;do yield*this.pop(),i=this.peek(1);while(i?.type==="flow-collection")}else if(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!n||n.sep?e.items.push({start:[this.sourceToken]}):n.start.push(this.sourceToken);return;case"map-value-ind":!n||n.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):n.sep?n.sep.push(this.sourceToken):Object.assign(n,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!n||n.value?e.items.push({start:[this.sourceToken]}):n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let r=this.flowScalar(this.type);!n||n.value?e.items.push({start:[],key:r,sep:[]}):n.sep?this.stack.push(r):Object.assign(n,{key:r,sep:[]});return}case"flow-map-end":case"flow-seq-end":e.end.push(this.sourceToken);return}let i=this.startBlockValue(e);i?this.stack.push(i):(yield*this.pop(),yield*this.step())}else{let i=this.peek(2);if(i.type==="block-map"&&(this.type==="map-value-ind"&&i.indent===e.indent||this.type==="newline"&&!i.items[i.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&i.type!=="flow-collection"){let r=Nn(i),s=Le(r);$a(e);let o=e.end.splice(1,e.end.length);o.push(this.sourceToken);let a={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:s,key:e,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let n=this.source.indexOf(` +`,n)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let n=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,n.value){let i="end"in n.value?n.value.end:void 0;(Array.isArray(i)?i[i.length-1]:void 0)?.type==="comment"?i?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"space":case"comment":if(n.value)e.items.push({start:[this.sourceToken]});else if(n.sep)n.sep.push(this.sourceToken);else{if(this.atIndentedComment(n.start,e.indent)){let r=e.items[e.items.length-2]?.value?.end;if(Array.isArray(r)){xn(r,n.start),r.push(this.sourceToken),e.items.pop();return}}n.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let i=!this.onKeyLine&&this.indent===e.indent,r=i&&(n.sep||n.explicitKey)&&this.type!=="seq-item-ind",s=[];if(r&&n.sep&&!n.value){let o=[];for(let a=0;ae.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(s=n.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":r||n.value?(s.push(this.sourceToken),e.items.push({start:s}),this.onKeyLine=!0):n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"explicit-key-ind":!n.sep&&!n.explicitKey?(n.start.push(this.sourceToken),n.explicitKey=!0):r||n.value?(s.push(this.sourceToken),e.items.push({start:s,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(n.explicitKey)if(n.sep)if(n.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(le(n.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:s,key:null,sep:[this.sourceToken]}]});else if($a(n.key)&&!le(n.sep,"newline")){let o=qe(n.start),a=n.key,c=n.sep;c.push(this.sourceToken),delete n.key,delete n.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:a,sep:c}]})}else s.length>0?n.sep=n.sep.concat(s,this.sourceToken):n.sep.push(this.sourceToken);else if(le(n.start,"newline"))Object.assign(n,{key:null,sep:[this.sourceToken]});else{let o=qe(n.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else n.sep?n.value||r?e.items.push({start:s,key:null,sep:[this.sourceToken]}):le(n.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):n.sep.push(this.sourceToken):Object.assign(n,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);r||n.value?(e.items.push({start:s,key:o,sep:[]}),this.onKeyLine=!0):n.sep?this.stack.push(o):(Object.assign(n,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(e);if(o){if(o.type==="block-seq"){if(!n.explicitKey&&n.sep&&!le(n.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else i&&e.items.push({start:s});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let n=e.items[e.items.length-1];switch(this.type){case"newline":if(n.value){let i="end"in n.value?n.value.end:void 0;(Array.isArray(i)?i[i.length-1]:void 0)?.type==="comment"?i?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else n.start.push(this.sourceToken);return;case"space":case"comment":if(n.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(n.start,e.indent)){let r=e.items[e.items.length-2]?.value?.end;if(Array.isArray(r)){xn(r,n.start),r.push(this.sourceToken),e.items.pop();return}}n.start.push(this.sourceToken)}return;case"anchor":case"tag":if(n.value||this.indent<=e.indent)break;n.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;n.value||le(n.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):n.start.push(this.sourceToken);return}if(this.indent>e.indent){let i=this.startBlockValue(e);if(i){this.stack.push(i);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let n=e.items[e.items.length-1];if(this.type==="flow-error-end"){let i;do yield*this.pop(),i=this.peek(1);while(i?.type==="flow-collection")}else if(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!n||n.sep?e.items.push({start:[this.sourceToken]}):n.start.push(this.sourceToken);return;case"map-value-ind":!n||n.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):n.sep?n.sep.push(this.sourceToken):Object.assign(n,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!n||n.value?e.items.push({start:[this.sourceToken]}):n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let r=this.flowScalar(this.type);!n||n.value?e.items.push({start:[],key:r,sep:[]}):n.sep?this.stack.push(r):Object.assign(n,{key:r,sep:[]});return}case"flow-map-end":case"flow-seq-end":e.end.push(this.sourceToken);return}let i=this.startBlockValue(e);i?this.stack.push(i):(yield*this.pop(),yield*this.step())}else{let i=this.peek(2);if(i.type==="block-map"&&(this.type==="map-value-ind"&&i.indent===e.indent||this.type==="newline"&&!i.items[i.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&i.type!=="flow-collection"){let r=Nn(i),s=qe(r);Wa(e);let o=e.end.splice(1,e.end.length);o.push(this.sourceToken);let a={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:s,key:e,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let n=this.source.indexOf(` `)+1;for(;n!==0;)this.onNewLine(this.offset+n),n=this.source.indexOf(` -`,n)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let n=Nn(e),i=Le(n);return i.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let n=Nn(e),i=Le(n);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,n){return this.type!=="comment"||this.indent<=n?!1:e.every(i=>i.type==="newline"||i.type==="space")}*documentEnd(e){this.type!=="doc-mode"&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};Ba.Parser=Ir});var Va=g(wt=>{"use strict";var Ka=vr(),am=ct(),gt=ft(),cm=wi(),lm=E(),um=Rr(),Ya=Tr();function Ua(t){let e=t.prettyErrors!==!1;return{lineCounter:t.lineCounter||e&&new um.LineCounter||null,prettyErrors:e}}function fm(t,e={}){let{lineCounter:n,prettyErrors:i}=Ua(e),r=new Ya.Parser(n?.addNewLine),s=new Ka.Composer(e),o=Array.from(s.compose(r.parse(t)));if(i&&n)for(let a of o)a.errors.forEach(gt.prettifyError(t,n)),a.warnings.forEach(gt.prettifyError(t,n));return o.length>0?o:Object.assign([],{empty:!0},s.streamInfo())}function Ja(t,e={}){let{lineCounter:n,prettyErrors:i}=Ua(e),r=new Ya.Parser(n?.addNewLine),s=new Ka.Composer(e),o=null;for(let a of s.compose(r.parse(t),!0,t.length))if(!o)o=a;else if(o.options.logLevel!=="silent"){o.errors.push(new gt.YAMLParseError(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return i&&n&&(o.errors.forEach(gt.prettifyError(t,n)),o.warnings.forEach(gt.prettifyError(t,n))),o}function dm(t,e,n){let i;typeof e=="function"?i=e:n===void 0&&e&&typeof e=="object"&&(n=e);let r=Ja(t,n);if(!r)return null;if(r.warnings.forEach(s=>cm.warn(r.options.logLevel,s)),r.errors.length>0){if(r.options.logLevel!=="silent")throw r.errors[0];r.errors=[]}return r.toJS(Object.assign({reviver:i},n))}function mm(t,e,n){let i=null;if(typeof e=="function"||Array.isArray(e)?i=e:n===void 0&&e&&(n=e),typeof n=="string"&&(n=n.length),typeof n=="number"){let r=Math.round(n);n=r<1?void 0:r>8?{indent:8}:{indent:r}}if(t===void 0){let{keepUndefined:r}=n??e??{};if(!r)return}return lm.isDocument(t)&&!i?t.toString(n):new am.Document(t,i,n).toString(n)}wt.parse=dm;wt.parseAllDocuments=fm;wt.parseDocument=Ja;wt.stringify=mm});var An=g(P=>{"use strict";var pm=vr(),hm=ct(),gm=Zi(),jr=ft(),wm=Je(),fe=E(),ym=oe(),vm=x(),bm=ce(),km=le(),Sm=En(),Cm=Or(),_m=Rr(),Em=Tr(),On=Va(),Ha=Be();P.Composer=pm.Composer;P.Document=hm.Document;P.Schema=gm.Schema;P.YAMLError=jr.YAMLError;P.YAMLParseError=jr.YAMLParseError;P.YAMLWarning=jr.YAMLWarning;P.Alias=wm.Alias;P.isAlias=fe.isAlias;P.isCollection=fe.isCollection;P.isDocument=fe.isDocument;P.isMap=fe.isMap;P.isNode=fe.isNode;P.isPair=fe.isPair;P.isScalar=fe.isScalar;P.isSeq=fe.isSeq;P.Pair=ym.Pair;P.Scalar=vm.Scalar;P.YAMLMap=bm.YAMLMap;P.YAMLSeq=km.YAMLSeq;P.CST=Sm;P.Lexer=Cm.Lexer;P.LineCounter=_m.LineCounter;P.Parser=Em.Parser;P.parse=On.parse;P.parseAllDocuments=On.parseAllDocuments;P.parseDocument=On.parseDocument;P.stringify=On.stringify;P.visit=Ha.visit;P.visitAsync=Ha.visitAsync});import Rn from"path";function xm(t,e){if(typeof t!="string")throw new Error(`${e} must be a string`);let n=t.trim();if(n.length===0||Rn.posix.isAbsolute(n)||Rn.win32.isAbsolute(n)||/^(?:~|[\\/])/u.test(n))throw new Error(`${e} must be a project-relative path`);if(n===".")return[];let i=n.replaceAll("\\","/").split("/");if(i.some(r=>r===".."))throw new Error(`${e} must stay inside the project root`);if(i.some(r=>r===""||r==="."))throw new Error(`${e} must not contain empty or dot path segments`);return i}function In(t){let e=xm(t,"native.artifact_root");return e.length===0?".":e.join("/")}function za(t,e="docs"){let n=t??e;if(n!=="legacy"&&n!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return n}function bt(t,e,n=!1){if(typeof t!="string")throw new Error(`${e} must be a string`);let i=t.trim().replaceAll("\\","/");if(i.length===0||Rn.posix.isAbsolute(i)||Rn.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${e} must be relative to its declared path base`);let r=i.split("/");if(r.some(s=>s===".."))throw new Error(`${e} must stay inside its declared path base`);if(r.some(s=>s===""||s==="."))throw new Error(`${e} must not contain empty or dot path segments`);if(!n&&/[*?]/u.test(i))throw new Error(`${e} cannot contain wildcards`);return r.join("/")}function yt(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function Qa(t,e,n){let i=t??e;if(i!=="en"&&i!=="zh-CN")throw new Error(`${n} must be en or zh-CN`);return i}function Xa(t,e){if(typeof t!="string"||t.length===0||t.includes("\\")||t.includes("\0")||t.startsWith("/")||t.split("/").includes(".."))throw new Error(`${e} contains an unsafe pattern`);if(t.length>Lr)throw new Error(`${e} exceeds ${Lr} characters`);let n=0;for(let i=0;iDr)throw new Error(`${e} contains more than ${Dr} wildcard tokens`);return t}function Ga(t,e,n){if(t===void 0)return[...n];if(!Array.isArray(t))throw new Error(`${e} contains an unsafe pattern`);return[...new Set(t.map(i=>Xa(i,e)))].sort((i,r)=>i.localeCompare(r,"en"))}function qr(t,e,n){let i=t??e;if(!Number.isSafeInteger(i)||i<1)throw new Error(`${n} must be a positive integer`);return i}function Om(t){if(t===void 0)return{...z,include:[...z.include],exclude:[...z.exclude]};let e=yt(t,"native.snapshot");return{include:Ga(e.include,"native.snapshot.include",z.include),exclude:Ga(e.exclude,"native.snapshot.exclude",z.exclude),max_files:qr(e.max_files,z.max_files,"native.snapshot.max_files"),max_total_bytes:qr(e.max_total_bytes,z.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:qr(e.max_duration_ms,z.max_duration_ms,"native.snapshot.max_duration_ms")}}function Am(t){if(t===void 0)return;let e=yt(t,"native.pending_root_move"),n=e.id,i=e.from_artifact_root,r=e.to_artifact_root,s=e.stage;if(typeof n!="string"||!/^[a-f0-9-]{8,}$/u.test(n))throw new Error("native.pending_root_move.id is invalid");if(typeof i!="string"||typeof r!="string")throw new Error("native.pending_root_move roots must be strings");if(s!=="copying"&&s!=="ready"&&s!=="switched")throw new Error("native.pending_root_move.stage is invalid");let o;if(e.cleanup!==void 0){let a=yt(e.cleanup,"native.pending_root_move.cleanup"),c=a.kind,l=a.state,m=a.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof m!="string"||!/^[a-f0-9]{64}$/u.test(m))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:m}}return{id:n,fromArtifactRoot:In(i),toArtifactRoot:In(r),stage:s,...o?{cleanup:o}:{}}}function Rm(t,e={}){let n=yt(t,"native"),i=n.artifact_root??(e.allowMissingArtifactRoot?"docs":void 0);if(typeof i!="string")throw new Error("native.artifact_root must be a string");let r=n.clarification_mode??"sequential";if(r!=="sequential"&&r!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let s=n.archive_confirmation??"automatic";if(s!=="automatic"&&s!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=n.max_verify_failures??Pm;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let a=Am(n.pending_root_move);return{artifact_root:In(i),language:Qa(n.language,"en","native.language"),clarification_mode:r,archive_confirmation:s,max_verify_failures:o,snapshot:Om(n.snapshot),...a?{pending_root_move:a}:{}}}function Im(t){let e=yt(t,"classic"),n=e.context_compression??"off";if(n!=="off"&&n!=="beta")throw new Error("classic.context_compression must be off or beta");let i=e.review_mode??"standard";if(i!=="off"&&i!=="standard"&&i!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let r=e.auto_transition??!0;if(typeof r!="boolean")throw new Error("classic.auto_transition must be true or false");return{artifact_layout:za(e.artifact_layout),language:Qa(e.language,"zh-CN","classic.language"),context_compression:n,review_mode:i,auto_transition:r}}function Tm(t){let e=t??!0;if(typeof e!="boolean")throw new Error("ambient_resume must be true or false");return e}function jm(t,e,n,i,r){let s=t.schema!==void 0;if(!(s||t.default_workflow!==void 0||t.workflows!==void 0||!r.allowPartialProject&&t.native!==void 0)||r.allowPartialProject&&!s)return null;if(t.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(t.default_workflow!=="native"&&t.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let a=t.workflows??[t.default_workflow];if(!Array.isArray(a)||a.length===0||a.some(l=>l!=="native"&&l!=="classic"))throw new Error("workflows must contain native and/or classic");let c=[...new Set(a)];if(!c.includes(t.default_workflow))throw new Error("workflows must include default_workflow");if(c.includes("native")&&!e)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:t.default_workflow,workflows:c,ambient_resume:i,...e?{native:e}:{},...n?{classic:n}:{}}}function De(t,e={}){let n=(0,Mr.parseDocument)(t,{uniqueKeys:!0});if(n.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${n.errors[0].message}`);let i=n.toJS();if(i==null)return{value:{},config:null,ambient_resume:!0};if(typeof i!="object"||Array.isArray(i))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let r=i,s=Tm(r.ambient_resume),o=r.native===void 0?void 0:Rm(r.native,{allowMissingArtifactRoot:e.allowMissingNativeFields}),a=r.classic===void 0?void 0:Im(r.classic),c=jm(r,o,a,s,{allowPartialProject:e.allowPartialProject??!1});return{value:r,config:c,ambient_resume:s,...o?{native:o}:{},...a?{classic:a}:{}}}var Mr,vt,Lr,Dr,Pm,Nm,z,de=L(()=>{"use strict";Mr=Zn(An(),1),vt=64*1024,Lr=1024,Dr=64,Pm=5,Nm=[".agents/skills/**",".amazonq/skills/**",".augment/skills/**",".bob/skills/**",".claude/skills/**",".cline/skills/**",".codebuddy/skills/**",".continue/skills/**",".cospec/skills/**",".crush/skills/**",".cursor/skills/**",".factory/skills/**",".forge/skills/**",".gemini/skills/**",".github/skills/**",".iflow/skills/**",".junie/skills/**",".kilocode/skills/**",".kimi-code/skills/**",".kiro/skills/**",".lingma/skills/**",".mimocode/skills/**",".opencode/skills/**",".pi/skills/**",".qoder/skills/**",".qwen/skills/**",".roo/skills/**",".trae-cn/skills/**",".trae/skills/**",".windsurf/skills/**",".zcode/skills/**"],z={include:["**/*"],exclude:[...Nm],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4}});function me(t){return t!==0&&t!==0n&&t!=="0"}function Tn(t,e){return me(t.dev)&&me(e.dev)&&me(t.ino)&&me(e.ino)}function Q(t,e){let n=me(t.dev)&&me(e.dev);if(n&&t.dev!==e.dev)return!1;let i=me(t.ino)&&me(e.ino);return i&&t.ino!==e.ino?!1:n&&i?!0:t.birthtime===e.birthtime}var jn=L(()=>{"use strict"});import{constants as qn,promises as Ce}from"fs";function Wr(t){return"birthtimeNs"in t&&typeof t.birthtimeNs=="bigint"?t.birthtimeNs:t.birthtimeMs}function Za(t){return"ctimeNs"in t&&typeof t.ctimeNs=="bigint"?t.ctimeNs:t.ctimeMs}function kt(t){return{dev:t.dev,ino:t.ino,birthtime:Wr(t)}}function Ln(t,e){let n=kt(t),i=kt(e);return Tn(n,i)?Q(n,i):Q(n,i)&&Wr(t)===Wr(e)&&Za(t)===Za(e)&&t.size===e.size}async function ec(t,e,n={}){if(!Number.isSafeInteger(e)||e<1)throw new Error("race-safe read byte limit must be a positive integer");let i=n.label??"file",r=n.bigint===!0,s=await Ce.lstat(t,{bigint:r});if(!s.isFile()||s.isSymbolicLink())throw new pe("not-regular-file",`${i} must be a regular file`);if(BigInt(s.size)>BigInt(e))throw new pe("too-large",`${i} exceeds ${e} bytes`);let o=await Ce.realpath(t);await n.verify?.("pre-open",{realPath:o,identity:kt(s)});let a=process.platform==="win32"?qn.O_RDONLY:qn.O_RDONLY|qn.O_NOFOLLOW|qn.O_NONBLOCK,c;try{c=await Ce.open(t,a)}catch(l){throw l.code==="ELOOP"?new pe("not-regular-file",`${i} must be a regular file`,{cause:l}):l}try{let[l,m,u]=await Promise.all([c.stat({bigint:r}),Ce.lstat(t,{bigint:r}),Ce.realpath(t)]);if(!l.isFile()||!m.isFile()||m.isSymbolicLink()||u!==o||!Ln(s,l)||!Ln(s,m))throw new pe("changed",`${i} changed while opening`);await n.verify?.("post-open",{realPath:u,identity:kt(l)}),await n.hooks?.afterOpen?.();let f=[],h=0,w=Buffer.allocUnsafe(Math.min(64*1024,e+1));for(;;){let b=e+1-h,{bytesRead:k}=await c.read(w,0,Math.min(w.length,b),null);if(k===0)break;if(h+=k,h>e)throw new pe("too-large",`${i} exceeds ${e} bytes`);f.push(Buffer.from(w.subarray(0,k)))}await n.hooks?.beforeFinalCheck?.();let[d,p,y]=await Promise.all([c.stat({bigint:r}),Ce.lstat(t,{bigint:r}),Ce.realpath(t)]);if(!p.isFile()||p.isSymbolicLink()||y!==o||!Ln(s,d)||!Ln(s,p))throw new pe("changed",`${i} changed while reading`);return await n.verify?.("post-read",{realPath:y,identity:kt(d)}),{bytes:Buffer.concat(f,h),stat:d,realPath:y}}finally{await c.close()}}var pe,tc=L(()=>{"use strict";jn();pe=class extends Error{reason;constructor(e,n,i){super(n,i),this.name="RaceSafeReadError",this.reason=e}}});import{promises as Dn}from"fs";import he from"path";function qm(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}function $r(t,e){let n=he.relative(t,e);return n===""||!he.isAbsolute(n)&&n!==".."&&!n.startsWith(`..${he.sep}`)}async function nc(t,e){let n=he.resolve(t),i=await Dn.lstat(n);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${e} project root must be a real directory`);return Dn.realpath(n)}async function ic(t,e,n,i){let r=t;for(let s=0;s{if(!$r(s,a.realPath))throw new Error(`${i.label} resolves outside the project root`);await ic(r.projectRoot,s,r.relative.split("/"),{label:i.label,expected:"file"})}})}var X=L(()=>{"use strict";tc();de()});import{createHash as Lm}from"crypto";function Dm(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function Mn(t,e={}){return(await Wn(t,e)).document}async function Mm(t){try{return(await K(t,St,vt,{label:St})).bytes}catch(e){if(Dm(e))return null;throw e}}function Wm(t){return t?{exists:!0,sha256:Lm("sha256").update(t).digest("hex")}:{exists:!1,sha256:null}}async function Wn(t,e={}){let n=await Mm(t);return{document:n?De(n.toString("utf8"),e):null,identity:Wm(n)}}var St,Ct=L(()=>{"use strict";de();X();St=".comet/config.yaml"});import{randomUUID as $m}from"crypto";import{constants as Fm,promises as O}from"fs";import q from"path";async function Fr(t,e){try{return await O.link(t,e),{linked:!0}}catch(n){let i=n.code;if(i!=="ENOTSUP"&&i!=="EOPNOTSUPP")throw n}return await O.copyFile(t,e,Fm.COPYFILE_EXCL),{linked:!1}}function Me(t,e){let n=q.relative(t,e);return n===""||!q.isAbsolute(n)&&n!==".."&&!n.startsWith(`..${q.sep}`)}function Fn(t){return{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs}}function Bm(t,e){return Q(t,Fn(e))}function $n(t,e){let n=Fn(t),i=Fn(e);return Tn(n,i)?Q(n,i):Q(n,i)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.size===e.size}async function Bn(t){let e=await O.lstat(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Contained atomic write parent must be a real directory: ${t}`);return{path:t,realPath:await O.realpath(t),...Fn(e)}}async function ge(t){for(let e of t){let n=await O.lstat(e.path);if(!n.isDirectory()||n.isSymbolicLink()||!Bm(e,n)||await O.realpath(e.path)!==e.realPath)throw new Error(`Contained atomic write parent changed before commit: ${e.path}`)}}async function Km(t,e){let n=q.resolve(t),i=q.resolve(e);if(!Me(n,i))throw new Error(`Contained atomic write parent is outside its managed root: ${e}`);let r=[await Bn(n)],s=q.relative(n,i).split(q.sep).filter(Boolean),o=n;for(let a of s){await ge(r),o=q.join(o,a);try{await O.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await Bn(o);if(!Me(r[0].realPath,c.realPath))throw new Error(`Contained atomic write parent resolves outside its managed root: ${o}`);r.push(c)}return await ge(r),r}async function Ym(t,e){let n=q.resolve(t),i=q.resolve(e);if(!Me(n,i))throw new Error(`Contained file parent is outside its managed root: ${e}`);let r=[await Bn(n)],s=q.relative(n,i).split(q.sep).filter(Boolean),o=n;for(let a of s){o=q.join(o,a);try{let c=await Bn(o);if(!Me(r[0].realPath,c.realPath))throw new Error(`Contained file parent resolves outside its managed root: ${o}`);r.push(c)}catch(c){if(c.code==="ENOENT")return null;throw c}}return await ge(r),r}async function rc(t){let e;try{e=await O.open(t,"r"),await e.sync()}catch(n){let i=n.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(i??""))throw n}finally{await e?.close()}}async function Um(t,e,n){let i=q.dirname(t),r=await Km(n.containedRoot,i),s=q.join(i,`.${q.basename(t)}.${$m()}.tmp`),o,a;try{await n.beforeTemporaryOpen?.(),o=await O.open(s,"wx"),a=await o.stat();let[c,l]=await Promise.all([O.lstat(s),O.realpath(s)]);if(await ge(r),!c.isFile()||c.isSymbolicLink()||!$n(a,c)||!Me(r[0].realPath,l))throw new Error("Contained atomic write temporary file opened outside its managed parent");if(typeof e=="string"?await o.writeFile(e,"utf8"):await o.writeFile(e),await o.sync(),!$n(a,await o.stat()))throw new Error("Contained atomic write temporary file changed while writing");await o.close(),o=void 0,await n.beforeCommit?.(),await ge(r);let m=await O.lstat(s);if(!m.isFile()||m.isSymbolicLink()||!$n(m,a))throw new Error("Contained atomic write temporary file changed before commit");n.exclusive?(await Fr(s,t),await O.unlink(s)):await O.rename(s,t),await rc(i)}catch(c){await o?.close();try{await ge(r),await O.rm(s,{force:!0})}catch{}throw c}}async function Z(t,e,n){await Um(t,e,n)}async function Br(t,e){let n=q.dirname(t),i=await Ym(e.containedRoot,n);if(!i)return!1;let r,s;try{r=await O.lstat(t),s=await O.realpath(t)}catch(c){if(c.code==="ENOENT")return!1;throw c}if(!r.isFile()||r.isSymbolicLink()||!Me(i[0].realPath,s))throw new Error("Contained file removal target must be a regular file inside its managed root");await e.beforeRemove?.(),await ge(i);let[o,a]=await Promise.all([O.lstat(t),O.realpath(t)]);if(!o.isFile()||o.isSymbolicLink()||!$n(r,o)||a!==s)throw new Error("Contained file removal target changed before removal");return await O.unlink(t),await ge(i),await rc(n),!0}var _e=L(()=>{"use strict";jn()});var tw,Kr=L(()=>{"use strict";_e();Ct();X();tw=16*1024});var Ur=L(()=>{"use strict";_e();de();Ct();X();Kr()});var Yn=L(()=>{"use strict"});var fc=L(()=>{"use strict"});var Vr=L(()=>{"use strict";Yn()});var dc=L(()=>{"use strict";Yn();Vr()});var cp,mc=L(()=>{"use strict";cp=Zn(An(),1);_e();de();X()});var pc=L(()=>{"use strict";Yn();_e();fc();dc();de();mc();X();Ct();Ur();Kr();Vr()});import{TextDecoder as up}from"util";function hc(t){return{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs}}function fp(t,e){try{return new up("utf-8",{fatal:!0}).decode(t.bytes)}catch(n){throw new Error(`${e} is not valid UTF-8`,{cause:n})}}async function Hr(t,e,n,i,r={}){try{let s=await K(t,e,n,{label:i,hooks:r.hooks});return{result:s,text:fp(s,i)}}catch(s){let o=s.code;if(o==="ENOENT"||o==="ENOTDIR")return null;throw s}}async function gc(t,e,n,i,r={}){return(await Hr(t,e,n,i,r))?.text??null}async function wc(t,e,n,i,r,s={}){if(Buffer.byteLength(n,"utf8")>i)throw new Error(`${r} exceeds ${i} bytes`);let o=await Hr(t,e,i,r),a=await $(t,e,{label:r,expected:"file"});await Z(a.target,n,{containedRoot:a.projectRoot,beforeCommit:async()=>{await s.beforeCommit?.();let c=await Hr(t,e,i,r);if(!(!o&&!c)){if(!o||!c)throw new Error(`${r} changed before commit`);if(o.result.realPath!==c.result.realPath||!Q(hc(o.result.stat),hc(c.result.stat))||o.text!==c.text)throw new Error(`${r} changed before commit`)}}})}async function yc(t,e,n,i={}){let r=await $(t,e,{label:n,expected:"file"});return r.exists?Br(r.target,{containedRoot:r.projectRoot,beforeRemove:i.beforeRemove}):!1}var vc=L(()=>{"use strict";pc();jn()});var _c={};Gc(_c,{RUN_STATE_FILE:()=>Jn,applyRunStateToDocument:()=>kc,readRunState:()=>Gr,removeRunState:()=>Cc,runStateFromDocument:()=>Un,writeRunState:()=>zr});import dp from"path";function Pt(t,e){let n=t[e];if(typeof n!="string"||n.length===0)throw new Error(`Invalid Run state: ${e} must be a non-empty string`);return n}function Et(t,e){let n=Pt(t,e);if(dp.isAbsolute(n)||/^(?:[A-Za-z]:|[\\/]|~)/u.test(n)||n.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Run state: ${e} must stay inside the change directory`);return n}function mp(t){let e=t.run_retries??"{}",n;try{n=typeof e=="string"?JSON.parse(e):e}catch(i){throw new Error("Invalid Run state: run_retries must be a JSON object",{cause:i})}if(!n||typeof n!="object"||Array.isArray(n))throw new Error("Invalid Run state: run_retries must be a JSON object");for(let i of Object.values(n))if(!Number.isInteger(i)||Number(i)<0)throw new Error("Invalid Run state: retry counts must be non-negative integers");return n}function Un(t){if(!t.run_id)return null;let e=Pt(t,"run_id"),n=Pt(t,"skill"),i=Pt(t,"skill_version"),r=Pt(t,"skill_hash"),s=Et(t,"pending_ref"),o=Et(t,"trajectory_ref"),a=Et(t,"context_ref"),c=Et(t,"artifacts_ref"),l=Et(t,"checkpoint_ref"),m=Number(t.iteration);if(!Number.isInteger(m)||m<0)throw new Error("Invalid Run state: iteration must be a non-negative integer");if(t.orchestration!=="deterministic"&&t.orchestration!=="adaptive")throw new Error("Invalid Run state: orchestration must be deterministic or adaptive");if(t.run_status!=="running"&&t.run_status!=="waiting"&&t.run_status!=="completed"&&t.run_status!=="failed")throw new Error("Invalid Run state: run_status is invalid");return{runId:e,skill:n,skillVersion:i,skillHash:r,orchestration:t.orchestration,currentStep:bc(t,"current_step"),iteration:m,pending:bc(t,"pending"),pendingRef:s,trajectoryRef:o,contextRef:a,artifactsRef:c,checkpointRef:l,status:t.run_status,retries:mp(t)}}function kc(t,e){e?t.run_id=e.runId:delete t.run_id}function pp(t){return{runId:t.runId,skill:t.skill,skillVersion:t.skillVersion,skillHash:t.skillHash,orchestration:t.orchestration,currentStep:t.currentStep,iteration:t.iteration,pending:t.pending,pendingRef:t.pendingRef,trajectoryRef:t.trajectoryRef,contextRef:t.contextRef,artifactsRef:t.artifactsRef,checkpointRef:t.checkpointRef,status:t.status,retries:t.retries}}function hp(t){let e={run_id:t.runId,skill:t.skill,skill_version:t.skillVersion,skill_hash:t.skillHash,orchestration:t.orchestration,current_step:t.currentStep,iteration:t.iteration,pending:t.pending,pending_ref:t.pendingRef,trajectory_ref:t.trajectoryRef,context_ref:t.contextRef,artifacts_ref:t.artifactsRef,checkpoint_ref:t.checkpointRef,run_status:t.status,run_retries:JSON.stringify(t.retries)};return Un(e)}async function Gr(t,e={}){let n=await gc(t,Jn,Sc,"Run state",e);if(n===null)return null;let i=JSON.parse(n);return hp(i)}async function zr(t,e,n={}){await wc(t,Jn,JSON.stringify(pp(e),null,2),Sc,"Run state",n)}async function Cc(t,e={}){await yc(t,Jn,"Run state",e)}var bc,Jn,Sc,Vn=L(()=>{"use strict";vc();bc=(t,e)=>{let n=t[e];return n==null?null:String(n)};Jn=".comet/run-state.json",Sc=256*1024});import{promises as zm}from"fs";import A from"path";import{promises as rs}from"fs";async function ei(t){try{return await rs.access(t),!0}catch(e){if(Qc(e))return!1;throw e}}async function ss(t){try{return await rs.readdir(t)}catch(e){let n=e?.code;if(n==="ENOENT"||n==="ENOTDIR")return[];throw e}}function Qc(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}de();Ct();Ur();X();var _t=class extends Error{code="classic-layout-unavailable";constructor(e="Classic artifact layout is unavailable from .comet/config.yaml"){super(e),this.name="ClassicLayoutUnavailableError"}},Jr=class extends Error{constructor(n,i,r){let s=ee(r,n),o=ee(r,i);super(`Classic layout conflict: both ${s}/ and ${o}/ exist; run comet doctor and resolve the conflict before writing`);this.configuredRoot=n;this.alternateRoot=i;this.name="ClassicLayoutConflictError"}configuredRoot;alternateRoot;code="classic-layout-conflict"},ac=".comet/config.yaml";function Qm(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function cc(t){await $(t,ac,{label:ac,expected:"file"})}function lc(t,e){let n=A.resolve(t),i=e==="docs"?A.join(n,"docs"):n,r=A.join(i,"openspec"),s=A.join(n,"docs","superpowers");return{projectRoot:n,artifactLayout:e,openSpecBase:i,openSpecRoot:r,changesDir:A.join(r,"changes"),archiveDir:A.join(r,"changes","archive"),specsDir:A.join(r,"specs"),superpowersRoot:s,superpowersSpecsDir:A.join(s,"specs"),superpowersPlansDir:A.join(s,"plans"),superpowersReportsDir:A.join(s,"reports")}}async function Xm(t){await cc(t);let e=await Mn(t,{allowPartialProject:!0,allowMissingNativeFields:!0});if(!e?.config)throw new _t;if(!(e.config.workflows??[e.config.default_workflow]).includes("classic"))throw new _t("Classic artifact layout is unavailable because Classic is not enabled");return e.classic?.artifact_layout??"legacy"}async function Zm(t,e){return lc(t,e??await Xm(t))}async function ep(t,e){let n=await Zm(t,e),i=n.artifactLayout==="legacy"?"docs":"legacy",r=lc(t,i).openSpecRoot,[s,o]=await Promise.all([$(n.projectRoot,ee(n.projectRoot,n.openSpecRoot),{label:"Configured Classic OpenSpec root",expected:"directory"}),$(n.projectRoot,ee(n.projectRoot,r),{label:"Alternate Classic OpenSpec root",expected:"directory"})]),a=s.exists,c=o.exists;return{paths:n,configuredRootExists:a,alternateRoot:r,alternateRootExists:c,dualRoots:a&&c}}async function tp(t,e){let n=[t.openSpecRoot,t.changesDir,t.archiveDir,t.specsDir,e,t.superpowersRoot,t.superpowersSpecsDir,t.superpowersPlansDir,t.superpowersReportsDir];for(let i of n){let r=ee(t.projectRoot,i);await $(t.projectRoot,r,{label:`Classic managed physical path ${r}`,expected:"directory"})}}async function Kn(t,e,n={}){let i=await ep(t,e);if(await tp(i.paths,i.alternateRoot),i.dualRoots&&!n.allowAlternateRoot)throw new Jr(i.paths.openSpecRoot,i.alternateRoot,i.paths.projectRoot);if(!i.configuredRootExists){let r=ee(i.paths.projectRoot,i.paths.openSpecRoot),s=ee(i.paths.projectRoot,i.alternateRoot);throw new _t(`Configured Classic OpenSpec root is missing: ${r} (alternate ${s} is ${i.alternateRootExists?"present":"missing"})`)}return i.paths}async function uc(t){let e=A.resolve(t),n=null;try{(await zm.lstat(e)).isDirectory()||(e=A.dirname(e))}catch(i){if(!Qm(i))throw i}for(;;){A.basename(e)==="openspec"&&(n=A.dirname(e));let i=A.join(e,".comet","config.yaml"),r=!1;if(await ei(i))try{await cc(e);let o=(await Mn(e))?.value;r=!!o&&typeof o=="object"&&!Array.isArray(o)&&(o.schema==="comet.project.v1"||o.default_workflow!==void 0||o.native!==void 0)}catch{}if(r||await ei(A.join(e,".git")))return e;let s=A.dirname(e);if(s===e)return n??A.resolve(t);e=s}}function ee(t,e){return A.relative(A.resolve(t),e).replaceAll("\\","/")}import{spawn as Up}from"child_process";var zn=Zn(An(),1);_e();X();import Zr from"path";Vn();var Ec=["full","hotfix","tweak"],Pc=1,gp=["open","design","build","verify","archive"],wp=["en","zh-CN"],yp=["off","beta"],vp=["subagent-driven-development","executing-plans","direct"],bp=["plan-ready"],kp=["confirmed"],Sp=["tdd","direct"],Cp=["off","standard","thorough"],_p=["current","branch","worktree"],Ep=["light","full"],Pp=["pending","pass","fail"],Np=["pending","handled"],xp=["pending","confirmed"],Xr=["workflow","language","phase","context_compression","build_mode","build_pause","subagent_dispatch","tdd_mode","review_mode","isolation","bound_branch","verify_mode","auto_transition","base_ref","design_doc","plan","verify_result","verify_failures","verification_report","branch_status","created_at","verified_at","archive_confirmation","archived","direct_override","handoff_context","handoff_hash","classic_profile","classic_migration"],Op=["run_id"],Ap=new Set([...Xr,...Op]),Rp=["workflow","phase","design_doc","plan","build_mode","isolation","verify_mode","verify_result","verified_at","archived"];function Nc(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function We(t,e){let n=t[e];if(n==null||n==="")return null;if(typeof n!="string")throw new Error(`Invalid Classic state: ${e} must be a string or null`);return n}function D(t,e,n,i=!0){let r=t[e];if(r==null||r===""){if(i)return null;throw new Error(`Invalid Classic state: ${e} is required`)}if(typeof r!="string"||!n.includes(r))throw new Error(`Invalid Classic state: ${e} must be one of ${n.join(", ")}${i?" or null":""}`);return r}function Qr(t,e,n=!0){let i=t[e];if(i==null||i===""){if(n)return null;throw new Error(`Invalid Classic state: ${e} is required`)}if(typeof i!="boolean")throw new Error(`Invalid Classic state: ${e} must be true or false`);return i}function Ip(t,e,n=0){let i=t[e];if(i==null||i==="")return n;if(typeof i!="number"||!Number.isInteger(i)||i<0)throw new Error(`Invalid Classic state: ${e} must be a non-negative integer`);return i}function Hn(t,e){let n=We(t,e);if(n===null)return null;if(/^(?:[A-Za-z]:|[\\/]|~)/u.test(n)||n.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Classic state: ${e} must be a relative repository path`);return n}function Tp(t,e){let n=We(t,e);if(n!==null&&!/^[a-f0-9]{64}$/u.test(n))throw new Error(`Invalid Classic state: ${e} must be a sha256 hex digest`);return n}function jp(t){let e=t.classic_migration;if(e==null||e==="")return null;if(e!==Pc)throw new Error(`Invalid Classic state: classic_migration must be ${Pc}`);return e}function qp(t){if(!Xr.some(n=>Nc(t,n)))return null;for(let n of Rp)if(!Nc(t,n))return null;return{workflow:D(t,"workflow",Ec,!1),language:D(t,"language",wp),phase:D(t,"phase",gp,!1),contextCompression:D(t,"context_compression",yp),buildMode:D(t,"build_mode",vp),buildPause:D(t,"build_pause",bp),subagentDispatch:D(t,"subagent_dispatch",kp),tddMode:D(t,"tdd_mode",Sp),reviewMode:D(t,"review_mode",Cp),isolation:D(t,"isolation",_p),boundBranch:We(t,"bound_branch"),verifyMode:D(t,"verify_mode",Ep),autoTransition:Qr(t,"auto_transition"),baseRef:We(t,"base_ref"),designDoc:Hn(t,"design_doc"),plan:Hn(t,"plan"),verifyResult:D(t,"verify_result",Pp,!1),verifyFailures:Ip(t,"verify_failures"),verificationReport:Hn(t,"verification_report"),branchStatus:D(t,"branch_status",Np),createdAt:We(t,"created_at"),verifiedAt:We(t,"verified_at"),archiveConfirmation:D(t,"archive_confirmation",xp),archived:Qr(t,"archived",!1),directOverride:Qr(t,"direct_override"),handoffContext:Hn(t,"handoff_context"),handoffHash:Tp(t,"handoff_hash"),classicProfile:D(t,"classic_profile",Ec),classicMigration:jp(t)}}function xc(t,e){let n=e??null;if(n===null&&e===void 0&&t.run_id&&t.skill)try{n=Un(t)}catch(i){let r=i instanceof Error?i.message:String(i);throw new Error(r.replace(/^Invalid Run state:/u,"Invalid Classic state:"),{cause:i})}return{classic:qp(t),run:n,unknownKeys:Object.keys(t).filter(i=>!Ap.has(i))}}Vn();var Lp=2*1024*1024;function Gn(t){let e=t.toJS();if(e===null)return{};if(typeof e!="object"||Array.isArray(e))throw new Error("Invalid Classic state document: root must be a mapping");return e}function Dp(t){let e=["skill","skill_version","skill_hash","orchestration","current_step","iteration","pending","pending_ref","trajectory_ref","context_ref","artifacts_ref","checkpoint_ref","run_status","run_retries"];for(let n of e)t.delete(n)}function Mp(t){let e=!1;for(let n of["build_command","verify_command"])t.has(n)&&(t.delete(n),e=!0);return e}async function Wp(t){let e;try{e=(await K(Zr.dirname(t),Zr.basename(t),Lp,{label:"Classic state document"})).bytes.toString("utf8")}catch(i){if(i.code!=="ENOENT")throw i;return new zn.Document({})}let n=(0,zn.parseDocument)(e);if(n.errors.length>0)throw new Error(`Invalid Classic state document: ${n.errors[0].message}`);return Gn(n),n}async function Oc(t,e={}){let n=e.migrate!==!1,i=Zr.join(t,".comet.yaml"),r=await Wp(i),s=Gn(r),o=Mp(r);o&&(s=Gn(r));let a=await Gr(t);if(!a&&s.run_id&&s.skill){let{runStateFromDocument:c}=await Promise.resolve().then(()=>(Vn(),_c));a=c(s),a&&n&&(await zr(t,a),Dp(r),o=!0)}return o&&n&&await Z(i,r.toString(),{containedRoot:t}),xc(Gn(r),a)}import Ic from"path";_e();de();X();import Nt from"path";var $p=2*1024*1024;function Ac(t,e,n){let i=Nt.resolve(t),r=Nt.isAbsolute(e)?Nt.resolve(e):Nt.resolve(i,e),s=Nt.relative(i,r).replaceAll("\\","/");return{root:i,relative:bt(s,n),target:r}}async function $e(t,e,n){let i=Ac(t,e,n.label);return $(i.root,i.relative,n)}async function xt(t,e,n){return(await $e(t,e,{label:n.label,expected:n.expected??"any"})).exists}async function Rc(t,e,n){return(await Fp(t,e,n)).toString("utf8")}async function Fp(t,e,n){let i=Ac(t,e,n.label);return(await K(i.root,i.relative,n.maxBytes??$p,{label:n.label,hooks:n.hooks})).bytes}function es(t){return t?/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t)?t.includes("..")?"Change name cannot contain '..' (path traversal not allowed)":null:`Invalid change name: '${t}' -Valid format: lowercase kebab-case (a-z, 0-9, single hyphens)`:"Change name cannot be empty"}function Bp(t){let e=es(t);if(e)throw new Error(e)}function Kp(t,e){return{label:ee(t,e),directory:e}}async function Yp(t,e,n){let i=Kp(t,e);if(!(await $e(t,e,{label:n,expected:"directory"})).exists)return{change:i,exists:!1,stateExists:!1};let s=await $e(t,Ic.join(e,".comet.yaml"),{label:`${n} state`,expected:"file"});return{change:i,exists:!0,stateExists:s.exists}}async function Tc(t,e=process.cwd()){Bp(t);let n=await Kn(e),i=await Yp(n.projectRoot,Ic.join(n.changesDir,t),`Classic active change ${t}`);return{...i.change,exists:i.exists,stateExists:i.stateExists}}var Fe="comet.resume_probe.v1";function jc(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Jp(t){if(!jc(t))throw new Error("Invalid CometResumeProbeInput: input must be an object");if(t.schema_version!==Fe)throw new Error(`Invalid CometResumeProbeInput: schema_version must be ${Fe}`);if(typeof t.utterance!="string")throw new Error("Invalid CometResumeProbeInput: utterance must be a string");let e=jc(t.agent_context)?t.agent_context:{};return{schema_version:Fe,utterance:t.utterance,locale:typeof t.locale=="string"?t.locale:"unknown",agent_context:{non_trivial_work:e.non_trivial_work===!0,already_in_comet_flow:e.already_in_comet_flow===!0}}}function F(t,e,n,i,r=[]){return{schema_version:Fe,action:t,changeName:e?.name??null,phase:e?.phase??null,nextCommand:t==="auto_resume"||t==="ask_user"?e?.nextCommand??null:null,confidence:n,reason:i,evidence:r}}async function Vp(t,e,n){return await xt(t,e,{label:n,expected:"file"})?Rc(t,e,{label:n}):""}async function qc(t,e,n){let i=["proposal.md","design.md","tasks.md"],r=[n.name,n.workflow,n.phase];for(let s of i)r.push(await Vp(t,`${e}/${s}`,`Classic change ${n.name} ${s}`));return r.join(` -`).toLowerCase()}function Hp(t){switch(t){case"open":return"/comet-open";case"design":return"/comet-design";case"build":return"/comet-build";case"verify":return"/comet-verify";case"archive":return"/comet-archive";default:return null}}function Gp(t,e,n){let i=n.classic,r=n.unknownKeys.filter(s=>s!=="run_id");return i?r.length>0?{name:e,valid:!1,workflow:i.workflow,phase:i.phase,currentStep:null,nextCommand:null,runtimeMode:"invalid",runtimeEval:null,evidence:[],error:`unknown field(s): ${r.join(", ")}`}:{name:e,valid:!0,workflow:i.workflow,phase:i.phase,currentStep:null,nextCommand:Hp(i.phase),runtimeMode:"engine-projection",runtimeEval:null,evidence:[]}:{name:e,valid:!1,workflow:"unknown",phase:"invalid",currentStep:null,nextCommand:null,runtimeMode:"invalid",runtimeEval:null,evidence:[],error:`${t} does not contain valid Comet state`}}async function zp(t,e){return await xt(t,`${e}/proposal.md`,{label:"Classic proposal",expected:"file"})||await xt(t,`${e}/design.md`,{label:"Classic design",expected:"file"})||await xt(t,`${e}/tasks.md`,{label:"Classic tasks",expected:"file"})}async function Qp(t){let e=(await Kn(t)).changesDir;if(!(await $e(t,e,{label:"Classic changes directory",expected:"directory"})).exists)return[];let i=await ss(e),r=[];for(let s of i){if(s==="archive"||es(s))continue;let o=await Tc(s,t);if(!o.exists)continue;let a=o.directory;if(!o.stateExists){if(!await zp(t,a))continue;let p={name:s,workflow:"unknown",phase:"invalid",nextCommand:null,diagnostic:{name:s,valid:!1,workflow:"unknown",phase:"invalid",currentStep:null,nextCommand:null,runtimeMode:"invalid",runtimeEval:null,evidence:[],error:"missing Comet state"},buildPause:null,hasClassicProjection:!1,verifyResult:null,text:"",missingCometState:!0};p.text=await qc(t,a,p),r.push(p);continue}let l=await Oc(a,{migrate:!1}),m=l.classic,u=Gp(a,s,l),f=!!m,h=m?.phase??u.phase,w=m?.workflow??u.workflow;if(h==="archive"||m?.archived)continue;let d={name:s,workflow:w,phase:h,nextCommand:u.nextCommand,diagnostic:u,buildPause:m?.buildPause??null,hasClassicProjection:f,verifyResult:m?.verifyResult??null,text:"",missingCometState:!1};d.text=await qc(t,a,d),r.push(d)}return r}var Xp=["continue","resume","carry on","finish","run it","commit","verify","archive","继续","接着","恢复","跑完","提交","验证","归档","修刚才"],Zp=["what","why","how","explain","summarize","reliable","靠谱吗","是什么","为什么","解释","总结","取名","命名"],eh=new Set(["add","build","cache","change","code","design","docs","file","fix","implement","plan","readme","task","test","update","修改","更新","修复","添加","文档","任务","计划","实现"]),th=["do not resume","don't resume","without comet","skip comet","不要恢复","不走 comet","不要走 comet","直接解释","只回答"];function ts(t,e){return e.some(n=>t.includes(n))}function Lc(t){return t.missingCometState||!t.hasClassicProjection||!t.diagnostic.valid||t.phase==="archive"||t.verifyResult==="fail"||t.diagnostic.runtimeEval&&!t.diagnostic.runtimeEval.passed?!0:t.phase!=="build"?!1:t.buildPause==="plan-ready"}function nh(t,e){let n=t.toLowerCase(),i=[];n.includes(e.name.toLowerCase())&&i.push({source:"user",quote:e.name});let r=e.text.split(/[^a-zA-Z0-9_\-\u4e00-\u9fff/]+/u).map(o=>o.trim().toLowerCase()).filter(o=>o.length>=4&&!eh.has(o)),s=[...new Set(r.filter(o=>n.includes(o)))].slice(0,3);for(let o of s)i.push({source:"repo",quote:o});return i}async function ih(t){return new Promise(e=>{let n=Up("git",["status","--short","--untracked-files=all"],{cwd:t,stdio:["ignore","pipe","ignore"],shell:!1}),i=[];n.stdout.on("data",r=>{i.push(Buffer.isBuffer(r)?r:Buffer.from(String(r)))}),n.on("error",()=>e([])),n.on("exit",r=>{if(r!==0){e([]);return}let s=Buffer.concat(i).toString("utf8").split(/\r?\n/u).map(o=>o.trim()).filter(Boolean);e(s)})})}async function Dc(t,e){let n=Jp(e),i=n.utterance.trim(),r=i.toLowerCase();if(n.agent_context.already_in_comet_flow)return F("out_of_scope",null,"low","already in Comet flow");if(ts(r,th))return F("out_of_scope",null,"low","user opted out of Comet resume",[{source:"user",quote:i}]);let s=await Qp(t);if(s.length===0)return F("none",null,"none","no active Comet changes");let o=await ih(t);if(s.length>1){let u=s.find(f=>r.includes(f.name.toLowerCase()));return u?o.length>0?F("ask_user",u,"low","uncommitted worktree changes require attribution",[{source:"repo",quote:`${o.length} dirty file(s)`}]):Lc(u)?F("ask_user",u,"low","active change is at a decision point"):F("auto_resume",u,"high","request names an active change",[{source:"user",quote:u.name}]):F("ask_user",null,"low","multiple active changes require a change name")}let[a]=s;if(o.length>0)return F("ask_user",a,"low","uncommitted worktree changes require attribution",[{source:"repo",quote:`${o.length} dirty file(s)`}]);if(Lc(a))return a.missingCometState?F("ask_user",a,"low","active OpenSpec change is missing Comet state"):F("ask_user",a,"low","active change is at a decision point",[{source:"state",quote:`phase: ${a.phase}`}]);let c=ts(r,Xp);if(!n.agent_context.non_trivial_work&&ts(r,Zp)&&!c)return F("out_of_scope",a,"low","user asked a question without workflow work");let m=nh(i,a);return c||m.length>0?F("auto_resume",a,"high","single active change and request is related",[{source:"state",quote:`phase: ${a.phase}`},...m]):n.agent_context.non_trivial_work?F("ask_user",a,"low","single active change exists but request looks unrelated"):F("out_of_scope",a,"low","request is not workflow work")}import{AsyncLocalStorage as rh}from"async_hooks";import{promises as Mc}from"fs";import Ot from"path";var ns=new rh;function sh(t,e){let n=Ot.relative(t,e);return n===""||!Ot.isAbsolute(n)&&n!==".."&&!n.startsWith(`..${Ot.sep}`)}async function oh(t){let e=Ot.resolve(t.invocationCwd??process.cwd()),n=Ot.resolve(t.projectRoot??await uc(e)),[i,r]=await Promise.all([Mc.realpath(e),Mc.realpath(n)]);if(!sh(r,i))throw new Error(`Classic command invocation cwd is outside the discovered project: ${e}`);return{invocationCwd:e,projectRoot:n}}async function Wc(t,e){let n=ns.getStore();if(n)return e(n);let i=await oh(t);return ns.run(i,()=>e(i))}function $c(){let t=ns.getStore();if(!t)throw new Error("Classic command project context is unavailable");return t.projectRoot}function Qn(t,e,n){return{exitCode:t,...e===void 0?{}:{stdout:e},...n===void 0?{}:{stderr:n}}}function Fc(){return Qn(64,void 0,`Usage: comet-resume-probe.mjs probe -Usage: comet-resume-probe.mjs probe --stdin`)}async function ah(){let t=[];for await(let e of process.stdin)t.push(Buffer.isBuffer(e)?e:Buffer.from(String(e)));return Buffer.concat(t).toString("utf8")}function ch(t){return{schema_version:Fe,utterance:t,locale:"unknown",agent_context:{non_trivial_work:!0,already_in_comet_flow:!1}}}function lh(t){try{return JSON.parse(t)}catch{return ch(t)}}var Bc=async(t,e)=>Wc(e,async()=>{let[n,i]=t;if(n!=="probe")return Fc();let r=i==="--stdin",s=r?await ah():i;if(!s)return Fc();try{let o=r?lh(s):JSON.parse(s),a=await Dc($c(),o);return Qn(0,`${JSON.stringify(a,null,2)} +`,n)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let n=Nn(e),i=qe(n);return i.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let n=Nn(e),i=qe(n);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,n){return this.type!=="comment"||this.indent<=n?!1:e.every(i=>i.type==="newline"||i.type==="space")}*documentEnd(e){this.type!=="doc-mode"&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};Fa.Parser=Ir});var Ja=g(wt=>{"use strict";var Ba=vr(),cm=ct(),gt=ft(),lm=wi(),um=E(),fm=Rr(),Ka=Tr();function Ya(t){let e=t.prettyErrors!==!1;return{lineCounter:t.lineCounter||e&&new fm.LineCounter||null,prettyErrors:e}}function dm(t,e={}){let{lineCounter:n,prettyErrors:i}=Ya(e),r=new Ka.Parser(n?.addNewLine),s=new Ba.Composer(e),o=Array.from(s.compose(r.parse(t)));if(i&&n)for(let a of o)a.errors.forEach(gt.prettifyError(t,n)),a.warnings.forEach(gt.prettifyError(t,n));return o.length>0?o:Object.assign([],{empty:!0},s.streamInfo())}function Ua(t,e={}){let{lineCounter:n,prettyErrors:i}=Ya(e),r=new Ka.Parser(n?.addNewLine),s=new Ba.Composer(e),o=null;for(let a of s.compose(r.parse(t),!0,t.length))if(!o)o=a;else if(o.options.logLevel!=="silent"){o.errors.push(new gt.YAMLParseError(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return i&&n&&(o.errors.forEach(gt.prettifyError(t,n)),o.warnings.forEach(gt.prettifyError(t,n))),o}function mm(t,e,n){let i;typeof e=="function"?i=e:n===void 0&&e&&typeof e=="object"&&(n=e);let r=Ua(t,n);if(!r)return null;if(r.warnings.forEach(s=>lm.warn(r.options.logLevel,s)),r.errors.length>0){if(r.options.logLevel!=="silent")throw r.errors[0];r.errors=[]}return r.toJS(Object.assign({reviver:i},n))}function pm(t,e,n){let i=null;if(typeof e=="function"||Array.isArray(e)?i=e:n===void 0&&e&&(n=e),typeof n=="string"&&(n=n.length),typeof n=="number"){let r=Math.round(n);n=r<1?void 0:r>8?{indent:8}:{indent:r}}if(t===void 0){let{keepUndefined:r}=n??e??{};if(!r)return}return um.isDocument(t)&&!i?t.toString(n):new cm.Document(t,i,n).toString(n)}wt.parse=mm;wt.parseAllDocuments=dm;wt.parseDocument=Ua;wt.stringify=pm});var An=g(P=>{"use strict";var hm=vr(),gm=ct(),wm=Zi(),jr=ft(),ym=Je(),ue=E(),vm=se(),bm=x(),km=ae(),Sm=ce(),Cm=En(),_m=Or(),Em=Rr(),Pm=Tr(),On=Ja(),Va=Be();P.Composer=hm.Composer;P.Document=gm.Document;P.Schema=wm.Schema;P.YAMLError=jr.YAMLError;P.YAMLParseError=jr.YAMLParseError;P.YAMLWarning=jr.YAMLWarning;P.Alias=ym.Alias;P.isAlias=ue.isAlias;P.isCollection=ue.isCollection;P.isDocument=ue.isDocument;P.isMap=ue.isMap;P.isNode=ue.isNode;P.isPair=ue.isPair;P.isScalar=ue.isScalar;P.isSeq=ue.isSeq;P.Pair=vm.Pair;P.Scalar=bm.Scalar;P.YAMLMap=km.YAMLMap;P.YAMLSeq=Sm.YAMLSeq;P.CST=Cm;P.Lexer=_m.Lexer;P.LineCounter=Em.LineCounter;P.Parser=Pm.Parser;P.parse=On.parse;P.parseAllDocuments=On.parseAllDocuments;P.parseDocument=On.parseDocument;P.stringify=On.stringify;P.visit=Va.visit;P.visitAsync=Va.visitAsync});import Rn from"path";function Om(t,e){if(typeof t!="string")throw new Error(`${e} must be a string`);let n=t.trim();if(n.length===0||Rn.posix.isAbsolute(n)||Rn.win32.isAbsolute(n)||/^(?:~|[\\/])/u.test(n))throw new Error(`${e} must be a project-relative path`);if(n===".")return[];let i=n.replaceAll("\\","/").split("/");if(i.some(r=>r===".."))throw new Error(`${e} must stay inside the project root`);if(i.some(r=>r===""||r==="."))throw new Error(`${e} must not contain empty or dot path segments`);return i}function In(t){let e=Om(t,"native.artifact_root");return e.length===0?".":e.join("/")}function Ga(t,e="docs"){let n=t??e;if(n!=="legacy"&&n!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return n}function bt(t,e,n=!1){if(typeof t!="string")throw new Error(`${e} must be a string`);let i=t.trim().replaceAll("\\","/");if(i.length===0||Rn.posix.isAbsolute(i)||Rn.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${e} must be relative to its declared path base`);let r=i.split("/");if(r.some(s=>s===".."))throw new Error(`${e} must stay inside its declared path base`);if(r.some(s=>s===""||s==="."))throw new Error(`${e} must not contain empty or dot path segments`);if(!n&&/[*?]/u.test(i))throw new Error(`${e} cannot contain wildcards`);return r.join("/")}function yt(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function za(t,e,n){let i=t??e;if(i!=="en"&&i!=="zh-CN")throw new Error(`${n} must be en or zh-CN`);return i}function Qa(t,e){if(typeof t!="string"||t.length===0||t.includes("\\")||t.includes("\0")||t.startsWith("/")||t.split("/").includes(".."))throw new Error(`${e} contains an unsafe pattern`);if(t.length>Lr)throw new Error(`${e} exceeds ${Lr} characters`);let n=0;for(let i=0;iDr)throw new Error(`${e} contains more than ${Dr} wildcard tokens`);return t}function Ha(t,e,n){if(t===void 0)return[...n];if(!Array.isArray(t))throw new Error(`${e} contains an unsafe pattern`);return[...new Set(t.map(i=>Qa(i,e)))].sort((i,r)=>i.localeCompare(r,"en"))}function qr(t,e,n){let i=t??e;if(!Number.isSafeInteger(i)||i<1)throw new Error(`${n} must be a positive integer`);return i}function Am(t){if(t===void 0)return{...z,include:[...z.include],exclude:[...z.exclude]};let e=yt(t,"native.snapshot");return{include:Ha(e.include,"native.snapshot.include",z.include),exclude:Ha(e.exclude,"native.snapshot.exclude",z.exclude),max_files:qr(e.max_files,z.max_files,"native.snapshot.max_files"),max_total_bytes:qr(e.max_total_bytes,z.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:qr(e.max_duration_ms,z.max_duration_ms,"native.snapshot.max_duration_ms")}}function Rm(t){if(t===void 0)return;let e=yt(t,"native.pending_root_move"),n=e.id,i=e.from_artifact_root,r=e.to_artifact_root,s=e.stage;if(typeof n!="string"||!/^[a-f0-9-]{8,}$/u.test(n))throw new Error("native.pending_root_move.id is invalid");if(typeof i!="string"||typeof r!="string")throw new Error("native.pending_root_move roots must be strings");if(s!=="copying"&&s!=="ready"&&s!=="switched")throw new Error("native.pending_root_move.stage is invalid");let o;if(e.cleanup!==void 0){let a=yt(e.cleanup,"native.pending_root_move.cleanup"),c=a.kind,l=a.state,m=a.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof m!="string"||!/^[a-f0-9]{64}$/u.test(m))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:m}}return{id:n,fromArtifactRoot:In(i),toArtifactRoot:In(r),stage:s,...o?{cleanup:o}:{}}}function Im(t,e={}){let n=yt(t,"native"),i=n.artifact_root??(e.allowMissingArtifactRoot?"docs":void 0);if(typeof i!="string")throw new Error("native.artifact_root must be a string");let r=n.clarification_mode??"sequential";if(r!=="sequential"&&r!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let s=n.archive_confirmation??"automatic";if(s!=="automatic"&&s!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=n.max_verify_failures??Nm;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let a=Rm(n.pending_root_move);return{artifact_root:In(i),language:za(n.language,"en","native.language"),clarification_mode:r,archive_confirmation:s,max_verify_failures:o,snapshot:Am(n.snapshot),...a?{pending_root_move:a}:{}}}function Tm(t){let e=yt(t,"classic"),n=e.context_compression??"off";if(n!=="off"&&n!=="beta")throw new Error("classic.context_compression must be off or beta");let i=e.review_mode??"standard";if(i!=="off"&&i!=="standard"&&i!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let r=e.auto_transition??!0;if(typeof r!="boolean")throw new Error("classic.auto_transition must be true or false");return{artifact_layout:Ga(e.artifact_layout),language:za(e.language,"zh-CN","classic.language"),context_compression:n,review_mode:i,auto_transition:r}}function jm(t){let e=t??!0;if(typeof e!="boolean")throw new Error("ambient_resume must be true or false");return e}function qm(t,e,n,i,r){let s=t.schema!==void 0;if(!(s||t.default_workflow!==void 0||t.workflows!==void 0||!r.allowPartialProject&&t.native!==void 0)||r.allowPartialProject&&!s)return null;if(t.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(t.default_workflow!=="native"&&t.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let a=t.workflows??[t.default_workflow];if(!Array.isArray(a)||a.length===0||a.some(l=>l!=="native"&&l!=="classic"))throw new Error("workflows must contain native and/or classic");let c=[...new Set(a)];if(!c.includes(t.default_workflow))throw new Error("workflows must include default_workflow");if(c.includes("native")&&!e)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:t.default_workflow,workflows:c,ambient_resume:i,...e?{native:e}:{},...n?{classic:n}:{}}}function Le(t,e={}){let n=(0,Mr.parseDocument)(t,{uniqueKeys:!0});if(n.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${n.errors[0].message}`);let i=n.toJS();if(i==null)return{value:{},config:null,ambient_resume:!0};if(typeof i!="object"||Array.isArray(i))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let r=i,s=jm(r.ambient_resume),o=r.native===void 0?void 0:Im(r.native,{allowMissingArtifactRoot:e.allowMissingNativeFields}),a=r.classic===void 0?void 0:Tm(r.classic),c=qm(r,o,a,s,{allowPartialProject:e.allowPartialProject??!1});return{value:r,config:c,ambient_resume:s,...o?{native:o}:{},...a?{classic:a}:{}}}var Mr,vt,Lr,Dr,Nm,xm,z,fe=L(()=>{"use strict";Mr=Zn(An(),1),vt=64*1024,Lr=1024,Dr=64,Nm=5,xm=[".agents/skills/**",".amazonq/skills/**",".augment/skills/**",".bob/skills/**",".claude/skills/**",".cline/skills/**",".codebuddy/skills/**",".continue/skills/**",".cospec/skills/**",".crush/skills/**",".cursor/skills/**",".factory/skills/**",".forge/skills/**",".gemini/skills/**",".github/skills/**",".iflow/skills/**",".junie/skills/**",".kilocode/skills/**",".kimi-code/skills/**",".kiro/skills/**",".lingma/skills/**",".mimocode/skills/**",".opencode/skills/**",".pi/skills/**",".qoder/skills/**",".qwen/skills/**",".roo/skills/**",".trae-cn/skills/**",".trae/skills/**",".windsurf/skills/**",".zcode/skills/**"],z={include:["**/*"],exclude:[...xm],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4}});function de(t){return t!==0&&t!==0n&&t!=="0"}function Tn(t,e){return de(t.dev)&&de(e.dev)&&de(t.ino)&&de(e.ino)}function Q(t,e){let n=de(t.dev)&&de(e.dev);if(n&&t.dev!==e.dev)return!1;let i=de(t.ino)&&de(e.ino);return i&&t.ino!==e.ino?!1:n&&i?!0:t.birthtime===e.birthtime}var jn=L(()=>{"use strict"});import{constants as qn,promises as Se}from"fs";function Wr(t){return"birthtimeNs"in t&&typeof t.birthtimeNs=="bigint"?t.birthtimeNs:t.birthtimeMs}function Xa(t){return"ctimeNs"in t&&typeof t.ctimeNs=="bigint"?t.ctimeNs:t.ctimeMs}function kt(t){return{dev:t.dev,ino:t.ino,birthtime:Wr(t)}}function Ln(t,e){let n=kt(t),i=kt(e);return Tn(n,i)?Q(n,i):Q(n,i)&&Wr(t)===Wr(e)&&Xa(t)===Xa(e)&&t.size===e.size}async function Za(t,e,n={}){if(!Number.isSafeInteger(e)||e<1)throw new Error("race-safe read byte limit must be a positive integer");let i=n.label??"file",r=n.bigint===!0,s=await Se.lstat(t,{bigint:r});if(!s.isFile()||s.isSymbolicLink())throw new me("not-regular-file",`${i} must be a regular file`);if(BigInt(s.size)>BigInt(e))throw new me("too-large",`${i} exceeds ${e} bytes`);let o=await Se.realpath(t);await n.verify?.("pre-open",{realPath:o,identity:kt(s)});let a=process.platform==="win32"?qn.O_RDONLY:qn.O_RDONLY|qn.O_NOFOLLOW|qn.O_NONBLOCK,c;try{c=await Se.open(t,a)}catch(l){throw l.code==="ELOOP"?new me("not-regular-file",`${i} must be a regular file`,{cause:l}):l}try{let[l,m,u]=await Promise.all([c.stat({bigint:r}),Se.lstat(t,{bigint:r}),Se.realpath(t)]);if(!l.isFile()||!m.isFile()||m.isSymbolicLink()||u!==o||!Ln(s,l)||!Ln(s,m))throw new me("changed",`${i} changed while opening`);await n.verify?.("post-open",{realPath:u,identity:kt(l)}),await n.hooks?.afterOpen?.();let f=[],h=0,w=Buffer.allocUnsafe(Math.min(64*1024,e+1));for(;;){let b=e+1-h,{bytesRead:k}=await c.read(w,0,Math.min(w.length,b),null);if(k===0)break;if(h+=k,h>e)throw new me("too-large",`${i} exceeds ${e} bytes`);f.push(Buffer.from(w.subarray(0,k)))}await n.hooks?.beforeFinalCheck?.();let[d,p,y]=await Promise.all([c.stat({bigint:r}),Se.lstat(t,{bigint:r}),Se.realpath(t)]);if(!p.isFile()||p.isSymbolicLink()||y!==o||!Ln(s,d)||!Ln(s,p))throw new me("changed",`${i} changed while reading`);return await n.verify?.("post-read",{realPath:y,identity:kt(d)}),{bytes:Buffer.concat(f,h),stat:d,realPath:y}}finally{await c.close()}}var me,ec=L(()=>{"use strict";jn();me=class extends Error{reason;constructor(e,n,i){super(n,i),this.name="RaceSafeReadError",this.reason=e}}});import{promises as Dn}from"fs";import pe from"path";function Lm(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}function $r(t,e){let n=pe.relative(t,e);return n===""||!pe.isAbsolute(n)&&n!==".."&&!n.startsWith(`..${pe.sep}`)}async function tc(t,e){let n=pe.resolve(t),i=await Dn.lstat(n);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${e} project root must be a real directory`);return Dn.realpath(n)}async function nc(t,e,n,i){let r=t;for(let s=0;s{if(!$r(s,a.realPath))throw new Error(`${i.label} resolves outside the project root`);await nc(r.projectRoot,s,r.relative.split("/"),{label:i.label,expected:"file"})}})}var X=L(()=>{"use strict";ec();fe()});import{createHash as Dm}from"crypto";function Mm(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function Mn(t,e={}){return(await Wn(t,e)).document}async function Wm(t){try{return(await K(t,St,vt,{label:St})).bytes}catch(e){if(Mm(e))return null;throw e}}function $m(t){return t?{exists:!0,sha256:Dm("sha256").update(t).digest("hex")}:{exists:!1,sha256:null}}async function Wn(t,e={}){let n=await Wm(t);return{document:n?Le(n.toString("utf8"),e):null,identity:$m(n)}}var St,Ct=L(()=>{"use strict";fe();X();St=".comet/config.yaml"});import{randomUUID as Fm}from"crypto";import{constants as Bm,promises as O}from"fs";import q from"path";async function Fr(t,e){try{return await O.link(t,e),{linked:!0}}catch(n){let i=n.code;if(i!=="ENOTSUP"&&i!=="EOPNOTSUPP")throw n}return await O.copyFile(t,e,Bm.COPYFILE_EXCL),{linked:!1}}function De(t,e){let n=q.relative(t,e);return n===""||!q.isAbsolute(n)&&n!==".."&&!n.startsWith(`..${q.sep}`)}function Fn(t){return{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs}}function Km(t,e){return Q(t,Fn(e))}function $n(t,e){let n=Fn(t),i=Fn(e);return Tn(n,i)?Q(n,i):Q(n,i)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.size===e.size}async function Bn(t){let e=await O.lstat(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Contained atomic write parent must be a real directory: ${t}`);return{path:t,realPath:await O.realpath(t),...Fn(e)}}async function he(t){for(let e of t){let n=await O.lstat(e.path);if(!n.isDirectory()||n.isSymbolicLink()||!Km(e,n)||await O.realpath(e.path)!==e.realPath)throw new Error(`Contained atomic write parent changed before commit: ${e.path}`)}}async function Ym(t,e){let n=q.resolve(t),i=q.resolve(e);if(!De(n,i))throw new Error(`Contained atomic write parent is outside its managed root: ${e}`);let r=[await Bn(n)],s=q.relative(n,i).split(q.sep).filter(Boolean),o=n;for(let a of s){await he(r),o=q.join(o,a);try{await O.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await Bn(o);if(!De(r[0].realPath,c.realPath))throw new Error(`Contained atomic write parent resolves outside its managed root: ${o}`);r.push(c)}return await he(r),r}async function Um(t,e){let n=q.resolve(t),i=q.resolve(e);if(!De(n,i))throw new Error(`Contained file parent is outside its managed root: ${e}`);let r=[await Bn(n)],s=q.relative(n,i).split(q.sep).filter(Boolean),o=n;for(let a of s){o=q.join(o,a);try{let c=await Bn(o);if(!De(r[0].realPath,c.realPath))throw new Error(`Contained file parent resolves outside its managed root: ${o}`);r.push(c)}catch(c){if(c.code==="ENOENT")return null;throw c}}return await he(r),r}async function ic(t){let e;try{e=await O.open(t,"r"),await e.sync()}catch(n){let i=n.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(i??""))throw n}finally{await e?.close()}}async function Jm(t,e,n){let i=q.dirname(t),r=await Ym(n.containedRoot,i),s=q.join(i,`.${q.basename(t)}.${Fm()}.tmp`),o,a;try{await n.beforeTemporaryOpen?.(),o=await O.open(s,"wx"),a=await o.stat();let[c,l]=await Promise.all([O.lstat(s),O.realpath(s)]);if(await he(r),!c.isFile()||c.isSymbolicLink()||!$n(a,c)||!De(r[0].realPath,l))throw new Error("Contained atomic write temporary file opened outside its managed parent");if(typeof e=="string"?await o.writeFile(e,"utf8"):await o.writeFile(e),await o.sync(),!$n(a,await o.stat()))throw new Error("Contained atomic write temporary file changed while writing");await o.close(),o=void 0,await n.beforeCommit?.(),await he(r);let m=await O.lstat(s);if(!m.isFile()||m.isSymbolicLink()||!$n(m,a))throw new Error("Contained atomic write temporary file changed before commit");n.exclusive?(await Fr(s,t),await O.unlink(s)):await O.rename(s,t),await ic(i)}catch(c){await o?.close();try{await he(r),await O.rm(s,{force:!0})}catch{}throw c}}async function Z(t,e,n){await Jm(t,e,n)}async function Br(t,e){let n=q.dirname(t),i=await Um(e.containedRoot,n);if(!i)return!1;let r,s;try{r=await O.lstat(t),s=await O.realpath(t)}catch(c){if(c.code==="ENOENT")return!1;throw c}if(!r.isFile()||r.isSymbolicLink()||!De(i[0].realPath,s))throw new Error("Contained file removal target must be a regular file inside its managed root");await e.beforeRemove?.(),await he(i);let[o,a]=await Promise.all([O.lstat(t),O.realpath(t)]);if(!o.isFile()||o.isSymbolicLink()||!$n(r,o)||a!==s)throw new Error("Contained file removal target changed before removal");return await O.unlink(t),await he(i),await ic(n),!0}var Ce=L(()=>{"use strict";jn()});var tw,Kr=L(()=>{"use strict";Ce();Ct();X();tw=16*1024});var Ur=L(()=>{"use strict";Ce();fe();Ct();X();Kr()});var Yn=L(()=>{"use strict"});var dc=L(()=>{"use strict"});var Jr=L(()=>{"use strict";Yn()});var mc=L(()=>{"use strict";Yn();Jr()});var cp,pc=L(()=>{"use strict";cp=Zn(An(),1);Ce();fe();X()});var hc=L(()=>{"use strict";Yn();Ce();dc();mc();fe();pc();X();Ct();Ur();Kr();Jr()});import{TextDecoder as up}from"util";function gc(t){return{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs}}function fp(t,e){try{return new up("utf-8",{fatal:!0}).decode(t.bytes)}catch(n){throw new Error(`${e} is not valid UTF-8`,{cause:n})}}async function Vr(t,e,n,i,r={}){try{let s=await K(t,e,n,{label:i,hooks:r.hooks});return{result:s,text:fp(s,i)}}catch(s){let o=s.code;if(o==="ENOENT"||o==="ENOTDIR")return null;throw s}}async function wc(t,e,n,i,r={}){return(await Vr(t,e,n,i,r))?.text??null}async function yc(t,e,n,i,r,s={}){if(Buffer.byteLength(n,"utf8")>i)throw new Error(`${r} exceeds ${i} bytes`);let o=await Vr(t,e,i,r),a=await F(t,e,{label:r,expected:"file"});await Z(a.target,n,{containedRoot:a.projectRoot,beforeCommit:async()=>{await s.beforeCommit?.();let c=await Vr(t,e,i,r);if(!(!o&&!c)){if(!o||!c)throw new Error(`${r} changed before commit`);if(o.result.realPath!==c.result.realPath||!Q(gc(o.result.stat),gc(c.result.stat))||o.text!==c.text)throw new Error(`${r} changed before commit`)}}})}async function vc(t,e,n,i={}){let r=await F(t,e,{label:n,expected:"file"});return r.exists?Br(r.target,{containedRoot:r.projectRoot,beforeRemove:i.beforeRemove}):!1}var bc=L(()=>{"use strict";hc();jn()});var Ec={};zc(Ec,{RUN_STATE_FILE:()=>Jn,applyRunStateToDocument:()=>Sc,readRunState:()=>Hr,removeRunState:()=>_c,runStateFromDocument:()=>Un,writeRunState:()=>Gr});import dp from"path";function Pt(t,e){let n=t[e];if(typeof n!="string"||n.length===0)throw new Error(`Invalid Run state: ${e} must be a non-empty string`);return n}function Et(t,e){let n=Pt(t,e);if(dp.isAbsolute(n)||/^(?:[A-Za-z]:|[\\/]|~)/u.test(n)||n.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Run state: ${e} must stay inside the change directory`);return n}function mp(t){let e=t.run_retries??"{}",n;try{n=typeof e=="string"?JSON.parse(e):e}catch(i){throw new Error("Invalid Run state: run_retries must be a JSON object",{cause:i})}if(!n||typeof n!="object"||Array.isArray(n))throw new Error("Invalid Run state: run_retries must be a JSON object");for(let i of Object.values(n))if(!Number.isInteger(i)||Number(i)<0)throw new Error("Invalid Run state: retry counts must be non-negative integers");return n}function Un(t){if(!t.run_id)return null;let e=Pt(t,"run_id"),n=Pt(t,"skill"),i=Pt(t,"skill_version"),r=Pt(t,"skill_hash"),s=Et(t,"pending_ref"),o=Et(t,"trajectory_ref"),a=Et(t,"context_ref"),c=Et(t,"artifacts_ref"),l=Et(t,"checkpoint_ref"),m=Number(t.iteration);if(!Number.isInteger(m)||m<0)throw new Error("Invalid Run state: iteration must be a non-negative integer");if(t.orchestration!=="deterministic"&&t.orchestration!=="adaptive")throw new Error("Invalid Run state: orchestration must be deterministic or adaptive");if(t.run_status!=="running"&&t.run_status!=="waiting"&&t.run_status!=="completed"&&t.run_status!=="failed")throw new Error("Invalid Run state: run_status is invalid");return{runId:e,skill:n,skillVersion:i,skillHash:r,orchestration:t.orchestration,currentStep:kc(t,"current_step"),iteration:m,pending:kc(t,"pending"),pendingRef:s,trajectoryRef:o,contextRef:a,artifactsRef:c,checkpointRef:l,status:t.run_status,retries:mp(t)}}function Sc(t,e){e?t.run_id=e.runId:delete t.run_id}function pp(t){return{runId:t.runId,skill:t.skill,skillVersion:t.skillVersion,skillHash:t.skillHash,orchestration:t.orchestration,currentStep:t.currentStep,iteration:t.iteration,pending:t.pending,pendingRef:t.pendingRef,trajectoryRef:t.trajectoryRef,contextRef:t.contextRef,artifactsRef:t.artifactsRef,checkpointRef:t.checkpointRef,status:t.status,retries:t.retries}}function hp(t){let e={run_id:t.runId,skill:t.skill,skill_version:t.skillVersion,skill_hash:t.skillHash,orchestration:t.orchestration,current_step:t.currentStep,iteration:t.iteration,pending:t.pending,pending_ref:t.pendingRef,trajectory_ref:t.trajectoryRef,context_ref:t.contextRef,artifacts_ref:t.artifactsRef,checkpoint_ref:t.checkpointRef,run_status:t.status,run_retries:JSON.stringify(t.retries)};return Un(e)}async function Hr(t,e={}){let n=await wc(t,Jn,Cc,"Run state",e);if(n===null)return null;let i=JSON.parse(n);return hp(i)}async function Gr(t,e,n={}){await yc(t,Jn,JSON.stringify(pp(e),null,2),Cc,"Run state",n)}async function _c(t,e={}){await vc(t,Jn,"Run state",e)}var kc,Jn,Cc,Vn=L(()=>{"use strict";bc();kc=(t,e)=>{let n=t[e];return n==null?null:String(n)};Jn=".comet/run-state.json",Cc=256*1024});import{promises as ac}from"fs";import A from"path";import{promises as is}from"fs";async function ei(t){try{return await is.access(t),!0}catch(e){if(Xc(e))return!1;throw e}}async function rs(t){try{return await is.readdir(t)}catch(e){let n=e?.code;if(n==="ENOENT"||n==="ENOTDIR")return[];throw e}}function Xc(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}fe();Ct();Ur();X();var _t=class extends Error{code="classic-layout-unavailable";constructor(e="Classic artifact layout is unavailable from .comet/config.yaml"){super(e),this.name="ClassicLayoutUnavailableError"}},oc=".comet/config.yaml";function cc(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function lc(t){await F(t,oc,{label:oc,expected:"file"})}function uc(t,e){let n=A.resolve(t),i=e==="docs"?A.join(n,"docs"):n,r=A.join(i,"openspec"),s=A.join(n,"docs","superpowers");return{projectRoot:n,artifactLayout:e,openSpecBase:i,openSpecRoot:r,changesDir:A.join(r,"changes"),archiveDir:A.join(r,"changes","archive"),specsDir:A.join(r,"specs"),superpowersRoot:s,superpowersSpecsDir:A.join(s,"specs"),superpowersPlansDir:A.join(s,"plans"),superpowersReportsDir:A.join(s,"reports")}}async function Qm(t){await lc(t);let e=await Mn(t,{allowPartialProject:!0,allowMissingNativeFields:!0});if(!e?.config)throw new _t;if(!(e.config.workflows??[e.config.default_workflow]).includes("classic"))throw new _t("Classic artifact layout is unavailable because Classic is not enabled");return e.classic?.artifact_layout??"legacy"}async function Xm(t,e){return uc(t,e??await Qm(t))}async function Zm(t){try{return await ac.lstat(t),!0}catch(e){if(cc(e))return!1;throw e}}async function ep(t,e){let n=await Xm(t,e),i=n.artifactLayout==="legacy"?"docs":"legacy",r=uc(t,i).openSpecRoot,[s,o]=await Promise.all([F(n.projectRoot,Me(n.projectRoot,n.openSpecRoot),{label:"Configured Classic OpenSpec root",expected:"directory"}),Zm(r)]),a=s.exists;return{paths:n,configuredRootExists:a,alternateRoot:r,alternateRootExists:o,dualRoots:a&&o}}async function tp(t){let e=[t.openSpecRoot,t.changesDir,t.archiveDir,t.specsDir,t.superpowersRoot,t.superpowersSpecsDir,t.superpowersPlansDir,t.superpowersReportsDir];for(let n of e){let i=Me(t.projectRoot,n);await F(t.projectRoot,i,{label:`Classic managed physical path ${i}`,expected:"directory"})}}async function Kn(t,e){let n=await ep(t,e);if(await tp(n.paths),!n.configuredRootExists){let i=Me(n.paths.projectRoot,n.paths.openSpecRoot),r=Me(n.paths.projectRoot,n.alternateRoot);throw new _t(`Configured Classic OpenSpec root is missing: ${i} (alternate ${r} is ${n.alternateRootExists?"present":"missing"})`)}return n.paths}async function fc(t){let e=A.resolve(t),n=null;try{(await ac.lstat(e)).isDirectory()||(e=A.dirname(e))}catch(i){if(!cc(i))throw i}for(;;){A.basename(e)==="openspec"&&(n=A.dirname(e));let i=A.join(e,".comet","config.yaml"),r=!1;if(await ei(i))try{await lc(e);let o=(await Mn(e))?.value;r=!!o&&typeof o=="object"&&!Array.isArray(o)&&(o.schema==="comet.project.v1"||o.default_workflow!==void 0||o.native!==void 0)}catch{}if(r||await ei(A.join(e,".git")))return e;let s=A.dirname(e);if(s===e)return n??A.resolve(t);e=s}}function Me(t,e){return A.relative(A.resolve(t),e).replaceAll("\\","/")}import{spawn as Up}from"child_process";var zn=Zn(An(),1);Ce();X();import Xr from"path";Vn();var Pc=["full","hotfix","tweak"],Nc=1,gp=["open","design","build","verify","archive"],wp=["en","zh-CN"],yp=["off","beta"],vp=["subagent-driven-development","executing-plans","direct"],bp=["plan-ready"],kp=["confirmed"],Sp=["tdd","direct"],Cp=["off","standard","thorough"],_p=["current","branch","worktree"],Ep=["light","full"],Pp=["pending","pass","fail"],Np=["pending","handled"],xp=["pending","confirmed"],Qr=["workflow","language","phase","context_compression","build_mode","build_pause","subagent_dispatch","tdd_mode","review_mode","isolation","bound_branch","verify_mode","auto_transition","base_ref","design_doc","plan","verify_result","verify_failures","verification_report","branch_status","created_at","verified_at","archive_confirmation","archived","direct_override","handoff_context","handoff_hash","classic_profile","classic_migration"],Op=["run_id"],Ap=new Set([...Qr,...Op]),Rp=["workflow","phase","design_doc","plan","build_mode","isolation","verify_mode","verify_result","verified_at","archived"];function xc(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function We(t,e){let n=t[e];if(n==null||n==="")return null;if(typeof n!="string")throw new Error(`Invalid Classic state: ${e} must be a string or null`);return n}function D(t,e,n,i=!0){let r=t[e];if(r==null||r===""){if(i)return null;throw new Error(`Invalid Classic state: ${e} is required`)}if(typeof r!="string"||!n.includes(r))throw new Error(`Invalid Classic state: ${e} must be one of ${n.join(", ")}${i?" or null":""}`);return r}function zr(t,e,n=!0){let i=t[e];if(i==null||i===""){if(n)return null;throw new Error(`Invalid Classic state: ${e} is required`)}if(typeof i!="boolean")throw new Error(`Invalid Classic state: ${e} must be true or false`);return i}function Ip(t,e,n=0){let i=t[e];if(i==null||i==="")return n;if(typeof i!="number"||!Number.isInteger(i)||i<0)throw new Error(`Invalid Classic state: ${e} must be a non-negative integer`);return i}function Hn(t,e){let n=We(t,e);if(n===null)return null;if(/^(?:[A-Za-z]:|[\\/]|~)/u.test(n)||n.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Classic state: ${e} must be a relative repository path`);return n}function Tp(t,e){let n=We(t,e);if(n!==null&&!/^[a-f0-9]{64}$/u.test(n))throw new Error(`Invalid Classic state: ${e} must be a sha256 hex digest`);return n}function jp(t){let e=t.classic_migration;if(e==null||e==="")return null;if(e!==Nc)throw new Error(`Invalid Classic state: classic_migration must be ${Nc}`);return e}function qp(t){if(!Qr.some(n=>xc(t,n)))return null;for(let n of Rp)if(!xc(t,n))return null;return{workflow:D(t,"workflow",Pc,!1),language:D(t,"language",wp),phase:D(t,"phase",gp,!1),contextCompression:D(t,"context_compression",yp),buildMode:D(t,"build_mode",vp),buildPause:D(t,"build_pause",bp),subagentDispatch:D(t,"subagent_dispatch",kp),tddMode:D(t,"tdd_mode",Sp),reviewMode:D(t,"review_mode",Cp),isolation:D(t,"isolation",_p),boundBranch:We(t,"bound_branch"),verifyMode:D(t,"verify_mode",Ep),autoTransition:zr(t,"auto_transition"),baseRef:We(t,"base_ref"),designDoc:Hn(t,"design_doc"),plan:Hn(t,"plan"),verifyResult:D(t,"verify_result",Pp,!1),verifyFailures:Ip(t,"verify_failures"),verificationReport:Hn(t,"verification_report"),branchStatus:D(t,"branch_status",Np),createdAt:We(t,"created_at"),verifiedAt:We(t,"verified_at"),archiveConfirmation:D(t,"archive_confirmation",xp),archived:zr(t,"archived",!1),directOverride:zr(t,"direct_override"),handoffContext:Hn(t,"handoff_context"),handoffHash:Tp(t,"handoff_hash"),classicProfile:D(t,"classic_profile",Pc),classicMigration:jp(t)}}function Oc(t,e){let n=e??null;if(n===null&&e===void 0&&t.run_id&&t.skill)try{n=Un(t)}catch(i){let r=i instanceof Error?i.message:String(i);throw new Error(r.replace(/^Invalid Run state:/u,"Invalid Classic state:"),{cause:i})}return{classic:qp(t),run:n,unknownKeys:Object.keys(t).filter(i=>!Ap.has(i))}}Vn();var Lp=2*1024*1024;function Gn(t){let e=t.toJS();if(e===null)return{};if(typeof e!="object"||Array.isArray(e))throw new Error("Invalid Classic state document: root must be a mapping");return e}function Dp(t){let e=["skill","skill_version","skill_hash","orchestration","current_step","iteration","pending","pending_ref","trajectory_ref","context_ref","artifacts_ref","checkpoint_ref","run_status","run_retries"];for(let n of e)t.delete(n)}function Mp(t){let e=!1;for(let n of["build_command","verify_command"])t.has(n)&&(t.delete(n),e=!0);return e}async function Wp(t){let e;try{e=(await K(Xr.dirname(t),Xr.basename(t),Lp,{label:"Classic state document"})).bytes.toString("utf8")}catch(i){if(i.code!=="ENOENT")throw i;return new zn.Document({})}let n=(0,zn.parseDocument)(e);if(n.errors.length>0)throw new Error(`Invalid Classic state document: ${n.errors[0].message}`);return Gn(n),n}async function Ac(t,e={}){let n=e.migrate!==!1,i=Xr.join(t,".comet.yaml"),r=await Wp(i),s=Gn(r),o=Mp(r);o&&(s=Gn(r));let a=await Hr(t);if(!a&&s.run_id&&s.skill){let{runStateFromDocument:c}=await Promise.resolve().then(()=>(Vn(),Ec));a=c(s),a&&n&&(await Gr(t,a),Dp(r),o=!0)}return o&&n&&await Z(i,r.toString(),{containedRoot:t}),Oc(Gn(r),a)}import Tc from"path";Ce();fe();X();import Nt from"path";var $p=2*1024*1024;function Rc(t,e,n){let i=Nt.resolve(t),r=Nt.isAbsolute(e)?Nt.resolve(e):Nt.resolve(i,e),s=Nt.relative(i,r).replaceAll("\\","/");return{root:i,relative:bt(s,n),target:r}}async function $e(t,e,n){let i=Rc(t,e,n.label);return F(i.root,i.relative,n)}async function xt(t,e,n){return(await $e(t,e,{label:n.label,expected:n.expected??"any"})).exists}async function Ic(t,e,n){return(await Fp(t,e,n)).toString("utf8")}async function Fp(t,e,n){let i=Rc(t,e,n.label);return(await K(i.root,i.relative,n.maxBytes??$p,{label:n.label,hooks:n.hooks})).bytes}function Zr(t){return t?/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t)?t.includes("..")?"Change name cannot contain '..' (path traversal not allowed)":null:`Invalid change name: '${t}' +Valid format: lowercase kebab-case (a-z, 0-9, single hyphens)`:"Change name cannot be empty"}function Bp(t){let e=Zr(t);if(e)throw new Error(e)}function Kp(t,e){return{label:Me(t,e),directory:e}}async function Yp(t,e,n){let i=Kp(t,e);if(!(await $e(t,e,{label:n,expected:"directory"})).exists)return{change:i,exists:!1,stateExists:!1};let s=await $e(t,Tc.join(e,".comet.yaml"),{label:`${n} state`,expected:"file"});return{change:i,exists:!0,stateExists:s.exists}}async function jc(t,e=process.cwd()){Bp(t);let n=await Kn(e),i=await Yp(n.projectRoot,Tc.join(n.changesDir,t),`Classic active change ${t}`);return{...i.change,exists:i.exists,stateExists:i.stateExists}}var Fe="comet.resume_probe.v1";function qc(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Jp(t){if(!qc(t))throw new Error("Invalid CometResumeProbeInput: input must be an object");if(t.schema_version!==Fe)throw new Error(`Invalid CometResumeProbeInput: schema_version must be ${Fe}`);if(typeof t.utterance!="string")throw new Error("Invalid CometResumeProbeInput: utterance must be a string");let e=qc(t.agent_context)?t.agent_context:{};return{schema_version:Fe,utterance:t.utterance,locale:typeof t.locale=="string"?t.locale:"unknown",agent_context:{non_trivial_work:e.non_trivial_work===!0,already_in_comet_flow:e.already_in_comet_flow===!0}}}function $(t,e,n,i,r=[]){return{schema_version:Fe,action:t,changeName:e?.name??null,phase:e?.phase??null,nextCommand:t==="auto_resume"||t==="ask_user"?e?.nextCommand??null:null,confidence:n,reason:i,evidence:r}}async function Vp(t,e,n){return await xt(t,e,{label:n,expected:"file"})?Ic(t,e,{label:n}):""}async function Lc(t,e,n){let i=["proposal.md","design.md","tasks.md"],r=[n.name,n.workflow,n.phase];for(let s of i)r.push(await Vp(t,`${e}/${s}`,`Classic change ${n.name} ${s}`));return r.join(` +`).toLowerCase()}function Hp(t){switch(t){case"open":return"/comet-open";case"design":return"/comet-design";case"build":return"/comet-build";case"verify":return"/comet-verify";case"archive":return"/comet-archive";default:return null}}function Gp(t,e,n){let i=n.classic,r=n.unknownKeys.filter(s=>s!=="run_id");return i?r.length>0?{name:e,valid:!1,workflow:i.workflow,phase:i.phase,currentStep:null,nextCommand:null,runtimeMode:"invalid",runtimeEval:null,evidence:[],error:`unknown field(s): ${r.join(", ")}`}:{name:e,valid:!0,workflow:i.workflow,phase:i.phase,currentStep:null,nextCommand:Hp(i.phase),runtimeMode:"engine-projection",runtimeEval:null,evidence:[]}:{name:e,valid:!1,workflow:"unknown",phase:"invalid",currentStep:null,nextCommand:null,runtimeMode:"invalid",runtimeEval:null,evidence:[],error:`${t} does not contain valid Comet state`}}async function zp(t,e){return await xt(t,`${e}/proposal.md`,{label:"Classic proposal",expected:"file"})||await xt(t,`${e}/design.md`,{label:"Classic design",expected:"file"})||await xt(t,`${e}/tasks.md`,{label:"Classic tasks",expected:"file"})}async function Qp(t){let e=(await Kn(t)).changesDir;if(!(await $e(t,e,{label:"Classic changes directory",expected:"directory"})).exists)return[];let i=await rs(e),r=[];for(let s of i){if(s==="archive"||Zr(s))continue;let o=await jc(s,t);if(!o.exists)continue;let a=o.directory;if(!o.stateExists){if(!await zp(t,a))continue;let p={name:s,workflow:"unknown",phase:"invalid",nextCommand:null,diagnostic:{name:s,valid:!1,workflow:"unknown",phase:"invalid",currentStep:null,nextCommand:null,runtimeMode:"invalid",runtimeEval:null,evidence:[],error:"missing Comet state"},buildPause:null,hasClassicProjection:!1,verifyResult:null,text:"",missingCometState:!0};p.text=await Lc(t,a,p),r.push(p);continue}let l=await Ac(a,{migrate:!1}),m=l.classic,u=Gp(a,s,l),f=!!m,h=m?.phase??u.phase,w=m?.workflow??u.workflow;if(h==="archive"||m?.archived)continue;let d={name:s,workflow:w,phase:h,nextCommand:u.nextCommand,diagnostic:u,buildPause:m?.buildPause??null,hasClassicProjection:f,verifyResult:m?.verifyResult??null,text:"",missingCometState:!1};d.text=await Lc(t,a,d),r.push(d)}return r}var Xp=["continue","resume","carry on","finish","run it","commit","verify","archive","继续","接着","恢复","跑完","提交","验证","归档","修刚才"],Zp=["what","why","how","explain","summarize","reliable","靠谱吗","是什么","为什么","解释","总结","取名","命名"],eh=new Set(["add","build","cache","change","code","design","docs","file","fix","implement","plan","readme","task","test","update","修改","更新","修复","添加","文档","任务","计划","实现"]),th=["do not resume","don't resume","without comet","skip comet","不要恢复","不走 comet","不要走 comet","直接解释","只回答"];function es(t,e){return e.some(n=>t.includes(n))}function Dc(t){return t.missingCometState||!t.hasClassicProjection||!t.diagnostic.valid||t.phase==="archive"||t.verifyResult==="fail"||t.diagnostic.runtimeEval&&!t.diagnostic.runtimeEval.passed?!0:t.phase!=="build"?!1:t.buildPause==="plan-ready"}function nh(t,e){let n=t.toLowerCase(),i=[];n.includes(e.name.toLowerCase())&&i.push({source:"user",quote:e.name});let r=e.text.split(/[^a-zA-Z0-9_\-\u4e00-\u9fff/]+/u).map(o=>o.trim().toLowerCase()).filter(o=>o.length>=4&&!eh.has(o)),s=[...new Set(r.filter(o=>n.includes(o)))].slice(0,3);for(let o of s)i.push({source:"repo",quote:o});return i}async function ih(t){return new Promise(e=>{let n=Up("git",["status","--short","--untracked-files=all"],{cwd:t,stdio:["ignore","pipe","ignore"],shell:!1}),i=[];n.stdout.on("data",r=>{i.push(Buffer.isBuffer(r)?r:Buffer.from(String(r)))}),n.on("error",()=>e([])),n.on("exit",r=>{if(r!==0){e([]);return}let s=Buffer.concat(i).toString("utf8").split(/\r?\n/u).map(o=>o.trim()).filter(Boolean);e(s)})})}async function Mc(t,e){let n=Jp(e),i=n.utterance.trim(),r=i.toLowerCase();if(n.agent_context.already_in_comet_flow)return $("out_of_scope",null,"low","already in Comet flow");if(es(r,th))return $("out_of_scope",null,"low","user opted out of Comet resume",[{source:"user",quote:i}]);let s=await Qp(t);if(s.length===0)return $("none",null,"none","no active Comet changes");let o=await ih(t);if(s.length>1){let u=s.find(f=>r.includes(f.name.toLowerCase()));return u?o.length>0?$("ask_user",u,"low","uncommitted worktree changes require attribution",[{source:"repo",quote:`${o.length} dirty file(s)`}]):Dc(u)?$("ask_user",u,"low","active change is at a decision point"):$("auto_resume",u,"high","request names an active change",[{source:"user",quote:u.name}]):$("ask_user",null,"low","multiple active changes require a change name")}let[a]=s;if(o.length>0)return $("ask_user",a,"low","uncommitted worktree changes require attribution",[{source:"repo",quote:`${o.length} dirty file(s)`}]);if(Dc(a))return a.missingCometState?$("ask_user",a,"low","active OpenSpec change is missing Comet state"):$("ask_user",a,"low","active change is at a decision point",[{source:"state",quote:`phase: ${a.phase}`}]);let c=es(r,Xp);if(!n.agent_context.non_trivial_work&&es(r,Zp)&&!c)return $("out_of_scope",a,"low","user asked a question without workflow work");let m=nh(i,a);return c||m.length>0?$("auto_resume",a,"high","single active change and request is related",[{source:"state",quote:`phase: ${a.phase}`},...m]):n.agent_context.non_trivial_work?$("ask_user",a,"low","single active change exists but request looks unrelated"):$("out_of_scope",a,"low","request is not workflow work")}import{AsyncLocalStorage as rh}from"async_hooks";import{promises as Wc}from"fs";import Ot from"path";var ts=new rh;function sh(t,e){let n=Ot.relative(t,e);return n===""||!Ot.isAbsolute(n)&&n!==".."&&!n.startsWith(`..${Ot.sep}`)}async function oh(t){let e=Ot.resolve(t.invocationCwd??process.cwd()),n=Ot.resolve(t.projectRoot??await fc(e)),[i,r]=await Promise.all([Wc.realpath(e),Wc.realpath(n)]);if(!sh(r,i))throw new Error(`Classic command invocation cwd is outside the discovered project: ${e}`);return{invocationCwd:e,projectRoot:n}}async function $c(t,e){let n=ts.getStore();if(n)return e(n);let i=await oh(t);return ts.run(i,()=>e(i))}function Fc(){let t=ts.getStore();if(!t)throw new Error("Classic command project context is unavailable");return t.projectRoot}function Qn(t,e,n){return{exitCode:t,...e===void 0?{}:{stdout:e},...n===void 0?{}:{stderr:n}}}function Bc(){return Qn(64,void 0,`Usage: comet-resume-probe.mjs probe +Usage: comet-resume-probe.mjs probe --stdin`)}async function ah(){let t=[];for await(let e of process.stdin)t.push(Buffer.isBuffer(e)?e:Buffer.from(String(e)));return Buffer.concat(t).toString("utf8")}function ch(t){return{schema_version:Fe,utterance:t,locale:"unknown",agent_context:{non_trivial_work:!0,already_in_comet_flow:!1}}}function lh(t){try{return JSON.parse(t)}catch{return ch(t)}}var Kc=async(t,e)=>$c(e,async()=>{let[n,i]=t;if(n!=="probe")return Bc();let r=i==="--stdin",s=r?await ah():i;if(!s)return Bc();try{let o=r?lh(s):JSON.parse(s),a=await Mc(Fc(),o);return Qn(0,`${JSON.stringify(a,null,2)} `)}catch(o){return o instanceof SyntaxError?Qn(1,void 0,`Invalid JSON: ${o.message}`):Qn(1,void 0,o instanceof Error?o.message:String(o))}});function uh(t,e){return{exitCode:e.exitCode,stdout:JSON.stringify({command:t,exitCode:e.exitCode,...e.stdout===void 0?{}:{stdout:e.stdout},...e.stderr===void 0?{}:{stderr:e.stderr}})+` -`}}async function Kc(t,e,n=process.argv.slice(2)){let i=n.includes("--json"),r=n.filter(a=>a!=="--json"),s;try{s=await e(r,{json:i})}catch(a){s={exitCode:70,stderr:a instanceof Error?a.message:String(a)}}let o=i?uh(t,s):s;return o.stdout&&process.stdout.write(o.stdout),o.stderr&&process.stderr.write(o.stderr+(o.stderr.endsWith(` +`}}async function Yc(t,e,n=process.argv.slice(2)){let i=n.includes("--json"),r=n.filter(a=>a!=="--json"),s;try{s=await e(r,{json:i})}catch(a){s={exitCode:70,stderr:a instanceof Error?a.message:String(a)}}let o=i?uh(t,s):s;return o.stdout&&process.stdout.write(o.stdout),o.stderr&&process.stderr.write(o.stderr+(o.stderr.endsWith(` `)?"":` -`)),o.exitCode}process.exitCode=await Kc("resume-probe",Bc); +`)),o.exitCode}process.exitCode=await Yc("resume-probe",Kc); diff --git a/assets/skills/comet/scripts/comet-runtime.mjs b/assets/skills/comet/scripts/comet-runtime.mjs index 2dcc3eced..3dd49c5e7 100644 --- a/assets/skills/comet/scripts/comet-runtime.mjs +++ b/assets/skills/comet/scripts/comet-runtime.mjs @@ -1,17 +1,17 @@ #!/usr/bin/env node import { createRequire as __cometCreateRequire } from 'module'; const require = __cometCreateRequire(import.meta.url); -var Hg=Object.create;var ma=Object.defineProperty;var Kg=Object.getOwnPropertyDescriptor;var Jg=Object.getOwnPropertyNames;var Ug=Object.getPrototypeOf,Vg=Object.prototype.hasOwnProperty;var Jr=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var pe=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(i){throw n=[i],i}};var v=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(n){throw t=0,n}},Yg=(e,t)=>{for(var n in t)ma(e,n,{get:t[n],enumerable:!0})},Gg=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Jg(t))!Vg.call(e,r)&&r!==n&&ma(e,r,{get:()=>t[r],enumerable:!(i=Kg(t,r))||i.enumerable});return e};var rt=(e,t,n)=>(n=e!=null?Hg(Ug(e)):{},Gg(t||!e||!e.__esModule?ma(n,"default",{value:e,enumerable:!0}):n,e));var M=v(oe=>{"use strict";var pa=Symbol.for("yaml.alias"),Ru=Symbol.for("yaml.document"),Ur=Symbol.for("yaml.map"),_u=Symbol.for("yaml.pair"),ha=Symbol.for("yaml.scalar"),Vr=Symbol.for("yaml.seq"),yt=Symbol.for("yaml.node.type"),Qg=e=>!!e&&typeof e=="object"&&e[yt]===pa,Zg=e=>!!e&&typeof e=="object"&&e[yt]===Ru,ew=e=>!!e&&typeof e=="object"&&e[yt]===Ur,tw=e=>!!e&&typeof e=="object"&&e[yt]===_u,xu=e=>!!e&&typeof e=="object"&&e[yt]===ha,nw=e=>!!e&&typeof e=="object"&&e[yt]===Vr;function Pu(e){if(e&&typeof e=="object")switch(e[yt]){case Ur:case Vr:return!0}return!1}function iw(e){if(e&&typeof e=="object")switch(e[yt]){case pa:case Ur:case ha:case Vr:return!0}return!1}var rw=e=>(xu(e)||Pu(e))&&!!e.anchor;oe.ALIAS=pa;oe.DOC=Ru;oe.MAP=Ur;oe.NODE_TYPE=yt;oe.PAIR=_u;oe.SCALAR=ha;oe.SEQ=Vr;oe.hasAnchor=rw;oe.isAlias=Qg;oe.isCollection=Pu;oe.isDocument=Zg;oe.isMap=ew;oe.isNode=iw;oe.isPair=tw;oe.isScalar=xu;oe.isSeq=nw});var _i=v(ga=>{"use strict";var ie=M(),ke=Symbol("break visit"),Ou=Symbol("skip children"),st=Symbol("remove node");function Yr(e,t){let n=$u(t);ie.isDocument(e)?Hn(null,e.contents,n,Object.freeze([e]))===st&&(e.contents=null):Hn(null,e,n,Object.freeze([]))}Yr.BREAK=ke;Yr.SKIP=Ou;Yr.REMOVE=st;function Hn(e,t,n,i){let r=Iu(e,t,n,i);if(ie.isNode(r)||ie.isPair(r))return Au(e,i,r),Hn(e,r,n,i);if(typeof r!="symbol"){if(ie.isCollection(t)){i=Object.freeze(i.concat(t));for(let s=0;s{"use strict";var Nu=M(),sw=_i(),ow={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},aw=e=>e.replace(/[!,[\]{}]/g,t=>ow[t]),xi=class e{constructor(t,n){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,n)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},e.defaultTags);break}return t}add(t,n){this.atNextDocument&&(this.yaml={explicit:e.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},e.defaultTags),this.atNextDocument=!1);let i=t.trim().split(/[ \t]+/),r=i.shift();switch(r){case"%TAG":{if(i.length!==2&&(n(0,"%TAG directive should contain exactly two parts"),i.length<2))return!1;let[s,o]=i;return this.tags[s]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,i.length!==1)return n(0,"%YAML directive should contain exactly one part"),!1;let[s]=i;if(s==="1.1"||s==="1.2")return this.yaml.version=s,!0;{let o=/^\d+\.\d+$/.test(s);return n(6,`Unsupported YAML version ${s}`,o),!1}}default:return n(0,`Unknown directive ${r}`,!0),!1}}tagName(t,n){if(t==="!")return"!";if(t[0]!=="!")return n(`Not a valid tag: ${t}`),null;if(t[1]==="<"){let o=t.slice(2,-1);return o==="!"||o==="!!"?(n(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&n("Verbatim tags must end with a >"),o)}let[,i,r]=t.match(/^(.*!)([^!]*)$/s);r||n(`The ${t} tag has no suffix`);let s=this.tags[i];if(s)try{return s+decodeURIComponent(r)}catch(o){return n(String(o)),null}return i==="!"?t:(n(`Could not resolve tag: ${t}`),null)}tagString(t){for(let[n,i]of Object.entries(this.tags))if(t.startsWith(i))return n+aw(t.substring(i.length));return t[0]==="!"?t:`!<${t}>`}toString(t){let n=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],i=Object.entries(this.tags),r;if(t&&i.length>0&&Nu.isNode(t.contents)){let s={};sw.visit(t.contents,(o,a)=>{Nu.isNode(a)&&a.tag&&(s[a.tag]=!0)}),r=Object.keys(s)}else r=[];for(let[s,o]of i)s==="!!"&&o==="tag:yaml.org,2002:"||(!t||r.some(a=>a.startsWith(o)))&&n.push(`%TAG ${s} ${o}`);return n.join(` -`)}};xi.defaultYaml={explicit:!1,version:"1.2"};xi.defaultTags={"!!":"tag:yaml.org,2002:"};Tu.Directives=xi});var zr=v(Pi=>{"use strict";var ju=M(),cw=_i();function lw(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let n=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw new Error(n)}return!0}function Lu(e){let t=new Set;return cw.visit(e,{Value(n,i){i.anchor&&t.add(i.anchor)}}),t}function Mu(e,t){for(let n=1;;++n){let i=`${e}${n}`;if(!t.has(i))return i}}function uw(e,t){let n=[],i=new Map,r=null;return{onAnchor:s=>{n.push(s),r??(r=Lu(e));let o=Mu(t,r);return r.add(o),o},setAnchors:()=>{for(let s of n){let o=i.get(s);if(typeof o=="object"&&o.anchor&&(ju.isScalar(o.node)||ju.isCollection(o.node)))o.node.anchor=o.anchor;else{let a=new Error("Failed to resolve repeated object (this should not happen)");throw a.source=s,a}}},sourceObjects:i}}Pi.anchorIsValid=lw;Pi.anchorNames=Lu;Pi.createNodeAnchors=uw;Pi.findNewAnchor=Mu});var ya=v(qu=>{"use strict";function Oi(e,t,n,i){if(i&&typeof i=="object")if(Array.isArray(i))for(let r=0,s=i.length;r{"use strict";var fw=M();function Du(e,t,n){if(Array.isArray(e))return e.map((i,r)=>Du(i,String(r),n));if(e&&typeof e.toJSON=="function"){if(!n||!fw.hasAnchor(e))return e.toJSON(t,n);let i={aliasCount:0,count:1,res:void 0};n.anchors.set(e,i),n.onCreate=s=>{i.res=s,delete n.onCreate};let r=e.toJSON(t,n);return n.onCreate&&n.onCreate(r),r}return typeof e=="bigint"&&!n?.keep?Number(e):e}Fu.toJS=Du});var Xr=v(Bu=>{"use strict";var dw=ya(),Wu=M(),mw=Mt(),va=class{constructor(t){Object.defineProperty(this,Wu.NODE_TYPE,{value:t})}clone(){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(t.range=this.range.slice()),t}toJS(t,{mapAsMap:n,maxAliasCount:i,onAnchor:r,reviver:s}={}){if(!Wu.isDocument(t))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:t,keep:!0,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},a=mw.toJS(this,"",o);if(typeof r=="function")for(let{count:c,res:l}of o.anchors.values())r(l,c);return typeof s=="function"?dw.applyReviver(s,{"":a},"",a):a}};Bu.NodeBase=va});var $i=v(Hu=>{"use strict";var pw=zr(),hw=_i(),Jn=M(),gw=Xr(),ww=Mt(),ba=class extends gw.NodeBase{constructor(t){super(Jn.ALIAS),this.source=t,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(t,n){if(n?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let i;n?.aliasResolveCache?i=n.aliasResolveCache:(i=[],hw.visit(t,{Node:(s,o)=>{(Jn.isAlias(o)||Jn.hasAnchor(o))&&i.push(o)}}),n&&(n.aliasResolveCache=i));let r;for(let s of i){if(s===this)break;s.anchor===this.source&&(r=s)}return r}toJSON(t,n){if(!n)return{source:this.source};let{anchors:i,doc:r,maxAliasCount:s}=n,o=this.resolve(r,n);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let a=i.get(o);if(a||(ww.toJS(o,null,n),a=i.get(o)),a?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(s>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=Qr(r,o,i)),a.count*a.aliasCount>s)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return a.res}toString(t,n,i){let r=`*${this.source}`;if(t){if(pw.anchorIsValid(this.source),t.options.verifyAliasOrder&&!t.anchors.has(this.source)){let s=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(s)}if(t.implicitKey)return`${r} `}return r}};function Qr(e,t,n){if(Jn.isAlias(t)){let i=t.resolve(e),r=n&&i&&n.get(i);return r?r.count*r.aliasCount:0}else if(Jn.isCollection(t)){let i=0;for(let r of t.items){let s=Qr(e,r,n);s>i&&(i=s)}return i}else if(Jn.isPair(t)){let i=Qr(e,t.key,n),r=Qr(e,t.value,n);return Math.max(i,r)}return 1}Hu.Alias=ba});var Z=v(Ca=>{"use strict";var yw=M(),vw=Xr(),bw=Mt(),Cw=e=>!e||typeof e!="function"&&typeof e!="object",qt=class extends vw.NodeBase{constructor(t){super(yw.SCALAR),this.value=t}toJSON(t,n){return n?.keep?this.value:bw.toJS(this.value,t,n)}toString(){return String(this.value)}};qt.BLOCK_FOLDED="BLOCK_FOLDED";qt.BLOCK_LITERAL="BLOCK_LITERAL";qt.PLAIN="PLAIN";qt.QUOTE_DOUBLE="QUOTE_DOUBLE";qt.QUOTE_SINGLE="QUOTE_SINGLE";Ca.Scalar=qt;Ca.isScalarValue=Cw});var Ii=v(Ju=>{"use strict";var kw=$i(),hn=M(),Ku=Z(),Sw="tag:yaml.org,2002:";function Ew(e,t,n){if(t){let i=n.filter(s=>s.tag===t),r=i.find(s=>!s.format)??i[0];if(!r)throw new Error(`Tag ${t} not found`);return r}return n.find(i=>i.identify?.(e)&&!i.format)}function Rw(e,t,n){if(hn.isDocument(e)&&(e=e.contents),hn.isNode(e))return e;if(hn.isPair(e)){let u=n.schema[hn.MAP].createNode?.(n.schema,null,n);return u.items.push(e),u}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:i,onAnchor:r,onTagObj:s,schema:o,sourceObjects:a}=n,c;if(i&&e&&typeof e=="object"){if(c=a.get(e),c)return c.anchor??(c.anchor=r(e)),new kw.Alias(c.anchor);c={anchor:null,node:null},a.set(e,c)}t?.startsWith("!!")&&(t=Sw+t.slice(2));let l=Ew(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let u=new Ku.Scalar(e);return c&&(c.node=u),u}l=e instanceof Map?o[hn.MAP]:Symbol.iterator in Object(e)?o[hn.SEQ]:o[hn.MAP]}s&&(s(l),delete n.onTagObj);let f=l?.createNode?l.createNode(n.schema,e,n):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(n.schema,e,n):new Ku.Scalar(e);return t?f.tag=t:l.default||(f.tag=l.tag),c&&(c.node=f),f}Ju.createNode=Rw});var es=v(Zr=>{"use strict";var _w=Ii(),ot=M(),xw=Xr();function ka(e,t,n){let i=n;for(let r=t.length-1;r>=0;--r){let s=t[r];if(typeof s=="number"&&Number.isInteger(s)&&s>=0){let o=[];o[s]=i,i=o}else i=new Map([[s,i]])}return _w.createNode(i,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}var Uu=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,Sa=class extends xw.NodeBase{constructor(t,n){super(t),Object.defineProperty(this,"schema",{value:n,configurable:!0,enumerable:!1,writable:!0})}clone(t){let n=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return t&&(n.schema=t),n.items=n.items.map(i=>ot.isNode(i)||ot.isPair(i)?i.clone(t):i),this.range&&(n.range=this.range.slice()),n}addIn(t,n){if(Uu(t))this.add(n);else{let[i,...r]=t,s=this.get(i,!0);if(ot.isCollection(s))s.addIn(r,n);else if(s===void 0&&this.schema)this.set(i,ka(this.schema,r,n));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${r}`)}}deleteIn(t){let[n,...i]=t;if(i.length===0)return this.delete(n);let r=this.get(n,!0);if(ot.isCollection(r))return r.deleteIn(i);throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}getIn(t,n){let[i,...r]=t,s=this.get(i,!0);return r.length===0?!n&&ot.isScalar(s)?s.value:s:ot.isCollection(s)?s.getIn(r,n):void 0}hasAllNullValues(t){return this.items.every(n=>{if(!ot.isPair(n))return!1;let i=n.value;return i==null||t&&ot.isScalar(i)&&i.value==null&&!i.commentBefore&&!i.comment&&!i.tag})}hasIn(t){let[n,...i]=t;if(i.length===0)return this.has(n);let r=this.get(n,!0);return ot.isCollection(r)?r.hasIn(i):!1}setIn(t,n){let[i,...r]=t;if(r.length===0)this.set(i,n);else{let s=this.get(i,!0);if(ot.isCollection(s))s.setIn(r,n);else if(s===void 0&&this.schema)this.set(i,ka(this.schema,r,n));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${r}`)}}};Zr.Collection=Sa;Zr.collectionFromPath=ka;Zr.isEmptyPath=Uu});var Ai=v(ts=>{"use strict";var Pw=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function Ea(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var Ow=(e,t,n)=>e.endsWith(` +var Jg=Object.create;var ma=Object.defineProperty;var Ug=Object.getOwnPropertyDescriptor;var Vg=Object.getOwnPropertyNames;var Yg=Object.getPrototypeOf,Gg=Object.prototype.hasOwnProperty;var Jr=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var pe=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(i){throw n=[i],i}};var v=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(n){throw t=0,n}},zg=(e,t)=>{for(var n in t)ma(e,n,{get:t[n],enumerable:!0})},Xg=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Vg(t))!Gg.call(e,r)&&r!==n&&ma(e,r,{get:()=>t[r],enumerable:!(i=Ug(t,r))||i.enumerable});return e};var st=(e,t,n)=>(n=e!=null?Jg(Yg(e)):{},Xg(t||!e||!e.__esModule?ma(n,"default",{value:e,enumerable:!0}):n,e));var M=v(oe=>{"use strict";var pa=Symbol.for("yaml.alias"),Ru=Symbol.for("yaml.document"),Ur=Symbol.for("yaml.map"),_u=Symbol.for("yaml.pair"),ha=Symbol.for("yaml.scalar"),Vr=Symbol.for("yaml.seq"),vt=Symbol.for("yaml.node.type"),ew=e=>!!e&&typeof e=="object"&&e[vt]===pa,tw=e=>!!e&&typeof e=="object"&&e[vt]===Ru,nw=e=>!!e&&typeof e=="object"&&e[vt]===Ur,iw=e=>!!e&&typeof e=="object"&&e[vt]===_u,xu=e=>!!e&&typeof e=="object"&&e[vt]===ha,rw=e=>!!e&&typeof e=="object"&&e[vt]===Vr;function Pu(e){if(e&&typeof e=="object")switch(e[vt]){case Ur:case Vr:return!0}return!1}function sw(e){if(e&&typeof e=="object")switch(e[vt]){case pa:case Ur:case ha:case Vr:return!0}return!1}var ow=e=>(xu(e)||Pu(e))&&!!e.anchor;oe.ALIAS=pa;oe.DOC=Ru;oe.MAP=Ur;oe.NODE_TYPE=vt;oe.PAIR=_u;oe.SCALAR=ha;oe.SEQ=Vr;oe.hasAnchor=ow;oe.isAlias=ew;oe.isCollection=Pu;oe.isDocument=tw;oe.isMap=nw;oe.isNode=sw;oe.isPair=iw;oe.isScalar=xu;oe.isSeq=rw});var _i=v(ga=>{"use strict";var ie=M(),ke=Symbol("break visit"),Ou=Symbol("skip children"),ot=Symbol("remove node");function Yr(e,t){let n=$u(t);ie.isDocument(e)?Hn(null,e.contents,n,Object.freeze([e]))===ot&&(e.contents=null):Hn(null,e,n,Object.freeze([]))}Yr.BREAK=ke;Yr.SKIP=Ou;Yr.REMOVE=ot;function Hn(e,t,n,i){let r=Iu(e,t,n,i);if(ie.isNode(r)||ie.isPair(r))return Au(e,i,r),Hn(e,r,n,i);if(typeof r!="symbol"){if(ie.isCollection(t)){i=Object.freeze(i.concat(t));for(let s=0;s{"use strict";var Nu=M(),aw=_i(),cw={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},lw=e=>e.replace(/[!,[\]{}]/g,t=>cw[t]),xi=class e{constructor(t,n){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,n)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},e.defaultTags);break}return t}add(t,n){this.atNextDocument&&(this.yaml={explicit:e.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},e.defaultTags),this.atNextDocument=!1);let i=t.trim().split(/[ \t]+/),r=i.shift();switch(r){case"%TAG":{if(i.length!==2&&(n(0,"%TAG directive should contain exactly two parts"),i.length<2))return!1;let[s,o]=i;return this.tags[s]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,i.length!==1)return n(0,"%YAML directive should contain exactly one part"),!1;let[s]=i;if(s==="1.1"||s==="1.2")return this.yaml.version=s,!0;{let o=/^\d+\.\d+$/.test(s);return n(6,`Unsupported YAML version ${s}`,o),!1}}default:return n(0,`Unknown directive ${r}`,!0),!1}}tagName(t,n){if(t==="!")return"!";if(t[0]!=="!")return n(`Not a valid tag: ${t}`),null;if(t[1]==="<"){let o=t.slice(2,-1);return o==="!"||o==="!!"?(n(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&n("Verbatim tags must end with a >"),o)}let[,i,r]=t.match(/^(.*!)([^!]*)$/s);r||n(`The ${t} tag has no suffix`);let s=this.tags[i];if(s)try{return s+decodeURIComponent(r)}catch(o){return n(String(o)),null}return i==="!"?t:(n(`Could not resolve tag: ${t}`),null)}tagString(t){for(let[n,i]of Object.entries(this.tags))if(t.startsWith(i))return n+lw(t.substring(i.length));return t[0]==="!"?t:`!<${t}>`}toString(t){let n=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],i=Object.entries(this.tags),r;if(t&&i.length>0&&Nu.isNode(t.contents)){let s={};aw.visit(t.contents,(o,a)=>{Nu.isNode(a)&&a.tag&&(s[a.tag]=!0)}),r=Object.keys(s)}else r=[];for(let[s,o]of i)s==="!!"&&o==="tag:yaml.org,2002:"||(!t||r.some(a=>a.startsWith(o)))&&n.push(`%TAG ${s} ${o}`);return n.join(` +`)}};xi.defaultYaml={explicit:!1,version:"1.2"};xi.defaultTags={"!!":"tag:yaml.org,2002:"};Tu.Directives=xi});var zr=v(Pi=>{"use strict";var ju=M(),uw=_i();function fw(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let n=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw new Error(n)}return!0}function Lu(e){let t=new Set;return uw.visit(e,{Value(n,i){i.anchor&&t.add(i.anchor)}}),t}function Mu(e,t){for(let n=1;;++n){let i=`${e}${n}`;if(!t.has(i))return i}}function dw(e,t){let n=[],i=new Map,r=null;return{onAnchor:s=>{n.push(s),r??(r=Lu(e));let o=Mu(t,r);return r.add(o),o},setAnchors:()=>{for(let s of n){let o=i.get(s);if(typeof o=="object"&&o.anchor&&(ju.isScalar(o.node)||ju.isCollection(o.node)))o.node.anchor=o.anchor;else{let a=new Error("Failed to resolve repeated object (this should not happen)");throw a.source=s,a}}},sourceObjects:i}}Pi.anchorIsValid=fw;Pi.anchorNames=Lu;Pi.createNodeAnchors=dw;Pi.findNewAnchor=Mu});var ya=v(qu=>{"use strict";function Oi(e,t,n,i){if(i&&typeof i=="object")if(Array.isArray(i))for(let r=0,s=i.length;r{"use strict";var mw=M();function Du(e,t,n){if(Array.isArray(e))return e.map((i,r)=>Du(i,String(r),n));if(e&&typeof e.toJSON=="function"){if(!n||!mw.hasAnchor(e))return e.toJSON(t,n);let i={aliasCount:0,count:1,res:void 0};n.anchors.set(e,i),n.onCreate=s=>{i.res=s,delete n.onCreate};let r=e.toJSON(t,n);return n.onCreate&&n.onCreate(r),r}return typeof e=="bigint"&&!n?.keep?Number(e):e}Fu.toJS=Du});var Xr=v(Bu=>{"use strict";var pw=ya(),Wu=M(),hw=Mt(),va=class{constructor(t){Object.defineProperty(this,Wu.NODE_TYPE,{value:t})}clone(){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(t.range=this.range.slice()),t}toJS(t,{mapAsMap:n,maxAliasCount:i,onAnchor:r,reviver:s}={}){if(!Wu.isDocument(t))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:t,keep:!0,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},a=hw.toJS(this,"",o);if(typeof r=="function")for(let{count:c,res:l}of o.anchors.values())r(l,c);return typeof s=="function"?pw.applyReviver(s,{"":a},"",a):a}};Bu.NodeBase=va});var $i=v(Hu=>{"use strict";var gw=zr(),ww=_i(),Jn=M(),yw=Xr(),vw=Mt(),ba=class extends yw.NodeBase{constructor(t){super(Jn.ALIAS),this.source=t,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(t,n){if(n?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let i;n?.aliasResolveCache?i=n.aliasResolveCache:(i=[],ww.visit(t,{Node:(s,o)=>{(Jn.isAlias(o)||Jn.hasAnchor(o))&&i.push(o)}}),n&&(n.aliasResolveCache=i));let r;for(let s of i){if(s===this)break;s.anchor===this.source&&(r=s)}return r}toJSON(t,n){if(!n)return{source:this.source};let{anchors:i,doc:r,maxAliasCount:s}=n,o=this.resolve(r,n);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let a=i.get(o);if(a||(vw.toJS(o,null,n),a=i.get(o)),a?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(s>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=Qr(r,o,i)),a.count*a.aliasCount>s)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return a.res}toString(t,n,i){let r=`*${this.source}`;if(t){if(gw.anchorIsValid(this.source),t.options.verifyAliasOrder&&!t.anchors.has(this.source)){let s=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(s)}if(t.implicitKey)return`${r} `}return r}};function Qr(e,t,n){if(Jn.isAlias(t)){let i=t.resolve(e),r=n&&i&&n.get(i);return r?r.count*r.aliasCount:0}else if(Jn.isCollection(t)){let i=0;for(let r of t.items){let s=Qr(e,r,n);s>i&&(i=s)}return i}else if(Jn.isPair(t)){let i=Qr(e,t.key,n),r=Qr(e,t.value,n);return Math.max(i,r)}return 1}Hu.Alias=ba});var Z=v(Ca=>{"use strict";var bw=M(),Cw=Xr(),kw=Mt(),Sw=e=>!e||typeof e!="function"&&typeof e!="object",qt=class extends Cw.NodeBase{constructor(t){super(bw.SCALAR),this.value=t}toJSON(t,n){return n?.keep?this.value:kw.toJS(this.value,t,n)}toString(){return String(this.value)}};qt.BLOCK_FOLDED="BLOCK_FOLDED";qt.BLOCK_LITERAL="BLOCK_LITERAL";qt.PLAIN="PLAIN";qt.QUOTE_DOUBLE="QUOTE_DOUBLE";qt.QUOTE_SINGLE="QUOTE_SINGLE";Ca.Scalar=qt;Ca.isScalarValue=Sw});var Ii=v(Ju=>{"use strict";var Ew=$i(),hn=M(),Ku=Z(),Rw="tag:yaml.org,2002:";function _w(e,t,n){if(t){let i=n.filter(s=>s.tag===t),r=i.find(s=>!s.format)??i[0];if(!r)throw new Error(`Tag ${t} not found`);return r}return n.find(i=>i.identify?.(e)&&!i.format)}function xw(e,t,n){if(hn.isDocument(e)&&(e=e.contents),hn.isNode(e))return e;if(hn.isPair(e)){let u=n.schema[hn.MAP].createNode?.(n.schema,null,n);return u.items.push(e),u}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:i,onAnchor:r,onTagObj:s,schema:o,sourceObjects:a}=n,c;if(i&&e&&typeof e=="object"){if(c=a.get(e),c)return c.anchor??(c.anchor=r(e)),new Ew.Alias(c.anchor);c={anchor:null,node:null},a.set(e,c)}t?.startsWith("!!")&&(t=Rw+t.slice(2));let l=_w(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let u=new Ku.Scalar(e);return c&&(c.node=u),u}l=e instanceof Map?o[hn.MAP]:Symbol.iterator in Object(e)?o[hn.SEQ]:o[hn.MAP]}s&&(s(l),delete n.onTagObj);let f=l?.createNode?l.createNode(n.schema,e,n):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(n.schema,e,n):new Ku.Scalar(e);return t?f.tag=t:l.default||(f.tag=l.tag),c&&(c.node=f),f}Ju.createNode=xw});var es=v(Zr=>{"use strict";var Pw=Ii(),at=M(),Ow=Xr();function ka(e,t,n){let i=n;for(let r=t.length-1;r>=0;--r){let s=t[r];if(typeof s=="number"&&Number.isInteger(s)&&s>=0){let o=[];o[s]=i,i=o}else i=new Map([[s,i]])}return Pw.createNode(i,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}var Uu=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,Sa=class extends Ow.NodeBase{constructor(t,n){super(t),Object.defineProperty(this,"schema",{value:n,configurable:!0,enumerable:!1,writable:!0})}clone(t){let n=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return t&&(n.schema=t),n.items=n.items.map(i=>at.isNode(i)||at.isPair(i)?i.clone(t):i),this.range&&(n.range=this.range.slice()),n}addIn(t,n){if(Uu(t))this.add(n);else{let[i,...r]=t,s=this.get(i,!0);if(at.isCollection(s))s.addIn(r,n);else if(s===void 0&&this.schema)this.set(i,ka(this.schema,r,n));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${r}`)}}deleteIn(t){let[n,...i]=t;if(i.length===0)return this.delete(n);let r=this.get(n,!0);if(at.isCollection(r))return r.deleteIn(i);throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}getIn(t,n){let[i,...r]=t,s=this.get(i,!0);return r.length===0?!n&&at.isScalar(s)?s.value:s:at.isCollection(s)?s.getIn(r,n):void 0}hasAllNullValues(t){return this.items.every(n=>{if(!at.isPair(n))return!1;let i=n.value;return i==null||t&&at.isScalar(i)&&i.value==null&&!i.commentBefore&&!i.comment&&!i.tag})}hasIn(t){let[n,...i]=t;if(i.length===0)return this.has(n);let r=this.get(n,!0);return at.isCollection(r)?r.hasIn(i):!1}setIn(t,n){let[i,...r]=t;if(r.length===0)this.set(i,n);else{let s=this.get(i,!0);if(at.isCollection(s))s.setIn(r,n);else if(s===void 0&&this.schema)this.set(i,ka(this.schema,r,n));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${r}`)}}};Zr.Collection=Sa;Zr.collectionFromPath=ka;Zr.isEmptyPath=Uu});var Ai=v(ts=>{"use strict";var $w=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function Ea(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var Iw=(e,t,n)=>e.endsWith(` `)?Ea(n,t):n.includes(` `)?` -`+Ea(n,t):(e.endsWith(" ")?"":" ")+n;ts.indentComment=Ea;ts.lineComment=Ow;ts.stringifyComment=Pw});var Yu=v(Ni=>{"use strict";var $w="flow",Ra="block",ns="quoted";function Iw(e,t,n="flow",{indentAtStart:i,lineWidth:r=80,minContentWidth:s=20,onFold:o,onOverflow:a}={}){if(!r||r<0)return e;rr-Math.max(2,s)?l.push(0):u=r-i);let d,p,g=!1,h=-1,m=-1,y=-1;n===Ra&&(h=Vu(e,h,t.length),h!==-1&&(u=h+c));for(let C;C=e[h+=1];){if(n===ns&&C==="\\"){switch(m=h,e[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}y=h}if(C===` +`+Ea(n,t):(e.endsWith(" ")?"":" ")+n;ts.indentComment=Ea;ts.lineComment=Iw;ts.stringifyComment=$w});var Yu=v(Ni=>{"use strict";var Aw="flow",Ra="block",ns="quoted";function Nw(e,t,n="flow",{indentAtStart:i,lineWidth:r=80,minContentWidth:s=20,onFold:o,onOverflow:a}={}){if(!r||r<0)return e;rr-Math.max(2,s)?l.push(0):u=r-i);let d,p,g=!1,h=-1,m=-1,y=-1;n===Ra&&(h=Vu(e,h,t.length),h!==-1&&(u=h+c));for(let C;C=e[h+=1];){if(n===ns&&C==="\\"){switch(m=h,e[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}y=h}if(C===` `)n===Ra&&(h=Vu(e,h,t.length)),u=h+t.length+c,d=void 0;else{if(C===" "&&p&&p!==" "&&p!==` `&&p!==" "){let k=e[h+1];k&&k!==" "&&k!==` `&&k!==" "&&(d=h)}if(h>=u)if(d)l.push(d),u=d+c,d=void 0;else if(n===ns){for(;p===" "||p===" ";)p=C,C=e[h+=1],g=!0;let k=h>y+1?h-2:m-1;if(f[k])return e;l.push(k),f[k]=!0,u=k+c,d=void 0}else g=!0}p=C}if(g&&a&&a(),l.length===0)return e;o&&o();let w=e.slice(0,l[0]);for(let C=0;C{"use strict";var Ke=Z(),Dt=Yu(),rs=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),ss=e=>/^(%|---|\.\.\.)/m.test(e);function Aw(e,t,n){if(!t||t<0)return!1;let i=t-n,r=e.length;if(r<=i)return!1;for(let s=0,o=0;s{"use strict";var Ke=Z(),Dt=Yu(),rs=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),ss=e=>/^(%|---|\.\.\.)/m.test(e);function Tw(e,t,n){if(!t||t<0)return!1;let i=t-n,r=e.length;if(r<=i)return!1;for(let s=0,o=0;si)return!0;if(o=s+1,r-o<=i)return!1}return!0}function Ti(e,t){let n=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return n;let{implicitKey:i}=t,r=t.options.doubleQuotedMinMultiLineLength,s=t.indent||(ss(e)?" ":""),o="",a=0;for(let c=0,l=n[c];l;l=n[++c])if(l===" "&&n[c+1]==="\\"&&n[c+2]==="n"&&(o+=n.slice(a,c)+"\\ ",c+=1,a=c,l="\\"),l==="\\")switch(n[c+1]){case"u":{o+=n.slice(a,c);let f=n.substr(c+2,4);switch(f){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:f.substr(0,2)==="00"?o+="\\x"+f.substr(2):o+=n.substr(c,6)}c+=5,a=c+1}break;case"n":if(i||n[c+2]==='"'||n.length `;let u,d;for(d=n.length;d>0;--d){let E=n[d-1];if(E!==` `&&E!==" "&&E!==" ")break}let p=n.substring(d),g=p.indexOf(` @@ -29,47 +29,47 @@ ${n}`)+"'";return t.implicitKey?i:Dt.foldFlowLines(i,n,Dt.FOLD_FLOW,rs(t,!1))}fu `)y=m;else break}let w=n.substring(0,y{R=!0});let b=Dt.foldFlowLines(`${w}${E}${p}`,l,Dt.FOLD_BLOCK,O);if(!R)return`>${k} ${l}${b}`}return n=n.replace(/\n+/g,`$&${l}`),`|${k} -${l}${w}${n}${p}`}function Nw(e,t,n,i){let{type:r,value:s}=e,{actualString:o,implicitKey:a,indent:c,indentStep:l,inFlow:f}=t;if(a&&s.includes(` +${l}${w}${n}${p}`}function jw(e,t,n,i){let{type:r,value:s}=e,{actualString:o,implicitKey:a,indent:c,indentStep:l,inFlow:f}=t;if(a&&s.includes(` `)||f&&/[[\]{},]/.test(s))return Un(s,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(s))return a||f||!s.includes(` `)?Un(s,t):is(e,t,n,i);if(!a&&!f&&r!==Ke.Scalar.PLAIN&&s.includes(` `))return is(e,t,n,i);if(ss(s)){if(c==="")return t.forceBlockIndent=!0,is(e,t,n,i);if(a&&c===l)return Un(s,t)}let u=s.replace(/\n+/g,`$& -${c}`);if(o){let d=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(u),{compat:p,tags:g}=t.doc.schema;if(g.some(d)||p?.some(d))return Un(s,t)}return a?u:Dt.foldFlowLines(u,c,Dt.FOLD_FLOW,rs(t,!1))}function Tw(e,t,n,i){let{implicitKey:r,inFlow:s}=t,o=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)}),{type:a}=e;a!==Ke.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=Ke.Scalar.QUOTE_DOUBLE);let c=f=>{switch(f){case Ke.Scalar.BLOCK_FOLDED:case Ke.Scalar.BLOCK_LITERAL:return r||s?Un(o.value,t):is(o,t,n,i);case Ke.Scalar.QUOTE_DOUBLE:return Ti(o.value,t);case Ke.Scalar.QUOTE_SINGLE:return _a(o.value,t);case Ke.Scalar.PLAIN:return Nw(o,t,n,i);default:return null}},l=c(a);if(l===null){let{defaultKeyType:f,defaultStringType:u}=t.options,d=r&&f||u;if(l=c(d),l===null)throw new Error(`Unsupported default string type ${d}`)}return l}Gu.stringifyString=Tw});var Li=v(Pa=>{"use strict";var jw=zr(),Ft=M(),Lw=Ai(),Mw=ji();function qw(e,t){let n=Object.assign({blockQuote:!0,commentString:Lw.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},e.schema.toStringOptions,t),i;switch(n.collectionStyle){case"block":i=!1;break;case"flow":i=!0;break;default:i=null}return{anchors:new Set,doc:e,flowCollectionPadding:n.flowCollectionPadding?" ":"",indent:"",indentStep:typeof n.indent=="number"?" ".repeat(n.indent):" ",inFlow:i,options:n}}function Dw(e,t){if(t.tag){let r=e.filter(s=>s.tag===t.tag);if(r.length>0)return r.find(s=>s.format===t.format)??r[0]}let n,i;if(Ft.isScalar(t)){i=t.value;let r=e.filter(s=>s.identify?.(i));if(r.length>1){let s=r.filter(o=>o.test);s.length>0&&(r=s)}n=r.find(s=>s.format===t.format)??r.find(s=>!s.format)}else i=t,n=e.find(r=>r.nodeClass&&i instanceof r.nodeClass);if(!n){let r=i?.constructor?.name??(i===null?"null":typeof i);throw new Error(`Tag not resolved for ${r} value`)}return n}function Fw(e,t,{anchors:n,doc:i}){if(!i.directives)return"";let r=[],s=(Ft.isScalar(e)||Ft.isCollection(e))&&e.anchor;s&&jw.anchorIsValid(s)&&(n.add(s),r.push(`&${s}`));let o=e.tag??(t.default?null:t.tag);return o&&r.push(i.directives.tagString(o)),r.join(" ")}function Ww(e,t,n,i){if(Ft.isPair(e))return e.toString(t,n,i);if(Ft.isAlias(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw new TypeError("Cannot stringify circular structure without alias nodes");t.resolvedAliases?t.resolvedAliases.add(e):t.resolvedAliases=new Set([e]),e=e.resolve(t.doc)}let r,s=Ft.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>r=c});r??(r=Dw(t.doc.schema.tags,s));let o=Fw(s,r,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);let a=typeof r.stringify=="function"?r.stringify(s,t,n,i):Ft.isScalar(s)?Mw.stringifyString(s,t,n,i):s.toString(t,n,i);return o?Ft.isScalar(s)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o} -${t.indent}${a}`:a}Pa.createStringifyContext=qw;Pa.stringify=Ww});var Zu=v(Qu=>{"use strict";var vt=M(),zu=Z(),Xu=Li(),Mi=Ai();function Bw({key:e,value:t},n,i,r){let{allNullValues:s,doc:o,indent:a,indentStep:c,options:{commentString:l,indentSeq:f,simpleKeys:u}}=n,d=vt.isNode(e)&&e.comment||null;if(u){if(d)throw new Error("With simple keys, key nodes cannot have comments");if(vt.isCollection(e)||!vt.isNode(e)&&typeof e=="object"){let O="With simple keys, collection cannot be used as a key value";throw new Error(O)}}let p=!u&&(!e||d&&t==null&&!n.inFlow||vt.isCollection(e)||(vt.isScalar(e)?e.type===zu.Scalar.BLOCK_FOLDED||e.type===zu.Scalar.BLOCK_LITERAL:typeof e=="object"));n=Object.assign({},n,{allNullValues:!1,implicitKey:!p&&(u||!s),indent:a+c});let g=!1,h=!1,m=Xu.stringify(e,n,()=>g=!0,()=>h=!0);if(!p&&!n.inFlow&&m.length>1024){if(u)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");p=!0}if(n.inFlow){if(s||t==null)return g&&i&&i(),m===""?"?":p?`? ${m}`:m}else if(s&&!u||t==null&&p)return m=`? ${m}`,d&&!g?m+=Mi.lineComment(m,n.indent,l(d)):h&&r&&r(),m;g&&(d=null),p?(d&&(m+=Mi.lineComment(m,n.indent,l(d))),m=`? ${m} -${a}:`):(m=`${m}:`,d&&(m+=Mi.lineComment(m,n.indent,l(d))));let y,w,C;vt.isNode(t)?(y=!!t.spaceBefore,w=t.commentBefore,C=t.comment):(y=!1,w=null,C=null,t&&typeof t=="object"&&(t=o.createNode(t))),n.implicitKey=!1,!p&&!d&&vt.isScalar(t)&&(n.indentAtStart=m.length+1),h=!1,!f&&c.length>=2&&!n.inFlow&&!p&&vt.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(n.indent=n.indent.substring(2));let k=!1,E=Xu.stringify(t,n,()=>k=!0,()=>h=!0),R=" ";if(d||y||w){if(R=y?` +${c}`);if(o){let d=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(u),{compat:p,tags:g}=t.doc.schema;if(g.some(d)||p?.some(d))return Un(s,t)}return a?u:Dt.foldFlowLines(u,c,Dt.FOLD_FLOW,rs(t,!1))}function Lw(e,t,n,i){let{implicitKey:r,inFlow:s}=t,o=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)}),{type:a}=e;a!==Ke.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=Ke.Scalar.QUOTE_DOUBLE);let c=f=>{switch(f){case Ke.Scalar.BLOCK_FOLDED:case Ke.Scalar.BLOCK_LITERAL:return r||s?Un(o.value,t):is(o,t,n,i);case Ke.Scalar.QUOTE_DOUBLE:return Ti(o.value,t);case Ke.Scalar.QUOTE_SINGLE:return _a(o.value,t);case Ke.Scalar.PLAIN:return jw(o,t,n,i);default:return null}},l=c(a);if(l===null){let{defaultKeyType:f,defaultStringType:u}=t.options,d=r&&f||u;if(l=c(d),l===null)throw new Error(`Unsupported default string type ${d}`)}return l}Gu.stringifyString=Lw});var Li=v(Pa=>{"use strict";var Mw=zr(),Ft=M(),qw=Ai(),Dw=ji();function Fw(e,t){let n=Object.assign({blockQuote:!0,commentString:qw.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},e.schema.toStringOptions,t),i;switch(n.collectionStyle){case"block":i=!1;break;case"flow":i=!0;break;default:i=null}return{anchors:new Set,doc:e,flowCollectionPadding:n.flowCollectionPadding?" ":"",indent:"",indentStep:typeof n.indent=="number"?" ".repeat(n.indent):" ",inFlow:i,options:n}}function Ww(e,t){if(t.tag){let r=e.filter(s=>s.tag===t.tag);if(r.length>0)return r.find(s=>s.format===t.format)??r[0]}let n,i;if(Ft.isScalar(t)){i=t.value;let r=e.filter(s=>s.identify?.(i));if(r.length>1){let s=r.filter(o=>o.test);s.length>0&&(r=s)}n=r.find(s=>s.format===t.format)??r.find(s=>!s.format)}else i=t,n=e.find(r=>r.nodeClass&&i instanceof r.nodeClass);if(!n){let r=i?.constructor?.name??(i===null?"null":typeof i);throw new Error(`Tag not resolved for ${r} value`)}return n}function Bw(e,t,{anchors:n,doc:i}){if(!i.directives)return"";let r=[],s=(Ft.isScalar(e)||Ft.isCollection(e))&&e.anchor;s&&Mw.anchorIsValid(s)&&(n.add(s),r.push(`&${s}`));let o=e.tag??(t.default?null:t.tag);return o&&r.push(i.directives.tagString(o)),r.join(" ")}function Hw(e,t,n,i){if(Ft.isPair(e))return e.toString(t,n,i);if(Ft.isAlias(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw new TypeError("Cannot stringify circular structure without alias nodes");t.resolvedAliases?t.resolvedAliases.add(e):t.resolvedAliases=new Set([e]),e=e.resolve(t.doc)}let r,s=Ft.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>r=c});r??(r=Ww(t.doc.schema.tags,s));let o=Bw(s,r,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);let a=typeof r.stringify=="function"?r.stringify(s,t,n,i):Ft.isScalar(s)?Dw.stringifyString(s,t,n,i):s.toString(t,n,i);return o?Ft.isScalar(s)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o} +${t.indent}${a}`:a}Pa.createStringifyContext=Fw;Pa.stringify=Hw});var Zu=v(Qu=>{"use strict";var bt=M(),zu=Z(),Xu=Li(),Mi=Ai();function Kw({key:e,value:t},n,i,r){let{allNullValues:s,doc:o,indent:a,indentStep:c,options:{commentString:l,indentSeq:f,simpleKeys:u}}=n,d=bt.isNode(e)&&e.comment||null;if(u){if(d)throw new Error("With simple keys, key nodes cannot have comments");if(bt.isCollection(e)||!bt.isNode(e)&&typeof e=="object"){let O="With simple keys, collection cannot be used as a key value";throw new Error(O)}}let p=!u&&(!e||d&&t==null&&!n.inFlow||bt.isCollection(e)||(bt.isScalar(e)?e.type===zu.Scalar.BLOCK_FOLDED||e.type===zu.Scalar.BLOCK_LITERAL:typeof e=="object"));n=Object.assign({},n,{allNullValues:!1,implicitKey:!p&&(u||!s),indent:a+c});let g=!1,h=!1,m=Xu.stringify(e,n,()=>g=!0,()=>h=!0);if(!p&&!n.inFlow&&m.length>1024){if(u)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");p=!0}if(n.inFlow){if(s||t==null)return g&&i&&i(),m===""?"?":p?`? ${m}`:m}else if(s&&!u||t==null&&p)return m=`? ${m}`,d&&!g?m+=Mi.lineComment(m,n.indent,l(d)):h&&r&&r(),m;g&&(d=null),p?(d&&(m+=Mi.lineComment(m,n.indent,l(d))),m=`? ${m} +${a}:`):(m=`${m}:`,d&&(m+=Mi.lineComment(m,n.indent,l(d))));let y,w,C;bt.isNode(t)?(y=!!t.spaceBefore,w=t.commentBefore,C=t.comment):(y=!1,w=null,C=null,t&&typeof t=="object"&&(t=o.createNode(t))),n.implicitKey=!1,!p&&!d&&bt.isScalar(t)&&(n.indentAtStart=m.length+1),h=!1,!f&&c.length>=2&&!n.inFlow&&!p&&bt.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(n.indent=n.indent.substring(2));let k=!1,E=Xu.stringify(t,n,()=>k=!0,()=>h=!0),R=" ";if(d||y||w){if(R=y?` `:"",w){let O=l(w);R+=` ${Mi.indentComment(O,n.indent)}`}E===""&&!n.inFlow?R===` `&&C&&(R=` `):R+=` -${n.indent}`}else if(!p&&vt.isCollection(t)){let O=E[0],b=E.indexOf(` +${n.indent}`}else if(!p&&bt.isCollection(t)){let O=E[0],b=E.indexOf(` `),L=b!==-1,Ie=n.inFlow??t.flow??t.items.length===0;if(L||!Ie){let Q=!1;if(L&&(O==="&"||O==="!")){let K=E.indexOf(" ");O==="&"&&K!==-1&&K{"use strict";var ef=Jr("process");function Hw(e,...t){e==="debug"&&console.log(...t)}function Kw(e,t){(e==="debug"||e==="warn")&&(typeof ef.emitWarning=="function"?ef.emitWarning(t):console.warn(t))}Oa.debug=Hw;Oa.warn=Kw});var us=v(ls=>{"use strict";var cs=M(),tf=Z(),os="<<",as={identify:e=>e===os||typeof e=="symbol"&&e.description===os,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new tf.Scalar(Symbol(os)),{addToJSMap:nf}),stringify:()=>os},Jw=(e,t)=>(as.identify(t)||cs.isScalar(t)&&(!t.type||t.type===tf.Scalar.PLAIN)&&as.identify(t.value))&&e?.doc.schema.tags.some(n=>n.tag===as.tag&&n.default);function nf(e,t,n){let i=rf(e,n);if(cs.isSeq(i))for(let r of i.items)Ia(e,t,r);else if(Array.isArray(i))for(let r of i)Ia(e,t,r);else Ia(e,t,i)}function Ia(e,t,n){let i=rf(e,n);if(!cs.isMap(i))throw new Error("Merge sources must be maps or map aliases");let r=i.toJSON(null,e,Map);for(let[s,o]of r)t instanceof Map?t.has(s)||t.set(s,o):t instanceof Set?t.add(s):Object.prototype.hasOwnProperty.call(t,s)||Object.defineProperty(t,s,{value:o,writable:!0,enumerable:!0,configurable:!0});return t}function rf(e,t){return e&&cs.isAlias(t)?t.resolve(e.doc,e):t}ls.addMergeToJSMap=nf;ls.isMergeKey=Jw;ls.merge=as});var Na=v(af=>{"use strict";var Uw=$a(),sf=us(),Vw=Li(),of=M(),Aa=Mt();function Yw(e,t,{key:n,value:i}){if(of.isNode(n)&&n.addToJSMap)n.addToJSMap(e,t,i);else if(sf.isMergeKey(e,n))sf.addMergeToJSMap(e,t,i);else{let r=Aa.toJS(n,"",e);if(t instanceof Map)t.set(r,Aa.toJS(i,r,e));else if(t instanceof Set)t.add(r);else{let s=Gw(n,r,e),o=Aa.toJS(i,s,e);s in t?Object.defineProperty(t,s,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[s]=o}}return t}function Gw(e,t,n){if(t===null)return"";if(typeof t!="object")return String(t);if(of.isNode(e)&&n?.doc){let i=Vw.createStringifyContext(n.doc,{});i.anchors=new Set;for(let s of n.anchors.keys())i.anchors.add(s.anchor);i.inFlow=!0,i.inStringifyKey=!0;let r=e.toString(i);if(!n.mapKeyWarned){let s=JSON.stringify(r);s.length>40&&(s=s.substring(0,36)+'..."'),Uw.warn(n.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${s}. Set mapAsMap: true to use object keys.`),n.mapKeyWarned=!0}return r}return JSON.stringify(t)}af.addPairToJSMap=Yw});var Wt=v(Ta=>{"use strict";var cf=Ii(),zw=Zu(),Xw=Na(),fs=M();function Qw(e,t,n){let i=cf.createNode(e,void 0,n),r=cf.createNode(t,void 0,n);return new ds(i,r)}var ds=class e{constructor(t,n=null){Object.defineProperty(this,fs.NODE_TYPE,{value:fs.PAIR}),this.key=t,this.value=n}clone(t){let{key:n,value:i}=this;return fs.isNode(n)&&(n=n.clone(t)),fs.isNode(i)&&(i=i.clone(t)),new e(n,i)}toJSON(t,n){let i=n?.mapAsMap?new Map:{};return Xw.addPairToJSMap(n,i,this)}toString(t,n,i){return t?.doc?zw.stringifyPair(this,t,n,i):JSON.stringify(this)}};Ta.Pair=ds;Ta.createPair=Qw});var ja=v(uf=>{"use strict";var gn=M(),lf=Li(),ms=Ai();function Zw(e,t,n){return(t.inFlow??e.flow?ty:ey)(e,t,n)}function ey({comment:e,items:t},n,{blockItemPrefix:i,flowChars:r,itemIndent:s,onChompKeep:o,onComment:a}){let{indent:c,options:{commentString:l}}=n,f=Object.assign({},n,{indent:s,type:null}),u=!1,d=[];for(let g=0;gm=null,()=>u=!0);m&&(y+=ms.lineComment(y,s,l(m))),u&&m&&(u=!1),d.push(i+y)}let p;if(d.length===0)p=r.start+r.end;else{p=d[0];for(let g=1;g{"use strict";var ef=Jr("process");function Jw(e,...t){e==="debug"&&console.log(...t)}function Uw(e,t){(e==="debug"||e==="warn")&&(typeof ef.emitWarning=="function"?ef.emitWarning(t):console.warn(t))}Oa.debug=Jw;Oa.warn=Uw});var us=v(ls=>{"use strict";var cs=M(),tf=Z(),os="<<",as={identify:e=>e===os||typeof e=="symbol"&&e.description===os,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new tf.Scalar(Symbol(os)),{addToJSMap:nf}),stringify:()=>os},Vw=(e,t)=>(as.identify(t)||cs.isScalar(t)&&(!t.type||t.type===tf.Scalar.PLAIN)&&as.identify(t.value))&&e?.doc.schema.tags.some(n=>n.tag===as.tag&&n.default);function nf(e,t,n){let i=rf(e,n);if(cs.isSeq(i))for(let r of i.items)Ia(e,t,r);else if(Array.isArray(i))for(let r of i)Ia(e,t,r);else Ia(e,t,i)}function Ia(e,t,n){let i=rf(e,n);if(!cs.isMap(i))throw new Error("Merge sources must be maps or map aliases");let r=i.toJSON(null,e,Map);for(let[s,o]of r)t instanceof Map?t.has(s)||t.set(s,o):t instanceof Set?t.add(s):Object.prototype.hasOwnProperty.call(t,s)||Object.defineProperty(t,s,{value:o,writable:!0,enumerable:!0,configurable:!0});return t}function rf(e,t){return e&&cs.isAlias(t)?t.resolve(e.doc,e):t}ls.addMergeToJSMap=nf;ls.isMergeKey=Vw;ls.merge=as});var Na=v(af=>{"use strict";var Yw=$a(),sf=us(),Gw=Li(),of=M(),Aa=Mt();function zw(e,t,{key:n,value:i}){if(of.isNode(n)&&n.addToJSMap)n.addToJSMap(e,t,i);else if(sf.isMergeKey(e,n))sf.addMergeToJSMap(e,t,i);else{let r=Aa.toJS(n,"",e);if(t instanceof Map)t.set(r,Aa.toJS(i,r,e));else if(t instanceof Set)t.add(r);else{let s=Xw(n,r,e),o=Aa.toJS(i,s,e);s in t?Object.defineProperty(t,s,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[s]=o}}return t}function Xw(e,t,n){if(t===null)return"";if(typeof t!="object")return String(t);if(of.isNode(e)&&n?.doc){let i=Gw.createStringifyContext(n.doc,{});i.anchors=new Set;for(let s of n.anchors.keys())i.anchors.add(s.anchor);i.inFlow=!0,i.inStringifyKey=!0;let r=e.toString(i);if(!n.mapKeyWarned){let s=JSON.stringify(r);s.length>40&&(s=s.substring(0,36)+'..."'),Yw.warn(n.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${s}. Set mapAsMap: true to use object keys.`),n.mapKeyWarned=!0}return r}return JSON.stringify(t)}af.addPairToJSMap=zw});var Wt=v(Ta=>{"use strict";var cf=Ii(),Qw=Zu(),Zw=Na(),fs=M();function ey(e,t,n){let i=cf.createNode(e,void 0,n),r=cf.createNode(t,void 0,n);return new ds(i,r)}var ds=class e{constructor(t,n=null){Object.defineProperty(this,fs.NODE_TYPE,{value:fs.PAIR}),this.key=t,this.value=n}clone(t){let{key:n,value:i}=this;return fs.isNode(n)&&(n=n.clone(t)),fs.isNode(i)&&(i=i.clone(t)),new e(n,i)}toJSON(t,n){let i=n?.mapAsMap?new Map:{};return Zw.addPairToJSMap(n,i,this)}toString(t,n,i){return t?.doc?Qw.stringifyPair(this,t,n,i):JSON.stringify(this)}};Ta.Pair=ds;Ta.createPair=ey});var ja=v(uf=>{"use strict";var gn=M(),lf=Li(),ms=Ai();function ty(e,t,n){return(t.inFlow??e.flow?iy:ny)(e,t,n)}function ny({comment:e,items:t},n,{blockItemPrefix:i,flowChars:r,itemIndent:s,onChompKeep:o,onComment:a}){let{indent:c,options:{commentString:l}}=n,f=Object.assign({},n,{indent:s,type:null}),u=!1,d=[];for(let g=0;gm=null,()=>u=!0);m&&(y+=ms.lineComment(y,s,l(m))),u&&m&&(u=!1),d.push(i+y)}let p;if(d.length===0)p=r.start+r.end;else{p=d[0];for(let g=1;gm=null);l||(l=u.length>f||y.includes(` +`+ms.indentComment(l(e),c),a&&a()):u&&o&&o(),p}function iy({items:e},t,{flowChars:n,itemIndent:i}){let{indent:r,indentStep:s,flowCollectionPadding:o,options:{commentString:a}}=t;i+=s;let c=Object.assign({},t,{indent:i,inFlow:!0,type:null}),l=!1,f=0,u=[];for(let g=0;gm=null);l||(l=u.length>f||y.includes(` `)),g0&&(l||(l=u.reduce((w,C)=>w+C.length+2,2)+(y.length+2)>t.options.lineWidth)),l&&(y+=",")),m&&(y+=ms.lineComment(y,i,a(m))),u.push(y),f=u.length}let{start:d,end:p}=n;if(u.length===0)return d+p;if(!l){let g=u.reduce((h,m)=>h+m.length+2,2);l=t.options.lineWidth>0&&g>t.options.lineWidth}if(l){let g=d;for(let h of u)g+=h?` ${s}${r}${h}`:` `;return`${g} -${r}${p}`}else return`${d}${o}${u.join(" ")}${o}${p}`}function ps({indent:e,options:{commentString:t}},n,i,r){if(i&&r&&(i=i.replace(/^\n+/,"")),i){let s=ms.indentComment(t(i),e);n.push(s.trimStart())}}uf.stringifyCollection=Zw});var Ht=v(Ma=>{"use strict";var ny=ja(),iy=Na(),ry=es(),Bt=M(),hs=Wt(),sy=Z();function qi(e,t){let n=Bt.isScalar(t)?t.value:t;for(let i of e)if(Bt.isPair(i)&&(i.key===t||i.key===n||Bt.isScalar(i.key)&&i.key.value===n))return i}var La=class extends ry.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(Bt.MAP,t),this.items=[]}static from(t,n,i){let{keepUndefined:r,replacer:s}=i,o=new this(t),a=(c,l)=>{if(typeof s=="function")l=s.call(n,c,l);else if(Array.isArray(s)&&!s.includes(c))return;(l!==void 0||r)&&o.items.push(hs.createPair(c,l,i))};if(n instanceof Map)for(let[c,l]of n)a(c,l);else if(n&&typeof n=="object")for(let c of Object.keys(n))a(c,n[c]);return typeof t.sortMapEntries=="function"&&o.items.sort(t.sortMapEntries),o}add(t,n){let i;Bt.isPair(t)?i=t:!t||typeof t!="object"||!("key"in t)?i=new hs.Pair(t,t?.value):i=new hs.Pair(t.key,t.value);let r=qi(this.items,i.key),s=this.schema?.sortMapEntries;if(r){if(!n)throw new Error(`Key ${i.key} already set`);Bt.isScalar(r.value)&&sy.isScalarValue(i.value)?r.value.value=i.value:r.value=i.value}else if(s){let o=this.items.findIndex(a=>s(i,a)<0);o===-1?this.items.push(i):this.items.splice(o,0,i)}else this.items.push(i)}delete(t){let n=qi(this.items,t);return n?this.items.splice(this.items.indexOf(n),1).length>0:!1}get(t,n){let r=qi(this.items,t)?.value;return(!n&&Bt.isScalar(r)?r.value:r)??void 0}has(t){return!!qi(this.items,t)}set(t,n){this.add(new hs.Pair(t,n),!0)}toJSON(t,n,i){let r=i?new i:n?.mapAsMap?new Map:{};n?.onCreate&&n.onCreate(r);for(let s of this.items)iy.addPairToJSMap(n,r,s);return r}toString(t,n,i){if(!t)return JSON.stringify(this);for(let r of this.items)if(!Bt.isPair(r))throw new Error(`Map items must all be pairs; found ${JSON.stringify(r)} instead`);return!t.allNullValues&&this.hasAllNullValues(!1)&&(t=Object.assign({},t,{allNullValues:!0})),ny.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:i,onComment:n})}};Ma.YAMLMap=La;Ma.findPair=qi});var Vn=v(df=>{"use strict";var oy=M(),ff=Ht(),ay={collection:"map",default:!0,nodeClass:ff.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return oy.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,n)=>ff.YAMLMap.from(e,t,n)};df.map=ay});var Kt=v(mf=>{"use strict";var cy=Ii(),ly=ja(),uy=es(),ws=M(),fy=Z(),dy=Mt(),qa=class extends uy.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(ws.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let n=gs(t);return typeof n!="number"?!1:this.items.splice(n,1).length>0}get(t,n){let i=gs(t);if(typeof i!="number")return;let r=this.items[i];return!n&&ws.isScalar(r)?r.value:r}has(t){let n=gs(t);return typeof n=="number"&&n=0?t:null}mf.YAMLSeq=qa});var Yn=v(hf=>{"use strict";var my=M(),pf=Kt(),py={collection:"seq",default:!0,nodeClass:pf.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return my.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,n)=>pf.YAMLSeq.from(e,t,n)};hf.seq=py});var Di=v(gf=>{"use strict";var hy=ji(),gy={identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify(e,t,n,i){return t=Object.assign({actualString:!0},t),hy.stringifyString(e,t,n,i)}};gf.string=gy});var ys=v(vf=>{"use strict";var wf=Z(),yf={identify:e=>e==null,createNode:()=>new wf.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new wf.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&yf.test.test(e)?e:t.options.nullStr};vf.nullTag=yf});var Da=v(Cf=>{"use strict";var wy=Z(),bf={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new wy.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},n){if(e&&bf.test.test(e)){let i=e[0]==="t"||e[0]==="T";if(t===i)return e}return t?n.options.trueStr:n.options.falseStr}};Cf.boolTag=bf});var Gn=v(kf=>{"use strict";function yy({format:e,minFractionDigits:t,tag:n,value:i}){if(typeof i=="bigint")return String(i);let r=typeof i=="number"?i:Number(i);if(!isFinite(r))return isNaN(r)?".nan":r<0?"-.inf":".inf";let s=Object.is(i,-0)?"-0":JSON.stringify(i);if(!e&&t&&(!n||n==="tag:yaml.org,2002:float")&&/^-?\d/.test(s)&&!s.includes("e")){let o=s.indexOf(".");o<0&&(o=s.length,s+=".");let a=t-(s.length-o-1);for(;a-- >0;)s+="0"}return s}kf.stringifyNumber=yy});var Wa=v(vs=>{"use strict";var vy=Z(),Fa=Gn(),by={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()==="nan"?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Fa.stringifyNumber},Cy={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():Fa.stringifyNumber(e)}},ky={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(e){let t=new vy.Scalar(parseFloat(e)),n=e.indexOf(".");return n!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-n-1),t},stringify:Fa.stringifyNumber};vs.float=ky;vs.floatExp=Cy;vs.floatNaN=by});var Ha=v(Cs=>{"use strict";var Sf=Gn(),bs=e=>typeof e=="bigint"||Number.isInteger(e),Ba=(e,t,n,{intAsBigInt:i})=>i?BigInt(e):parseInt(e.substring(t),n);function Ef(e,t,n){let{value:i}=e;return bs(i)&&i>=0?n+i.toString(t):Sf.stringifyNumber(e)}var Sy={identify:e=>bs(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,n)=>Ba(e,2,8,n),stringify:e=>Ef(e,8,"0o")},Ey={identify:bs,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,n)=>Ba(e,0,10,n),stringify:Sf.stringifyNumber},Ry={identify:e=>bs(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,n)=>Ba(e,2,16,n),stringify:e=>Ef(e,16,"0x")};Cs.int=Ey;Cs.intHex=Ry;Cs.intOct=Sy});var _f=v(Rf=>{"use strict";var _y=Vn(),xy=ys(),Py=Yn(),Oy=Di(),$y=Da(),Ka=Wa(),Ja=Ha(),Iy=[_y.map,Py.seq,Oy.string,xy.nullTag,$y.boolTag,Ja.intOct,Ja.int,Ja.intHex,Ka.floatNaN,Ka.floatExp,Ka.float];Rf.schema=Iy});var Of=v(Pf=>{"use strict";var Ay=Z(),Ny=Vn(),Ty=Yn();function xf(e){return typeof e=="bigint"||Number.isInteger(e)}var ks=({value:e})=>JSON.stringify(e),jy=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:ks},{identify:e=>e==null,createNode:()=>new Ay.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:ks},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:ks},{identify:xf,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:n})=>n?BigInt(e):parseInt(e,10),stringify:({value:e})=>xf(e)?e.toString():JSON.stringify(e)},{identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:e=>parseFloat(e),stringify:ks}],Ly={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},My=[Ny.map,Ty.seq].concat(jy,Ly);Pf.schema=My});var Va=v($f=>{"use strict";var Fi=Jr("buffer"),Ua=Z(),qy=ji(),Dy={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof Fi.Buffer=="function")return Fi.Buffer.from(e,"base64");if(typeof atob=="function"){let n=atob(e.replace(/[\n\r]/g,"")),i=new Uint8Array(n.length);for(let r=0;r{"use strict";var Ss=M(),Ya=Wt(),Fy=Z(),Wy=Kt();function If(e,t){if(Ss.isSeq(e))for(let n=0;n1&&t("Each pair must have its own sequence indicator");let r=i.items[0]||new Ya.Pair(new Fy.Scalar(null));if(i.commentBefore&&(r.key.commentBefore=r.key.commentBefore?`${i.commentBefore} +${r}${p}`}else return`${d}${o}${u.join(" ")}${o}${p}`}function ps({indent:e,options:{commentString:t}},n,i,r){if(i&&r&&(i=i.replace(/^\n+/,"")),i){let s=ms.indentComment(t(i),e);n.push(s.trimStart())}}uf.stringifyCollection=ty});var Ht=v(Ma=>{"use strict";var ry=ja(),sy=Na(),oy=es(),Bt=M(),hs=Wt(),ay=Z();function qi(e,t){let n=Bt.isScalar(t)?t.value:t;for(let i of e)if(Bt.isPair(i)&&(i.key===t||i.key===n||Bt.isScalar(i.key)&&i.key.value===n))return i}var La=class extends oy.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(Bt.MAP,t),this.items=[]}static from(t,n,i){let{keepUndefined:r,replacer:s}=i,o=new this(t),a=(c,l)=>{if(typeof s=="function")l=s.call(n,c,l);else if(Array.isArray(s)&&!s.includes(c))return;(l!==void 0||r)&&o.items.push(hs.createPair(c,l,i))};if(n instanceof Map)for(let[c,l]of n)a(c,l);else if(n&&typeof n=="object")for(let c of Object.keys(n))a(c,n[c]);return typeof t.sortMapEntries=="function"&&o.items.sort(t.sortMapEntries),o}add(t,n){let i;Bt.isPair(t)?i=t:!t||typeof t!="object"||!("key"in t)?i=new hs.Pair(t,t?.value):i=new hs.Pair(t.key,t.value);let r=qi(this.items,i.key),s=this.schema?.sortMapEntries;if(r){if(!n)throw new Error(`Key ${i.key} already set`);Bt.isScalar(r.value)&&ay.isScalarValue(i.value)?r.value.value=i.value:r.value=i.value}else if(s){let o=this.items.findIndex(a=>s(i,a)<0);o===-1?this.items.push(i):this.items.splice(o,0,i)}else this.items.push(i)}delete(t){let n=qi(this.items,t);return n?this.items.splice(this.items.indexOf(n),1).length>0:!1}get(t,n){let r=qi(this.items,t)?.value;return(!n&&Bt.isScalar(r)?r.value:r)??void 0}has(t){return!!qi(this.items,t)}set(t,n){this.add(new hs.Pair(t,n),!0)}toJSON(t,n,i){let r=i?new i:n?.mapAsMap?new Map:{};n?.onCreate&&n.onCreate(r);for(let s of this.items)sy.addPairToJSMap(n,r,s);return r}toString(t,n,i){if(!t)return JSON.stringify(this);for(let r of this.items)if(!Bt.isPair(r))throw new Error(`Map items must all be pairs; found ${JSON.stringify(r)} instead`);return!t.allNullValues&&this.hasAllNullValues(!1)&&(t=Object.assign({},t,{allNullValues:!0})),ry.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:i,onComment:n})}};Ma.YAMLMap=La;Ma.findPair=qi});var Vn=v(df=>{"use strict";var cy=M(),ff=Ht(),ly={collection:"map",default:!0,nodeClass:ff.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return cy.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,n)=>ff.YAMLMap.from(e,t,n)};df.map=ly});var Kt=v(mf=>{"use strict";var uy=Ii(),fy=ja(),dy=es(),ws=M(),my=Z(),py=Mt(),qa=class extends dy.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(ws.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let n=gs(t);return typeof n!="number"?!1:this.items.splice(n,1).length>0}get(t,n){let i=gs(t);if(typeof i!="number")return;let r=this.items[i];return!n&&ws.isScalar(r)?r.value:r}has(t){let n=gs(t);return typeof n=="number"&&n=0?t:null}mf.YAMLSeq=qa});var Yn=v(hf=>{"use strict";var hy=M(),pf=Kt(),gy={collection:"seq",default:!0,nodeClass:pf.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return hy.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,n)=>pf.YAMLSeq.from(e,t,n)};hf.seq=gy});var Di=v(gf=>{"use strict";var wy=ji(),yy={identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify(e,t,n,i){return t=Object.assign({actualString:!0},t),wy.stringifyString(e,t,n,i)}};gf.string=yy});var ys=v(vf=>{"use strict";var wf=Z(),yf={identify:e=>e==null,createNode:()=>new wf.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new wf.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&yf.test.test(e)?e:t.options.nullStr};vf.nullTag=yf});var Da=v(Cf=>{"use strict";var vy=Z(),bf={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new vy.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},n){if(e&&bf.test.test(e)){let i=e[0]==="t"||e[0]==="T";if(t===i)return e}return t?n.options.trueStr:n.options.falseStr}};Cf.boolTag=bf});var Gn=v(kf=>{"use strict";function by({format:e,minFractionDigits:t,tag:n,value:i}){if(typeof i=="bigint")return String(i);let r=typeof i=="number"?i:Number(i);if(!isFinite(r))return isNaN(r)?".nan":r<0?"-.inf":".inf";let s=Object.is(i,-0)?"-0":JSON.stringify(i);if(!e&&t&&(!n||n==="tag:yaml.org,2002:float")&&/^-?\d/.test(s)&&!s.includes("e")){let o=s.indexOf(".");o<0&&(o=s.length,s+=".");let a=t-(s.length-o-1);for(;a-- >0;)s+="0"}return s}kf.stringifyNumber=by});var Wa=v(vs=>{"use strict";var Cy=Z(),Fa=Gn(),ky={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()==="nan"?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Fa.stringifyNumber},Sy={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():Fa.stringifyNumber(e)}},Ey={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(e){let t=new Cy.Scalar(parseFloat(e)),n=e.indexOf(".");return n!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-n-1),t},stringify:Fa.stringifyNumber};vs.float=Ey;vs.floatExp=Sy;vs.floatNaN=ky});var Ha=v(Cs=>{"use strict";var Sf=Gn(),bs=e=>typeof e=="bigint"||Number.isInteger(e),Ba=(e,t,n,{intAsBigInt:i})=>i?BigInt(e):parseInt(e.substring(t),n);function Ef(e,t,n){let{value:i}=e;return bs(i)&&i>=0?n+i.toString(t):Sf.stringifyNumber(e)}var Ry={identify:e=>bs(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,n)=>Ba(e,2,8,n),stringify:e=>Ef(e,8,"0o")},_y={identify:bs,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,n)=>Ba(e,0,10,n),stringify:Sf.stringifyNumber},xy={identify:e=>bs(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,n)=>Ba(e,2,16,n),stringify:e=>Ef(e,16,"0x")};Cs.int=_y;Cs.intHex=xy;Cs.intOct=Ry});var _f=v(Rf=>{"use strict";var Py=Vn(),Oy=ys(),$y=Yn(),Iy=Di(),Ay=Da(),Ka=Wa(),Ja=Ha(),Ny=[Py.map,$y.seq,Iy.string,Oy.nullTag,Ay.boolTag,Ja.intOct,Ja.int,Ja.intHex,Ka.floatNaN,Ka.floatExp,Ka.float];Rf.schema=Ny});var Of=v(Pf=>{"use strict";var Ty=Z(),jy=Vn(),Ly=Yn();function xf(e){return typeof e=="bigint"||Number.isInteger(e)}var ks=({value:e})=>JSON.stringify(e),My=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:ks},{identify:e=>e==null,createNode:()=>new Ty.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:ks},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:ks},{identify:xf,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:n})=>n?BigInt(e):parseInt(e,10),stringify:({value:e})=>xf(e)?e.toString():JSON.stringify(e)},{identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:e=>parseFloat(e),stringify:ks}],qy={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},Dy=[jy.map,Ly.seq].concat(My,qy);Pf.schema=Dy});var Va=v($f=>{"use strict";var Fi=Jr("buffer"),Ua=Z(),Fy=ji(),Wy={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof Fi.Buffer=="function")return Fi.Buffer.from(e,"base64");if(typeof atob=="function"){let n=atob(e.replace(/[\n\r]/g,"")),i=new Uint8Array(n.length);for(let r=0;r{"use strict";var Ss=M(),Ya=Wt(),By=Z(),Hy=Kt();function If(e,t){if(Ss.isSeq(e))for(let n=0;n1&&t("Each pair must have its own sequence indicator");let r=i.items[0]||new Ya.Pair(new By.Scalar(null));if(i.commentBefore&&(r.key.commentBefore=r.key.commentBefore?`${i.commentBefore} ${r.key.commentBefore}`:i.commentBefore),i.comment){let s=r.value??r.key;s.comment=s.comment?`${i.comment} -${s.comment}`:i.comment}i=r}e.items[n]=Ss.isPair(i)?i:new Ya.Pair(i)}}else t("Expected a sequence for this tag");return e}function Af(e,t,n){let{replacer:i}=n,r=new Wy.YAMLSeq(e);r.tag="tag:yaml.org,2002:pairs";let s=0;if(t&&Symbol.iterator in Object(t))for(let o of t){typeof i=="function"&&(o=i.call(t,String(s++),o));let a,c;if(Array.isArray(o))if(o.length===2)a=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)a=l[0],c=o[a];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else a=o;r.items.push(Ya.createPair(a,c,n))}return r}var By={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:If,createNode:Af};Es.createPairs=Af;Es.pairs=By;Es.resolvePairs=If});var Xa=v(za=>{"use strict";var Nf=M(),Ga=Mt(),Wi=Ht(),Hy=Kt(),Tf=Rs(),wn=class e extends Hy.YAMLSeq{constructor(){super(),this.add=Wi.YAMLMap.prototype.add.bind(this),this.delete=Wi.YAMLMap.prototype.delete.bind(this),this.get=Wi.YAMLMap.prototype.get.bind(this),this.has=Wi.YAMLMap.prototype.has.bind(this),this.set=Wi.YAMLMap.prototype.set.bind(this),this.tag=e.tag}toJSON(t,n){if(!n)return super.toJSON(t);let i=new Map;n?.onCreate&&n.onCreate(i);for(let r of this.items){let s,o;if(Nf.isPair(r)?(s=Ga.toJS(r.key,"",n),o=Ga.toJS(r.value,s,n)):s=Ga.toJS(r,"",n),i.has(s))throw new Error("Ordered maps must not include duplicate keys");i.set(s,o)}return i}static from(t,n,i){let r=Tf.createPairs(t,n,i),s=new this;return s.items=r.items,s}};wn.tag="tag:yaml.org,2002:omap";var Ky={collection:"seq",identify:e=>e instanceof Map,nodeClass:wn,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let n=Tf.resolvePairs(e,t),i=[];for(let{key:r}of n.items)Nf.isScalar(r)&&(i.includes(r.value)?t(`Ordered maps must not include duplicate keys: ${r.value}`):i.push(r.value));return Object.assign(new wn,n)},createNode:(e,t,n)=>wn.from(e,t,n)};za.YAMLOMap=wn;za.omap=Ky});var Df=v(Qa=>{"use strict";var jf=Z();function Lf({value:e,source:t},n){return t&&(e?Mf:qf).test.test(t)?t:e?n.options.trueStr:n.options.falseStr}var Mf={identify:e=>e===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new jf.Scalar(!0),stringify:Lf},qf={identify:e=>e===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new jf.Scalar(!1),stringify:Lf};Qa.falseTag=qf;Qa.trueTag=Mf});var Ff=v(_s=>{"use strict";var Jy=Z(),Za=Gn(),Uy={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()==="nan"?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Za.stringifyNumber},Vy={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e.replace(/_/g,"")),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():Za.stringifyNumber(e)}},Yy={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(e){let t=new Jy.Scalar(parseFloat(e.replace(/_/g,""))),n=e.indexOf(".");if(n!==-1){let i=e.substring(n+1).replace(/_/g,"");i[i.length-1]==="0"&&(t.minFractionDigits=i.length)}return t},stringify:Za.stringifyNumber};_s.float=Yy;_s.floatExp=Vy;_s.floatNaN=Uy});var Bf=v(Hi=>{"use strict";var Wf=Gn(),Bi=e=>typeof e=="bigint"||Number.isInteger(e);function xs(e,t,n,{intAsBigInt:i}){let r=e[0];if((r==="-"||r==="+")&&(t+=1),e=e.substring(t).replace(/_/g,""),i){switch(n){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`;break}let o=BigInt(e);return r==="-"?BigInt(-1)*o:o}let s=parseInt(e,n);return r==="-"?-1*s:s}function ec(e,t,n){let{value:i}=e;if(Bi(i)){let r=i.toString(t);return i<0?"-"+n+r.substr(1):n+r}return Wf.stringifyNumber(e)}var Gy={identify:Bi,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,n)=>xs(e,2,2,n),stringify:e=>ec(e,2,"0b")},zy={identify:Bi,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,n)=>xs(e,1,8,n),stringify:e=>ec(e,8,"0")},Xy={identify:Bi,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,n)=>xs(e,0,10,n),stringify:Wf.stringifyNumber},Qy={identify:Bi,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,n)=>xs(e,2,16,n),stringify:e=>ec(e,16,"0x")};Hi.int=Xy;Hi.intBin=Gy;Hi.intHex=Qy;Hi.intOct=zy});var nc=v(tc=>{"use strict";var $s=M(),Ps=Wt(),Os=Ht(),yn=class e extends Os.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let n;$s.isPair(t)?n=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?n=new Ps.Pair(t.key,null):n=new Ps.Pair(t,null),Os.findPair(this.items,n.key)||this.items.push(n)}get(t,n){let i=Os.findPair(this.items,t);return!n&&$s.isPair(i)?$s.isScalar(i.key)?i.key.value:i.key:i}set(t,n){if(typeof n!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof n}`);let i=Os.findPair(this.items,t);i&&!n?this.items.splice(this.items.indexOf(i),1):!i&&n&&this.items.push(new Ps.Pair(t))}toJSON(t,n){return super.toJSON(t,n,Set)}toString(t,n,i){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),n,i);throw new Error("Set items must all have null values")}static from(t,n,i){let{replacer:r}=i,s=new this(t);if(n&&Symbol.iterator in Object(n))for(let o of n)typeof r=="function"&&(o=r.call(n,o,o)),s.items.push(Ps.createPair(o,null,i));return s}};yn.tag="tag:yaml.org,2002:set";var Zy={collection:"map",identify:e=>e instanceof Set,nodeClass:yn,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,n)=>yn.from(e,t,n),resolve(e,t){if($s.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new yn,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};tc.YAMLSet=yn;tc.set=Zy});var rc=v(Is=>{"use strict";var ev=Gn();function ic(e,t){let n=e[0],i=n==="-"||n==="+"?e.substring(1):e,r=o=>t?BigInt(o):Number(o),s=i.replace(/_/g,"").split(":").reduce((o,a)=>o*r(60)+r(a),r(0));return n==="-"?r(-1)*s:s}function Hf(e){let{value:t}=e,n=o=>o;if(typeof t=="bigint")n=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return ev.stringifyNumber(e);let i="";t<0&&(i="-",t*=n(-1));let r=n(60),s=[t%r];return t<60?s.unshift(0):(t=(t-s[0])/r,s.unshift(t%r),t>=60&&(t=(t-s[0])/r,s.unshift(t))),i+s.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var tv={identify:e=>typeof e=="bigint"||Number.isInteger(e),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(e,t,{intAsBigInt:n})=>ic(e,n),stringify:Hf},nv={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:e=>ic(e,!1),stringify:Hf},Kf={identify:e=>e instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(e){let t=e.match(Kf.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,n,i,r,s,o,a]=t.map(Number),c=t[7]?Number((t[7]+"00").substr(1,3)):0,l=Date.UTC(n,i-1,r,s||0,o||0,a||0,c),f=t[8];if(f&&f!=="Z"){let u=ic(f,!1);Math.abs(u)<30&&(u*=60),l-=6e4*u}return new Date(l)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};Is.floatTime=nv;Is.intTime=tv;Is.timestamp=Kf});var Vf=v(Uf=>{"use strict";var iv=Vn(),rv=ys(),sv=Yn(),ov=Di(),av=Va(),Jf=Df(),sc=Ff(),As=Bf(),cv=us(),lv=Xa(),uv=Rs(),fv=nc(),oc=rc(),dv=[iv.map,sv.seq,ov.string,rv.nullTag,Jf.trueTag,Jf.falseTag,As.intBin,As.intOct,As.int,As.intHex,sc.floatNaN,sc.floatExp,sc.float,av.binary,cv.merge,lv.omap,uv.pairs,fv.set,oc.intTime,oc.floatTime,oc.timestamp];Uf.schema=dv});var id=v(lc=>{"use strict";var Xf=Vn(),mv=ys(),Qf=Yn(),pv=Di(),hv=Da(),ac=Wa(),cc=Ha(),gv=_f(),wv=Of(),Zf=Va(),Ki=us(),ed=Xa(),td=Rs(),Yf=Vf(),nd=nc(),Ns=rc(),Gf=new Map([["core",gv.schema],["failsafe",[Xf.map,Qf.seq,pv.string]],["json",wv.schema],["yaml11",Yf.schema],["yaml-1.1",Yf.schema]]),zf={binary:Zf.binary,bool:hv.boolTag,float:ac.float,floatExp:ac.floatExp,floatNaN:ac.floatNaN,floatTime:Ns.floatTime,int:cc.int,intHex:cc.intHex,intOct:cc.intOct,intTime:Ns.intTime,map:Xf.map,merge:Ki.merge,null:mv.nullTag,omap:ed.omap,pairs:td.pairs,seq:Qf.seq,set:nd.set,timestamp:Ns.timestamp},yv={"tag:yaml.org,2002:binary":Zf.binary,"tag:yaml.org,2002:merge":Ki.merge,"tag:yaml.org,2002:omap":ed.omap,"tag:yaml.org,2002:pairs":td.pairs,"tag:yaml.org,2002:set":nd.set,"tag:yaml.org,2002:timestamp":Ns.timestamp};function vv(e,t,n){let i=Gf.get(t);if(i&&!e)return n&&!i.includes(Ki.merge)?i.concat(Ki.merge):i.slice();let r=i;if(!r)if(Array.isArray(e))r=[];else{let s=Array.from(Gf.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${t}"; use one of ${s} or define customTags array`)}if(Array.isArray(e))for(let s of e)r=r.concat(s);else typeof e=="function"&&(r=e(r.slice()));return n&&(r=r.concat(Ki.merge)),r.reduce((s,o)=>{let a=typeof o=="string"?zf[o]:o;if(!a){let c=JSON.stringify(o),l=Object.keys(zf).map(f=>JSON.stringify(f)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return s.includes(a)||s.push(a),s},[])}lc.coreKnownTags=yv;lc.getTags=vv});var dc=v(rd=>{"use strict";var uc=M(),bv=Vn(),Cv=Yn(),kv=Di(),Ts=id(),Sv=(e,t)=>e.keyt.key?1:0,fc=class e{constructor({compat:t,customTags:n,merge:i,resolveKnownTags:r,schema:s,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(t)?Ts.getTags(t,"compat"):t?Ts.getTags(null,t):null,this.name=typeof s=="string"&&s||"core",this.knownTags=r?Ts.coreKnownTags:{},this.tags=Ts.getTags(n,this.name,i),this.toStringOptions=a??null,Object.defineProperty(this,uc.MAP,{value:bv.map}),Object.defineProperty(this,uc.SCALAR,{value:kv.string}),Object.defineProperty(this,uc.SEQ,{value:Cv.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?Sv:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};rd.Schema=fc});var od=v(sd=>{"use strict";var Ev=M(),mc=Li(),Ji=Ai();function Rv(e,t){let n=[],i=t.directives===!0;if(t.directives!==!1&&e.directives){let c=e.directives.toString(e);c?(n.push(c),i=!0):e.directives.docStart&&(i=!0)}i&&n.push("---");let r=mc.createStringifyContext(e,t),{commentString:s}=r.options;if(e.commentBefore){n.length!==1&&n.unshift("");let c=s(e.commentBefore);n.unshift(Ji.indentComment(c,""))}let o=!1,a=null;if(e.contents){if(Ev.isNode(e.contents)){if(e.contents.spaceBefore&&i&&n.push(""),e.contents.commentBefore){let f=s(e.contents.commentBefore);n.push(Ji.indentComment(f,""))}r.forceBlockIndent=!!e.comment,a=e.contents.comment}let c=a?void 0:()=>o=!0,l=mc.stringify(e.contents,r,()=>a=null,c);a&&(l+=Ji.lineComment(l,"",s(a))),(l[0]==="|"||l[0]===">")&&n[n.length-1]==="---"?n[n.length-1]=`--- ${l}`:n.push(l)}else n.push(mc.stringify(e.contents,r));if(e.directives?.docEnd)if(e.comment){let c=s(e.comment);c.includes(` +${s.comment}`:i.comment}i=r}e.items[n]=Ss.isPair(i)?i:new Ya.Pair(i)}}else t("Expected a sequence for this tag");return e}function Af(e,t,n){let{replacer:i}=n,r=new Hy.YAMLSeq(e);r.tag="tag:yaml.org,2002:pairs";let s=0;if(t&&Symbol.iterator in Object(t))for(let o of t){typeof i=="function"&&(o=i.call(t,String(s++),o));let a,c;if(Array.isArray(o))if(o.length===2)a=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)a=l[0],c=o[a];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else a=o;r.items.push(Ya.createPair(a,c,n))}return r}var Ky={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:If,createNode:Af};Es.createPairs=Af;Es.pairs=Ky;Es.resolvePairs=If});var Xa=v(za=>{"use strict";var Nf=M(),Ga=Mt(),Wi=Ht(),Jy=Kt(),Tf=Rs(),wn=class e extends Jy.YAMLSeq{constructor(){super(),this.add=Wi.YAMLMap.prototype.add.bind(this),this.delete=Wi.YAMLMap.prototype.delete.bind(this),this.get=Wi.YAMLMap.prototype.get.bind(this),this.has=Wi.YAMLMap.prototype.has.bind(this),this.set=Wi.YAMLMap.prototype.set.bind(this),this.tag=e.tag}toJSON(t,n){if(!n)return super.toJSON(t);let i=new Map;n?.onCreate&&n.onCreate(i);for(let r of this.items){let s,o;if(Nf.isPair(r)?(s=Ga.toJS(r.key,"",n),o=Ga.toJS(r.value,s,n)):s=Ga.toJS(r,"",n),i.has(s))throw new Error("Ordered maps must not include duplicate keys");i.set(s,o)}return i}static from(t,n,i){let r=Tf.createPairs(t,n,i),s=new this;return s.items=r.items,s}};wn.tag="tag:yaml.org,2002:omap";var Uy={collection:"seq",identify:e=>e instanceof Map,nodeClass:wn,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let n=Tf.resolvePairs(e,t),i=[];for(let{key:r}of n.items)Nf.isScalar(r)&&(i.includes(r.value)?t(`Ordered maps must not include duplicate keys: ${r.value}`):i.push(r.value));return Object.assign(new wn,n)},createNode:(e,t,n)=>wn.from(e,t,n)};za.YAMLOMap=wn;za.omap=Uy});var Df=v(Qa=>{"use strict";var jf=Z();function Lf({value:e,source:t},n){return t&&(e?Mf:qf).test.test(t)?t:e?n.options.trueStr:n.options.falseStr}var Mf={identify:e=>e===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new jf.Scalar(!0),stringify:Lf},qf={identify:e=>e===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new jf.Scalar(!1),stringify:Lf};Qa.falseTag=qf;Qa.trueTag=Mf});var Ff=v(_s=>{"use strict";var Vy=Z(),Za=Gn(),Yy={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()==="nan"?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Za.stringifyNumber},Gy={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e.replace(/_/g,"")),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():Za.stringifyNumber(e)}},zy={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(e){let t=new Vy.Scalar(parseFloat(e.replace(/_/g,""))),n=e.indexOf(".");if(n!==-1){let i=e.substring(n+1).replace(/_/g,"");i[i.length-1]==="0"&&(t.minFractionDigits=i.length)}return t},stringify:Za.stringifyNumber};_s.float=zy;_s.floatExp=Gy;_s.floatNaN=Yy});var Bf=v(Hi=>{"use strict";var Wf=Gn(),Bi=e=>typeof e=="bigint"||Number.isInteger(e);function xs(e,t,n,{intAsBigInt:i}){let r=e[0];if((r==="-"||r==="+")&&(t+=1),e=e.substring(t).replace(/_/g,""),i){switch(n){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`;break}let o=BigInt(e);return r==="-"?BigInt(-1)*o:o}let s=parseInt(e,n);return r==="-"?-1*s:s}function ec(e,t,n){let{value:i}=e;if(Bi(i)){let r=i.toString(t);return i<0?"-"+n+r.substr(1):n+r}return Wf.stringifyNumber(e)}var Xy={identify:Bi,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,n)=>xs(e,2,2,n),stringify:e=>ec(e,2,"0b")},Qy={identify:Bi,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,n)=>xs(e,1,8,n),stringify:e=>ec(e,8,"0")},Zy={identify:Bi,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,n)=>xs(e,0,10,n),stringify:Wf.stringifyNumber},ev={identify:Bi,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,n)=>xs(e,2,16,n),stringify:e=>ec(e,16,"0x")};Hi.int=Zy;Hi.intBin=Xy;Hi.intHex=ev;Hi.intOct=Qy});var nc=v(tc=>{"use strict";var $s=M(),Ps=Wt(),Os=Ht(),yn=class e extends Os.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let n;$s.isPair(t)?n=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?n=new Ps.Pair(t.key,null):n=new Ps.Pair(t,null),Os.findPair(this.items,n.key)||this.items.push(n)}get(t,n){let i=Os.findPair(this.items,t);return!n&&$s.isPair(i)?$s.isScalar(i.key)?i.key.value:i.key:i}set(t,n){if(typeof n!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof n}`);let i=Os.findPair(this.items,t);i&&!n?this.items.splice(this.items.indexOf(i),1):!i&&n&&this.items.push(new Ps.Pair(t))}toJSON(t,n){return super.toJSON(t,n,Set)}toString(t,n,i){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),n,i);throw new Error("Set items must all have null values")}static from(t,n,i){let{replacer:r}=i,s=new this(t);if(n&&Symbol.iterator in Object(n))for(let o of n)typeof r=="function"&&(o=r.call(n,o,o)),s.items.push(Ps.createPair(o,null,i));return s}};yn.tag="tag:yaml.org,2002:set";var tv={collection:"map",identify:e=>e instanceof Set,nodeClass:yn,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,n)=>yn.from(e,t,n),resolve(e,t){if($s.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new yn,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};tc.YAMLSet=yn;tc.set=tv});var rc=v(Is=>{"use strict";var nv=Gn();function ic(e,t){let n=e[0],i=n==="-"||n==="+"?e.substring(1):e,r=o=>t?BigInt(o):Number(o),s=i.replace(/_/g,"").split(":").reduce((o,a)=>o*r(60)+r(a),r(0));return n==="-"?r(-1)*s:s}function Hf(e){let{value:t}=e,n=o=>o;if(typeof t=="bigint")n=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return nv.stringifyNumber(e);let i="";t<0&&(i="-",t*=n(-1));let r=n(60),s=[t%r];return t<60?s.unshift(0):(t=(t-s[0])/r,s.unshift(t%r),t>=60&&(t=(t-s[0])/r,s.unshift(t))),i+s.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var iv={identify:e=>typeof e=="bigint"||Number.isInteger(e),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(e,t,{intAsBigInt:n})=>ic(e,n),stringify:Hf},rv={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:e=>ic(e,!1),stringify:Hf},Kf={identify:e=>e instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(e){let t=e.match(Kf.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,n,i,r,s,o,a]=t.map(Number),c=t[7]?Number((t[7]+"00").substr(1,3)):0,l=Date.UTC(n,i-1,r,s||0,o||0,a||0,c),f=t[8];if(f&&f!=="Z"){let u=ic(f,!1);Math.abs(u)<30&&(u*=60),l-=6e4*u}return new Date(l)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};Is.floatTime=rv;Is.intTime=iv;Is.timestamp=Kf});var Vf=v(Uf=>{"use strict";var sv=Vn(),ov=ys(),av=Yn(),cv=Di(),lv=Va(),Jf=Df(),sc=Ff(),As=Bf(),uv=us(),fv=Xa(),dv=Rs(),mv=nc(),oc=rc(),pv=[sv.map,av.seq,cv.string,ov.nullTag,Jf.trueTag,Jf.falseTag,As.intBin,As.intOct,As.int,As.intHex,sc.floatNaN,sc.floatExp,sc.float,lv.binary,uv.merge,fv.omap,dv.pairs,mv.set,oc.intTime,oc.floatTime,oc.timestamp];Uf.schema=pv});var id=v(lc=>{"use strict";var Xf=Vn(),hv=ys(),Qf=Yn(),gv=Di(),wv=Da(),ac=Wa(),cc=Ha(),yv=_f(),vv=Of(),Zf=Va(),Ki=us(),ed=Xa(),td=Rs(),Yf=Vf(),nd=nc(),Ns=rc(),Gf=new Map([["core",yv.schema],["failsafe",[Xf.map,Qf.seq,gv.string]],["json",vv.schema],["yaml11",Yf.schema],["yaml-1.1",Yf.schema]]),zf={binary:Zf.binary,bool:wv.boolTag,float:ac.float,floatExp:ac.floatExp,floatNaN:ac.floatNaN,floatTime:Ns.floatTime,int:cc.int,intHex:cc.intHex,intOct:cc.intOct,intTime:Ns.intTime,map:Xf.map,merge:Ki.merge,null:hv.nullTag,omap:ed.omap,pairs:td.pairs,seq:Qf.seq,set:nd.set,timestamp:Ns.timestamp},bv={"tag:yaml.org,2002:binary":Zf.binary,"tag:yaml.org,2002:merge":Ki.merge,"tag:yaml.org,2002:omap":ed.omap,"tag:yaml.org,2002:pairs":td.pairs,"tag:yaml.org,2002:set":nd.set,"tag:yaml.org,2002:timestamp":Ns.timestamp};function Cv(e,t,n){let i=Gf.get(t);if(i&&!e)return n&&!i.includes(Ki.merge)?i.concat(Ki.merge):i.slice();let r=i;if(!r)if(Array.isArray(e))r=[];else{let s=Array.from(Gf.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${t}"; use one of ${s} or define customTags array`)}if(Array.isArray(e))for(let s of e)r=r.concat(s);else typeof e=="function"&&(r=e(r.slice()));return n&&(r=r.concat(Ki.merge)),r.reduce((s,o)=>{let a=typeof o=="string"?zf[o]:o;if(!a){let c=JSON.stringify(o),l=Object.keys(zf).map(f=>JSON.stringify(f)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return s.includes(a)||s.push(a),s},[])}lc.coreKnownTags=bv;lc.getTags=Cv});var dc=v(rd=>{"use strict";var uc=M(),kv=Vn(),Sv=Yn(),Ev=Di(),Ts=id(),Rv=(e,t)=>e.keyt.key?1:0,fc=class e{constructor({compat:t,customTags:n,merge:i,resolveKnownTags:r,schema:s,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(t)?Ts.getTags(t,"compat"):t?Ts.getTags(null,t):null,this.name=typeof s=="string"&&s||"core",this.knownTags=r?Ts.coreKnownTags:{},this.tags=Ts.getTags(n,this.name,i),this.toStringOptions=a??null,Object.defineProperty(this,uc.MAP,{value:kv.map}),Object.defineProperty(this,uc.SCALAR,{value:Ev.string}),Object.defineProperty(this,uc.SEQ,{value:Sv.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?Rv:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};rd.Schema=fc});var od=v(sd=>{"use strict";var _v=M(),mc=Li(),Ji=Ai();function xv(e,t){let n=[],i=t.directives===!0;if(t.directives!==!1&&e.directives){let c=e.directives.toString(e);c?(n.push(c),i=!0):e.directives.docStart&&(i=!0)}i&&n.push("---");let r=mc.createStringifyContext(e,t),{commentString:s}=r.options;if(e.commentBefore){n.length!==1&&n.unshift("");let c=s(e.commentBefore);n.unshift(Ji.indentComment(c,""))}let o=!1,a=null;if(e.contents){if(_v.isNode(e.contents)){if(e.contents.spaceBefore&&i&&n.push(""),e.contents.commentBefore){let f=s(e.contents.commentBefore);n.push(Ji.indentComment(f,""))}r.forceBlockIndent=!!e.comment,a=e.contents.comment}let c=a?void 0:()=>o=!0,l=mc.stringify(e.contents,r,()=>a=null,c);a&&(l+=Ji.lineComment(l,"",s(a))),(l[0]==="|"||l[0]===">")&&n[n.length-1]==="---"?n[n.length-1]=`--- ${l}`:n.push(l)}else n.push(mc.stringify(e.contents,r));if(e.directives?.docEnd)if(e.comment){let c=s(e.comment);c.includes(` `)?(n.push("..."),n.push(Ji.indentComment(c,""))):n.push(`... ${c}`)}else n.push("...");else{let c=e.comment;c&&o&&(c=c.replace(/^\n+/,"")),c&&((!o||a)&&n[n.length-1]!==""&&n.push(""),n.push(Ji.indentComment(s(c),"")))}return n.join(` `)+` -`}sd.stringifyDocument=Rv});var Ui=v(ad=>{"use strict";var _v=$i(),zn=es(),De=M(),xv=Wt(),Pv=Mt(),Ov=dc(),$v=od(),pc=zr(),Iv=ya(),Av=Ii(),hc=wa(),gc=class e{constructor(t,n,i){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,De.NODE_TYPE,{value:De.DOC});let r=null;typeof n=="function"||Array.isArray(n)?r=n:i===void 0&&n&&(i=n,n=void 0);let s=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},i);this.options=s;let{version:o}=s;i?._directives?(this.directives=i._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new hc.Directives({version:o}),this.setSchema(o,i),this.contents=t===void 0?null:this.createNode(t,r,i)}clone(){let t=Object.create(e.prototype,{[De.NODE_TYPE]:{value:De.DOC}});return t.commentBefore=this.commentBefore,t.comment=this.comment,t.errors=this.errors.slice(),t.warnings=this.warnings.slice(),t.options=Object.assign({},this.options),this.directives&&(t.directives=this.directives.clone()),t.schema=this.schema.clone(),t.contents=De.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){Xn(this.contents)&&this.contents.add(t)}addIn(t,n){Xn(this.contents)&&this.contents.addIn(t,n)}createAlias(t,n){if(!t.anchor){let i=pc.anchorNames(this);t.anchor=!n||i.has(n)?pc.findNewAnchor(n||"a",i):n}return new _v.Alias(t.anchor)}createNode(t,n,i){let r;if(typeof n=="function")t=n.call({"":t},"",t),r=n;else if(Array.isArray(n)){let m=w=>typeof w=="number"||w instanceof String||w instanceof Number,y=n.filter(m).map(String);y.length>0&&(n=n.concat(y)),r=n}else i===void 0&&n&&(i=n,n=void 0);let{aliasDuplicateObjects:s,anchorPrefix:o,flow:a,keepUndefined:c,onTagObj:l,tag:f}=i??{},{onAnchor:u,setAnchors:d,sourceObjects:p}=pc.createNodeAnchors(this,o||"a"),g={aliasDuplicateObjects:s??!0,keepUndefined:c??!1,onAnchor:u,onTagObj:l,replacer:r,schema:this.schema,sourceObjects:p},h=Av.createNode(t,f,g);return a&&De.isCollection(h)&&(h.flow=!0),d(),h}createPair(t,n,i={}){let r=this.createNode(t,null,i),s=this.createNode(n,null,i);return new xv.Pair(r,s)}delete(t){return Xn(this.contents)?this.contents.delete(t):!1}deleteIn(t){return zn.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):Xn(this.contents)?this.contents.deleteIn(t):!1}get(t,n){return De.isCollection(this.contents)?this.contents.get(t,n):void 0}getIn(t,n){return zn.isEmptyPath(t)?!n&&De.isScalar(this.contents)?this.contents.value:this.contents:De.isCollection(this.contents)?this.contents.getIn(t,n):void 0}has(t){return De.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return zn.isEmptyPath(t)?this.contents!==void 0:De.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,n){this.contents==null?this.contents=zn.collectionFromPath(this.schema,[t],n):Xn(this.contents)&&this.contents.set(t,n)}setIn(t,n){zn.isEmptyPath(t)?this.contents=n:this.contents==null?this.contents=zn.collectionFromPath(this.schema,Array.from(t),n):Xn(this.contents)&&this.contents.setIn(t,n)}setSchema(t,n={}){typeof t=="number"&&(t=String(t));let i;switch(t){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new hc.Directives({version:"1.1"}),i={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=t:this.directives=new hc.Directives({version:t}),i={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,i=null;break;default:{let r=JSON.stringify(t);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${r}`)}}if(n.schema instanceof Object)this.schema=n.schema;else if(i)this.schema=new Ov.Schema(Object.assign(i,n));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:t,jsonArg:n,mapAsMap:i,maxAliasCount:r,onAnchor:s,reviver:o}={}){let a={anchors:new Map,doc:this,keep:!t,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},c=Pv.toJS(this.contents,n??"",a);if(typeof s=="function")for(let{count:l,res:f}of a.anchors.values())s(f,l);return typeof o=="function"?Iv.applyReviver(o,{"":c},"",c):c}toJSON(t,n){return this.toJS({json:!0,jsonArg:t,mapAsMap:!1,onAnchor:n})}toString(t={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in t&&(!Number.isInteger(t.indent)||Number(t.indent)<=0)){let n=JSON.stringify(t.indent);throw new Error(`"indent" option must be a positive integer, not ${n}`)}return $v.stringifyDocument(this,t)}};function Xn(e){if(De.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}ad.Document=gc});var Gi=v(Yi=>{"use strict";var Vi=class extends Error{constructor(t,n,i,r){super(),this.name=t,this.code=i,this.message=r,this.pos=n}},wc=class extends Vi{constructor(t,n,i){super("YAMLParseError",t,n,i)}},yc=class extends Vi{constructor(t,n,i){super("YAMLWarning",t,n,i)}},Nv=(e,t)=>n=>{if(n.pos[0]===-1)return;n.linePos=n.pos.map(a=>t.linePos(a));let{line:i,col:r}=n.linePos[0];n.message+=` at line ${i}, column ${r}`;let s=r-1,o=e.substring(t.lineStarts[i-1],t.lineStarts[i]).replace(/[\n\r]+$/,"");if(s>=60&&o.length>80){let a=Math.min(s-39,o.length-79);o="…"+o.substring(a),s-=a-1}if(o.length>80&&(o=o.substring(0,79)+"…"),i>1&&/^ *$/.test(o.substring(0,s))){let a=e.substring(t.lineStarts[i-2],t.lineStarts[i-1]);a.length>80&&(a=a.substring(0,79)+`… +`}sd.stringifyDocument=xv});var Ui=v(ad=>{"use strict";var Pv=$i(),zn=es(),De=M(),Ov=Wt(),$v=Mt(),Iv=dc(),Av=od(),pc=zr(),Nv=ya(),Tv=Ii(),hc=wa(),gc=class e{constructor(t,n,i){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,De.NODE_TYPE,{value:De.DOC});let r=null;typeof n=="function"||Array.isArray(n)?r=n:i===void 0&&n&&(i=n,n=void 0);let s=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},i);this.options=s;let{version:o}=s;i?._directives?(this.directives=i._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new hc.Directives({version:o}),this.setSchema(o,i),this.contents=t===void 0?null:this.createNode(t,r,i)}clone(){let t=Object.create(e.prototype,{[De.NODE_TYPE]:{value:De.DOC}});return t.commentBefore=this.commentBefore,t.comment=this.comment,t.errors=this.errors.slice(),t.warnings=this.warnings.slice(),t.options=Object.assign({},this.options),this.directives&&(t.directives=this.directives.clone()),t.schema=this.schema.clone(),t.contents=De.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){Xn(this.contents)&&this.contents.add(t)}addIn(t,n){Xn(this.contents)&&this.contents.addIn(t,n)}createAlias(t,n){if(!t.anchor){let i=pc.anchorNames(this);t.anchor=!n||i.has(n)?pc.findNewAnchor(n||"a",i):n}return new Pv.Alias(t.anchor)}createNode(t,n,i){let r;if(typeof n=="function")t=n.call({"":t},"",t),r=n;else if(Array.isArray(n)){let m=w=>typeof w=="number"||w instanceof String||w instanceof Number,y=n.filter(m).map(String);y.length>0&&(n=n.concat(y)),r=n}else i===void 0&&n&&(i=n,n=void 0);let{aliasDuplicateObjects:s,anchorPrefix:o,flow:a,keepUndefined:c,onTagObj:l,tag:f}=i??{},{onAnchor:u,setAnchors:d,sourceObjects:p}=pc.createNodeAnchors(this,o||"a"),g={aliasDuplicateObjects:s??!0,keepUndefined:c??!1,onAnchor:u,onTagObj:l,replacer:r,schema:this.schema,sourceObjects:p},h=Tv.createNode(t,f,g);return a&&De.isCollection(h)&&(h.flow=!0),d(),h}createPair(t,n,i={}){let r=this.createNode(t,null,i),s=this.createNode(n,null,i);return new Ov.Pair(r,s)}delete(t){return Xn(this.contents)?this.contents.delete(t):!1}deleteIn(t){return zn.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):Xn(this.contents)?this.contents.deleteIn(t):!1}get(t,n){return De.isCollection(this.contents)?this.contents.get(t,n):void 0}getIn(t,n){return zn.isEmptyPath(t)?!n&&De.isScalar(this.contents)?this.contents.value:this.contents:De.isCollection(this.contents)?this.contents.getIn(t,n):void 0}has(t){return De.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return zn.isEmptyPath(t)?this.contents!==void 0:De.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,n){this.contents==null?this.contents=zn.collectionFromPath(this.schema,[t],n):Xn(this.contents)&&this.contents.set(t,n)}setIn(t,n){zn.isEmptyPath(t)?this.contents=n:this.contents==null?this.contents=zn.collectionFromPath(this.schema,Array.from(t),n):Xn(this.contents)&&this.contents.setIn(t,n)}setSchema(t,n={}){typeof t=="number"&&(t=String(t));let i;switch(t){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new hc.Directives({version:"1.1"}),i={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=t:this.directives=new hc.Directives({version:t}),i={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,i=null;break;default:{let r=JSON.stringify(t);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${r}`)}}if(n.schema instanceof Object)this.schema=n.schema;else if(i)this.schema=new Iv.Schema(Object.assign(i,n));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:t,jsonArg:n,mapAsMap:i,maxAliasCount:r,onAnchor:s,reviver:o}={}){let a={anchors:new Map,doc:this,keep:!t,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},c=$v.toJS(this.contents,n??"",a);if(typeof s=="function")for(let{count:l,res:f}of a.anchors.values())s(f,l);return typeof o=="function"?Nv.applyReviver(o,{"":c},"",c):c}toJSON(t,n){return this.toJS({json:!0,jsonArg:t,mapAsMap:!1,onAnchor:n})}toString(t={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in t&&(!Number.isInteger(t.indent)||Number(t.indent)<=0)){let n=JSON.stringify(t.indent);throw new Error(`"indent" option must be a positive integer, not ${n}`)}return Av.stringifyDocument(this,t)}};function Xn(e){if(De.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}ad.Document=gc});var Gi=v(Yi=>{"use strict";var Vi=class extends Error{constructor(t,n,i,r){super(),this.name=t,this.code=i,this.message=r,this.pos=n}},wc=class extends Vi{constructor(t,n,i){super("YAMLParseError",t,n,i)}},yc=class extends Vi{constructor(t,n,i){super("YAMLWarning",t,n,i)}},jv=(e,t)=>n=>{if(n.pos[0]===-1)return;n.linePos=n.pos.map(a=>t.linePos(a));let{line:i,col:r}=n.linePos[0];n.message+=` at line ${i}, column ${r}`;let s=r-1,o=e.substring(t.lineStarts[i-1],t.lineStarts[i]).replace(/[\n\r]+$/,"");if(s>=60&&o.length>80){let a=Math.min(s-39,o.length-79);o="…"+o.substring(a),s-=a-1}if(o.length>80&&(o=o.substring(0,79)+"…"),i>1&&/^ *$/.test(o.substring(0,s))){let a=e.substring(t.lineStarts[i-2],t.lineStarts[i-1]);a.length>80&&(a=a.substring(0,79)+`… `),o=a+o}if(/[^ ]/.test(o)){let a=1,c=n.linePos[1];c?.line===i&&c.col>r&&(a=Math.max(1,Math.min(c.col-r,80-s)));let l=" ".repeat(s)+"^".repeat(a);n.message+=`: ${o} ${l} -`}};Yi.YAMLError=Vi;Yi.YAMLParseError=wc;Yi.YAMLWarning=yc;Yi.prettifyError=Nv});var zi=v(cd=>{"use strict";function Tv(e,{flow:t,indicator:n,next:i,offset:r,onError:s,parentIndent:o,startOnNewline:a}){let c=!1,l=a,f=a,u="",d="",p=!1,g=!1,h=null,m=null,y=null,w=null,C=null,k=null,E=null;for(let b of e)switch(g&&(b.type!=="space"&&b.type!=="newline"&&b.type!=="comma"&&s(b.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),g=!1),h&&(l&&b.type!=="comment"&&b.type!=="newline"&&s(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),h=null),b.type){case"space":!t&&(n!=="doc-start"||i?.type!=="flow-collection")&&b.source.includes(" ")&&(h=b),f=!0;break;case"comment":{f||s(b,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let L=b.source.substring(1)||" ";u?u+=d+L:u=L,d="",l=!1;break}case"newline":l?u?u+=b.source:(!k||n!=="seq-item-ind")&&(c=!0):d+=b.source,l=!0,p=!0,(m||y)&&(w=b),f=!0;break;case"anchor":m&&s(b,"MULTIPLE_ANCHORS","A node can have at most one anchor"),b.source.endsWith(":")&&s(b.offset+b.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),m=b,E??(E=b.offset),l=!1,f=!1,g=!0;break;case"tag":{y&&s(b,"MULTIPLE_TAGS","A node can have at most one tag"),y=b,E??(E=b.offset),l=!1,f=!1,g=!0;break}case n:(m||y)&&s(b,"BAD_PROP_ORDER",`Anchors and tags must be after the ${b.source} indicator`),k&&s(b,"UNEXPECTED_TOKEN",`Unexpected ${b.source} in ${t??"collection"}`),k=b,l=n==="seq-item-ind"||n==="explicit-key-ind",f=!1;break;case"comma":if(t){C&&s(b,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),C=b,l=!1,f=!1;break}default:s(b,"UNEXPECTED_TOKEN",`Unexpected ${b.type} token`),l=!1,f=!1}let R=e[e.length-1],O=R?R.offset+R.source.length:r;return g&&i&&i.type!=="space"&&i.type!=="newline"&&i.type!=="comma"&&(i.type!=="scalar"||i.source!=="")&&s(i.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),h&&(l&&h.indent<=o||i?.type==="block-map"||i?.type==="block-seq")&&s(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:C,found:k,spaceBefore:c,comment:u,hasNewline:p,anchor:m,tag:y,newlineAfterProp:w,end:O,start:E??O}}cd.resolveProps=Tv});var js=v(ld=>{"use strict";function vc(e){if(!e)return null;switch(e.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(e.source.includes(` -`))return!0;if(e.end){for(let t of e.end)if(t.type==="newline")return!0}return!1;case"flow-collection":for(let t of e.items){for(let n of t.start)if(n.type==="newline")return!0;if(t.sep){for(let n of t.sep)if(n.type==="newline")return!0}if(vc(t.key)||vc(t.value))return!0}return!1;default:return!0}}ld.containsNewline=vc});var bc=v(ud=>{"use strict";var jv=js();function Lv(e,t,n){if(t?.type==="flow-collection"){let i=t.end[0];i.indent===e&&(i.source==="]"||i.source==="}")&&jv.containsNewline(t)&&n(i,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}ud.flowIndentCheck=Lv});var Cc=v(dd=>{"use strict";var fd=M();function Mv(e,t,n){let{uniqueKeys:i}=e.options;if(i===!1)return!1;let r=typeof i=="function"?i:(s,o)=>s===o||fd.isScalar(s)&&fd.isScalar(o)&&s.value===o.value;return t.some(s=>r(s.key,n))}dd.mapIncludes=Mv});var yd=v(wd=>{"use strict";var md=Wt(),qv=Ht(),pd=zi(),Dv=js(),hd=bc(),Fv=Cc(),gd="All mapping items must start at the same column";function Wv({composeNode:e,composeEmptyNode:t},n,i,r,s){let o=s?.nodeClass??qv.YAMLMap,a=new o(n.schema);n.atRoot&&(n.atRoot=!1);let c=i.offset,l=null;for(let f of i.items){let{start:u,key:d,sep:p,value:g}=f,h=pd.resolveProps(u,{indicator:"explicit-key-ind",next:d??p?.[0],offset:c,onError:r,parentIndent:i.indent,startOnNewline:!0}),m=!h.found;if(m){if(d&&(d.type==="block-seq"?r(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in d&&d.indent!==i.indent&&r(c,"BAD_INDENT",gd)),!h.anchor&&!h.tag&&!p){l=h.end,h.comment&&(a.comment?a.comment+=` -`+h.comment:a.comment=h.comment);continue}(h.newlineAfterProp||Dv.containsNewline(d))&&r(d??u[u.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else h.found?.indent!==i.indent&&r(c,"BAD_INDENT",gd);n.atKey=!0;let y=h.end,w=d?e(n,d,h,r):t(n,y,u,null,h,r);n.schema.compat&&hd.flowIndentCheck(i.indent,d,r),n.atKey=!1,Fv.mapIncludes(n,a.items,w)&&r(y,"DUPLICATE_KEY","Map keys must be unique");let C=pd.resolveProps(p??[],{indicator:"map-value-ind",next:g,offset:w.range[2],onError:r,parentIndent:i.indent,startOnNewline:!d||d.type==="block-scalar"});if(c=C.end,C.found){m&&(g?.type==="block-map"&&!C.hasNewline&&r(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),n.options.strict&&h.start{"use strict";var Bv=Kt(),Hv=zi(),Kv=bc();function Jv({composeNode:e,composeEmptyNode:t},n,i,r,s){let o=s?.nodeClass??Bv.YAMLSeq,a=new o(n.schema);n.atRoot&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let c=i.offset,l=null;for(let{start:f,value:u}of i.items){let d=Hv.resolveProps(f,{indicator:"seq-item-ind",next:u,offset:c,onError:r,parentIndent:i.indent,startOnNewline:!0});if(!d.found)if(d.anchor||d.tag||u)u?.type==="block-seq"?r(d.end,"BAD_INDENT","All sequence items must start at the same column"):r(c,"MISSING_CHAR","Sequence item without - indicator");else{l=d.end,d.comment&&(a.comment=d.comment);continue}let p=u?e(n,u,d,r):t(n,d.end,f,null,d,r);n.schema.compat&&Kv.flowIndentCheck(i.indent,u,r),c=p.range[2],a.items.push(p)}return a.range=[i.offset,c,l??c],a}vd.resolveBlockSeq=Jv});var Qn=v(Cd=>{"use strict";function Uv(e,t,n,i){let r="";if(e){let s=!1,o="";for(let a of e){let{source:c,type:l}=a;switch(l){case"space":s=!0;break;case"comment":{n&&!s&&i(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let f=c.substring(1)||" ";r?r+=o+f:r=f,o="";break}case"newline":r&&(o+=c),s=!0;break;default:i(a,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}t+=c.length}}return{comment:r,offset:t}}Cd.resolveEnd=Uv});var Rd=v(Ed=>{"use strict";var Vv=M(),Yv=Wt(),kd=Ht(),Gv=Kt(),zv=Qn(),Sd=zi(),Xv=js(),Qv=Cc(),kc="Block collections are not allowed within flow collections",Sc=e=>e&&(e.type==="block-map"||e.type==="block-seq");function Zv({composeNode:e,composeEmptyNode:t},n,i,r,s){let o=i.start.source==="{",a=o?"flow map":"flow sequence",c=s?.nodeClass??(o?kd.YAMLMap:Gv.YAMLSeq),l=new c(n.schema);l.flow=!0;let f=n.atRoot;f&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let u=i.offset+i.start.source.length;for(let m=0;m{"use strict";function Lv(e,{flow:t,indicator:n,next:i,offset:r,onError:s,parentIndent:o,startOnNewline:a}){let c=!1,l=a,f=a,u="",d="",p=!1,g=!1,h=null,m=null,y=null,w=null,C=null,k=null,E=null;for(let b of e)switch(g&&(b.type!=="space"&&b.type!=="newline"&&b.type!=="comma"&&s(b.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),g=!1),h&&(l&&b.type!=="comment"&&b.type!=="newline"&&s(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),h=null),b.type){case"space":!t&&(n!=="doc-start"||i?.type!=="flow-collection")&&b.source.includes(" ")&&(h=b),f=!0;break;case"comment":{f||s(b,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let L=b.source.substring(1)||" ";u?u+=d+L:u=L,d="",l=!1;break}case"newline":l?u?u+=b.source:(!k||n!=="seq-item-ind")&&(c=!0):d+=b.source,l=!0,p=!0,(m||y)&&(w=b),f=!0;break;case"anchor":m&&s(b,"MULTIPLE_ANCHORS","A node can have at most one anchor"),b.source.endsWith(":")&&s(b.offset+b.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),m=b,E??(E=b.offset),l=!1,f=!1,g=!0;break;case"tag":{y&&s(b,"MULTIPLE_TAGS","A node can have at most one tag"),y=b,E??(E=b.offset),l=!1,f=!1,g=!0;break}case n:(m||y)&&s(b,"BAD_PROP_ORDER",`Anchors and tags must be after the ${b.source} indicator`),k&&s(b,"UNEXPECTED_TOKEN",`Unexpected ${b.source} in ${t??"collection"}`),k=b,l=n==="seq-item-ind"||n==="explicit-key-ind",f=!1;break;case"comma":if(t){C&&s(b,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),C=b,l=!1,f=!1;break}default:s(b,"UNEXPECTED_TOKEN",`Unexpected ${b.type} token`),l=!1,f=!1}let R=e[e.length-1],O=R?R.offset+R.source.length:r;return g&&i&&i.type!=="space"&&i.type!=="newline"&&i.type!=="comma"&&(i.type!=="scalar"||i.source!=="")&&s(i.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),h&&(l&&h.indent<=o||i?.type==="block-map"||i?.type==="block-seq")&&s(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:C,found:k,spaceBefore:c,comment:u,hasNewline:p,anchor:m,tag:y,newlineAfterProp:w,end:O,start:E??O}}cd.resolveProps=Lv});var js=v(ld=>{"use strict";function vc(e){if(!e)return null;switch(e.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(e.source.includes(` +`))return!0;if(e.end){for(let t of e.end)if(t.type==="newline")return!0}return!1;case"flow-collection":for(let t of e.items){for(let n of t.start)if(n.type==="newline")return!0;if(t.sep){for(let n of t.sep)if(n.type==="newline")return!0}if(vc(t.key)||vc(t.value))return!0}return!1;default:return!0}}ld.containsNewline=vc});var bc=v(ud=>{"use strict";var Mv=js();function qv(e,t,n){if(t?.type==="flow-collection"){let i=t.end[0];i.indent===e&&(i.source==="]"||i.source==="}")&&Mv.containsNewline(t)&&n(i,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}ud.flowIndentCheck=qv});var Cc=v(dd=>{"use strict";var fd=M();function Dv(e,t,n){let{uniqueKeys:i}=e.options;if(i===!1)return!1;let r=typeof i=="function"?i:(s,o)=>s===o||fd.isScalar(s)&&fd.isScalar(o)&&s.value===o.value;return t.some(s=>r(s.key,n))}dd.mapIncludes=Dv});var yd=v(wd=>{"use strict";var md=Wt(),Fv=Ht(),pd=zi(),Wv=js(),hd=bc(),Bv=Cc(),gd="All mapping items must start at the same column";function Hv({composeNode:e,composeEmptyNode:t},n,i,r,s){let o=s?.nodeClass??Fv.YAMLMap,a=new o(n.schema);n.atRoot&&(n.atRoot=!1);let c=i.offset,l=null;for(let f of i.items){let{start:u,key:d,sep:p,value:g}=f,h=pd.resolveProps(u,{indicator:"explicit-key-ind",next:d??p?.[0],offset:c,onError:r,parentIndent:i.indent,startOnNewline:!0}),m=!h.found;if(m){if(d&&(d.type==="block-seq"?r(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in d&&d.indent!==i.indent&&r(c,"BAD_INDENT",gd)),!h.anchor&&!h.tag&&!p){l=h.end,h.comment&&(a.comment?a.comment+=` +`+h.comment:a.comment=h.comment);continue}(h.newlineAfterProp||Wv.containsNewline(d))&&r(d??u[u.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else h.found?.indent!==i.indent&&r(c,"BAD_INDENT",gd);n.atKey=!0;let y=h.end,w=d?e(n,d,h,r):t(n,y,u,null,h,r);n.schema.compat&&hd.flowIndentCheck(i.indent,d,r),n.atKey=!1,Bv.mapIncludes(n,a.items,w)&&r(y,"DUPLICATE_KEY","Map keys must be unique");let C=pd.resolveProps(p??[],{indicator:"map-value-ind",next:g,offset:w.range[2],onError:r,parentIndent:i.indent,startOnNewline:!d||d.type==="block-scalar"});if(c=C.end,C.found){m&&(g?.type==="block-map"&&!C.hasNewline&&r(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),n.options.strict&&h.start{"use strict";var Kv=Kt(),Jv=zi(),Uv=bc();function Vv({composeNode:e,composeEmptyNode:t},n,i,r,s){let o=s?.nodeClass??Kv.YAMLSeq,a=new o(n.schema);n.atRoot&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let c=i.offset,l=null;for(let{start:f,value:u}of i.items){let d=Jv.resolveProps(f,{indicator:"seq-item-ind",next:u,offset:c,onError:r,parentIndent:i.indent,startOnNewline:!0});if(!d.found)if(d.anchor||d.tag||u)u?.type==="block-seq"?r(d.end,"BAD_INDENT","All sequence items must start at the same column"):r(c,"MISSING_CHAR","Sequence item without - indicator");else{l=d.end,d.comment&&(a.comment=d.comment);continue}let p=u?e(n,u,d,r):t(n,d.end,f,null,d,r);n.schema.compat&&Uv.flowIndentCheck(i.indent,u,r),c=p.range[2],a.items.push(p)}return a.range=[i.offset,c,l??c],a}vd.resolveBlockSeq=Vv});var Qn=v(Cd=>{"use strict";function Yv(e,t,n,i){let r="";if(e){let s=!1,o="";for(let a of e){let{source:c,type:l}=a;switch(l){case"space":s=!0;break;case"comment":{n&&!s&&i(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let f=c.substring(1)||" ";r?r+=o+f:r=f,o="";break}case"newline":r&&(o+=c),s=!0;break;default:i(a,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}t+=c.length}}return{comment:r,offset:t}}Cd.resolveEnd=Yv});var Rd=v(Ed=>{"use strict";var Gv=M(),zv=Wt(),kd=Ht(),Xv=Kt(),Qv=Qn(),Sd=zi(),Zv=js(),eb=Cc(),kc="Block collections are not allowed within flow collections",Sc=e=>e&&(e.type==="block-map"||e.type==="block-seq");function tb({composeNode:e,composeEmptyNode:t},n,i,r,s){let o=i.start.source==="{",a=o?"flow map":"flow sequence",c=s?.nodeClass??(o?kd.YAMLMap:Xv.YAMLSeq),l=new c(n.schema);l.flow=!0;let f=n.atRoot;f&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let u=i.offset+i.start.source.length;for(let m=0;m0){let m=zv.resolveEnd(g,h,n.options.strict,r);m.comment&&(l.comment?l.comment+=` -`+m.comment:l.comment=m.comment),l.range=[i.offset,h,m.offset]}else l.range=[i.offset,h,h];return l}Ed.resolveFlowCollection=Zv});var xd=v(_d=>{"use strict";var eb=M(),tb=Z(),nb=Ht(),ib=Kt(),rb=yd(),sb=bd(),ob=Rd();function Ec(e,t,n,i,r,s){let o=n.type==="block-map"?rb.resolveBlockMap(e,t,n,i,s):n.type==="block-seq"?sb.resolveBlockSeq(e,t,n,i,s):ob.resolveFlowCollection(e,t,n,i,s),a=o.constructor;return r==="!"||r===a.tagName?(o.tag=a.tagName,o):(r&&(o.tag=r),o)}function ab(e,t,n,i,r){let s=i.tag,o=s?t.directives.tagName(s.source,d=>r(s,"TAG_RESOLVE_FAILED",d)):null;if(n.type==="block-seq"){let{anchor:d,newlineAfterProp:p}=i,g=d&&s?d.offset>s.offset?d:s:d??s;g&&(!p||p.offsetd.tag===o&&d.collection===a);if(!c){let d=t.schema.knownTags[o];if(d?.collection===a)t.schema.tags.push(Object.assign({},d,{default:!1})),c=d;else return d?r(s,"BAD_COLLECTION_TYPE",`${d.tag} used for ${a} collection, but expects ${d.collection??"scalar"}`,!0):r(s,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),Ec(e,t,n,r,o)}let l=Ec(e,t,n,r,o,c),f=c.resolve?.(l,d=>r(s,"TAG_RESOLVE_FAILED",d),t.options)??l,u=eb.isNode(f)?f:new tb.Scalar(f);return u.range=l.range,u.tag=o,c?.format&&(u.format=c.format),u}_d.composeCollection=ab});var _c=v(Pd=>{"use strict";var Rc=Z();function cb(e,t,n){let i=t.offset,r=lb(t,e.options.strict,n);if(!r)return{value:"",type:null,comment:"",range:[i,i,i]};let s=r.mode===">"?Rc.Scalar.BLOCK_FOLDED:Rc.Scalar.BLOCK_LITERAL,o=t.source?ub(t.source):[],a=o.length;for(let h=o.length-1;h>=0;--h){let m=o[h][1];if(m===""||m==="\r")a=h;else break}if(a===0){let h=r.chomp==="+"&&o.length>0?` +`+L.comment:b.comment=L.comment);let Q=new zv.Pair(b,Ie);if(n.options.keepSourceTokens&&(Q.srcToken=y),o){let K=l;eb.mapIncludes(n,K.items,b)&&r(O,"DUPLICATE_KEY","Map keys must be unique"),K.items.push(Q)}else{let K=new kd.YAMLMap(n.schema);K.flow=!0,K.items.push(Q);let Ce=(Ie??b).range;K.range=[b.range[0],Ce[1],Ce[2]],l.items.push(K)}u=Ie?Ie.range[2]:L.end}}let d=o?"}":"]",[p,...g]=i.end,h=u;if(p?.source===d)h=p.offset+p.source.length;else{let m=a[0].toUpperCase()+a.substring(1),y=f?`${m} must end with a ${d}`:`${m} in block collection must be sufficiently indented and end with a ${d}`;r(u,f?"MISSING_CHAR":"BAD_INDENT",y),p&&p.source.length!==1&&g.unshift(p)}if(g.length>0){let m=Qv.resolveEnd(g,h,n.options.strict,r);m.comment&&(l.comment?l.comment+=` +`+m.comment:l.comment=m.comment),l.range=[i.offset,h,m.offset]}else l.range=[i.offset,h,h];return l}Ed.resolveFlowCollection=tb});var xd=v(_d=>{"use strict";var nb=M(),ib=Z(),rb=Ht(),sb=Kt(),ob=yd(),ab=bd(),cb=Rd();function Ec(e,t,n,i,r,s){let o=n.type==="block-map"?ob.resolveBlockMap(e,t,n,i,s):n.type==="block-seq"?ab.resolveBlockSeq(e,t,n,i,s):cb.resolveFlowCollection(e,t,n,i,s),a=o.constructor;return r==="!"||r===a.tagName?(o.tag=a.tagName,o):(r&&(o.tag=r),o)}function lb(e,t,n,i,r){let s=i.tag,o=s?t.directives.tagName(s.source,d=>r(s,"TAG_RESOLVE_FAILED",d)):null;if(n.type==="block-seq"){let{anchor:d,newlineAfterProp:p}=i,g=d&&s?d.offset>s.offset?d:s:d??s;g&&(!p||p.offsetd.tag===o&&d.collection===a);if(!c){let d=t.schema.knownTags[o];if(d?.collection===a)t.schema.tags.push(Object.assign({},d,{default:!1})),c=d;else return d?r(s,"BAD_COLLECTION_TYPE",`${d.tag} used for ${a} collection, but expects ${d.collection??"scalar"}`,!0):r(s,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),Ec(e,t,n,r,o)}let l=Ec(e,t,n,r,o,c),f=c.resolve?.(l,d=>r(s,"TAG_RESOLVE_FAILED",d),t.options)??l,u=nb.isNode(f)?f:new ib.Scalar(f);return u.range=l.range,u.tag=o,c?.format&&(u.format=c.format),u}_d.composeCollection=lb});var _c=v(Pd=>{"use strict";var Rc=Z();function ub(e,t,n){let i=t.offset,r=fb(t,e.options.strict,n);if(!r)return{value:"",type:null,comment:"",range:[i,i,i]};let s=r.mode===">"?Rc.Scalar.BLOCK_FOLDED:Rc.Scalar.BLOCK_LITERAL,o=t.source?db(t.source):[],a=o.length;for(let h=o.length-1;h>=0;--h){let m=o[h][1];if(m===""||m==="\r")a=h;else break}if(a===0){let h=r.chomp==="+"&&o.length>0?` `.repeat(Math.max(1,o.length-1)):"",m=i+r.length;return t.source&&(m+=t.source.length),{value:h,type:s,comment:r.comment,range:[i,m,m]}}let c=t.indent+r.indent,l=t.offset+r.length,f=0;for(let h=0;hc&&(c=m.length);else{m.length=a;--h)o[h][0].length>c&&(a=h+1);let u="",d="",p=!1;for(let h=0;hc||y[0]===" "?(d===" "?d=` @@ -84,41 +84,41 @@ ${l} `+o[h][0].slice(c);u[u.length-1]!==` `&&(u+=` `);break;default:u+=` -`}let g=i+r.length+t.source.length;return{value:u,type:s,comment:r.comment,range:[i,g,g]}}function lb({offset:e,props:t},n,i){if(t[0].type!=="block-scalar-header")return i(t[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:r}=t[0],s=r[0],o=0,a="",c=-1;for(let d=1;d{"use strict";var xc=Z(),fb=Qn();function db(e,t,n){let{offset:i,type:r,source:s,end:o}=e,a,c,l=(d,p,g)=>n(i+d,p,g);switch(r){case"scalar":a=xc.Scalar.PLAIN,c=mb(s,l);break;case"single-quoted-scalar":a=xc.Scalar.QUOTE_SINGLE,c=pb(s,l);break;case"double-quoted-scalar":a=xc.Scalar.QUOTE_DOUBLE,c=hb(s,l);break;default:return n(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${r}`),{value:"",type:null,comment:"",range:[i,i+s.length,i+s.length]}}let f=i+s.length,u=fb.resolveEnd(o,f,t,n);return{value:c,type:a,comment:u.comment,range:[i,f,u.offset]}}function mb(e,t){let n="";switch(e[0]){case" ":n="a tab character";break;case",":n="flow indicator character ,";break;case"%":n="directive indicator character %";break;case"|":case">":{n=`block scalar indicator ${e[0]}`;break}case"@":case"`":{n=`reserved character ${e[0]}`;break}}return n&&t(0,"BAD_SCALAR_START",`Plain value cannot start with ${n}`),Od(e)}function pb(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),Od(e.slice(1,-1)).replace(/''/g,"'")}function Od(e){let t,n;try{t=new RegExp(`(.*?)(?{"use strict";var xc=Z(),mb=Qn();function pb(e,t,n){let{offset:i,type:r,source:s,end:o}=e,a,c,l=(d,p,g)=>n(i+d,p,g);switch(r){case"scalar":a=xc.Scalar.PLAIN,c=hb(s,l);break;case"single-quoted-scalar":a=xc.Scalar.QUOTE_SINGLE,c=gb(s,l);break;case"double-quoted-scalar":a=xc.Scalar.QUOTE_DOUBLE,c=wb(s,l);break;default:return n(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${r}`),{value:"",type:null,comment:"",range:[i,i+s.length,i+s.length]}}let f=i+s.length,u=mb.resolveEnd(o,f,t,n);return{value:c,type:a,comment:u.comment,range:[i,f,u.offset]}}function hb(e,t){let n="";switch(e[0]){case" ":n="a tab character";break;case",":n="flow indicator character ,";break;case"%":n="directive indicator character %";break;case"|":case">":{n=`block scalar indicator ${e[0]}`;break}case"@":case"`":{n=`reserved character ${e[0]}`;break}}return n&&t(0,"BAD_SCALAR_START",`Plain value cannot start with ${n}`),Od(e)}function gb(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),Od(e.slice(1,-1)).replace(/''/g,"'")}function Od(e){let t,n;try{t=new RegExp(`(.*?)(?s?e.slice(s,i+1):r)}else n+=r}return(e[e.length-1]!=='"'||e.length===1)&&t(e.length,"MISSING_CHAR",'Missing closing "quote'),n}function gb(e,t){let n="",i=e[t+1];for(;(i===" "||i===" "||i===` +`)&&(n+=i>s?e.slice(s,i+1):r)}else n+=r}return(e[e.length-1]!=='"'||e.length===1)&&t(e.length,"MISSING_CHAR",'Missing closing "quote'),n}function yb(e,t){let n="",i=e[t+1];for(;(i===" "||i===" "||i===` `||i==="\r")&&!(i==="\r"&&e[t+2]!==` `);)i===` `&&(n+=` -`),t+=1,i=e[t+1];return n||(n=" "),{fold:n,offset:t}}var wb={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:` -`,r:"\r",t:" ",v:"\v",N:"…",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function yb(e,t,n,i){let r=e.substr(t,n),o=r.length===n&&/^[0-9a-fA-F]+$/.test(r)?parseInt(r,16):NaN;try{return String.fromCodePoint(o)}catch{let a=e.substr(t-2,n+2);return i(t-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),a}}$d.resolveFlowScalar=db});var Nd=v(Ad=>{"use strict";var vn=M(),Id=Z(),vb=_c(),bb=Pc();function Cb(e,t,n,i){let{value:r,type:s,comment:o,range:a}=t.type==="block-scalar"?vb.resolveBlockScalar(e,t,i):bb.resolveFlowScalar(t,e.options.strict,i),c=n?e.directives.tagName(n.source,u=>i(n,"TAG_RESOLVE_FAILED",u)):null,l;e.options.stringKeys&&e.atKey?l=e.schema[vn.SCALAR]:c?l=kb(e.schema,r,c,n,i):t.type==="scalar"?l=Sb(e,r,t,i):l=e.schema[vn.SCALAR];let f;try{let u=l.resolve(r,d=>i(n??t,"TAG_RESOLVE_FAILED",d),e.options);f=vn.isScalar(u)?u:new Id.Scalar(u)}catch(u){let d=u instanceof Error?u.message:String(u);i(n??t,"TAG_RESOLVE_FAILED",d),f=new Id.Scalar(r)}return f.range=a,f.source=r,s&&(f.type=s),c&&(f.tag=c),l.format&&(f.format=l.format),o&&(f.comment=o),f}function kb(e,t,n,i,r){if(n==="!")return e[vn.SCALAR];let s=[];for(let a of e.tags)if(!a.collection&&a.tag===n)if(a.default&&a.test)s.push(a);else return a;for(let a of s)if(a.test?.test(t))return a;let o=e.knownTags[n];return o&&!o.collection?(e.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(r(i,"TAG_RESOLVE_FAILED",`Unresolved tag: ${n}`,n!=="tag:yaml.org,2002:str"),e[vn.SCALAR])}function Sb({atKey:e,directives:t,schema:n},i,r,s){let o=n.tags.find(a=>(a.default===!0||e&&a.default==="key")&&a.test?.test(i))||n[vn.SCALAR];if(n.compat){let a=n.compat.find(c=>c.default&&c.test?.test(i))??n[vn.SCALAR];if(o.tag!==a.tag){let c=t.tagString(o.tag),l=t.tagString(a.tag),f=`Value may be parsed as either ${c} or ${l}`;s(r,"TAG_RESOLVE_FAILED",f,!0)}}return o}Ad.composeScalar=Cb});var jd=v(Td=>{"use strict";function Eb(e,t,n){if(t){n??(n=t.length);for(let i=n-1;i>=0;--i){let r=t[i];switch(r.type){case"space":case"comment":case"newline":e-=r.source.length;continue}for(r=t[++i];r?.type==="space";)e+=r.source.length,r=t[++i];break}}return e}Td.emptyScalarPosition=Eb});var qd=v($c=>{"use strict";var Rb=$i(),_b=M(),xb=xd(),Ld=Nd(),Pb=Qn(),Ob=jd(),$b={composeNode:Md,composeEmptyNode:Oc};function Md(e,t,n,i){let r=e.atKey,{spaceBefore:s,comment:o,anchor:a,tag:c}=n,l,f=!0;switch(t.type){case"alias":l=Ib(e,t,i),(a||c)&&i(t,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=Ld.composeScalar(e,t,c,i),a&&(l.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=xb.composeCollection($b,e,t,n,i),a&&(l.anchor=a.source.substring(1))}catch(u){let d=u instanceof Error?u.message:String(u);i(t,"RESOURCE_EXHAUSTION",d)}break;default:{let u=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;i(t,"UNEXPECTED_TOKEN",u),f=!1}}return l??(l=Oc(e,t.offset,void 0,null,n,i)),a&&l.anchor===""&&i(a,"BAD_ALIAS","Anchor cannot be an empty string"),r&&e.options.stringKeys&&(!_b.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&i(c??t,"NON_STRING_KEY","With stringKeys, all keys must be strings"),s&&(l.spaceBefore=!0),o&&(t.type==="scalar"&&t.source===""?l.comment=o:l.commentBefore=o),e.options.keepSourceTokens&&f&&(l.srcToken=t),l}function Oc(e,t,n,i,{spaceBefore:r,comment:s,anchor:o,tag:a,end:c},l){let f={type:"scalar",offset:Ob.emptyScalarPosition(t,n,i),indent:-1,source:""},u=Ld.composeScalar(e,f,a,l);return o&&(u.anchor=o.source.substring(1),u.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),r&&(u.spaceBefore=!0),s&&(u.comment=s,u.range[2]=c),u}function Ib({options:e},{offset:t,source:n,end:i},r){let s=new Rb.Alias(n.substring(1));s.source===""&&r(t,"BAD_ALIAS","Alias cannot be an empty string"),s.source.endsWith(":")&&r(t+n.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=t+n.length,a=Pb.resolveEnd(i,o,e.strict,r);return s.range=[t,o,a.offset],a.comment&&(s.comment=a.comment),s}$c.composeEmptyNode=Oc;$c.composeNode=Md});var Wd=v(Fd=>{"use strict";var Ab=Ui(),Dd=qd(),Nb=Qn(),Tb=zi();function jb(e,t,{offset:n,start:i,value:r,end:s},o){let a=Object.assign({_directives:t},e),c=new Ab.Document(void 0,a),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},f=Tb.resolveProps(i,{indicator:"doc-start",next:r??s?.[0],offset:n,onError:o,parentIndent:0,startOnNewline:!0});f.found&&(c.directives.docStart=!0,r&&(r.type==="block-map"||r.type==="block-seq")&&!f.hasNewline&&o(f.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=r?Dd.composeNode(l,r,f,o):Dd.composeEmptyNode(l,f.end,i,null,f,o);let u=c.contents.range[2],d=Nb.resolveEnd(s,u,!1,o);return d.comment&&(c.comment=d.comment),c.range=[n,u,d.offset],c}Fd.composeDoc=jb});var Ac=v(Kd=>{"use strict";var Lb=Jr("process"),Mb=wa(),qb=Ui(),Xi=Gi(),Bd=M(),Db=Wd(),Fb=Qn();function Qi(e){if(typeof e=="number")return[e,e+1];if(Array.isArray(e))return e.length===2?e:[e[0],e[1]];let{offset:t,source:n}=e;return[t,t+(typeof n=="string"?n.length:1)]}function Hd(e){let t="",n=!1,i=!1;for(let r=0;r{"use strict";var vn=M(),Id=Z(),Cb=_c(),kb=Pc();function Sb(e,t,n,i){let{value:r,type:s,comment:o,range:a}=t.type==="block-scalar"?Cb.resolveBlockScalar(e,t,i):kb.resolveFlowScalar(t,e.options.strict,i),c=n?e.directives.tagName(n.source,u=>i(n,"TAG_RESOLVE_FAILED",u)):null,l;e.options.stringKeys&&e.atKey?l=e.schema[vn.SCALAR]:c?l=Eb(e.schema,r,c,n,i):t.type==="scalar"?l=Rb(e,r,t,i):l=e.schema[vn.SCALAR];let f;try{let u=l.resolve(r,d=>i(n??t,"TAG_RESOLVE_FAILED",d),e.options);f=vn.isScalar(u)?u:new Id.Scalar(u)}catch(u){let d=u instanceof Error?u.message:String(u);i(n??t,"TAG_RESOLVE_FAILED",d),f=new Id.Scalar(r)}return f.range=a,f.source=r,s&&(f.type=s),c&&(f.tag=c),l.format&&(f.format=l.format),o&&(f.comment=o),f}function Eb(e,t,n,i,r){if(n==="!")return e[vn.SCALAR];let s=[];for(let a of e.tags)if(!a.collection&&a.tag===n)if(a.default&&a.test)s.push(a);else return a;for(let a of s)if(a.test?.test(t))return a;let o=e.knownTags[n];return o&&!o.collection?(e.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(r(i,"TAG_RESOLVE_FAILED",`Unresolved tag: ${n}`,n!=="tag:yaml.org,2002:str"),e[vn.SCALAR])}function Rb({atKey:e,directives:t,schema:n},i,r,s){let o=n.tags.find(a=>(a.default===!0||e&&a.default==="key")&&a.test?.test(i))||n[vn.SCALAR];if(n.compat){let a=n.compat.find(c=>c.default&&c.test?.test(i))??n[vn.SCALAR];if(o.tag!==a.tag){let c=t.tagString(o.tag),l=t.tagString(a.tag),f=`Value may be parsed as either ${c} or ${l}`;s(r,"TAG_RESOLVE_FAILED",f,!0)}}return o}Ad.composeScalar=Sb});var jd=v(Td=>{"use strict";function _b(e,t,n){if(t){n??(n=t.length);for(let i=n-1;i>=0;--i){let r=t[i];switch(r.type){case"space":case"comment":case"newline":e-=r.source.length;continue}for(r=t[++i];r?.type==="space";)e+=r.source.length,r=t[++i];break}}return e}Td.emptyScalarPosition=_b});var qd=v($c=>{"use strict";var xb=$i(),Pb=M(),Ob=xd(),Ld=Nd(),$b=Qn(),Ib=jd(),Ab={composeNode:Md,composeEmptyNode:Oc};function Md(e,t,n,i){let r=e.atKey,{spaceBefore:s,comment:o,anchor:a,tag:c}=n,l,f=!0;switch(t.type){case"alias":l=Nb(e,t,i),(a||c)&&i(t,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=Ld.composeScalar(e,t,c,i),a&&(l.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=Ob.composeCollection(Ab,e,t,n,i),a&&(l.anchor=a.source.substring(1))}catch(u){let d=u instanceof Error?u.message:String(u);i(t,"RESOURCE_EXHAUSTION",d)}break;default:{let u=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;i(t,"UNEXPECTED_TOKEN",u),f=!1}}return l??(l=Oc(e,t.offset,void 0,null,n,i)),a&&l.anchor===""&&i(a,"BAD_ALIAS","Anchor cannot be an empty string"),r&&e.options.stringKeys&&(!Pb.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&i(c??t,"NON_STRING_KEY","With stringKeys, all keys must be strings"),s&&(l.spaceBefore=!0),o&&(t.type==="scalar"&&t.source===""?l.comment=o:l.commentBefore=o),e.options.keepSourceTokens&&f&&(l.srcToken=t),l}function Oc(e,t,n,i,{spaceBefore:r,comment:s,anchor:o,tag:a,end:c},l){let f={type:"scalar",offset:Ib.emptyScalarPosition(t,n,i),indent:-1,source:""},u=Ld.composeScalar(e,f,a,l);return o&&(u.anchor=o.source.substring(1),u.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),r&&(u.spaceBefore=!0),s&&(u.comment=s,u.range[2]=c),u}function Nb({options:e},{offset:t,source:n,end:i},r){let s=new xb.Alias(n.substring(1));s.source===""&&r(t,"BAD_ALIAS","Alias cannot be an empty string"),s.source.endsWith(":")&&r(t+n.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=t+n.length,a=$b.resolveEnd(i,o,e.strict,r);return s.range=[t,o,a.offset],a.comment&&(s.comment=a.comment),s}$c.composeEmptyNode=Oc;$c.composeNode=Md});var Wd=v(Fd=>{"use strict";var Tb=Ui(),Dd=qd(),jb=Qn(),Lb=zi();function Mb(e,t,{offset:n,start:i,value:r,end:s},o){let a=Object.assign({_directives:t},e),c=new Tb.Document(void 0,a),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},f=Lb.resolveProps(i,{indicator:"doc-start",next:r??s?.[0],offset:n,onError:o,parentIndent:0,startOnNewline:!0});f.found&&(c.directives.docStart=!0,r&&(r.type==="block-map"||r.type==="block-seq")&&!f.hasNewline&&o(f.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=r?Dd.composeNode(l,r,f,o):Dd.composeEmptyNode(l,f.end,i,null,f,o);let u=c.contents.range[2],d=jb.resolveEnd(s,u,!1,o);return d.comment&&(c.comment=d.comment),c.range=[n,u,d.offset],c}Fd.composeDoc=Mb});var Ac=v(Kd=>{"use strict";var qb=Jr("process"),Db=wa(),Fb=Ui(),Xi=Gi(),Bd=M(),Wb=Wd(),Bb=Qn();function Qi(e){if(typeof e=="number")return[e,e+1];if(Array.isArray(e))return e.length===2?e:[e[0],e[1]];let{offset:t,source:n}=e;return[t,t+(typeof n=="string"?n.length:1)]}function Hd(e){let t="",n=!1,i=!1;for(let r=0;r{let o=Qi(n);s?this.warnings.push(new Xi.YAMLWarning(o,i,r)):this.errors.push(new Xi.YAMLParseError(o,i,r))},this.directives=new Mb.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,n){let{comment:i,afterEmptyLine:r}=Hd(this.prelude);if(i){let s=t.contents;if(n)t.comment=t.comment?`${t.comment} +`)+(s.substring(1)||" "),n=!0,i=!1;break;case"%":e[r+1]?.[0]!=="#"&&(r+=1),n=!1;break;default:n||(i=!0),n=!1}}return{comment:t,afterEmptyLine:i}}var Ic=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(n,i,r,s)=>{let o=Qi(n);s?this.warnings.push(new Xi.YAMLWarning(o,i,r)):this.errors.push(new Xi.YAMLParseError(o,i,r))},this.directives=new Db.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,n){let{comment:i,afterEmptyLine:r}=Hd(this.prelude);if(i){let s=t.contents;if(n)t.comment=t.comment?`${t.comment} ${i}`:i;else if(r||t.directives.docStart||!s)t.commentBefore=i;else if(Bd.isCollection(s)&&!s.flow&&s.items.length>0){let o=s.items[0];Bd.isPair(o)&&(o=o.key);let a=o.commentBefore;o.commentBefore=a?`${i} ${a}`:i}else{let o=s.commentBefore;s.commentBefore=o?`${i} -${o}`:i}}if(n){for(let s=0;s{let s=Qi(t);s[0]+=n,this.onError(s,"BAD_DIRECTIVE",i,r)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let n=Db.composeDoc(this.options,this.directives,t,this.onError);this.atDirectives&&!n.directives.docStart&&this.onError(t,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(n,!1),this.doc&&(yield this.doc),this.doc=n,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(t.source);break;case"error":{let n=t.source?`${t.message}: ${JSON.stringify(t.source)}`:t.message,i=new Xi.YAMLParseError(Qi(t),"UNEXPECTED_TOKEN",n);this.atDirectives||!this.doc?this.errors.push(i):this.doc.errors.push(i);break}case"doc-end":{if(!this.doc){let i="Unexpected doc-end without preceding document";this.errors.push(new Xi.YAMLParseError(Qi(t),"UNEXPECTED_TOKEN",i));break}this.doc.directives.docEnd=!0;let n=Fb.resolveEnd(t.end,t.offset+t.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),n.comment){let i=this.doc.comment;this.doc.comment=i?`${i} -${n.comment}`:n.comment}this.doc.range[2]=n.offset;break}default:this.errors.push(new Xi.YAMLParseError(Qi(t),"UNEXPECTED_TOKEN",`Unsupported token ${t.type}`))}}*end(t=!1,n=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(t){let i=Object.assign({_directives:this.directives},this.options),r=new qb.Document(void 0,i);this.atDirectives&&this.onError(n,"MISSING_CHAR","Missing directives-end indicator line"),r.range=[0,n,n],this.decorate(r,!1),yield r}}};Kd.Composer=Ic});var Vd=v(Ls=>{"use strict";var Wb=_c(),Bb=Pc(),Hb=Gi(),Jd=ji();function Kb(e,t=!0,n){if(e){let i=(r,s,o)=>{let a=typeof r=="number"?r:Array.isArray(r)?r[0]:r.offset;if(n)n(a,s,o);else throw new Hb.YAMLParseError([a,a+1],s,o)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return Bb.resolveFlowScalar(e,t,i);case"block-scalar":return Wb.resolveBlockScalar({options:{strict:t}},e,i)}}return null}function Jb(e,t){let{implicitKey:n=!1,indent:i,inFlow:r=!1,offset:s=-1,type:o="PLAIN"}=t,a=Jd.stringifyString({type:o,value:e},{implicitKey:n,indent:i>0?" ".repeat(i):"",inFlow:r,options:{blockQuote:!0,lineWidth:-1}}),c=t.end??[{type:"newline",offset:-1,indent:i,source:` +${o}`:i}}if(n){for(let s=0;s{let s=Qi(t);s[0]+=n,this.onError(s,"BAD_DIRECTIVE",i,r)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let n=Wb.composeDoc(this.options,this.directives,t,this.onError);this.atDirectives&&!n.directives.docStart&&this.onError(t,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(n,!1),this.doc&&(yield this.doc),this.doc=n,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(t.source);break;case"error":{let n=t.source?`${t.message}: ${JSON.stringify(t.source)}`:t.message,i=new Xi.YAMLParseError(Qi(t),"UNEXPECTED_TOKEN",n);this.atDirectives||!this.doc?this.errors.push(i):this.doc.errors.push(i);break}case"doc-end":{if(!this.doc){let i="Unexpected doc-end without preceding document";this.errors.push(new Xi.YAMLParseError(Qi(t),"UNEXPECTED_TOKEN",i));break}this.doc.directives.docEnd=!0;let n=Bb.resolveEnd(t.end,t.offset+t.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),n.comment){let i=this.doc.comment;this.doc.comment=i?`${i} +${n.comment}`:n.comment}this.doc.range[2]=n.offset;break}default:this.errors.push(new Xi.YAMLParseError(Qi(t),"UNEXPECTED_TOKEN",`Unsupported token ${t.type}`))}}*end(t=!1,n=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(t){let i=Object.assign({_directives:this.directives},this.options),r=new Fb.Document(void 0,i);this.atDirectives&&this.onError(n,"MISSING_CHAR","Missing directives-end indicator line"),r.range=[0,n,n],this.decorate(r,!1),yield r}}};Kd.Composer=Ic});var Vd=v(Ls=>{"use strict";var Hb=_c(),Kb=Pc(),Jb=Gi(),Jd=ji();function Ub(e,t=!0,n){if(e){let i=(r,s,o)=>{let a=typeof r=="number"?r:Array.isArray(r)?r[0]:r.offset;if(n)n(a,s,o);else throw new Jb.YAMLParseError([a,a+1],s,o)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return Kb.resolveFlowScalar(e,t,i);case"block-scalar":return Hb.resolveBlockScalar({options:{strict:t}},e,i)}}return null}function Vb(e,t){let{implicitKey:n=!1,indent:i,inFlow:r=!1,offset:s=-1,type:o="PLAIN"}=t,a=Jd.stringifyString({type:o,value:e},{implicitKey:n,indent:i>0?" ".repeat(i):"",inFlow:r,options:{blockQuote:!0,lineWidth:-1}}),c=t.end??[{type:"newline",offset:-1,indent:i,source:` `}];switch(a[0]){case"|":case">":{let l=a.indexOf(` `),f=a.substring(0,l),u=a.substring(l+1)+` `,d=[{type:"block-scalar-header",offset:s,indent:i,source:f}];return Ud(d,c)||d.push({type:"newline",offset:-1,indent:i,source:` -`}),{type:"block-scalar",offset:s,indent:i,props:d,source:u}}case'"':return{type:"double-quoted-scalar",offset:s,indent:i,source:a,end:c};case"'":return{type:"single-quoted-scalar",offset:s,indent:i,source:a,end:c};default:return{type:"scalar",offset:s,indent:i,source:a,end:c}}}function Ub(e,t,n={}){let{afterKey:i=!1,implicitKey:r=!1,inFlow:s=!1,type:o}=n,a="indent"in e?e.indent:null;if(i&&typeof a=="number"&&(a+=2),!o)switch(e.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let l=e.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let c=Jd.stringifyString({type:o,value:t},{implicitKey:r||a===null,indent:a!==null&&a>0?" ".repeat(a):"",inFlow:s,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":Vb(e,c);break;case'"':Nc(e,c,"double-quoted-scalar");break;case"'":Nc(e,c,"single-quoted-scalar");break;default:Nc(e,c,"scalar")}}function Vb(e,t){let n=t.indexOf(` +`}),{type:"block-scalar",offset:s,indent:i,props:d,source:u}}case'"':return{type:"double-quoted-scalar",offset:s,indent:i,source:a,end:c};case"'":return{type:"single-quoted-scalar",offset:s,indent:i,source:a,end:c};default:return{type:"scalar",offset:s,indent:i,source:a,end:c}}}function Yb(e,t,n={}){let{afterKey:i=!1,implicitKey:r=!1,inFlow:s=!1,type:o}=n,a="indent"in e?e.indent:null;if(i&&typeof a=="number"&&(a+=2),!o)switch(e.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let l=e.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let c=Jd.stringifyString({type:o,value:t},{implicitKey:r||a===null,indent:a!==null&&a>0?" ".repeat(a):"",inFlow:s,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":Gb(e,c);break;case'"':Nc(e,c,"double-quoted-scalar");break;case"'":Nc(e,c,"single-quoted-scalar");break;default:Nc(e,c,"scalar")}}function Gb(e,t){let n=t.indexOf(` `),i=t.substring(0,n),r=t.substring(n+1)+` `;if(e.type==="block-scalar"){let s=e.props[0];if(s.type!=="block-scalar-header")throw new Error("Invalid block scalar header");s.source=i,e.source=r}else{let{offset:s}=e,o="indent"in e?e.indent:-1,a=[{type:"block-scalar-header",offset:s,indent:o,source:i}];Ud(a,"end"in e?e.end:void 0)||a.push({type:"newline",offset:-1,indent:o,source:` `});for(let c of Object.keys(e))c!=="type"&&c!=="offset"&&delete e[c];Object.assign(e,{type:"block-scalar",indent:o,props:a,source:r})}}function Ud(e,t){if(t)for(let n of t)switch(n.type){case"space":case"comment":e.push(n);break;case"newline":return e.push(n),!0}return!1}function Nc(e,t,n){switch(e.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":e.type=n,e.source=t;break;case"block-scalar":{let i=e.props.slice(1),r=t.length;e.props[0].type==="block-scalar-header"&&(r-=e.props[0].source.length);for(let s of i)s.offset+=r;delete e.props,Object.assign(e,{type:n,source:t,end:i});break}case"block-map":case"block-seq":{let r={type:"newline",offset:e.offset+t.length,indent:e.indent,source:` -`};delete e.items,Object.assign(e,{type:n,source:t,end:[r]});break}default:{let i="indent"in e?e.indent:-1,r="end"in e&&Array.isArray(e.end)?e.end.filter(s=>s.type==="space"||s.type==="comment"||s.type==="newline"):[];for(let s of Object.keys(e))s!=="type"&&s!=="offset"&&delete e[s];Object.assign(e,{type:n,indent:i,source:t,end:r})}}}Ls.createScalarToken=Jb;Ls.resolveAsScalar=Kb;Ls.setScalarValue=Ub});var Gd=v(Yd=>{"use strict";var Yb=e=>"type"in e?qs(e):Ms(e);function qs(e){switch(e.type){case"block-scalar":{let t="";for(let n of e.props)t+=qs(n);return t+e.source}case"block-map":case"block-seq":{let t="";for(let n of e.items)t+=Ms(n);return t}case"flow-collection":{let t=e.start.source;for(let n of e.items)t+=Ms(n);for(let n of e.end)t+=n.source;return t}case"document":{let t=Ms(e);if(e.end)for(let n of e.end)t+=n.source;return t}default:{let t=e.source;if("end"in e&&e.end)for(let n of e.end)t+=n.source;return t}}}function Ms({start:e,key:t,sep:n,value:i}){let r="";for(let s of e)r+=s.source;if(t&&(r+=qs(t)),n)for(let s of n)r+=s.source;return i&&(r+=qs(i)),r}Yd.stringify=Yb});var Zd=v(Qd=>{"use strict";var Tc=Symbol("break visit"),Gb=Symbol("skip children"),zd=Symbol("remove item");function bn(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),Xd(Object.freeze([]),e,t)}bn.BREAK=Tc;bn.SKIP=Gb;bn.REMOVE=zd;bn.itemAtPath=(e,t)=>{let n=e;for(let[i,r]of t){let s=n?.[i];if(s&&"items"in s)n=s.items[r];else return}return n};bn.parentCollection=(e,t)=>{let n=bn.itemAtPath(e,t.slice(0,-1)),i=t[t.length-1][0],r=n?.[i];if(r&&"items"in r)return r;throw new Error("Parent collection not found")};function Xd(e,t,n){let i=n(t,e);if(typeof i=="symbol")return i;for(let r of["key","value"]){let s=t[r];if(s&&"items"in s){for(let o=0;o{"use strict";var jc=Vd(),zb=Gd(),Xb=Zd(),Lc="\uFEFF",Mc="",qc="",Dc="",Qb=e=>!!e&&"items"in e,Zb=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function eC(e){switch(e){case Lc:return"";case Mc:return"";case qc:return"";case Dc:return"";default:return JSON.stringify(e)}}function tC(e){switch(e){case Lc:return"byte-order-mark";case Mc:return"doc-mode";case qc:return"flow-error-end";case Dc:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case` +`};delete e.items,Object.assign(e,{type:n,source:t,end:[r]});break}default:{let i="indent"in e?e.indent:-1,r="end"in e&&Array.isArray(e.end)?e.end.filter(s=>s.type==="space"||s.type==="comment"||s.type==="newline"):[];for(let s of Object.keys(e))s!=="type"&&s!=="offset"&&delete e[s];Object.assign(e,{type:n,indent:i,source:t,end:r})}}}Ls.createScalarToken=Vb;Ls.resolveAsScalar=Ub;Ls.setScalarValue=Yb});var Gd=v(Yd=>{"use strict";var zb=e=>"type"in e?qs(e):Ms(e);function qs(e){switch(e.type){case"block-scalar":{let t="";for(let n of e.props)t+=qs(n);return t+e.source}case"block-map":case"block-seq":{let t="";for(let n of e.items)t+=Ms(n);return t}case"flow-collection":{let t=e.start.source;for(let n of e.items)t+=Ms(n);for(let n of e.end)t+=n.source;return t}case"document":{let t=Ms(e);if(e.end)for(let n of e.end)t+=n.source;return t}default:{let t=e.source;if("end"in e&&e.end)for(let n of e.end)t+=n.source;return t}}}function Ms({start:e,key:t,sep:n,value:i}){let r="";for(let s of e)r+=s.source;if(t&&(r+=qs(t)),n)for(let s of n)r+=s.source;return i&&(r+=qs(i)),r}Yd.stringify=zb});var Zd=v(Qd=>{"use strict";var Tc=Symbol("break visit"),Xb=Symbol("skip children"),zd=Symbol("remove item");function bn(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),Xd(Object.freeze([]),e,t)}bn.BREAK=Tc;bn.SKIP=Xb;bn.REMOVE=zd;bn.itemAtPath=(e,t)=>{let n=e;for(let[i,r]of t){let s=n?.[i];if(s&&"items"in s)n=s.items[r];else return}return n};bn.parentCollection=(e,t)=>{let n=bn.itemAtPath(e,t.slice(0,-1)),i=t[t.length-1][0],r=n?.[i];if(r&&"items"in r)return r;throw new Error("Parent collection not found")};function Xd(e,t,n){let i=n(t,e);if(typeof i=="symbol")return i;for(let r of["key","value"]){let s=t[r];if(s&&"items"in s){for(let o=0;o{"use strict";var jc=Vd(),Qb=Gd(),Zb=Zd(),Lc="\uFEFF",Mc="",qc="",Dc="",eC=e=>!!e&&"items"in e,tC=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function nC(e){switch(e){case Lc:return"";case Mc:return"";case qc:return"";case Dc:return"";default:return JSON.stringify(e)}}function iC(e){switch(e){case Lc:return"byte-order-mark";case Mc:return"doc-mode";case qc:return"flow-error-end";case Dc:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case` `:case`\r -`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(e[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}Se.createScalarToken=jc.createScalarToken;Se.resolveAsScalar=jc.resolveAsScalar;Se.setScalarValue=jc.setScalarValue;Se.stringify=zb.stringify;Se.visit=Xb.visit;Se.BOM=Lc;Se.DOCUMENT=Mc;Se.FLOW_END=qc;Se.SCALAR=Dc;Se.isCollection=Qb;Se.isScalar=Zb;Se.prettyToken=eC;Se.tokenType=tC});var Bc=v(tm=>{"use strict";var Zi=Ds();function Je(e){switch(e){case void 0:case" ":case` -`:case"\r":case" ":return!0;default:return!1}}var em=new Set("0123456789ABCDEFabcdef"),nC=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Fs=new Set(",[]{}"),iC=new Set(` ,[]{} -\r `),Fc=e=>!e||iC.has(e),Wc=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(t,n=!1){if(t){if(typeof t!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+t:t,this.lineEndPos=null}this.atEnd=!n;let i=this.next??"stream";for(;i&&(n||this.hasChars(1));)i=yield*this.parseNext(i)}atLineEnd(){let t=this.pos,n=this.buffer[t];for(;n===" "||n===" ";)n=this.buffer[++t];return!n||n==="#"||n===` +`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(e[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}Se.createScalarToken=jc.createScalarToken;Se.resolveAsScalar=jc.resolveAsScalar;Se.setScalarValue=jc.setScalarValue;Se.stringify=Qb.stringify;Se.visit=Zb.visit;Se.BOM=Lc;Se.DOCUMENT=Mc;Se.FLOW_END=qc;Se.SCALAR=Dc;Se.isCollection=eC;Se.isScalar=tC;Se.prettyToken=nC;Se.tokenType=iC});var Bc=v(tm=>{"use strict";var Zi=Ds();function Je(e){switch(e){case void 0:case" ":case` +`:case"\r":case" ":return!0;default:return!1}}var em=new Set("0123456789ABCDEFabcdef"),rC=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Fs=new Set(",[]{}"),sC=new Set(` ,[]{} +\r `),Fc=e=>!e||sC.has(e),Wc=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(t,n=!1){if(t){if(typeof t!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+t:t,this.lineEndPos=null}this.atEnd=!n;let i=this.next??"stream";for(;i&&(n||this.hasChars(1));)i=yield*this.parseNext(i)}atLineEnd(){let t=this.pos,n=this.buffer[t];for(;n===" "||n===" ";)n=this.buffer[++t];return!n||n==="#"||n===` `?!0:n==="\r"?this.buffer[t+1]===` `:!1}charAt(t){return this.buffer[this.pos+t]}continueScalar(t){let n=this.buffer[t];if(this.indentNext>0){let i=0;for(;n===" ";)n=this.buffer[++i+t];if(n==="\r"){let r=this.buffer[i+t+1];if(r===` `||!r&&!this.atEnd)return t+i+1}return n===` @@ -133,16 +133,16 @@ ${n.comment}`:n.comment}this.doc.range[2]=n.offset;break}default:this.errors.pus `&&s>=this.pos&&s+1+n>a)t=s;else break}while(!0);return yield Zi.SCALAR,yield*this.pushToIndex(t+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let t=this.flowLevel>0,n=this.pos-1,i=this.pos-1,r;for(;r=this.buffer[++i];)if(r===":"){let s=this.buffer[i+1];if(Je(s)||t&&Fs.has(s))break;n=i}else if(Je(r)){let s=this.buffer[i+1];if(r==="\r"&&(s===` `?(i+=1,r=` `,s=this.buffer[i+1]):n=i),s==="#"||t&&Fs.has(s))break;if(r===` -`){let o=this.continueScalar(i+1);if(o===-1)break;i=Math.max(i,o-2)}}else{if(t&&Fs.has(r))break;n=i}return!r&&!this.atEnd?this.setNext("plain-scalar"):(yield Zi.SCALAR,yield*this.pushToIndex(n+1,!0),t?"flow":"doc")}*pushCount(t){return t>0?(yield this.buffer.substr(this.pos,t),this.pos+=t,t):0}*pushToIndex(t,n){let i=this.buffer.slice(this.pos,t);return i?(yield i,this.pos+=i.length,i.length):(n&&(yield""),0)}*pushIndicators(){let t=0;e:for(;;){switch(this.charAt(0)){case"!":t+=yield*this.pushTag(),t+=yield*this.pushSpaces(!0);continue e;case"&":t+=yield*this.pushUntil(Fc),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let n=this.flowLevel>0,i=this.charAt(1);if(Je(i)||n&&Fs.has(i)){n?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,t+=yield*this.pushCount(1),t+=yield*this.pushSpaces(!0);continue e}}}break e}return t}*pushTag(){if(this.charAt(1)==="<"){let t=this.pos+2,n=this.buffer[t];for(;!Je(n)&&n!==">";)n=this.buffer[++t];return yield*this.pushToIndex(n===">"?t+1:t,!1)}else{let t=this.pos+1,n=this.buffer[t];for(;n;)if(nC.has(n))n=this.buffer[++t];else if(n==="%"&&em.has(this.buffer[t+1])&&em.has(this.buffer[t+2]))n=this.buffer[t+=3];else break;return yield*this.pushToIndex(t,!1)}}*pushNewline(){let t=this.buffer[this.pos];return t===` +`){let o=this.continueScalar(i+1);if(o===-1)break;i=Math.max(i,o-2)}}else{if(t&&Fs.has(r))break;n=i}return!r&&!this.atEnd?this.setNext("plain-scalar"):(yield Zi.SCALAR,yield*this.pushToIndex(n+1,!0),t?"flow":"doc")}*pushCount(t){return t>0?(yield this.buffer.substr(this.pos,t),this.pos+=t,t):0}*pushToIndex(t,n){let i=this.buffer.slice(this.pos,t);return i?(yield i,this.pos+=i.length,i.length):(n&&(yield""),0)}*pushIndicators(){let t=0;e:for(;;){switch(this.charAt(0)){case"!":t+=yield*this.pushTag(),t+=yield*this.pushSpaces(!0);continue e;case"&":t+=yield*this.pushUntil(Fc),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let n=this.flowLevel>0,i=this.charAt(1);if(Je(i)||n&&Fs.has(i)){n?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,t+=yield*this.pushCount(1),t+=yield*this.pushSpaces(!0);continue e}}}break e}return t}*pushTag(){if(this.charAt(1)==="<"){let t=this.pos+2,n=this.buffer[t];for(;!Je(n)&&n!==">";)n=this.buffer[++t];return yield*this.pushToIndex(n===">"?t+1:t,!1)}else{let t=this.pos+1,n=this.buffer[t];for(;n;)if(rC.has(n))n=this.buffer[++t];else if(n==="%"&&em.has(this.buffer[t+1])&&em.has(this.buffer[t+2]))n=this.buffer[t+=3];else break;return yield*this.pushToIndex(t,!1)}}*pushNewline(){let t=this.buffer[this.pos];return t===` `?yield*this.pushCount(1):t==="\r"&&this.charAt(1)===` -`?yield*this.pushCount(2):0}*pushSpaces(t){let n=this.pos-1,i;do i=this.buffer[++n];while(i===" "||t&&i===" ");let r=n-this.pos;return r>0&&(yield this.buffer.substr(this.pos,r),this.pos=n),r}*pushUntil(t){let n=this.pos,i=this.buffer[n];for(;!t(i);)i=this.buffer[++n];return yield*this.pushToIndex(n,!1)}};tm.Lexer=Wc});var Kc=v(nm=>{"use strict";var Hc=class{constructor(){this.lineStarts=[],this.addNewLine=t=>this.lineStarts.push(t),this.linePos=t=>{let n=0,i=this.lineStarts.length;for(;n>1;this.lineStarts[s]{"use strict";var rC=Jr("process"),im=Ds(),sC=Bc();function Jt(e,t){for(let n=0;n=0;)switch(e[t].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;e[++t]?.type==="space";);return e.splice(t,e.length)}function Bs(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let n=0;n0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let t=this.peek(1);if(this.type==="doc-end"&&t?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!t)return yield*this.stream();switch(t.type){case"document":return yield*this.document(t);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(t);case"block-scalar":return yield*this.blockScalar(t);case"block-map":return yield*this.blockMap(t);case"block-seq":return yield*this.blockSequence(t);case"flow-collection":return yield*this.flowCollection(t);case"doc-end":return yield*this.documentEnd(t)}yield*this.pop()}peek(t){return this.stack[this.stack.length-t]}*pop(t){let n=t??this.stack.pop();if(!n)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield n;else{let i=this.peek(1);switch(n.type==="block-scalar"?n.indent="indent"in i?i.indent:0:n.type==="flow-collection"&&i.type==="document"&&(n.indent=0),n.type==="flow-collection"&&sm(n),i.type){case"document":i.value=n;break;case"block-scalar":i.props.push(n);break;case"block-map":{let r=i.items[i.items.length-1];if(r.value){i.items.push({start:[],key:n,sep:[]}),this.onKeyLine=!0;return}else if(r.sep)r.value=n;else{Object.assign(r,{key:n,sep:[]}),this.onKeyLine=!r.explicitKey;return}break}case"block-seq":{let r=i.items[i.items.length-1];r.value?i.items.push({start:[],value:n}):r.value=n;break}case"flow-collection":{let r=i.items[i.items.length-1];!r||r.value?i.items.push({start:[],key:n,sep:[]}):r.sep?r.value=n:Object.assign(r,{key:n,sep:[]});return}default:yield*this.pop(),yield*this.pop(n)}if((i.type==="document"||i.type==="block-map"||i.type==="block-seq")&&(n.type==="block-map"||n.type==="block-seq")){let r=n.items[n.items.length-1];r&&!r.sep&&!r.value&&r.start.length>0&&rm(r.start)===-1&&(n.indent===0||r.start.every(s=>s.type!=="comment"||s.indent0&&(yield this.buffer.substr(this.pos,r),this.pos=n),r}*pushUntil(t){let n=this.pos,i=this.buffer[n];for(;!t(i);)i=this.buffer[++n];return yield*this.pushToIndex(n,!1)}};tm.Lexer=Wc});var Kc=v(nm=>{"use strict";var Hc=class{constructor(){this.lineStarts=[],this.addNewLine=t=>this.lineStarts.push(t),this.linePos=t=>{let n=0,i=this.lineStarts.length;for(;n>1;this.lineStarts[s]{"use strict";var oC=Jr("process"),im=Ds(),aC=Bc();function Jt(e,t){for(let n=0;n=0;)switch(e[t].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;e[++t]?.type==="space";);return e.splice(t,e.length)}function Bs(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let n=0;n0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let t=this.peek(1);if(this.type==="doc-end"&&t?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!t)return yield*this.stream();switch(t.type){case"document":return yield*this.document(t);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(t);case"block-scalar":return yield*this.blockScalar(t);case"block-map":return yield*this.blockMap(t);case"block-seq":return yield*this.blockSequence(t);case"flow-collection":return yield*this.flowCollection(t);case"doc-end":return yield*this.documentEnd(t)}yield*this.pop()}peek(t){return this.stack[this.stack.length-t]}*pop(t){let n=t??this.stack.pop();if(!n)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield n;else{let i=this.peek(1);switch(n.type==="block-scalar"?n.indent="indent"in i?i.indent:0:n.type==="flow-collection"&&i.type==="document"&&(n.indent=0),n.type==="flow-collection"&&sm(n),i.type){case"document":i.value=n;break;case"block-scalar":i.props.push(n);break;case"block-map":{let r=i.items[i.items.length-1];if(r.value){i.items.push({start:[],key:n,sep:[]}),this.onKeyLine=!0;return}else if(r.sep)r.value=n;else{Object.assign(r,{key:n,sep:[]}),this.onKeyLine=!r.explicitKey;return}break}case"block-seq":{let r=i.items[i.items.length-1];r.value?i.items.push({start:[],value:n}):r.value=n;break}case"flow-collection":{let r=i.items[i.items.length-1];!r||r.value?i.items.push({start:[],key:n,sep:[]}):r.sep?r.value=n:Object.assign(r,{key:n,sep:[]});return}default:yield*this.pop(),yield*this.pop(n)}if((i.type==="document"||i.type==="block-map"||i.type==="block-seq")&&(n.type==="block-map"||n.type==="block-seq")){let r=n.items[n.items.length-1];r&&!r.sep&&!r.value&&r.start.length>0&&rm(r.start)===-1&&(n.indent===0||r.start.every(s=>s.type!=="comment"||s.indent=t.indent){let i=!this.onKeyLine&&this.indent===t.indent,r=i&&(n.sep||n.explicitKey)&&this.type!=="seq-item-ind",s=[];if(r&&n.sep&&!n.value){let o=[];for(let a=0;at.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(s=n.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":r||n.value?(s.push(this.sourceToken),t.items.push({start:s}),this.onKeyLine=!0):n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"explicit-key-ind":!n.sep&&!n.explicitKey?(n.start.push(this.sourceToken),n.explicitKey=!0):r||n.value?(s.push(this.sourceToken),t.items.push({start:s,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(n.explicitKey)if(n.sep)if(n.value)t.items.push({start:[],key:null,sep:[this.sourceToken]});else if(Jt(n.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:s,key:null,sep:[this.sourceToken]}]});else if(om(n.key)&&!Jt(n.sep,"newline")){let o=Zn(n.start),a=n.key,c=n.sep;c.push(this.sourceToken),delete n.key,delete n.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:a,sep:c}]})}else s.length>0?n.sep=n.sep.concat(s,this.sourceToken):n.sep.push(this.sourceToken);else if(Jt(n.start,"newline"))Object.assign(n,{key:null,sep:[this.sourceToken]});else{let o=Zn(n.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else n.sep?n.value||r?t.items.push({start:s,key:null,sep:[this.sourceToken]}):Jt(n.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):n.sep.push(this.sourceToken):Object.assign(n,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);r||n.value?(t.items.push({start:s,key:o,sep:[]}),this.onKeyLine=!0):n.sep?this.stack.push(o):(Object.assign(n,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(t);if(o){if(o.type==="block-seq"){if(!n.explicitKey&&n.sep&&!Jt(n.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else i&&t.items.push({start:s});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(t){let n=t.items[t.items.length-1];switch(this.type){case"newline":if(n.value){let i="end"in n.value?n.value.end:void 0;(Array.isArray(i)?i[i.length-1]:void 0)?.type==="comment"?i?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else n.start.push(this.sourceToken);return;case"space":case"comment":if(n.value)t.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(n.start,t.indent)){let r=t.items[t.items.length-2]?.value?.end;if(Array.isArray(r)){Bs(r,n.start),r.push(this.sourceToken),t.items.pop();return}}n.start.push(this.sourceToken)}return;case"anchor":case"tag":if(n.value||this.indent<=t.indent)break;n.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==t.indent)break;n.value||Jt(n.start,"seq-item-ind")?t.items.push({start:[this.sourceToken]}):n.start.push(this.sourceToken);return}if(this.indent>t.indent){let i=this.startBlockValue(t);if(i){this.stack.push(i);return}}yield*this.pop(),yield*this.step()}*flowCollection(t){let n=t.items[t.items.length-1];if(this.type==="flow-error-end"){let i;do yield*this.pop(),i=this.peek(1);while(i?.type==="flow-collection")}else if(t.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!n||n.sep?t.items.push({start:[this.sourceToken]}):n.start.push(this.sourceToken);return;case"map-value-ind":!n||n.value?t.items.push({start:[],key:null,sep:[this.sourceToken]}):n.sep?n.sep.push(this.sourceToken):Object.assign(n,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!n||n.value?t.items.push({start:[this.sourceToken]}):n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let r=this.flowScalar(this.type);!n||n.value?t.items.push({start:[],key:r,sep:[]}):n.sep?this.stack.push(r):Object.assign(n,{key:r,sep:[]});return}case"flow-map-end":case"flow-seq-end":t.end.push(this.sourceToken);return}let i=this.startBlockValue(t);i?this.stack.push(i):(yield*this.pop(),yield*this.step())}else{let i=this.peek(2);if(i.type==="block-map"&&(this.type==="map-value-ind"&&i.indent===t.indent||this.type==="newline"&&!i.items[i.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&i.type!=="flow-collection"){let r=Ws(i),s=Zn(r);sm(t);let o=t.end.splice(1,t.end.length);o.push(this.sourceToken);let a={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:s,key:t,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(t)}}flowScalar(t){if(this.onNewLine){let n=this.source.indexOf(` `)+1;for(;n!==0;)this.onNewLine(this.offset+n),n=this.source.indexOf(` -`,n)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let n=Ws(t),i=Zn(n);return i.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let n=Ws(t),i=Zn(n);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(t,n){return this.type!=="comment"||this.indent<=n?!1:t.every(i=>i.type==="newline"||i.type==="space")}*documentEnd(t){this.type!=="doc-mode"&&(t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(t){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};am.Parser=Jc});var dm=v(tr=>{"use strict";var cm=Ac(),oC=Ui(),er=Gi(),aC=$a(),cC=M(),lC=Kc(),lm=Uc();function um(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new lC.LineCounter||null,prettyErrors:t}}function uC(e,t={}){let{lineCounter:n,prettyErrors:i}=um(t),r=new lm.Parser(n?.addNewLine),s=new cm.Composer(t),o=Array.from(s.compose(r.parse(e)));if(i&&n)for(let a of o)a.errors.forEach(er.prettifyError(e,n)),a.warnings.forEach(er.prettifyError(e,n));return o.length>0?o:Object.assign([],{empty:!0},s.streamInfo())}function fm(e,t={}){let{lineCounter:n,prettyErrors:i}=um(t),r=new lm.Parser(n?.addNewLine),s=new cm.Composer(t),o=null;for(let a of s.compose(r.parse(e),!0,e.length))if(!o)o=a;else if(o.options.logLevel!=="silent"){o.errors.push(new er.YAMLParseError(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return i&&n&&(o.errors.forEach(er.prettifyError(e,n)),o.warnings.forEach(er.prettifyError(e,n))),o}function fC(e,t,n){let i;typeof t=="function"?i=t:n===void 0&&t&&typeof t=="object"&&(n=t);let r=fm(e,n);if(!r)return null;if(r.warnings.forEach(s=>aC.warn(r.options.logLevel,s)),r.errors.length>0){if(r.options.logLevel!=="silent")throw r.errors[0];r.errors=[]}return r.toJS(Object.assign({reviver:i},n))}function dC(e,t,n){let i=null;if(typeof t=="function"||Array.isArray(t)?i=t:n===void 0&&t&&(n=t),typeof n=="string"&&(n=n.length),typeof n=="number"){let r=Math.round(n);n=r<1?void 0:r>8?{indent:8}:{indent:r}}if(e===void 0){let{keepUndefined:r}=n??t??{};if(!r)return}return cC.isDocument(e)&&!i?e.toString(n):new oC.Document(e,i,n).toString(n)}tr.parse=fC;tr.parseAllDocuments=uC;tr.parseDocument=fm;tr.stringify=dC});var Ue=v(F=>{"use strict";var mC=Ac(),pC=Ui(),hC=dc(),Vc=Gi(),gC=$i(),Ut=M(),wC=Wt(),yC=Z(),vC=Ht(),bC=Kt(),CC=Ds(),kC=Bc(),SC=Kc(),EC=Uc(),Hs=dm(),mm=_i();F.Composer=mC.Composer;F.Document=pC.Document;F.Schema=hC.Schema;F.YAMLError=Vc.YAMLError;F.YAMLParseError=Vc.YAMLParseError;F.YAMLWarning=Vc.YAMLWarning;F.Alias=gC.Alias;F.isAlias=Ut.isAlias;F.isCollection=Ut.isCollection;F.isDocument=Ut.isDocument;F.isMap=Ut.isMap;F.isNode=Ut.isNode;F.isPair=Ut.isPair;F.isScalar=Ut.isScalar;F.isSeq=Ut.isSeq;F.Pair=wC.Pair;F.Scalar=yC.Scalar;F.YAMLMap=vC.YAMLMap;F.YAMLSeq=bC.YAMLSeq;F.CST=CC;F.Lexer=kC.Lexer;F.LineCounter=SC.LineCounter;F.Parser=EC.Parser;F.parse=Hs.parse;F.parseAllDocuments=Hs.parseAllDocuments;F.parseDocument=Hs.parseDocument;F.stringify=Hs.stringify;F.visit=mm.visit;F.visitAsync=mm.visitAsync});import Js from"path";function gm(e,t){return Ks[t][e]}function _C(e,t,n){let i=/^(\s*)([a-z_]+):/u.exec(e);if(!i)return null;let r=i[1].length,s=i[2];if(r===0&&s in Ks.en)return s;if(r===2&&t){let o=`${t}.${s}`;if(o in Ks.en)return o}if(r===4&&t==="native"&&n==="snapshot"){let o=`native.snapshot.${s}`;if(o in Ks.en)return o}return null}function kn(e,t){let n=[],i=null,r=null;for(let s of(0,Us.stringify)(e).trimEnd().split(` -`)){let o=_C(s,i,r);if(o){let a=s.match(/^\s*/u)?.[0]??"";for(let c of gm(o,t).split(` +`,n)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let n=Ws(t),i=Zn(n);return i.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let n=Ws(t),i=Zn(n);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(t,n){return this.type!=="comment"||this.indent<=n?!1:t.every(i=>i.type==="newline"||i.type==="space")}*documentEnd(t){this.type!=="doc-mode"&&(t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(t){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};am.Parser=Jc});var dm=v(tr=>{"use strict";var cm=Ac(),cC=Ui(),er=Gi(),lC=$a(),uC=M(),fC=Kc(),lm=Uc();function um(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new fC.LineCounter||null,prettyErrors:t}}function dC(e,t={}){let{lineCounter:n,prettyErrors:i}=um(t),r=new lm.Parser(n?.addNewLine),s=new cm.Composer(t),o=Array.from(s.compose(r.parse(e)));if(i&&n)for(let a of o)a.errors.forEach(er.prettifyError(e,n)),a.warnings.forEach(er.prettifyError(e,n));return o.length>0?o:Object.assign([],{empty:!0},s.streamInfo())}function fm(e,t={}){let{lineCounter:n,prettyErrors:i}=um(t),r=new lm.Parser(n?.addNewLine),s=new cm.Composer(t),o=null;for(let a of s.compose(r.parse(e),!0,e.length))if(!o)o=a;else if(o.options.logLevel!=="silent"){o.errors.push(new er.YAMLParseError(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return i&&n&&(o.errors.forEach(er.prettifyError(e,n)),o.warnings.forEach(er.prettifyError(e,n))),o}function mC(e,t,n){let i;typeof t=="function"?i=t:n===void 0&&t&&typeof t=="object"&&(n=t);let r=fm(e,n);if(!r)return null;if(r.warnings.forEach(s=>lC.warn(r.options.logLevel,s)),r.errors.length>0){if(r.options.logLevel!=="silent")throw r.errors[0];r.errors=[]}return r.toJS(Object.assign({reviver:i},n))}function pC(e,t,n){let i=null;if(typeof t=="function"||Array.isArray(t)?i=t:n===void 0&&t&&(n=t),typeof n=="string"&&(n=n.length),typeof n=="number"){let r=Math.round(n);n=r<1?void 0:r>8?{indent:8}:{indent:r}}if(e===void 0){let{keepUndefined:r}=n??t??{};if(!r)return}return uC.isDocument(e)&&!i?e.toString(n):new cC.Document(e,i,n).toString(n)}tr.parse=mC;tr.parseAllDocuments=dC;tr.parseDocument=fm;tr.stringify=pC});var Ue=v(F=>{"use strict";var hC=Ac(),gC=Ui(),wC=dc(),Vc=Gi(),yC=$i(),Ut=M(),vC=Wt(),bC=Z(),CC=Ht(),kC=Kt(),SC=Ds(),EC=Bc(),RC=Kc(),_C=Uc(),Hs=dm(),mm=_i();F.Composer=hC.Composer;F.Document=gC.Document;F.Schema=wC.Schema;F.YAMLError=Vc.YAMLError;F.YAMLParseError=Vc.YAMLParseError;F.YAMLWarning=Vc.YAMLWarning;F.Alias=yC.Alias;F.isAlias=Ut.isAlias;F.isCollection=Ut.isCollection;F.isDocument=Ut.isDocument;F.isMap=Ut.isMap;F.isNode=Ut.isNode;F.isPair=Ut.isPair;F.isScalar=Ut.isScalar;F.isSeq=Ut.isSeq;F.Pair=vC.Pair;F.Scalar=bC.Scalar;F.YAMLMap=CC.YAMLMap;F.YAMLSeq=kC.YAMLSeq;F.CST=SC;F.Lexer=EC.Lexer;F.LineCounter=RC.LineCounter;F.Parser=_C.Parser;F.parse=Hs.parse;F.parseAllDocuments=Hs.parseAllDocuments;F.parseDocument=Hs.parseDocument;F.stringify=Hs.stringify;F.visit=mm.visit;F.visitAsync=mm.visitAsync});import Js from"path";function gm(e,t){return Ks[t][e]}function PC(e,t,n){let i=/^(\s*)([a-z_]+):/u.exec(e);if(!i)return null;let r=i[1].length,s=i[2];if(r===0&&s in Ks.en)return s;if(r===2&&t){let o=`${t}.${s}`;if(o in Ks.en)return o}if(r===4&&t==="native"&&n==="snapshot"){let o=`native.snapshot.${s}`;if(o in Ks.en)return o}return null}function kn(e,t){let n=[],i=null,r=null;for(let s of(0,Us.stringify)(e).trimEnd().split(` +`)){let o=PC(s,i,r);if(o){let a=s.match(/^\s*/u)?.[0]??"";for(let c of gm(o,t).split(` `))n.push(`${a}${c}`)}n.push(s),/^[a-z_]+:/u.test(s)?(s.startsWith("native:")?i="native":s.startsWith("classic:")?i="classic":i=null,r=null):/^ {2}[a-z_]+:/u.test(s)&&i==="native"&&(r=s.startsWith(" snapshot:")?"snapshot":null)}return n.push(""),n.join(` -`)}function xC(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let n=e.trim();if(n.length===0||Js.posix.isAbsolute(n)||Js.win32.isAbsolute(n)||/^(?:~|[\\/])/u.test(n))throw new Error(`${t} must be a project-relative path`);if(n===".")return[];let i=n.replaceAll("\\","/").split("/");if(i.some(r=>r===".."))throw new Error(`${t} must stay inside the project root`);if(i.some(r=>r===""||r==="."))throw new Error(`${t} must not contain empty or dot path segments`);return i}function nr(e){let t=xC(e,"native.artifact_root");return t.length===0?".":t.join("/")}function wm(e,t="docs"){let n=e??t;if(n!=="legacy"&&n!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return n}function Vt(e,t,n=!1){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim().replaceAll("\\","/");if(i.length===0||Js.posix.isAbsolute(i)||Js.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${t} must be relative to its declared path base`);let r=i.split("/");if(r.some(s=>s===".."))throw new Error(`${t} must stay inside its declared path base`);if(r.some(s=>s===""||s==="."))throw new Error(`${t} must not contain empty or dot path segments`);if(!n&&/[*?]/u.test(i))throw new Error(`${t} cannot contain wildcards`);return r.join("/")}function ir(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function ym(e,t,n){let i=e??t;if(i!=="en"&&i!=="zh-CN")throw new Error(`${n} must be en or zh-CN`);return i}function vm(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||e.startsWith("/")||e.split("/").includes(".."))throw new Error(`${t} contains an unsafe pattern`);if(e.length>Gc)throw new Error(`${t} exceeds ${Gc} characters`);let n=0;for(let i=0;izc)throw new Error(`${t} contains more than ${zc} wildcard tokens`);return e}function pm(e,t,n){if(e===void 0)return[...n];if(!Array.isArray(e))throw new Error(`${t} contains an unsafe pattern`);return[...new Set(e.map(i=>vm(i,t)))].sort((i,r)=>i.localeCompare(r,"en"))}function Yc(e,t,n){let i=e??t;if(!Number.isSafeInteger(i)||i<1)throw new Error(`${n} must be a positive integer`);return i}function PC(e){if(e===void 0)return{...Fe,include:[...Fe.include],exclude:[...Fe.exclude]};let t=ir(e,"native.snapshot");return{include:pm(t.include,"native.snapshot.include",Fe.include),exclude:pm(t.exclude,"native.snapshot.exclude",Fe.exclude),max_files:Yc(t.max_files,Fe.max_files,"native.snapshot.max_files"),max_total_bytes:Yc(t.max_total_bytes,Fe.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:Yc(t.max_duration_ms,Fe.max_duration_ms,"native.snapshot.max_duration_ms")}}function OC(e){if(e===void 0)return;let t=ir(e,"native.pending_root_move"),n=t.id,i=t.from_artifact_root,r=t.to_artifact_root,s=t.stage;if(typeof n!="string"||!/^[a-f0-9-]{8,}$/u.test(n))throw new Error("native.pending_root_move.id is invalid");if(typeof i!="string"||typeof r!="string")throw new Error("native.pending_root_move roots must be strings");if(s!=="copying"&&s!=="ready"&&s!=="switched")throw new Error("native.pending_root_move.stage is invalid");let o;if(t.cleanup!==void 0){let a=ir(t.cleanup,"native.pending_root_move.cleanup"),c=a.kind,l=a.state,f=a.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof f!="string"||!/^[a-f0-9]{64}$/u.test(f))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:f}}return{id:n,fromArtifactRoot:nr(i),toArtifactRoot:nr(r),stage:s,...o?{cleanup:o}:{}}}function $C(e,t={}){let n=ir(e,"native"),i=n.artifact_root??(t.allowMissingArtifactRoot?"docs":void 0);if(typeof i!="string")throw new Error("native.artifact_root must be a string");let r=n.clarification_mode??"sequential";if(r!=="sequential"&&r!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let s=n.archive_confirmation??"automatic";if(s!=="automatic"&&s!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=n.max_verify_failures??hm;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let a=OC(n.pending_root_move);return{artifact_root:nr(i),language:ym(n.language,"en","native.language"),clarification_mode:r,archive_confirmation:s,max_verify_failures:o,snapshot:PC(n.snapshot),...a?{pending_root_move:a}:{}}}function IC(e){let t=ir(e,"classic"),n=t.context_compression??"off";if(n!=="off"&&n!=="beta")throw new Error("classic.context_compression must be off or beta");let i=t.review_mode??"standard";if(i!=="off"&&i!=="standard"&&i!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let r=t.auto_transition??!0;if(typeof r!="boolean")throw new Error("classic.auto_transition must be true or false");return{artifact_layout:wm(t.artifact_layout),language:ym(t.language,"zh-CN","classic.language"),context_compression:n,review_mode:i,auto_transition:r}}function AC(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function NC(e,t,n,i,r){let s=e.schema!==void 0;if(!(s||e.default_workflow!==void 0||e.workflows!==void 0||!r.allowPartialProject&&e.native!==void 0)||r.allowPartialProject&&!s)return null;if(e.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(e.default_workflow!=="native"&&e.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let a=e.workflows??[e.default_workflow];if(!Array.isArray(a)||a.length===0||a.some(l=>l!=="native"&&l!=="classic"))throw new Error("workflows must contain native and/or classic");let c=[...new Set(a)];if(!c.includes(e.default_workflow))throw new Error("workflows must include default_workflow");if(c.includes("native")&&!t)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:e.default_workflow,workflows:c,ambient_resume:i,...t?{native:t}:{},...n?{classic:n}:{}}}function at(e,t={}){let n=(0,Us.parseDocument)(e,{uniqueKeys:!0});if(n.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${n.errors[0].message}`);let i=n.toJS();if(i==null)return{value:{},config:null,ambient_resume:!0};if(typeof i!="object"||Array.isArray(i))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let r=i,s=AC(r.ambient_resume),o=r.native===void 0?void 0:$C(r.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),a=r.classic===void 0?void 0:IC(r.classic),c=NC(r,o,a,s,{allowPartialProject:t.allowPartialProject??!1});return{value:r,config:c,ambient_resume:s,...o?{native:o}:{},...a?{classic:a}:{}}}function Xc(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,native:{artifact_root:nr(e),language:t,clarification_mode:"sequential",archive_confirmation:"automatic",max_verify_failures:hm,snapshot:{...Fe,include:[...Fe.include],exclude:[...Fe.exclude]}}}}var Us,Cn,Gc,zc,hm,RC,Fe,Ks,ct=pe(()=>{"use strict";Us=rt(Ue(),1),Cn=64*1024,Gc=1024,zc=64,hm=5,RC=[".agents/skills/**",".amazonq/skills/**",".augment/skills/**",".bob/skills/**",".claude/skills/**",".cline/skills/**",".codebuddy/skills/**",".continue/skills/**",".cospec/skills/**",".crush/skills/**",".cursor/skills/**",".factory/skills/**",".forge/skills/**",".gemini/skills/**",".github/skills/**",".iflow/skills/**",".junie/skills/**",".kilocode/skills/**",".kimi-code/skills/**",".kiro/skills/**",".lingma/skills/**",".mimocode/skills/**",".opencode/skills/**",".pi/skills/**",".qoder/skills/**",".qwen/skills/**",".roo/skills/**",".trae-cn/skills/**",".trae/skills/**",".windsurf/skills/**",".zcode/skills/**"],Fe={include:["**/*"],exclude:[...RC],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4},Ks={en:{schema:"# Configuration schema used by Comet. Do not edit this value.",default_workflow:"# Default workflow entered by /comet. Must also appear in workflows.",workflows:"# Workflows enabled in this project: native, classic, or both.",ambient_resume:`# Enables automatic recovery through the read-only Ambient Resume probe for both Native and Classic. Set false to disable it. +`)}function OC(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let n=e.trim();if(n.length===0||Js.posix.isAbsolute(n)||Js.win32.isAbsolute(n)||/^(?:~|[\\/])/u.test(n))throw new Error(`${t} must be a project-relative path`);if(n===".")return[];let i=n.replaceAll("\\","/").split("/");if(i.some(r=>r===".."))throw new Error(`${t} must stay inside the project root`);if(i.some(r=>r===""||r==="."))throw new Error(`${t} must not contain empty or dot path segments`);return i}function nr(e){let t=OC(e,"native.artifact_root");return t.length===0?".":t.join("/")}function wm(e,t="docs"){let n=e??t;if(n!=="legacy"&&n!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return n}function Vt(e,t,n=!1){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim().replaceAll("\\","/");if(i.length===0||Js.posix.isAbsolute(i)||Js.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${t} must be relative to its declared path base`);let r=i.split("/");if(r.some(s=>s===".."))throw new Error(`${t} must stay inside its declared path base`);if(r.some(s=>s===""||s==="."))throw new Error(`${t} must not contain empty or dot path segments`);if(!n&&/[*?]/u.test(i))throw new Error(`${t} cannot contain wildcards`);return r.join("/")}function ir(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function ym(e,t,n){let i=e??t;if(i!=="en"&&i!=="zh-CN")throw new Error(`${n} must be en or zh-CN`);return i}function vm(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||e.startsWith("/")||e.split("/").includes(".."))throw new Error(`${t} contains an unsafe pattern`);if(e.length>Gc)throw new Error(`${t} exceeds ${Gc} characters`);let n=0;for(let i=0;izc)throw new Error(`${t} contains more than ${zc} wildcard tokens`);return e}function pm(e,t,n){if(e===void 0)return[...n];if(!Array.isArray(e))throw new Error(`${t} contains an unsafe pattern`);return[...new Set(e.map(i=>vm(i,t)))].sort((i,r)=>i.localeCompare(r,"en"))}function Yc(e,t,n){let i=e??t;if(!Number.isSafeInteger(i)||i<1)throw new Error(`${n} must be a positive integer`);return i}function $C(e){if(e===void 0)return{...Fe,include:[...Fe.include],exclude:[...Fe.exclude]};let t=ir(e,"native.snapshot");return{include:pm(t.include,"native.snapshot.include",Fe.include),exclude:pm(t.exclude,"native.snapshot.exclude",Fe.exclude),max_files:Yc(t.max_files,Fe.max_files,"native.snapshot.max_files"),max_total_bytes:Yc(t.max_total_bytes,Fe.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:Yc(t.max_duration_ms,Fe.max_duration_ms,"native.snapshot.max_duration_ms")}}function IC(e){if(e===void 0)return;let t=ir(e,"native.pending_root_move"),n=t.id,i=t.from_artifact_root,r=t.to_artifact_root,s=t.stage;if(typeof n!="string"||!/^[a-f0-9-]{8,}$/u.test(n))throw new Error("native.pending_root_move.id is invalid");if(typeof i!="string"||typeof r!="string")throw new Error("native.pending_root_move roots must be strings");if(s!=="copying"&&s!=="ready"&&s!=="switched")throw new Error("native.pending_root_move.stage is invalid");let o;if(t.cleanup!==void 0){let a=ir(t.cleanup,"native.pending_root_move.cleanup"),c=a.kind,l=a.state,f=a.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof f!="string"||!/^[a-f0-9]{64}$/u.test(f))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:f}}return{id:n,fromArtifactRoot:nr(i),toArtifactRoot:nr(r),stage:s,...o?{cleanup:o}:{}}}function AC(e,t={}){let n=ir(e,"native"),i=n.artifact_root??(t.allowMissingArtifactRoot?"docs":void 0);if(typeof i!="string")throw new Error("native.artifact_root must be a string");let r=n.clarification_mode??"sequential";if(r!=="sequential"&&r!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let s=n.archive_confirmation??"automatic";if(s!=="automatic"&&s!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=n.max_verify_failures??hm;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let a=IC(n.pending_root_move);return{artifact_root:nr(i),language:ym(n.language,"en","native.language"),clarification_mode:r,archive_confirmation:s,max_verify_failures:o,snapshot:$C(n.snapshot),...a?{pending_root_move:a}:{}}}function NC(e){let t=ir(e,"classic"),n=t.context_compression??"off";if(n!=="off"&&n!=="beta")throw new Error("classic.context_compression must be off or beta");let i=t.review_mode??"standard";if(i!=="off"&&i!=="standard"&&i!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let r=t.auto_transition??!0;if(typeof r!="boolean")throw new Error("classic.auto_transition must be true or false");return{artifact_layout:wm(t.artifact_layout),language:ym(t.language,"zh-CN","classic.language"),context_compression:n,review_mode:i,auto_transition:r}}function TC(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function jC(e,t,n,i,r){let s=e.schema!==void 0;if(!(s||e.default_workflow!==void 0||e.workflows!==void 0||!r.allowPartialProject&&e.native!==void 0)||r.allowPartialProject&&!s)return null;if(e.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(e.default_workflow!=="native"&&e.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let a=e.workflows??[e.default_workflow];if(!Array.isArray(a)||a.length===0||a.some(l=>l!=="native"&&l!=="classic"))throw new Error("workflows must contain native and/or classic");let c=[...new Set(a)];if(!c.includes(e.default_workflow))throw new Error("workflows must include default_workflow");if(c.includes("native")&&!t)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:e.default_workflow,workflows:c,ambient_resume:i,...t?{native:t}:{},...n?{classic:n}:{}}}function ct(e,t={}){let n=(0,Us.parseDocument)(e,{uniqueKeys:!0});if(n.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${n.errors[0].message}`);let i=n.toJS();if(i==null)return{value:{},config:null,ambient_resume:!0};if(typeof i!="object"||Array.isArray(i))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let r=i,s=TC(r.ambient_resume),o=r.native===void 0?void 0:AC(r.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),a=r.classic===void 0?void 0:NC(r.classic),c=jC(r,o,a,s,{allowPartialProject:t.allowPartialProject??!1});return{value:r,config:c,ambient_resume:s,...o?{native:o}:{},...a?{classic:a}:{}}}function Xc(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,native:{artifact_root:nr(e),language:t,clarification_mode:"sequential",archive_confirmation:"automatic",max_verify_failures:hm,snapshot:{...Fe,include:[...Fe.include],exclude:[...Fe.exclude]}}}}var Us,Cn,Gc,zc,hm,xC,Fe,Ks,lt=pe(()=>{"use strict";Us=st(Ue(),1),Cn=64*1024,Gc=1024,zc=64,hm=5,xC=[".agents/skills/**",".amazonq/skills/**",".augment/skills/**",".bob/skills/**",".claude/skills/**",".cline/skills/**",".codebuddy/skills/**",".continue/skills/**",".cospec/skills/**",".crush/skills/**",".cursor/skills/**",".factory/skills/**",".forge/skills/**",".gemini/skills/**",".github/skills/**",".iflow/skills/**",".junie/skills/**",".kilocode/skills/**",".kimi-code/skills/**",".kiro/skills/**",".lingma/skills/**",".mimocode/skills/**",".opencode/skills/**",".pi/skills/**",".qoder/skills/**",".qwen/skills/**",".roo/skills/**",".trae-cn/skills/**",".trae/skills/**",".windsurf/skills/**",".zcode/skills/**"],Fe={include:["**/*"],exclude:[...xC],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4},Ks={en:{schema:"# Configuration schema used by Comet. Do not edit this value.",default_workflow:"# Default workflow entered by /comet. Must also appear in workflows.",workflows:"# Workflows enabled in this project: native, classic, or both.",ambient_resume:`# Enables automatic recovery through the read-only Ambient Resume probe for both Native and Classic. Set false to disable it. # ambient_resume: true | false`,native:"# Native workflow settings. They do not change Classic state or behavior.","native.artifact_root":"# Root directory where Native stores Comet specs, changes, and runtime data.","native.language":`# Artifact language used by Native workflow documents. # language: en | zh-CN`,"native.clarification_mode":`# Controls whether Native asks one clarification at a time or every currently answerable question in a round. # clarification_mode: sequential | batch`,"native.archive_confirmation":`# Controls whether Native archives automatically after a successful preview or waits for explicit user confirmation. @@ -160,51 +160,51 @@ ${n.comment}`:n.comment}this.doc.range[2]=n.offset;break}default:this.errors.pus # 可选值:en | zh-CN`,"classic.context_compression":`# 新建 Classic change 是否启用 beta 上下文压缩。 # 可选值:off | beta`,"classic.review_mode":`# 新建 Classic change 默认使用的审查深度。 # 可选值:off | standard | thorough`,"classic.auto_transition":`# Classic 阶段通过后是否自动进入下一阶段。 -# 可选值:true | false`}}});function Yt(e){return e!==0&&e!==0n&&e!=="0"}function Sn(e,t){return Yt(e.dev)&&Yt(t.dev)&&Yt(e.ino)&&Yt(t.ino)}function Ae(e,t){let n=Yt(e.dev)&&Yt(t.dev);if(n&&e.dev!==t.dev)return!1;let i=Yt(e.ino)&&Yt(t.ino);return i&&e.ino!==t.ino?!1:n&&i?!0:e.birthtime===t.birthtime}var rr=pe(()=>{"use strict"});import{constants as Vs,promises as En}from"fs";function Qc(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function bm(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function sr(e){return{dev:e.dev,ino:e.ino,birthtime:Qc(e)}}function Ys(e,t){let n=sr(e),i=sr(t);return Sn(n,i)?Ae(n,i):Ae(n,i)&&Qc(e)===Qc(t)&&bm(e)===bm(t)&&e.size===t.size}async function Gs(e,t,n={}){if(!Number.isSafeInteger(t)||t<1)throw new Error("race-safe read byte limit must be a positive integer");let i=n.label??"file",r=n.bigint===!0,s=await En.lstat(e,{bigint:r});if(!s.isFile()||s.isSymbolicLink())throw new Gt("not-regular-file",`${i} must be a regular file`);if(BigInt(s.size)>BigInt(t))throw new Gt("too-large",`${i} exceeds ${t} bytes`);let o=await En.realpath(e);await n.verify?.("pre-open",{realPath:o,identity:sr(s)});let a=process.platform==="win32"?Vs.O_RDONLY:Vs.O_RDONLY|Vs.O_NOFOLLOW|Vs.O_NONBLOCK,c;try{c=await En.open(e,a)}catch(l){throw l.code==="ELOOP"?new Gt("not-regular-file",`${i} must be a regular file`,{cause:l}):l}try{let[l,f,u]=await Promise.all([c.stat({bigint:r}),En.lstat(e,{bigint:r}),En.realpath(e)]);if(!l.isFile()||!f.isFile()||f.isSymbolicLink()||u!==o||!Ys(s,l)||!Ys(s,f))throw new Gt("changed",`${i} changed while opening`);await n.verify?.("post-open",{realPath:u,identity:sr(l)}),await n.hooks?.afterOpen?.();let d=[],p=0,g=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let w=t+1-p,{bytesRead:C}=await c.read(g,0,Math.min(g.length,w),null);if(C===0)break;if(p+=C,p>t)throw new Gt("too-large",`${i} exceeds ${t} bytes`);d.push(Buffer.from(g.subarray(0,C)))}await n.hooks?.beforeFinalCheck?.();let[h,m,y]=await Promise.all([c.stat({bigint:r}),En.lstat(e,{bigint:r}),En.realpath(e)]);if(!m.isFile()||m.isSymbolicLink()||y!==o||!Ys(s,h)||!Ys(s,m))throw new Gt("changed",`${i} changed while reading`);return await n.verify?.("post-read",{realPath:y,identity:sr(h)}),{bytes:Buffer.concat(d,p),stat:h,realPath:y}}finally{await c.close()}}var Gt,Zc=pe(()=>{"use strict";rr();Gt=class extends Error{reason;constructor(t,n,i){super(n,i),this.name="RaceSafeReadError",this.reason=t}}});import{promises as zt}from"fs";import Ve from"path";function Cm(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function zs(e,t){let n=Ve.relative(e,t);return n===""||!Ve.isAbsolute(n)&&n!==".."&&!n.startsWith(`..${Ve.sep}`)}async function el(e,t){let n=Ve.resolve(e),i=await zt.lstat(n);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return zt.realpath(n)}async function tl(e,t,n,i){let r=e;for(let s=0;s{if(!zs(s,a.realPath))throw new Error(`${i.label} resolves outside the project root`);await tl(r.projectRoot,s,r.relative.split("/"),{label:i.label,expected:"file"})}})}var Ne=pe(()=>{"use strict";Zc();ct()});import{createHash as TC}from"crypto";function il(e,t){return e.exists===t.exists&&e.sha256===t.sha256}function jC(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function lt(e,t={}){return(await Rn(e,t)).document}async function km(e){try{return(await U(e,ae,Cn,{label:ae})).bytes}catch(t){if(jC(t))return null;throw t}}function Sm(e){return e?{exists:!0,sha256:TC("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function bt(e){return Sm(await km(e))}async function Rn(e,t={}){let n=await km(e);return{document:n?at(n.toString("utf8"),t):null,identity:Sm(n)}}async function rl(e){return(await lt(e))?.config??null}var ae,Ct=pe(()=>{"use strict";ct();Ne();ae=".comet/config.yaml"});import{randomUUID as LC}from"crypto";import{constants as MC,promises as ee}from"fs";import ce from"path";async function to(e,t){try{return await ee.link(e,t),{linked:!0}}catch(n){let i=n.code;if(i!=="ENOTSUP"&&i!=="EOPNOTSUPP")throw n}return await ee.copyFile(e,t,MC.COPYFILE_EXCL),{linked:!1}}function ei(e,t){let n=ce.relative(e,t);return n===""||!ce.isAbsolute(n)&&n!==".."&&!n.startsWith(`..${ce.sep}`)}function Zs(e){return{dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs}}function qC(e,t){return Ae(e,Zs(t))}function Qs(e,t){let n=Zs(e),i=Zs(t);return Sn(n,i)?Ae(n,i):Ae(n,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function eo(e){let t=await ee.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Contained atomic write parent must be a real directory: ${e}`);return{path:e,realPath:await ee.realpath(e),...Zs(t)}}async function Xt(e){for(let t of e){let n=await ee.lstat(t.path);if(!n.isDirectory()||n.isSymbolicLink()||!qC(t,n)||await ee.realpath(t.path)!==t.realPath)throw new Error(`Contained atomic write parent changed before commit: ${t.path}`)}}async function DC(e,t){let n=ce.resolve(e),i=ce.resolve(t);if(!ei(n,i))throw new Error(`Contained atomic write parent is outside its managed root: ${t}`);let r=[await eo(n)],s=ce.relative(n,i).split(ce.sep).filter(Boolean),o=n;for(let a of s){await Xt(r),o=ce.join(o,a);try{await ee.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await eo(o);if(!ei(r[0].realPath,c.realPath))throw new Error(`Contained atomic write parent resolves outside its managed root: ${o}`);r.push(c)}return await Xt(r),r}async function FC(e,t){let n=ce.resolve(e),i=ce.resolve(t);if(!ei(n,i))throw new Error(`Contained file parent is outside its managed root: ${t}`);let r=[await eo(n)],s=ce.relative(n,i).split(ce.sep).filter(Boolean),o=n;for(let a of s){o=ce.join(o,a);try{let c=await eo(o);if(!ei(r[0].realPath,c.realPath))throw new Error(`Contained file parent resolves outside its managed root: ${o}`);r.push(c)}catch(c){if(c.code==="ENOENT")return null;throw c}}return await Xt(r),r}async function Em(e){let t;try{t=await ee.open(e,"r"),await t.sync()}catch(n){let i=n.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(i??""))throw n}finally{await t?.close()}}async function WC(e,t,n){let i=ce.dirname(e),r=await DC(n.containedRoot,i),s=ce.join(i,`.${ce.basename(e)}.${LC()}.tmp`),o,a;try{await n.beforeTemporaryOpen?.(),o=await ee.open(s,"wx"),a=await o.stat();let[c,l]=await Promise.all([ee.lstat(s),ee.realpath(s)]);if(await Xt(r),!c.isFile()||c.isSymbolicLink()||!Qs(a,c)||!ei(r[0].realPath,l))throw new Error("Contained atomic write temporary file opened outside its managed parent");if(typeof t=="string"?await o.writeFile(t,"utf8"):await o.writeFile(t),await o.sync(),!Qs(a,await o.stat()))throw new Error("Contained atomic write temporary file changed while writing");await o.close(),o=void 0,await n.beforeCommit?.(),await Xt(r);let f=await ee.lstat(s);if(!f.isFile()||f.isSymbolicLink()||!Qs(f,a))throw new Error("Contained atomic write temporary file changed before commit");n.exclusive?(await to(s,e),await ee.unlink(s)):await ee.rename(s,e),await Em(i)}catch(c){await o?.close();try{await Xt(r),await ee.rm(s,{force:!0})}catch{}throw c}}async function Te(e,t,n){await WC(e,t,n)}async function sl(e,t){let n=ce.dirname(e),i=await FC(t.containedRoot,n);if(!i)return!1;let r,s;try{r=await ee.lstat(e),s=await ee.realpath(e)}catch(c){if(c.code==="ENOENT")return!1;throw c}if(!r.isFile()||r.isSymbolicLink()||!ei(i[0].realPath,s))throw new Error("Contained file removal target must be a regular file inside its managed root");await t.beforeRemove?.(),await Xt(i);let[o,a]=await Promise.all([ee.lstat(e),ee.realpath(e)]);if(!o.isFile()||o.isSymbolicLink()||!Qs(r,o)||a!==s)throw new Error("Contained file removal target changed before removal");return await ee.unlink(e),await Xt(i),await Em(n),!0}var _n=pe(()=>{"use strict";rr()});import{createHash as BC,randomUUID as HC}from"crypto";import{promises as Qt}from"fs";function Pm(e){return`.comet/config.yaml.${e}.next`}function Om(e){return`.comet/config.yaml.${e}.quarantine`}function KC(e){return`.comet/config-write-transaction.${e}.cleanup`}function ol(e){return BC("sha256").update(e).digest("hex")}function $m(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function cl(e){let t;try{t=(await U(e,no,al,{label:"project config write transaction"})).bytes}catch(o){if($m(o))return null;throw o}let n;try{n=JSON.parse(t.toString("utf8"))}catch{throw new Error("Invalid project config write transaction: expected JSON")}if(!n||typeof n!="object"||Array.isArray(n))throw new Error("Invalid project config write transaction: expected an object");let i=n,r=Object.keys(i).sort(),s=["candidate","expected_sha256","id","output_sha256","owner_pid","quarantine","schema"].sort();if(r.join(` +# 可选值:true | false`}}});function Yt(e){return e!==0&&e!==0n&&e!=="0"}function Sn(e,t){return Yt(e.dev)&&Yt(t.dev)&&Yt(e.ino)&&Yt(t.ino)}function Ae(e,t){let n=Yt(e.dev)&&Yt(t.dev);if(n&&e.dev!==t.dev)return!1;let i=Yt(e.ino)&&Yt(t.ino);return i&&e.ino!==t.ino?!1:n&&i?!0:e.birthtime===t.birthtime}var rr=pe(()=>{"use strict"});import{constants as Vs,promises as En}from"fs";function Qc(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function bm(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function sr(e){return{dev:e.dev,ino:e.ino,birthtime:Qc(e)}}function Ys(e,t){let n=sr(e),i=sr(t);return Sn(n,i)?Ae(n,i):Ae(n,i)&&Qc(e)===Qc(t)&&bm(e)===bm(t)&&e.size===t.size}async function Gs(e,t,n={}){if(!Number.isSafeInteger(t)||t<1)throw new Error("race-safe read byte limit must be a positive integer");let i=n.label??"file",r=n.bigint===!0,s=await En.lstat(e,{bigint:r});if(!s.isFile()||s.isSymbolicLink())throw new Gt("not-regular-file",`${i} must be a regular file`);if(BigInt(s.size)>BigInt(t))throw new Gt("too-large",`${i} exceeds ${t} bytes`);let o=await En.realpath(e);await n.verify?.("pre-open",{realPath:o,identity:sr(s)});let a=process.platform==="win32"?Vs.O_RDONLY:Vs.O_RDONLY|Vs.O_NOFOLLOW|Vs.O_NONBLOCK,c;try{c=await En.open(e,a)}catch(l){throw l.code==="ELOOP"?new Gt("not-regular-file",`${i} must be a regular file`,{cause:l}):l}try{let[l,f,u]=await Promise.all([c.stat({bigint:r}),En.lstat(e,{bigint:r}),En.realpath(e)]);if(!l.isFile()||!f.isFile()||f.isSymbolicLink()||u!==o||!Ys(s,l)||!Ys(s,f))throw new Gt("changed",`${i} changed while opening`);await n.verify?.("post-open",{realPath:u,identity:sr(l)}),await n.hooks?.afterOpen?.();let d=[],p=0,g=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let w=t+1-p,{bytesRead:C}=await c.read(g,0,Math.min(g.length,w),null);if(C===0)break;if(p+=C,p>t)throw new Gt("too-large",`${i} exceeds ${t} bytes`);d.push(Buffer.from(g.subarray(0,C)))}await n.hooks?.beforeFinalCheck?.();let[h,m,y]=await Promise.all([c.stat({bigint:r}),En.lstat(e,{bigint:r}),En.realpath(e)]);if(!m.isFile()||m.isSymbolicLink()||y!==o||!Ys(s,h)||!Ys(s,m))throw new Gt("changed",`${i} changed while reading`);return await n.verify?.("post-read",{realPath:y,identity:sr(h)}),{bytes:Buffer.concat(d,p),stat:h,realPath:y}}finally{await c.close()}}var Gt,Zc=pe(()=>{"use strict";rr();Gt=class extends Error{reason;constructor(t,n,i){super(n,i),this.name="RaceSafeReadError",this.reason=t}}});import{promises as zt}from"fs";import Ve from"path";function Cm(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function zs(e,t){let n=Ve.relative(e,t);return n===""||!Ve.isAbsolute(n)&&n!==".."&&!n.startsWith(`..${Ve.sep}`)}async function el(e,t){let n=Ve.resolve(e),i=await zt.lstat(n);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return zt.realpath(n)}async function tl(e,t,n,i){let r=e;for(let s=0;s{if(!zs(s,a.realPath))throw new Error(`${i.label} resolves outside the project root`);await tl(r.projectRoot,s,r.relative.split("/"),{label:i.label,expected:"file"})}})}var Ne=pe(()=>{"use strict";Zc();lt()});import{createHash as LC}from"crypto";function il(e,t){return e.exists===t.exists&&e.sha256===t.sha256}function MC(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function ut(e,t={}){return(await Rn(e,t)).document}async function km(e){try{return(await U(e,ae,Cn,{label:ae})).bytes}catch(t){if(MC(t))return null;throw t}}function Sm(e){return e?{exists:!0,sha256:LC("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function Ct(e){return Sm(await km(e))}async function Rn(e,t={}){let n=await km(e);return{document:n?ct(n.toString("utf8"),t):null,identity:Sm(n)}}async function rl(e){return(await ut(e))?.config??null}var ae,kt=pe(()=>{"use strict";lt();Ne();ae=".comet/config.yaml"});import{randomUUID as qC}from"crypto";import{constants as DC,promises as ee}from"fs";import ce from"path";async function to(e,t){try{return await ee.link(e,t),{linked:!0}}catch(n){let i=n.code;if(i!=="ENOTSUP"&&i!=="EOPNOTSUPP")throw n}return await ee.copyFile(e,t,DC.COPYFILE_EXCL),{linked:!1}}function ei(e,t){let n=ce.relative(e,t);return n===""||!ce.isAbsolute(n)&&n!==".."&&!n.startsWith(`..${ce.sep}`)}function Zs(e){return{dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs}}function FC(e,t){return Ae(e,Zs(t))}function Qs(e,t){let n=Zs(e),i=Zs(t);return Sn(n,i)?Ae(n,i):Ae(n,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function eo(e){let t=await ee.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Contained atomic write parent must be a real directory: ${e}`);return{path:e,realPath:await ee.realpath(e),...Zs(t)}}async function Xt(e){for(let t of e){let n=await ee.lstat(t.path);if(!n.isDirectory()||n.isSymbolicLink()||!FC(t,n)||await ee.realpath(t.path)!==t.realPath)throw new Error(`Contained atomic write parent changed before commit: ${t.path}`)}}async function WC(e,t){let n=ce.resolve(e),i=ce.resolve(t);if(!ei(n,i))throw new Error(`Contained atomic write parent is outside its managed root: ${t}`);let r=[await eo(n)],s=ce.relative(n,i).split(ce.sep).filter(Boolean),o=n;for(let a of s){await Xt(r),o=ce.join(o,a);try{await ee.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await eo(o);if(!ei(r[0].realPath,c.realPath))throw new Error(`Contained atomic write parent resolves outside its managed root: ${o}`);r.push(c)}return await Xt(r),r}async function BC(e,t){let n=ce.resolve(e),i=ce.resolve(t);if(!ei(n,i))throw new Error(`Contained file parent is outside its managed root: ${t}`);let r=[await eo(n)],s=ce.relative(n,i).split(ce.sep).filter(Boolean),o=n;for(let a of s){o=ce.join(o,a);try{let c=await eo(o);if(!ei(r[0].realPath,c.realPath))throw new Error(`Contained file parent resolves outside its managed root: ${o}`);r.push(c)}catch(c){if(c.code==="ENOENT")return null;throw c}}return await Xt(r),r}async function Em(e){let t;try{t=await ee.open(e,"r"),await t.sync()}catch(n){let i=n.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(i??""))throw n}finally{await t?.close()}}async function HC(e,t,n){let i=ce.dirname(e),r=await WC(n.containedRoot,i),s=ce.join(i,`.${ce.basename(e)}.${qC()}.tmp`),o,a;try{await n.beforeTemporaryOpen?.(),o=await ee.open(s,"wx"),a=await o.stat();let[c,l]=await Promise.all([ee.lstat(s),ee.realpath(s)]);if(await Xt(r),!c.isFile()||c.isSymbolicLink()||!Qs(a,c)||!ei(r[0].realPath,l))throw new Error("Contained atomic write temporary file opened outside its managed parent");if(typeof t=="string"?await o.writeFile(t,"utf8"):await o.writeFile(t),await o.sync(),!Qs(a,await o.stat()))throw new Error("Contained atomic write temporary file changed while writing");await o.close(),o=void 0,await n.beforeCommit?.(),await Xt(r);let f=await ee.lstat(s);if(!f.isFile()||f.isSymbolicLink()||!Qs(f,a))throw new Error("Contained atomic write temporary file changed before commit");n.exclusive?(await to(s,e),await ee.unlink(s)):await ee.rename(s,e),await Em(i)}catch(c){await o?.close();try{await Xt(r),await ee.rm(s,{force:!0})}catch{}throw c}}async function Te(e,t,n){await HC(e,t,n)}async function sl(e,t){let n=ce.dirname(e),i=await BC(t.containedRoot,n);if(!i)return!1;let r,s;try{r=await ee.lstat(e),s=await ee.realpath(e)}catch(c){if(c.code==="ENOENT")return!1;throw c}if(!r.isFile()||r.isSymbolicLink()||!ei(i[0].realPath,s))throw new Error("Contained file removal target must be a regular file inside its managed root");await t.beforeRemove?.(),await Xt(i);let[o,a]=await Promise.all([ee.lstat(e),ee.realpath(e)]);if(!o.isFile()||o.isSymbolicLink()||!Qs(r,o)||a!==s)throw new Error("Contained file removal target changed before removal");return await ee.unlink(e),await Xt(i),await Em(n),!0}var _n=pe(()=>{"use strict";rr()});import{createHash as KC,randomUUID as JC}from"crypto";import{promises as Qt}from"fs";function Pm(e){return`.comet/config.yaml.${e}.next`}function Om(e){return`.comet/config.yaml.${e}.quarantine`}function UC(e){return`.comet/config-write-transaction.${e}.cleanup`}function ol(e){return KC("sha256").update(e).digest("hex")}function $m(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function cl(e){let t;try{t=(await U(e,no,al,{label:"project config write transaction"})).bytes}catch(o){if($m(o))return null;throw o}let n;try{n=JSON.parse(t.toString("utf8"))}catch{throw new Error("Invalid project config write transaction: expected JSON")}if(!n||typeof n!="object"||Array.isArray(n))throw new Error("Invalid project config write transaction: expected an object");let i=n,r=Object.keys(i).sort(),s=["candidate","expected_sha256","id","output_sha256","owner_pid","quarantine","schema"].sort();if(r.join(` `)!==s.join(` -`))throw new Error("Invalid project config write transaction: unexpected fields");if(i.schema!==_m)throw new Error("Invalid project config write transaction: unsupported schema");if(typeof i.id!="string"||!xm.test(i.id))throw new Error("Invalid project config write transaction: invalid id");if(typeof i.owner_pid!="number"||!Number.isSafeInteger(i.owner_pid)||i.owner_pid<=0)throw new Error("Invalid project config write transaction: invalid owner pid");if(typeof i.expected_sha256!="string"||!io.test(i.expected_sha256)||typeof i.output_sha256!="string"||!io.test(i.output_sha256))throw new Error("Invalid project config write transaction: invalid config hash");if(i.candidate!==Pm(i.id)||i.quarantine!==Om(i.id))throw new Error("Invalid project config write transaction: paths do not match its id");return{journal:i,source:t.toString("utf8")}}async function ro(e,t){try{let{bytes:n}=await U(e,t,al,{label:t});return ol(n)}catch(n){if($m(n))return null;throw n}}async function Rm(e,t,n,i){let r=await T(e,t,{label:t,expected:"file"});if(!r.exists)return!1;let s=`${t}.${HC()}.cleanup`,o=await T(e,s,{label:`${t} cleanup`,expected:"file"});if(o.exists)throw new Error(`Owned cleanup path already exists: ${s}`);if(await Qt.rename(r.target,o.target),await i?.(t,s),await ro(e,s)!==n){try{let c=await T(e,t,{label:t,expected:"file"});c.exists||(await Qt.link(o.target,c.target),await Qt.unlink(o.target))}catch{}throw new Error(`Refusing to remove modified project config transaction file: ${t}`)}return await Qt.unlink(o.target),!0}function JC(e){if(e===process.pid)return!0;try{return process.kill(e,0),!0}catch(t){return t.code!=="ESRCH"}}async function UC(e,t){let n=KC(t.journal.id),i=await T(e,n,{label:"project config write transaction cleanup",expected:"file"});if(i.exists)throw new Error("Project config write transaction cleanup path already exists");let r=await T(e,no,{label:"project config write transaction",expected:"file"});if(!r.exists)throw new Error("Project config write transaction changed before cleanup");await Qt.rename(r.target,i.target);let s=await U(e,n,al,{label:"project config write transaction cleanup"});if(ol(s.bytes)!==ol(t.source)){try{let o=await T(e,no,{label:"project config write transaction",expected:"file"});o.exists||await Qt.link(i.target,o.target)}catch{}throw new Error("Project config write transaction changed before cleanup")}await Qt.unlink(i.target)}async function Im(e,t,n,i){if(!xm.test(t))throw new Error("Invalid project config write transaction id");if(!io.test(n)||!io.test(i))throw new Error("Invalid project config write transaction hash");if(await cl(e))throw new Error("An unfinished project config write transaction exists; run comet doctor --repair");let r={schema:_m,id:t,owner_pid:process.pid,expected_sha256:n,output_sha256:i,candidate:Pm(t),quarantine:Om(t)};return await Te((await T(e,no,{label:"project config write transaction",expected:"file"})).target,`${JSON.stringify(r,null,2)} -`,{containedRoot:e,exclusive:!0}),{candidate:r.candidate,quarantine:r.quarantine}}async function so(e){let t=await cl(e);if(!t)return null;let{journal:n}=t,[i,r,s]=await Promise.all([bt(e),ro(e,n.candidate),ro(e,n.quarantine)]);if(r!==null&&r!==n.output_sha256)throw new Error("Project config write transaction candidate changed after creation");if(s!==null&&s!==n.expected_sha256)throw new Error("Project config write transaction quarantine changed after creation");let o;return!i.exists&&s===n.expected_sha256?o="config-quarantined":i.sha256===n.output_sha256?o="published-cleanup-pending":i.exists&&i.sha256!==n.expected_sha256&&i.sha256!==n.output_sha256?o="successor-preserved-cleanup-pending":o="prepared",{id:n.id,stage:o,candidate:n.candidate,quarantine:n.quarantine,allowedRepair:"rollback-or-cleanup"}}async function oo(e,t={}){let n=await cl(e);if(!n)return!1;let{journal:i}=n;if(t.ownerId!==i.id&&JC(i.owner_pid))throw new Error(`Project config write transaction ${i.id} is still active in process ${i.owner_pid}`);if(!await so(e))return!1;let s=await bt(e),o=await ro(e,i.quarantine);if(!s.exists){if(o!==i.expected_sha256)throw new Error("Cannot recover project config write transaction: the config and owned quarantine are missing");let a=await T(e,ae,{label:ae,expected:"file"}),c=await T(e,i.quarantine,{label:"project config write transaction quarantine",expected:"file"});try{await Qt.link(c.target,a.target)}catch(l){if(l.code!=="EEXIST")throw l}if(s=await bt(e),!s.exists)throw new Error("Cannot recover project config write transaction: config publish failed")}return await Rm(e,i.candidate,i.output_sha256,t.testHooks?.afterOwnedFileQuarantine),s.exists&&await Rm(e,i.quarantine,i.expected_sha256,t.testHooks?.afterOwnedFileQuarantine),await UC(e,n),!0}var _m,no,al,xm,io,ll=pe(()=>{"use strict";_n();Ct();Ne();_m="comet.project-config-write.v1",no=".comet/config-write-transaction.json",al=16*1024,xm=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,io=/^[0-9a-f]{64}$/});import{createHash as Am,randomUUID as VC}from"crypto";import{promises as Tm}from"fs";import ul from"path";async function fl(e,t){if(!t)return;let n=await bt(e);if(!il(n,t))throw new Error("Project config changed before commit; rerun the operation")}async function dl(e,t,n={}){at(t,{allowPartialProject:n.allowPartialProject??!1});let i=ul.resolve(e);if(await so(i))throw new Error("An unfinished project config write transaction exists; run comet doctor --repair");let r=n.expectedIdentity??await bt(i);await fl(i,r);let s=await T(i,ae,{label:ae,expected:"file"}),o=VC(),a=Am("sha256").update(t).digest("hex"),c=r.exists&&r.sha256?await Im(i,o,r.sha256,a):null,l=c!==null,f=c?.candidate??`.comet/config.yaml.${o}.next`,u=ul.join(i,...f.split("/")),d=c?.quarantine??null;try{if(await Te(u,t,{containedRoot:i,exclusive:!0}),await n.beforeCommit?.(),await fl(i,r),await T(i,f,{label:"project config candidate",expected:"file"}),r.exists){if(!d)throw new Error("Project config write transaction was not created");let g=ul.join(i,...d.split("/"));if(await T(i,ae,{label:ae,expected:"file"}),(await T(i,d,{label:"project config quarantine",expected:"file"})).exists)throw new Error("Project config quarantine already exists");await Tm.rename(s.target,g);let{bytes:m}=await U(i,d,Cn,{label:"project config quarantine"});if(Am("sha256").update(m).digest("hex")!==r.sha256)throw new Error("Project config changed before final publish; successor was preserved")}else if(s.exists)throw new Error("Project config changed before final publish; successor was preserved");await n.beforePublish?.(),await T(i,f,{label:"project config candidate",expected:"file"});try{await to(u,s.target)}catch(g){throw new Error("Project config final publish failed; successor was preserved",{cause:g})}let p=await bt(i);if(!p.exists||p.sha256!==a)throw new Error("Project config changed during final publish; successor was preserved");l&&(await oo(i,{ownerId:o}),l=!1)}catch(p){if(l)try{await oo(i,{ownerId:o})&&(l=!1)}catch{}throw p}finally{l||await YC(i,f).catch(()=>!1)}}async function YC(e,t){let n=await T(e,t,{label:t,expected:"file"});return n.exists?(await Tm.unlink(n.target),!0):!1}var ml=pe(()=>{"use strict";_n();ct();Ct();Ne();ll()});var mo=pe(()=>{"use strict"});var Um=pe(()=>{"use strict"});var gl=pe(()=>{"use strict";mo()});var Vm=pe(()=>{"use strict";mo();gl()});function Sk(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function Ek(e){let t=(0,Ym.parseDocument)(e,{uniqueKeys:!0});if(t.errors.length>0)throw new Error(`Invalid global Comet config: ${t.errors[0].message}`);let n=t.toJS();if(n==null)return{};if(typeof n!="object"||Array.isArray(n))throw new Error("Invalid global Comet config: root must be a mapping");return n}function zm(e){if(e.native?.pending_root_move)throw new Error("Global Comet config cannot contain native.pending_root_move");let t=e.native?(({pending_root_move:n,...i})=>i)(e.native):void 0;return{...e,schema:"comet.global.v1",...t?{native:t}:{}}}function Rk(e){let t=at(JSON.stringify({...e,schema:"comet.project.v1"})).config;if(!t)throw new Error("Invalid global Comet config: workflow template is incomplete");return zm(t)}function _k(e){let t=at(e,{allowPartialProject:!0,allowMissingNativeFields:!0});if(!t.native&&!t.classic)return null;let n=t.native?"native":"classic",i=t.native?.language??t.classic?.language??"en",r=Xc(t.native?.artifact_root??"docs",i);return{schema:"comet.global.v1",default_workflow:n,workflows:[n],ambient_resume:t.ambient_resume,...t.native?{native:{...r.native,...t.native}}:{},...t.classic?{classic:t.classic}:{}}}function Xm(e){let t=Ek(e);if(Object.keys(t).length===0)return null;if(t.schema===void 0)return _k(e);if(t.schema!=="comet.global.v1")throw new Error("Unsupported Comet global schema");return Rk(t)}async function wl(e){try{let t=await U(e,Gm,Cn,{label:"global Comet config"});return Xm(t.bytes.toString("utf8"))}catch(t){if(Sk(t))return null;throw t}}var Ym,Gm,yl=pe(()=>{"use strict";Ym=rt(Ue(),1);_n();ct();Ne();Gm=".comet/config.yaml"});var Qm=pe(()=>{"use strict";mo();_n();Um();Vm();ct();yl();Ne();Ct();ml();ll();gl()});import{TextDecoder as xk}from"util";function Zm(e){return{dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs}}function Pk(e,t){try{return new xk("utf-8",{fatal:!0}).decode(e.bytes)}catch(n){throw new Error(`${t} is not valid UTF-8`,{cause:n})}}async function vl(e,t,n,i,r={}){try{let s=await U(e,t,n,{label:i,hooks:r.hooks});return{result:s,text:Pk(s,i)}}catch(s){let o=s.code;if(o==="ENOENT"||o==="ENOTDIR")return null;throw s}}async function Rt(e,t,n,i,r={}){return(await vl(e,t,n,i,r))?.text??null}async function tn(e,t,n,i,r,s={}){if(Buffer.byteLength(n,"utf8")>i)throw new Error(`${r} exceeds ${i} bytes`);let o=await vl(e,t,i,r),a=await T(e,t,{label:r,expected:"file"});await Te(a.target,n,{containedRoot:a.projectRoot,beforeCommit:async()=>{await s.beforeCommit?.();let c=await vl(e,t,i,r);if(!(!o&&!c)){if(!o||!c)throw new Error(`${r} changed before commit`);if(o.result.realPath!==c.result.realPath||!Ae(Zm(o.result.stat),Zm(c.result.stat))||o.text!==c.text)throw new Error(`${r} changed before commit`)}}})}async function po(e,t,n,i,r,s={}){let o=await Rt(e,t,i,r);await tn(e,t,`${o??""}${n}`,i,r,s)}async function ho(e,t,n,i={}){let r=await T(e,t,{label:n,expected:"file"});return r.exists?sl(r.target,{containedRoot:r.projectRoot,beforeRemove:i.beforeRemove}):!1}var go=pe(()=>{"use strict";Qm();rr()});var np={};Yg(np,{RUN_STATE_FILE:()=>yo,applyRunStateToDocument:()=>bl,readRunState:()=>mr,removeRunState:()=>Cl,runStateFromDocument:()=>wo,writeRunState:()=>vo});import Ok from"path";function dr(e,t){let n=e[t];if(typeof n!="string"||n.length===0)throw new Error(`Invalid Run state: ${t} must be a non-empty string`);return n}function fr(e,t){let n=dr(e,t);if(Ok.isAbsolute(n)||/^(?:[A-Za-z]:|[\\/]|~)/u.test(n)||n.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Run state: ${t} must stay inside the change directory`);return n}function $k(e){let t=e.run_retries??"{}",n;try{n=typeof t=="string"?JSON.parse(t):t}catch(i){throw new Error("Invalid Run state: run_retries must be a JSON object",{cause:i})}if(!n||typeof n!="object"||Array.isArray(n))throw new Error("Invalid Run state: run_retries must be a JSON object");for(let i of Object.values(n))if(!Number.isInteger(i)||Number(i)<0)throw new Error("Invalid Run state: retry counts must be non-negative integers");return n}function wo(e){if(!e.run_id)return null;let t=dr(e,"run_id"),n=dr(e,"skill"),i=dr(e,"skill_version"),r=dr(e,"skill_hash"),s=fr(e,"pending_ref"),o=fr(e,"trajectory_ref"),a=fr(e,"context_ref"),c=fr(e,"artifacts_ref"),l=fr(e,"checkpoint_ref"),f=Number(e.iteration);if(!Number.isInteger(f)||f<0)throw new Error("Invalid Run state: iteration must be a non-negative integer");if(e.orchestration!=="deterministic"&&e.orchestration!=="adaptive")throw new Error("Invalid Run state: orchestration must be deterministic or adaptive");if(e.run_status!=="running"&&e.run_status!=="waiting"&&e.run_status!=="completed"&&e.run_status!=="failed")throw new Error("Invalid Run state: run_status is invalid");return{runId:t,skill:n,skillVersion:i,skillHash:r,orchestration:e.orchestration,currentStep:ep(e,"current_step"),iteration:f,pending:ep(e,"pending"),pendingRef:s,trajectoryRef:o,contextRef:a,artifactsRef:c,checkpointRef:l,status:e.run_status,retries:$k(e)}}function bl(e,t){t?e.run_id=t.runId:delete e.run_id}function Ik(e){return{runId:e.runId,skill:e.skill,skillVersion:e.skillVersion,skillHash:e.skillHash,orchestration:e.orchestration,currentStep:e.currentStep,iteration:e.iteration,pending:e.pending,pendingRef:e.pendingRef,trajectoryRef:e.trajectoryRef,contextRef:e.contextRef,artifactsRef:e.artifactsRef,checkpointRef:e.checkpointRef,status:e.status,retries:e.retries}}function Ak(e){let t={run_id:e.runId,skill:e.skill,skill_version:e.skillVersion,skill_hash:e.skillHash,orchestration:e.orchestration,current_step:e.currentStep,iteration:e.iteration,pending:e.pending,pending_ref:e.pendingRef,trajectory_ref:e.trajectoryRef,context_ref:e.contextRef,artifacts_ref:e.artifactsRef,checkpoint_ref:e.checkpointRef,run_status:e.status,run_retries:JSON.stringify(e.retries)};return wo(t)}async function mr(e,t={}){let n=await Rt(e,yo,tp,"Run state",t);if(n===null)return null;let i=JSON.parse(n);return Ak(i)}async function vo(e,t,n={}){await tn(e,yo,JSON.stringify(Ik(t),null,2),tp,"Run state",n)}async function Cl(e,t={}){await ho(e,yo,"Run state",t)}var ep,yo,tp,pr=pe(()=>{"use strict";go();ep=(e,t)=>{let n=e[t];return n==null?null:String(n)};yo=".comet/run-state.json",tp=256*1024});import{pathToFileURL as Nx}from"url";import{createHash as KS}from"crypto";import{promises as JS}from"fs";import ft from"path";import{spawnSync as nk}from"child_process";function zg(e){return e.length>0&&/^[A-Za-z0-9@+=:,./\\_-]+$/.test(e)?e:`"${e.replace(/"/g,'""')}"`}function ku(e){return e.map(t=>zg(t))}import{promises as GC}from"fs";import G from"path";import{promises as Su}from"fs";async function Ri(e){try{return await Su.access(e),!0}catch(t){if(Xg(t))return!1;throw t}}async function Eu(e){try{return await Su.readdir(e)}catch(t){let n=t?.code;if(n==="ENOENT"||n==="ENOTDIR")return[];throw t}}function Xg(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}ct();Ct();ml();Ne();var or=class extends Error{code="classic-layout-unavailable";constructor(t="Classic artifact layout is unavailable from .comet/config.yaml"){super(t),this.name="ClassicLayoutUnavailableError"}},pl=class extends Error{constructor(n,i,r){let s=A(r,n),o=A(r,i);super(`Classic layout conflict: both ${s}/ and ${o}/ exist; run comet doctor and resolve the conflict before writing`);this.configuredRoot=n;this.alternateRoot=i;this.name="ClassicLayoutConflictError"}configuredRoot;alternateRoot;code="classic-layout-conflict"},jm=".comet/config.yaml";function zC(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function ao(e){await T(e,jm,{label:jm,expected:"file"})}function kt(e,t){let n=G.resolve(e),i=t==="docs"?G.join(n,"docs"):n,r=G.join(i,"openspec"),s=G.join(n,"docs","superpowers");return{projectRoot:n,artifactLayout:t,openSpecBase:i,openSpecRoot:r,changesDir:G.join(r,"changes"),archiveDir:G.join(r,"changes","archive"),specsDir:G.join(r,"specs"),superpowersRoot:s,superpowersSpecsDir:G.join(s,"specs"),superpowersPlansDir:G.join(s,"plans"),superpowersReportsDir:G.join(s,"reports")}}async function Zt(e){await ao(e);let t=await lt(e,{allowPartialProject:!0,allowMissingNativeFields:!0});if(!t?.config)throw new or;if(!(t.config.workflows??[t.config.default_workflow]).includes("classic"))throw new or("Classic artifact layout is unavailable because Classic is not enabled");return t.classic?.artifact_layout??"legacy"}async function Lm(e){await ao(e);let t=(await lt(e))?.config;if(!t)throw new Error(".comet/config.yaml must use comet.project.v1 before migration");if(!(t.workflows??[t.default_workflow]).includes("classic"))throw new Error("Classic root move requires the Classic workflow to be enabled")}async function Mm(e,t,n={}){await ao(e);let i=await Rn(e,{allowPartialProject:!0}),r=i.document;if(!r)throw new Error(".comet/config.yaml does not exist");let s=r.value.classic;if(!s||typeof s!="object"||Array.isArray(s))throw new Error("classic must be a mapping");let o={...r.value,classic:{...s,artifact_layout:t}},a=kn(o,r.classic?.language==="zh-CN"||r.native?.language==="zh-CN"?"zh-CN":"en");at(a,{allowPartialProject:!0}),await dl(e,a,{expectedIdentity:n.expectedIdentity??i.identity,beforeCommit:n.beforeCommit})}async function XC(e,t){return kt(e,t??await Zt(e))}async function QC(e,t){let n=await XC(e,t),i=n.artifactLayout==="legacy"?"docs":"legacy",r=kt(e,i).openSpecRoot,[s,o]=await Promise.all([T(n.projectRoot,A(n.projectRoot,n.openSpecRoot),{label:"Configured Classic OpenSpec root",expected:"directory"}),T(n.projectRoot,A(n.projectRoot,r),{label:"Alternate Classic OpenSpec root",expected:"directory"})]),a=s.exists,c=o.exists;return{paths:n,configuredRootExists:a,alternateRoot:r,alternateRootExists:c,dualRoots:a&&c}}async function ZC(e,t){let n=[e.openSpecRoot,e.changesDir,e.archiveDir,e.specsDir,t,e.superpowersRoot,e.superpowersSpecsDir,e.superpowersPlansDir,e.superpowersReportsDir];for(let i of n){let r=A(e.projectRoot,i);await T(e.projectRoot,r,{label:`Classic managed physical path ${r}`,expected:"directory"})}}async function z(e,t,n={}){let i=await QC(e,t);if(await ZC(i.paths,i.alternateRoot),i.dualRoots&&!n.allowAlternateRoot)throw new pl(i.paths.openSpecRoot,i.alternateRoot,i.paths.projectRoot);if(!i.configuredRootExists){let r=A(i.paths.projectRoot,i.paths.openSpecRoot),s=A(i.paths.projectRoot,i.alternateRoot);throw new or(`Configured Classic OpenSpec root is missing: ${r} (alternate ${s} is ${i.alternateRootExists?"present":"missing"})`)}return i.paths}async function Ee(e,t,n={}){let i=G.join(G.resolve(e),".comet","classic-root-move.json");if(await Ri(i))throw new Error("Classic root move transaction is incomplete; inspect it with comet doctor and recover it explicitly before writing");let r=await z(e,t,n);if(!await Ri(r.openSpecRoot))throw new Error(`Configured Classic OpenSpec root is missing: ${A(r.projectRoot,r.openSpecRoot)}`);return r}async function le(e){let t=G.resolve(e),n=null;try{(await GC.lstat(t)).isDirectory()||(t=G.dirname(t))}catch(i){if(!zC(i))throw i}for(;;){G.basename(t)==="openspec"&&(n=G.dirname(t));let i=G.join(t,".comet","config.yaml"),r=!1;if(await Ri(i))try{await ao(t);let o=(await lt(t))?.value;r=!!o&&typeof o=="object"&&!Array.isArray(o)&&(o.schema==="comet.project.v1"||o.default_workflow!==void 0||o.native!==void 0)}catch{}if(r||await Ri(G.join(t,".git")))return t;let s=G.dirname(t);if(s===t)return n??G.resolve(e);t=s}}function A(e,t){return G.relative(G.resolve(e),t).replaceAll("\\","/")}var qm=rt(Ue(),1);Ne();import ek from"path";var tk=1024*1024;async function Dm(e,t){let n=t??await z(e),i=ek.join(n.openSpecRoot,"config.yaml"),r=A(n.projectRoot,i),s;try{s=(await U(n.projectRoot,r,tk,{label:"Classic OpenSpec project config",bigint:!0})).bytes.toString("utf8")}catch(l){throw l.code==="ENOENT"?new Error(`Classic OpenSpec root is unhealthy: ${r} is missing; rerun OpenSpec initialization for the configured Classic layout`,{cause:l}):new Error(`Classic OpenSpec root is unhealthy: ${l instanceof Error?l.message:String(l)}`,{cause:l})}let o=(0,qm.parseDocument)(s,{uniqueKeys:!0});if(o.errors.length>0)throw new Error(`Classic OpenSpec root is unhealthy: ${r} is invalid YAML (${o.errors[0].message})`);let a=o.toJS();if(!a||typeof a!="object"||Array.isArray(a))throw new Error(`Classic OpenSpec root is unhealthy: ${r} must contain a mapping`);let c=a.schema;if(typeof c!="string"||c.trim()==="")throw new Error(`Classic OpenSpec root is unhealthy: ${r} must declare a non-empty schema`);return{layout:n,configPath:r,schema:c}}function ik(e){return e[0]==="--"?e.slice(1):[...e]}async function hl(e,t=process.cwd()){let n=ik(e);if(n.length===0)return{exitCode:64,stderr:"Usage: comet classic openspec -- "};let i=await le(t),r=await Ee(i);await Dm(i,r);let s=process.env.COMET_OPENSPEC||"openspec",o=process.platform==="win32",a=nk(s,o?ku(n):n,{cwd:r.openSpecBase,encoding:"utf8",shell:o,windowsHide:!0});if(a.error){let c=a.error.code;return{exitCode:c==="ENOENT"?127:70,stdout:a.stdout||void 0,stderr:a.stderr||(c==="ENOENT"?`OpenSpec CLI not found: ${s}`:a.error.message)}}return{exitCode:a.status??1,stdout:a.stdout||void 0,stderr:a.stderr||void 0}}var Fm=async e=>hl(e);import{promises as sk}from"fs";import On from"path";_n();ct();Ne();import ar from"path";var rk=2*1024*1024;function co(e,t,n){let i=ar.resolve(e),r=ar.isAbsolute(t)?ar.resolve(t):ar.resolve(i,t),s=ar.relative(i,r).replaceAll("\\","/");return{root:i,relative:Vt(s,n),target:r}}async function Y(e,t,n){let i=co(e,t,n.label);return T(i.root,i.relative,n)}async function X(e,t,n){return(await Y(e,t,{label:n.label,expected:n.expected??"any"})).exists}async function xn(e,t,n,i){return await X(e,t,{label:n,expected:"file"})?(await lo(e,t,{label:n,hooks:i})).byteLength>0:!1}async function W(e,t,n){return(await lo(e,t,n)).toString("utf8")}async function lo(e,t,n){let i=co(e,t,n.label);return(await U(i.root,i.relative,n.maxBytes??rk,{label:n.label,hooks:n.hooks})).bytes}async function Pn(e,t,n){let i=co(e,t,n);return nl(i.root,i.relative,{label:n})}async function ti(e,t,n,i){let r=co(e,t,i.label);await T(r.root,r.relative,{label:i.label,expected:"file"}),await Te(r.target,n,{containedRoot:r.root,beforeTemporaryOpen:i.beforeTemporaryOpen,beforeCommit:i.beforeCommit,exclusive:i.exclusive})}function ge(e){return e?/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e)?e.includes("..")?"Change name cannot contain '..' (path traversal not allowed)":null:`Invalid change name: '${e}' -Valid format: lowercase kebab-case (a-z, 0-9, single hyphens)`:"Change name cannot be empty"}function en(e){let t=ge(e);if(t)throw new Error(t)}function ok(e,t){return{label:A(e,t),directory:t}}async function ni(e,t,n){let i=ok(e,t);if(!(await Y(e,t,{label:n,expected:"directory"})).exists)return{change:i,exists:!1,stateExists:!1};let s=await Y(e,On.join(t,".comet.yaml"),{label:`${n} state`,expected:"file"});return{change:i,exists:!0,stateExists:s.exists}}function Wm(e,t){let n=t.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&");return new RegExp(`^\\d{4}-\\d{2}-\\d{2}-${n}$`,"u").test(e)}async function Bm(e,t,n,i={}){if(!i.skipExactCompatibility){let o=await ni(e,On.join(t,n),`Classic archived change ${n}`);if(o.exists)return o.change}if(!(await Y(e,t,{label:"Classic archive directory",expected:"directory"})).exists)return null;let s=[];for(let o of await sk.readdir(t,{withFileTypes:!0})){if(!Wm(o.name,n))continue;let a=await ni(e,On.join(t,o.name),`Classic archived change ${o.name}`);a.exists&&a.stateExists&&s.push(a.change)}return s.sort((o,a)=>a.directory.localeCompare(o.directory))[0]??null}async function Ye(e,t=process.cwd()){en(e);let n=await z(t),i=await ni(n.projectRoot,On.join(n.changesDir,e),`Classic active change ${e}`);return{...i.change,exists:i.exists,stateExists:i.stateExists}}async function Hm(e,t=process.cwd()){en(e);let n=await Ee(t),i=On.join(n.changesDir,e),r=await ni(n.projectRoot,i,`Classic active change ${e}`);return r.exists||await Pn(n.projectRoot,i,`Classic active change ${e}`),r.change}async function uo(e,t=process.cwd(),n={}){en(e);let i=await z(t);if(n.preferredArchiveName!==void 0){let r=n.preferredArchiveName;if(r!==e&&!Wm(r,e))throw new Error(`Classic preferred archive name '${r}' does not belong to change '${e}'`);let s=await ni(i.projectRoot,On.join(i.archiveDir,r),`Classic preferred archived change ${r}`);return s.exists&&s.stateExists?s.change:null}return Bm(i.projectRoot,i.archiveDir,e,n)}async function ii(e,t=process.cwd()){en(e);let n=await z(t),i=await ni(n.projectRoot,On.join(n.changesDir,e),`Classic active change ${e}`);if(i.exists)return i.change;let r=await Bm(n.projectRoot,n.archiveDir,e);return r||i.change}import{promises as Tp}from"fs";import ve from"path";import{fileURLToPath as Ol}from"url";import{promises as ck}from"fs";import St from"path";Ne();ct();import cr from"path";function ak(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function Km(e,t,n,i){let r=Vt(n,"Classic handoff artifact pointer");if((await T(e,r,{label:"Classic handoff artifact",expected:"file"})).exists)return null;let o=await z(e),a=`${A(e,o.changesDir)}/`,l=(o.artifactLayout==="docs"?[a,"openspec/changes/"]:[a]).find(w=>r.startsWith(w));if(!l)return null;let f=r.slice(l.length).split("/");if(f.length<4||f[1]!==".comet"||f.slice(2).some(w=>w.length===0))return null;let u=f[0];en(u);let d=f.slice(2),p=cr.resolve(t);if(cr.dirname(p)!==cr.resolve(o.archiveDir))return null;let g=cr.basename(p),h=/^\d{4}-\d{2}-\d{2}-(.+)$/u.exec(g);if(g!==u&&h?.[1]!==u)return null;await T(e,A(e,p),{label:"Classic archived change directory",expected:"directory"});let m=cr.join(p,".comet",...d),y=A(e,m);try{return await U(e,y,i,{label:"Historical Classic archived handoff artifact"}),y}catch(w){if(ak(w))return null;throw w}}Ne();var Jm=2*1024*1024;function lr(e,t){return St.relative(e,t).split(St.sep).join("/")}async function ur(e,t,n){if(!n)return{code:t,satisfied:!1};let i=n.replaceAll("\\","/");try{let r=await Xs(e,i,{label:`${t} artifact`});return{code:t,satisfied:r,source:i,...r?{resolvedSource:i}:{}}}catch(r){return{code:t,satisfied:!1,source:i,detail:`unsafe artifact pointer outside the project or through a special path: ${r instanceof Error?r.message:String(r)}`}}}async function lk(e,t,n){try{await z(e)}catch(r){return{code:"design.handoff",satisfied:!1,...n?{source:n.replaceAll("\\","/")}:{},detail:`Classic layout is unsafe or unavailable for handoff evidence: ${r instanceof Error?r.message:String(r)}`}}let i=await ur(e,"design.handoff",n);if(!n||i.satisfied||i.detail)return i;try{let r=await Km(e,t,n,Jm);return r?{...i,satisfied:!0,resolvedSource:r,detail:`resolved historical legacy pointer from archived change: ${r}`}:i}catch(r){return{...i,satisfied:!1,detail:`unsafe archived handoff fallback: ${r instanceof Error?r.message:String(r)}`}}}async function fo(e,t,n){return ur(e,t,lr(e,n))}async function uk(e,t){let n=St.join(t,"specs"),i;try{let o=lr(e,n);if(!(await T(e,o,{label:"OpenSpec delta-spec directory",expected:"directory"})).exists)return{code:"openspec.delta-spec",satisfied:!1};i=await ck.readdir(n)}catch(o){return o.code==="ENOENT"?{code:"openspec.delta-spec",satisfied:!1}:{code:"openspec.delta-spec",satisfied:!1,detail:`unsafe delta-spec path: ${o instanceof Error?o.message:String(o)}`}}let r=i.map(o=>St.join(n,o,"spec.md")),s=(await Promise.all(r.map(async o=>{try{return await Xs(e,lr(e,o),{label:"OpenSpec delta spec"})?o:null}catch{return null}}))).filter(o=>o!==null);return{code:"openspec.delta-spec",satisfied:s.length>0,source:s[0]?lr(e,s[0]):void 0,detail:`${s.length} delta spec${s.length===1?"":"s"}`}}async function fk(e,t){let n,i=lr(e,t);try{n=(await U(e,i,Jm,{label:"Classic tasks artifact"})).bytes.toString("utf8")}catch(o){return o.code==="ENOENT"?{code:"build.tasks-complete",satisfied:!1}:{code:"build.tasks-complete",satisfied:!1,source:i,detail:`unsafe tasks artifact: ${o instanceof Error?o.message:String(o)}`}}let r=[...n.matchAll(/^\s*[-*]\s+\[([ xX])\]\s+/gmu)],s=r.filter(o=>o[1].toLowerCase()==="x").length;return{code:"build.tasks-complete",satisfied:r.length>0&&s===r.length,source:i,detail:`${s} of ${r.length} tasks complete`}}function $n(e,t){return e.some(n=>n.code===t&&n.satisfied)}async function Ge(e,t){let n=await le(e),i=t.classic,r=St.join(e,"proposal.md"),s=St.join(e,"design.md"),o=St.join(e,"tasks.md"),a=t.run?St.resolve(e,t.run.checkpointRef):St.join(e,".comet","checkpoint.json"),c=await Promise.all([fo(n,"openspec.proposal",r),fo(n,"openspec.design",s),fo(n,"openspec.tasks",o),uk(n,e),ur(n,"design.document",i?.designDoc??null),ur(n,"build.plan",i?.plan??null),fk(n,o),ur(n,"verification.report",i?.verificationReport??null),lk(n,e,i?.handoffContext??null),fo(n,"run.checkpoint",a)]),l=c.find(f=>f.code==="design.handoff");return l&&!i?.handoffHash&&(l.satisfied=!1,l.detail="handoff hash is missing"),c.push({code:"archive.confirmed",satisfied:i?.archiveConfirmation==="confirmed"}),c}import{createHash as kS,randomUUID as SS}from"crypto";import{promises as Pl}from"fs";import _t from"path";function dk(e){return e.classicProfile??e.workflow}function mk(e){return!e.buildMode||!e.tddMode||!e.isolation||!e.verifyMode?!1:e.buildMode==="subagent-driven-development"?e.subagentDispatch==="confirmed":e.buildMode==="direct"?e.directOverride===!0:!0}function pk(e){return e.buildMode==="direct"&&e.tddMode==="direct"&&e.isolation!==null&&e.verifyMode==="light"}function hk(e,t,n){if(t.verifyResult==="fail")return e==="full"?"full.build.fix":`${e}.build.execute`;if(e==="full"){if(!$n(n,"build.plan"))return"full.build.plan";if(t.buildPause==="plan-ready")return"full.build.plan-ready";if(!mk(t))return"full.build.configure"}else if(!pk(t))throw new Error(`${e} build configuration is incomplete`);return $n(n,"build.tasks-complete")?`${e}.build.complete`:`${e}.build.execute`}function gk(e,t,n){return t.verifyResult!=="pass"||!$n(n,"verification.report")?`${e}.verify.run`:`${e}.verify.branch`}function wk(e,t){if(t.verifyResult!=="pass")throw new Error("archive requires verify_result=pass");return t.archiveConfirmation==="confirmed"?`${e}.archive.execute`:`${e}.archive.confirm`}function Et(e,t){let n=dk(e);if(e.archived&&e.phase!=="archive")throw new Error("archived=true requires phase=archive");if(e.archived)return"completed";if(n!=="full"&&e.phase==="design")throw new Error(`${n} workflow cannot enter design`);switch(e.phase){case"open":return`${n}.open`;case"design":return $n(t,"design.handoff")?"full.design.document":"full.design.handoff";case"build":return hk(n,e,t);case"verify":return gk(n,e,t);case"archive":return wk(n,e)}}var Co=rt(Ue(),1);_n();Ne();import wr from"path";pr();var Sl=["full","hotfix","tweak"],nn=1,rp=["open","design","build","verify","archive"],Nk=["en","zh-CN"],Tk=["off","beta"],jk=["subagent-driven-development","executing-plans","direct"],Lk=["plan-ready"],Mk=["confirmed"],qk=["tdd","direct"],Dk=["off","standard","thorough"],Fk=["current","branch","worktree"],Wk=["light","full"],Bk=["pending","pass","fail"],Hk=["pending","handled"],Kk=["pending","confirmed"],rn=["workflow","language","phase","context_compression","build_mode","build_pause","subagent_dispatch","tdd_mode","review_mode","isolation","bound_branch","verify_mode","auto_transition","base_ref","design_doc","plan","verify_result","verify_failures","verification_report","branch_status","created_at","verified_at","archive_confirmation","archived","direct_override","handoff_context","handoff_hash","classic_profile","classic_migration"],hr=["run_id"],sp=new Set([...rn,...hr]),Jk=["workflow","phase","design_doc","plan","build_mode","isolation","verify_mode","verify_result","verified_at","archived"];function ip(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function ri(e,t){let n=e[t];if(n==null||n==="")return null;if(typeof n!="string")throw new Error(`Invalid Classic state: ${t} must be a string or null`);return n}function we(e,t,n,i=!0){let r=e[t];if(r==null||r===""){if(i)return null;throw new Error(`Invalid Classic state: ${t} is required`)}if(typeof r!="string"||!n.includes(r))throw new Error(`Invalid Classic state: ${t} must be one of ${n.join(", ")}${i?" or null":""}`);return r}function kl(e,t,n=!0){let i=e[t];if(i==null||i===""){if(n)return null;throw new Error(`Invalid Classic state: ${t} is required`)}if(typeof i!="boolean")throw new Error(`Invalid Classic state: ${t} must be true or false`);return i}function Uk(e,t,n=0){let i=e[t];if(i==null||i==="")return n;if(typeof i!="number"||!Number.isInteger(i)||i<0)throw new Error(`Invalid Classic state: ${t} must be a non-negative integer`);return i}function bo(e,t){let n=ri(e,t);if(n===null)return null;if(/^(?:[A-Za-z]:|[\\/]|~)/u.test(n)||n.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Classic state: ${t} must be a relative repository path`);return n}function Vk(e,t){let n=ri(e,t);if(n!==null&&!/^[a-f0-9]{64}$/u.test(n))throw new Error(`Invalid Classic state: ${t} must be a sha256 hex digest`);return n}function Yk(e){let t=e.classic_migration;if(t==null||t==="")return null;if(t!==nn)throw new Error(`Invalid Classic state: classic_migration must be ${nn}`);return t}function Gk(e){if(!rn.some(n=>ip(e,n)))return null;for(let n of Jk)if(!ip(e,n))return null;return{workflow:we(e,"workflow",Sl,!1),language:we(e,"language",Nk),phase:we(e,"phase",rp,!1),contextCompression:we(e,"context_compression",Tk),buildMode:we(e,"build_mode",jk),buildPause:we(e,"build_pause",Lk),subagentDispatch:we(e,"subagent_dispatch",Mk),tddMode:we(e,"tdd_mode",qk),reviewMode:we(e,"review_mode",Dk),isolation:we(e,"isolation",Fk),boundBranch:ri(e,"bound_branch"),verifyMode:we(e,"verify_mode",Wk),autoTransition:kl(e,"auto_transition"),baseRef:ri(e,"base_ref"),designDoc:bo(e,"design_doc"),plan:bo(e,"plan"),verifyResult:we(e,"verify_result",Bk,!1),verifyFailures:Uk(e,"verify_failures"),verificationReport:bo(e,"verification_report"),branchStatus:we(e,"branch_status",Hk),createdAt:ri(e,"created_at"),verifiedAt:ri(e,"verified_at"),archiveConfirmation:we(e,"archive_confirmation",Kk),archived:kl(e,"archived",!1),directOverride:kl(e,"direct_override"),handoffContext:bo(e,"handoff_context"),handoffHash:Vk(e,"handoff_hash"),classicProfile:we(e,"classic_profile",Sl),classicMigration:Yk(e)}}function gr(e,t){let n=t??null;if(n===null&&t===void 0&&e.run_id&&e.skill)try{n=wo(e)}catch(i){let r=i instanceof Error?i.message:String(i);throw new Error(r.replace(/^Invalid Run state:/u,"Invalid Classic state:"),{cause:i})}return{classic:Gk(e),run:n,unknownKeys:Object.keys(e).filter(i=>!sp.has(i))}}function op(e){let t=e.workflow,n=e.phase,i=e.archived,r=e.design_doc;return{workflow:typeof t=="string"&&Sl.includes(t)?t:null,phase:typeof n=="string"&&rp.includes(n)?n:null,archived:i===!0,designDoc:typeof r=="string"&&r!==""?r:null,unknownKeys:Object.keys(e).filter(s=>!sp.has(s))}}function ap(e){return{workflow:e.workflow,language:e.language,phase:e.phase,context_compression:e.contextCompression,build_mode:e.buildMode,build_pause:e.buildPause,subagent_dispatch:e.subagentDispatch,tdd_mode:e.tddMode,review_mode:e.reviewMode,isolation:e.isolation,bound_branch:e.boundBranch,verify_mode:e.verifyMode,auto_transition:e.autoTransition,base_ref:e.baseRef,design_doc:e.designDoc,plan:e.plan,verify_result:e.verifyResult,verify_failures:e.verifyFailures,verification_report:e.verificationReport,branch_status:e.branchStatus,created_at:e.createdAt,verified_at:e.verifiedAt,archive_confirmation:e.archiveConfirmation,archived:e.archived,direct_override:e.directOverride,handoff_context:e.handoffContext,handoff_hash:e.handoffHash,classic_profile:e.classicProfile,classic_migration:e.classicMigration}}pr();var zk=2*1024*1024;function si(e){let t=e.toJS();if(t===null)return{};if(typeof t!="object"||Array.isArray(t))throw new Error("Invalid Classic state document: root must be a mapping");return t}function cp(e,t,n){e.get(t)!==n&&e.set(t,n)}function Xk(e,t){if(t.classic)for(let[n,i]of Object.entries(ap(t.classic)))cp(e,n,i);else for(let n of rn)e.delete(n);bl(e.toJS(),t.run),t.run?cp(e,"run_id",t.run.runId):e.delete("run_id")}function Qk(e){let t=["skill","skill_version","skill_hash","orchestration","current_step","iteration","pending","pending_ref","trajectory_ref","context_ref","artifacts_ref","checkpoint_ref","run_status","run_retries"];for(let n of t)e.delete(n)}function Zk(e){let t=!1;for(let n of["build_command","verify_command"])e.has(n)&&(e.delete(n),t=!0);return t}async function El(e){let t;try{t=(await U(wr.dirname(e),wr.basename(e),zk,{label:"Classic state document"})).bytes.toString("utf8")}catch(i){if(i.code!=="ENOENT")throw i;return new Co.Document({})}let n=(0,Co.parseDocument)(t);if(n.errors.length>0)throw new Error(`Invalid Classic state document: ${n.errors[0].message}`);return si(n),n}async function B(e,t={}){let n=t.migrate!==!1,i=wr.join(e,".comet.yaml"),r=await El(i),s=si(r),o=Zk(r);o&&(s=si(r));let a=await mr(e);if(!a&&s.run_id&&s.skill){let{runStateFromDocument:c}=await Promise.resolve().then(()=>(pr(),np));a=c(s),a&&n&&(await vo(e,a),Qk(r),o=!0)}return o&&n&&await Te(i,r.toString(),{containedRoot:e}),gr(si(r),a)}async function lp(e){let t=await El(wr.join(e,".comet.yaml"));return op(si(t))}async function je(e,t,n={}){let i=wr.join(e,".comet.yaml"),r=await El(i);Xk(r,{...t,unknownKeys:t.unknownKeys??[]}),gr(si(r),t.run??null),await Te(i,r.toString(),{containedRoot:e,beforeCommit:n.beforeCommit}),t.run?await vo(e,t.run):await Cl(e)}function up(e,t,n){return{runId:t,skill:e.definition.metadata.name,skillVersion:e.definition.metadata.version,skillHash:n,orchestration:e.definition.orchestration.mode,currentStep:e.definition.orchestration.entry??null,iteration:0,pending:null,pendingRef:".comet/pending-action.json",trajectoryRef:".comet/trajectory.jsonl",contextRef:".comet/context.md",artifactsRef:".comet/artifacts.json",checkpointRef:".comet/checkpoint.json",status:"running",retries:{}}}go();import ko from"path";var ut={trajectory:8*1024*1024,artifacts:1024*1024,context:1024*1024,pendingAction:256*1024,checkpoint:256*1024};function ze(e,t){if(ko.isAbsolute(t))throw new Error("Run path must stay inside the change directory");let n=ko.resolve(e),i=ko.resolve(n,t);if(i!==n&&!i.startsWith(n+ko.sep))throw new Error("Run path must stay inside the change directory")}async function We(e,t,n,i={}){ze(e,t),await po(e,t,`${JSON.stringify(n)} -`,ut.trajectory,"Run trajectory",i)}async function Le(e,t,n={}){ze(e,t);let i=await Rt(e,t,ut.trajectory,"Run trajectory",n);return i===null?[]:i.split(/\r?\n/).map((r,s)=>({line:r,number:s+1})).filter(({line:r})=>r.length>0).map(({line:r,number:s})=>{try{return JSON.parse(r)}catch(o){throw new Error(`Invalid Trajectory event at line ${s}`,{cause:o})}})}async function oi(e,t,n={}){ze(e,t);let i=await Rt(e,t,ut.artifacts,"Run artifacts",n);return i===null?{}:JSON.parse(i)}async function ai(e,t,n,i={}){ze(e,t),await tn(e,t,JSON.stringify(n,null,2)+` -`,ut.artifacts,"Run artifacts",i)}async function So(e,t,n,i={}){ze(e,t),await tn(e,t,n,ut.context,"Run context",i)}async function Eo(e,t,n={}){return ze(e,t),Rt(e,t,ut.context,"Run context",n)}async function Ro(e,t,n,i={}){ze(e,t),await tn(e,t,JSON.stringify(n,null,2)+` -`,ut.pendingAction,"Run pending action",i)}async function yr(e,t,n={}){ze(e,t);let i=await Rt(e,t,ut.pendingAction,"Run pending action",n);return i===null?null:JSON.parse(i)}async function _o(e,t,n={}){ze(e,t),await ho(e,t,"Run pending action",n)}async function ci(e,t,n,i={}){ze(e,t),await tn(e,t,JSON.stringify(n,null,2)+` -`,ut.checkpoint,"Run checkpoint",i)}async function fp(e,t,n={}){ze(e,t);let i=await Rt(e,t,ut.checkpoint,"Run checkpoint",n);return i===null?null:JSON.parse(i)}import{createHash as Rp,randomUUID as wS}from"crypto";import{promises as re}from"fs";import te from"path";var pp=rt(Ue(),1);import{promises as Rl}from"fs";import Be from"path";var eS=["invoke_skill","call_tool","handoff","ask_user","checkpoint"],tS=["deterministic","adaptive"],nS=["function","mcp","script","agent"],iS=["none","read","write","external"],rS=["progress","step","completion"],sS=["artifact_exists","state_equals"];function In(e,t,n){return new Error(`${e}: ${t} ${n}`)}function Re(e,t,n="document"){if(e===null||typeof e!="object"||Array.isArray(e))throw In(t,n,"must be an object")}function sn(e,t,n){if(!Array.isArray(e))throw In(t,n,"must be an array")}function ye(e,t,n){if(typeof e!="string")throw In(t,n,"must be a string")}function Xe(e,t,n,i){t in e&&ye(e[t],n,`${i}.${t}`)}function hp(e,t,n,i){if(t in e&&typeof e[t]!="boolean")throw In(n,`${i}.${t}`,"must be a boolean")}function on(e,t,n,i){if(typeof e!="string"||!t.includes(e))throw In(n,i,`must be one of ${t.join(", ")}`)}function xo(e,t,n){sn(e,t,n),e.forEach((i,r)=>{ye(i,t,`${n}[${r}]`)})}function dp(e,t,n){Re(e,t,n),ye(e.name,t,`${n}.name`),ye(e.description,t,`${n}.description`),hp(e,"required",t,n)}function oS(e,t,n){Re(e,t,n),ye(e.id,t,`${n}.id`),Xe(e,"source",t,n),Xe(e,"version",t,n)}function aS(e,t,n){Re(e,t,n),ye(e.id,t,`${n}.id`),ye(e.role,t,`${n}.role`),Xe(e,"instructions",t,n)}function cS(e,t,n){Re(e,t,n),ye(e.id,t,`${n}.id`),on(e.kind,nS,t,`${n}.kind`),ye(e.source,t,`${n}.source`),on(e.sideEffect,iS,t,`${n}.sideEffect`),hp(e,"requiresConfirmation",t,n)}function lS(e,t,n){Re(e,t,n),on(e.type,eS,t,`${n}.type`),Xe(e,"ref",t,n),Xe(e,"prompt",t,n),Xe(e,"question",t,n),"options"in e&&xo(e.options,t,`${n}.options`)}function uS(e,t,n){Re(e,t,n),ye(e.id,t,`${n}.id`),lS(e.action,t,`${n}.action`),Xe(e,"next",t,n),"completionEvals"in e&&xo(e.completionEvals,t,`${n}.completionEvals`)}function fS(e,t){let n="goal";Re(e,t,n),ye(e.statement,t,`${n}.statement`),sn(e.inputs,t,`${n}.inputs`),e.inputs.forEach((i,r)=>{dp(i,t,`${n}.inputs[${r}]`)}),sn(e.outputs,t,`${n}.outputs`),e.outputs.forEach((i,r)=>{dp(i,t,`${n}.outputs[${r}]`)}),xo(e.success,t,`${n}.success`)}function dS(e,t){let n="orchestration";Re(e,t,n),on(e.mode,tS,t,`${n}.mode`),Xe(e,"entry",t,n),"steps"in e&&(sn(e.steps,t,`${n}.steps`),e.steps.forEach((i,r)=>{uS(i,t,`${n}.steps[${r}]`)}))}function gp(e,t){return Re(e,t),on(e.apiVersion,["comet/v1alpha1"],t,"apiVersion"),on(e.kind,["Skill"],t,"kind"),Re(e.metadata,t,"metadata"),ye(e.metadata.name,t,"metadata.name"),ye(e.metadata.version,t,"metadata.version"),ye(e.metadata.description,t,"metadata.description"),fS(e.goal,t),dS(e.orchestration,t),sn(e.skills,t,"skills"),e.skills.forEach((n,i)=>{oS(n,t,`skills[${i}]`)}),sn(e.agents,t,"agents"),e.agents.forEach((n,i)=>{aS(n,t,`agents[${i}]`)}),sn(e.tools,t,"tools"),e.tools.forEach((n,i)=>{cS(n,t,`tools[${i}]`)}),e}function wp(e,t){Re(e,t);for(let n of["allowedSkills","allowedAgents","allowedTools","confirmationRequiredFor"])n in e&&xo(e[n],t,n);for(let n of["maxIterations","maxRetriesPerAction"])if(n in e&&(typeof e[n]!="number"||!Number.isFinite(e[n])))throw In(t,n,"must be a finite number");return e}function mS(e,t){return Re(e,t),"runtime"in e&&yp(e.runtime,t,"runtime"),e}function yp(e,t,n){return sn(e,t,n),e.forEach((i,r)=>{let s=`${n}[${r}]`;Re(i,t,s),ye(i.id,t,`${s}.id`),on(i.scope,rS,t,`${s}.scope`),on(i.type,sS,t,`${s}.type`),Xe(i,"artifact",t,s),Xe(i,"field",t,s),Xe(i,"equals",t,s)}),e}async function _l(e){let t=await Rl.readFile(e,"utf8");try{return(0,pp.parse)(t)}catch(n){let i=n instanceof Error?n.message:String(n);throw In(e,"document",i)}}async function pS(e){try{return await _l(e)}catch(t){if(t.code==="ENOENT")return null;throw t}}async function mp(e){try{return await Rl.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function hS(e){let t=Be.join(e,"checks.yaml"),n=Be.join(e,"evals.yaml"),[i,r]=await Promise.all([mp(t),mp(n)]);if(r)throw new Error(`${n}: evals.yaml is no longer supported; use checks.yaml`);return i?{document:mS(await _l(t),t)}:{document:null}}async function vp(e){let t=Be.resolve(e.root),n=Be.resolve(e.controlRoot);e.requireSkillMarkdown&&await Rl.access(Be.join(t,"SKILL.md"));let i=Be.join(n,"skill.yaml"),r=Be.join(n,"guardrails.yaml"),s=gp(await _l(i),i),o=await pS(r),a=o===null?null:wp(o,r),c=await hS(n),l={allowedSkills:s.skills.map(f=>f.id),allowedAgents:s.agents.map(f=>f.id),allowedTools:s.tools.map(f=>f.id),maxIterations:50,maxRetriesPerAction:3,confirmationRequiredFor:s.tools.filter(f=>f.requiresConfirmation).map(f=>f.id)};return{root:t,packageKind:e.packageKind==="runtime"?"runtime":void 0,definition:s,guardrails:{...l,...a},evals:c.document?.runtime??[]}}async function bp(e){let t=Be.resolve(e);return vp({root:t,controlRoot:Be.join(t,"comet"),packageKind:"skill",requireSkillMarkdown:!0})}async function Cp(e){let t=Be.resolve(e);return vp({root:t,controlRoot:t,packageKind:"runtime",requireSkillMarkdown:!1})}function kp(e,t,n=Be.join(t,"package.json")){Re(e,n);let i=e.packageKind==="runtime"?"runtime":void 0,r=gp(e.definition,n),s=wp(e.guardrails,n),o=yp(e.evals,n,"evals"),a={allowedSkills:r.skills.map(c=>c.id),allowedAgents:r.agents.map(c=>c.id),allowedTools:r.tools.map(c=>c.id),maxIterations:50,maxRetriesPerAction:3,confirmationRequiredFor:r.tools.filter(c=>c.requiresConfirmation).map(c=>c.id)};return{root:Be.resolve(t),packageKind:i,definition:r,guardrails:{...a,...s},evals:o}}import Sp from"path";function gS(e,t,n,i){e.type==="invoke_skill"&&!t.definition.skills.some(r=>r.id===e.ref)&&n.push(`step ${i} references undeclared skill: ${e.ref??"(missing)"}`),e.type==="call_tool"&&!t.definition.tools.some(r=>r.id===e.ref)&&n.push(`step ${i} references undeclared tool: ${e.ref??"(missing)"}`),e.type==="handoff"&&!t.definition.agents.some(r=>r.id===e.ref)&&n.push(`step ${i} references undeclared agent: ${e.ref??"(missing)"}`),e.type==="ask_user"&&!e.question&&n.push(`step ${i} ask_user action requires question`)}function Ep(e){let t=[],{definition:n,guardrails:i,evals:r}=e;n.apiVersion!=="comet/v1alpha1"&&t.push("unsupported apiVersion"),n.kind!=="Skill"&&t.push("kind must be Skill"),n.metadata.name||t.push("metadata.name is required"),n.goal.statement||t.push("goal.statement is required"),i.maxIterations<1&&t.push("maxIterations must be at least 1"),i.maxRetriesPerAction<0&&t.push("maxRetriesPerAction must not be negative");let s=n.orchestration.steps??[];if(n.orchestration.mode==="adaptive")(n.orchestration.entry||s.length>0)&&t.push("adaptive orchestration must not define entry or steps");else{let o=new Set;for(let a of s)o.has(a.id)&&t.push(`duplicate step id: ${a.id}`),o.add(a.id),gS(a.action,e,t,a.id);(!n.orchestration.entry||!o.has(n.orchestration.entry))&&t.push(`orchestration.entry references unknown step: ${n.orchestration.entry??"(missing)"}`);for(let a of s){a.next&&!o.has(a.next)&&t.push(`step ${a.id} has unknown next step: ${a.next}`);for(let c of a.completionEvals??[])r.some(l=>l.id===c)||t.push(`step ${a.id} references unknown eval: ${c}`)}}for(let o of n.tools){if(o.kind!=="script")continue;let a=Sp.posix.normalize(o.source.replaceAll("\\","/"));(Sp.isAbsolute(o.source)||a===".."||a.startsWith("../"))&&t.push(`script tool ${o.id} must reference a relative path inside the Skill package`)}for(let o of i.allowedSkills)n.skills.some(a=>a.id===o)||t.push(`guardrails allow undeclared skill: ${o}`);for(let o of i.allowedAgents)n.agents.some(a=>a.id===o)||t.push(`guardrails allow undeclared agent: ${o}`);for(let o of i.allowedTools)n.tools.some(a=>a.id===o)||t.push(`guardrails allow undeclared tool: ${o}`);return t}function Po(e){return Array.isArray(e)?e.map(Po):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,Po(n)])):e}function yS(e){return Po({...e.packageKind==="runtime"?{packageKind:"runtime"}:{},definition:e.definition,guardrails:e.guardrails,evals:e.evals})}function vS(e){return te.posix.normalize(e.replaceAll("\\","/"))}function li(e,t,n){let i=te.relative(e,t);if(!(i===""||!te.isAbsolute(i)&&!i.startsWith(`..${te.sep}`)))throw new Error(`${n} resolves outside the Skill package`)}async function _p(e,t,n){let i=vS(t);if(te.posix.isAbsolute(i)||i===".."||i.startsWith("../"))throw new Error(`${n} resolves outside the Skill package`);let r=te.resolve(e,...i.split("/"));li(e,r,n);let s;try{s=await re.realpath(r)}catch(o){throw o.code==="ENOENT"?new Error(`${n} does not exist: ${t}`,{cause:o}):o}if(li(e,s,n),!(await re.stat(s)).isFile())throw new Error(`${n} is not a file: ${t}`);return{path:i,content:await re.readFile(s)}}async function bS(e){let t=await re.realpath(e.root),n=e.packageKind==="runtime"?[]:[await _p(t,"SKILL.md","SKILL.md")];for(let i of e.definition.tools)i.kind==="script"&&n.push(await _p(t,i.source,`Script tool ${i.id}`));return n.sort((i,r)=>i.path.localeCompare(r.path))}function CS(e,t){let n=t.map(i=>({path:i.path,sha256:Rp("sha256").update(i.content).digest("hex")}));return Rp("sha256").update(JSON.stringify(Po({package:e,files:n}))).digest("hex")}function Op(e){return JSON.stringify(e,null,2)+` -`}async function $p(e){let t=yS(e),n=await bS(e);return{document:t,files:n,hash:CS(t,n)}}async function Oo(e){return(await $p(e)).hash}async function xp(e){try{return await re.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Pp(e,t){try{if((await re.readFile(te.join(e,"sha256"),"utf8")).trim()!==t.hash)throw new Error("hash mismatch");if(await re.readFile(te.join(e,"package.json"),"utf8")!==Op(t.document))throw new Error("package mismatch");for(let r of t.files)if(!(await re.readFile(te.join(e,...r.path.split("/")))).equals(r.content))throw new Error(`file mismatch: ${r.path}`)}catch(n){throw new Error(`Existing Skill snapshot is invalid: ${t.hash}`,{cause:n})}}async function xl(e,t){let n=await $p(e),i=te.resolve(t,".comet","skill-snapshots"),r=te.join(i,n.hash);if(await re.mkdir(i,{recursive:!0}),await xp(r))return await Pp(r,n),{hash:n.hash,snapshotDir:r};let s=te.join(i,`.tmp-${wS()}`);li(i,s,"Temporary snapshot"),li(i,r,"Published snapshot");try{await re.mkdir(s);for(let o of n.files){let a=te.join(s,...o.path.split("/"));li(s,a,`Snapshot file ${o.path}`),await re.mkdir(te.dirname(a),{recursive:!0}),await re.writeFile(a,o.content)}await re.writeFile(te.join(s,"package.json"),Op(n.document)),await re.writeFile(te.join(s,"sha256"),n.hash+` -`),await re.rename(s,r)}catch(o){if(await xp(r)){try{await Pp(r,n)}finally{await re.rm(s,{recursive:!0,force:!0})}return{hash:n.hash,snapshotDir:r}}throw await re.rm(s,{recursive:!0,force:!0}),o}return{hash:n.hash,snapshotDir:r}}async function $o(e,t){if(!/^[a-f0-9]{64}$/u.test(t))throw new Error(`Invalid Skill snapshot hash: ${t}`);let n=te.resolve(e,".comet","skill-snapshots"),i=te.join(n,t);li(n,i,"Skill snapshot");try{let r=(await re.readFile(te.join(i,"sha256"),"utf8")).trim();if(r!==t)throw new Error(`stored hash is ${r||"(empty)"}`);let s=te.join(i,"package.json"),o=JSON.parse(await re.readFile(s,"utf8")),a=kp(o,i,s),c=Ep(a);if(c.length>0)throw new Error(c.map(f=>` - ${f}`).join(` -`));let l=await Oo(a);if(l!==t)throw new Error(`calculated hash is ${l}`);return a}catch(r){throw new Error(`Skill snapshot is invalid or missing: ${t}`,{cause:r})}}async function Ip(e){try{return await Pl.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Ap(e){return kS("sha256").update(e).digest("hex")}function ES(e){return Ap(JSON.stringify(Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))))}function RS(e){return e.replaceAll(".","_").replaceAll("-","_")}async function _S(e,t){let n=await le(e),i=Object.fromEntries(t.filter(o=>o.satisfied&&o.source).map(o=>[RS(o.code),o.source])),r=_t.join(e,"subagent-progress.md");await Ip(r)&&(i.subagent_progress=_t.relative(n,r).split(_t.sep).join("/"));let s=t.find(o=>o.code==="design.handoff"&&o.satisfied);return s?.source&&(i.handoff_context=s.source),i}function xS(e,t,n){return[{sequence:1,timestamp:n,type:"run_started",runId:e.runId,data:{skill:e.skill,skillVersion:e.skillVersion,skillHash:e.skillHash}},{sequence:2,timestamp:n,type:"state_migrated",runId:e.runId,data:{kind:"classic",migrationVersion:nn,profile:t,source:"pre-migration"}}]}async function PS(e){await Promise.all(e.map(t=>Pl.rm(t,{recursive:!0,force:!0})))}async function Np(e,t){let n=await B(e);if(!n.classic)throw new Error("Classic migration requires a legacy state projection");let i=n.classic,r=i.classicProfile??i.workflow;if(n.run){if(i.classicMigration!==nn)throw new Error("Classic Run exists without a supported classic_migration marker");if(n.run.skill!==t.skillPackage.definition.metadata.name)throw new Error(`Classic Run skill mismatch: expected ${t.skillPackage.definition.metadata.name}, got ${n.run.skill}`);if(await Oo(t.skillPackage)!==n.run.skillHash)return await $o(e,n.run.skillHash),{classic:i,run:n.run,evidence:await Ge(e,n),migrated:!1,snapshotDir:_t.join(e,".comet","skill-snapshots",n.run.skillHash)};let d=await xl(t.skillPackage,e);return{classic:i,run:n.run,evidence:await Ge(e,n),migrated:!1,snapshotDir:d.snapshotDir}}let s=await Ge(e,n),o=Et(i,s);if(!t.skillPackage.definition.orchestration.steps?.some(u=>u.id===o))throw new Error(`Classic Skill package does not define resolved step: ${o}`);let a=await Oo(t.skillPackage),c=_t.join(e,".comet","skill-snapshots",a),l=await Ip(c),f=[];try{let u=await xl(t.skillPackage,e),d=up(t.skillPackage,t.runId?.()??SS(),u.hash);d.currentStep=o,o==="completed"&&(d.status="completed");let p={...i,classicProfile:r,classicMigration:nn},g=await _S(e,s),h=await le(e),m=s.find(k=>k.code==="design.handoff"&&k.satisfied),y=null;m?.source&&(y=await W(h,m.resolvedSource??m.source,{label:"Classic migration handoff context",hooks:t.handoffReadHooks}),await So(e,d.contextRef,y),f.push(_t.resolve(e,d.contextRef))),await ai(e,d.artifactsRef,g),f.push(_t.resolve(e,d.artifactsRef));let w=(t.now?.()??new Date).toISOString(),C={runId:d.runId,stateVersion:1,trajectoryOffset:2,contextHash:y===null?null:Ap(y),artifactsHash:ES(g),createdAt:w};await ci(e,d.checkpointRef,C),f.push(_t.resolve(e,d.checkpointRef)),f.push(_t.resolve(e,d.trajectoryRef));for(let k of xS(d,r,w))await We(e,d.trajectoryRef,k);return await je(e,{classic:p,run:d,unknownKeys:n.unknownKeys}),{classic:p,run:d,evidence:s,migrated:!0,snapshotDir:u.snapshotDir}}catch(u){throw await PS(f),l||await Pl.rm(c,{recursive:!0,force:!0}),u}}async function OS(e){try{return(await Tp.stat(e)).isDirectory()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Io(e){try{return(await Tp.stat(e)).isFile()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function $S(e){return await OS(e)?await Io(ve.join(e,"skill.yaml"))?!0:await Io(ve.join(e,"SKILL.md"))&&await Io(ve.join(e,"comet","skill.yaml")):!1}function jp(e){return{root:e,packageKind:"runtime",definition:{apiVersion:"comet/v1alpha1",kind:"Skill",metadata:{name:"comet-classic",version:"1",description:"Internal compatibility orchestration for classic Comet full, hotfix, and tweak workflows"},goal:{statement:"Advance or restore a classic Comet Run without changing the user command surface",inputs:[{name:"classic-state",description:"Validated ClassicState consistent with the Run projection",required:!0},{name:"evidence",description:"Structured evidence produced by the Classic Evidence collector",required:!0}],outputs:[{name:"run-state",description:"Atomically synchronized Classic and Run state",required:!0}],success:["Legacy fields and Run fields remain consistent","Every step invokes only a declared public Comet Skill","The completed state passes its completion eval"]},orchestration:{mode:"deterministic",entry:"full.open",steps:[{id:"full.open",action:{type:"invoke_skill",ref:"comet-open"},next:"full.design.handoff"},{id:"full.design.handoff",action:{type:"invoke_skill",ref:"comet-design"},next:"full.design.document"},{id:"full.design.document",action:{type:"invoke_skill",ref:"comet-design"},next:"full.build.plan"},{id:"full.build.plan",action:{type:"invoke_skill",ref:"comet-build"},next:"full.build.plan-ready"},{id:"full.build.plan-ready",action:{type:"invoke_skill",ref:"comet-build"},next:"full.build.configure"},{id:"full.build.configure",action:{type:"invoke_skill",ref:"comet-build"},next:"full.build.execute"},{id:"full.build.execute",action:{type:"invoke_skill",ref:"comet-build"},next:"full.build.complete"},{id:"full.build.complete",action:{type:"invoke_skill",ref:"comet-build"},next:"full.verify.run"},{id:"full.build.fix",action:{type:"invoke_skill",ref:"comet-build"},next:"full.build.execute"},{id:"full.verify.run",action:{type:"invoke_skill",ref:"comet-verify"},next:"full.verify.branch"},{id:"full.verify.branch",action:{type:"invoke_skill",ref:"comet-verify"},next:"full.archive.confirm"},{id:"full.archive.confirm",action:{type:"invoke_skill",ref:"comet-archive"},next:"full.archive.execute"},{id:"full.archive.execute",action:{type:"invoke_skill",ref:"comet-archive"},next:"completed"},{id:"hotfix.open",action:{type:"invoke_skill",ref:"comet-hotfix"},next:"hotfix.build.execute"},{id:"hotfix.build.execute",action:{type:"invoke_skill",ref:"comet-build"},next:"hotfix.build.complete"},{id:"hotfix.build.complete",action:{type:"invoke_skill",ref:"comet-build"},next:"hotfix.verify.run"},{id:"hotfix.verify.run",action:{type:"invoke_skill",ref:"comet-verify"},next:"hotfix.verify.branch"},{id:"hotfix.verify.branch",action:{type:"invoke_skill",ref:"comet-verify"},next:"hotfix.archive.confirm"},{id:"hotfix.archive.confirm",action:{type:"invoke_skill",ref:"comet-archive"},next:"hotfix.archive.execute"},{id:"hotfix.archive.execute",action:{type:"invoke_skill",ref:"comet-archive"},next:"completed"},{id:"tweak.open",action:{type:"invoke_skill",ref:"comet-tweak"},next:"tweak.build.execute"},{id:"tweak.build.execute",action:{type:"invoke_skill",ref:"comet-build"},next:"tweak.build.complete"},{id:"tweak.build.complete",action:{type:"invoke_skill",ref:"comet-build"},next:"tweak.verify.run"},{id:"tweak.verify.run",action:{type:"invoke_skill",ref:"comet-verify"},next:"tweak.verify.branch"},{id:"tweak.verify.branch",action:{type:"invoke_skill",ref:"comet-verify"},next:"tweak.archive.confirm"},{id:"tweak.archive.confirm",action:{type:"invoke_skill",ref:"comet-archive"},next:"tweak.archive.execute"},{id:"tweak.archive.execute",action:{type:"invoke_skill",ref:"comet-archive"},next:"completed"},{id:"completed",action:{type:"checkpoint"},completionEvals:["classic-completed"]}]},skills:[{id:"comet-open"},{id:"comet-design"},{id:"comet-build"},{id:"comet-verify"},{id:"comet-archive"},{id:"comet-hotfix"},{id:"comet-tweak"}],agents:[],tools:[]},guardrails:{allowedSkills:["comet-open","comet-design","comet-build","comet-verify","comet-archive","comet-hotfix","comet-tweak"],allowedAgents:[],allowedTools:[],maxIterations:500,maxRetriesPerAction:3,confirmationRequiredFor:[]},evals:[{id:"classic-completed",scope:"completion",type:"state_equals",field:"status",equals:"completed"}]}}async function Lp(){let e=ve.dirname(Ol(import.meta.url)),t=[process.env.COMET_RUNTIME_CLASSIC_ROOT,ve.resolve(e,"..","runtime","classic"),ve.resolve(e,"..","..","comet","runtime","classic"),ve.resolve(e,"..","..","assets","skills","comet","runtime","classic"),ve.resolve("assets","skills","comet","runtime","classic"),process.env.COMET_CLASSIC_SKILL_ROOT,ve.resolve(e,"..","..","comet-classic"),ve.resolve(e,"..","..","assets","skills","comet-classic"),ve.resolve("assets","skills","comet-classic")].filter(n=>!!n);for(let n of t)if(await $S(n))return n;return null}async function Mp(e){return await Io(ve.join(e,"skill.yaml"))?Cp(e):bp(e)}async function an(e){let t=await Lp();return Np(e,{skillPackage:t?await Mp(t):jp(ve.dirname(Ol(import.meta.url)))})}async function qp(e){let t=await B(e),n=Array.from(new Set(t.unknownKeys)).sort();if(n.length>0)throw new Error(`Invalid Classic state: unknown field(s): ${n.join(", ")}`);return an(e)}async function $l(e,t){let n=t??await B(e,{migrate:!1}),i=Array.from(new Set(n.unknownKeys)).sort();if(i.length>0)throw new Error(`Invalid Classic state: unknown field(s): ${i.join(", ")}`);if(!n.classic||!n.run)throw new Error("Classic runtime validation requires synchronized Classic and Run projections");if(n.classic.classicMigration!==nn)throw new Error("Classic Run exists without a supported classic_migration marker");let r=await Lp(),s=r?await Mp(r):jp(ve.dirname(Ol(import.meta.url)));if(n.run.skill!==s.definition.metadata.name)throw new Error(`Classic Run skill mismatch: expected ${s.definition.metadata.name}, got ${n.run.skill}`);let o=await $o(e,n.run.skillHash);if(o.definition.metadata.name!==n.run.skill)throw new Error(`Classic Run snapshot skill mismatch: expected ${n.run.skill}, got ${o.definition.metadata.name}`);let a=await Ge(e,n),c=Et(n.classic,a);if(n.run.currentStep!==c)throw new Error(`Classic Run step mismatch: expected ${c}, got ${n.run.currentStep}`);return{classic:n.classic,run:n.run,evidence:a,migrated:!1,snapshotDir:ve.join(e,".comet","skill-snapshots",n.run.skillHash)}}async function cn(e,t,n,i){let r=await B(e);if(!r.classic||!r.run)throw new Error("Classic transition requires synchronized Classic and Run projections");let s=await Ge(e,{classic:t,run:n,unknownKeys:r.unknownKeys}),o=Et(t,s),a={...n,currentStep:o,iteration:n.iteration+1,status:o==="completed"?"completed":"running"};await je(e,{classic:t,run:a,unknownKeys:r.unknownKeys});let c=await Le(e,a.trajectoryRef);return await We(e,a.trajectoryRef,{sequence:c.length+1,timestamp:new Date().toISOString(),type:"state_transitioned",runId:a.runId,data:{kind:"classic",fromStep:n.currentStep,toStep:o,...i}}),a}go();import IS from"path";var AS=IS.join(".comet","state-events.jsonl"),NS=8*1024*1024;async function An(e,t){let n={schemaVersion:1,timestamp:new Date().toISOString(),...t};return await po(e,AS,`${JSON.stringify(n)} -`,NS,"Classic state event log"),n}var Dp=["open-complete","design-complete","build-complete","verify-pass","verify-fail","archive-confirm","archive-reopen","archived","preset-escalate"],TS={"open-complete":{event:"open-complete",from:"open",guardRefs:["open-artifacts-present"]},"design-complete":{event:"design-complete",from:"design",guardRefs:["design-evidence-present"]},"build-complete":{event:"build-complete",from:"build",guardRefs:["build-decisions-selected"]},"verify-pass":{event:"verify-pass",from:"verify",guardRefs:["verification-report-present"]},"verify-fail":{event:"verify-fail",from:"verify",guardRefs:["verification-failed"]},"archive-confirm":{event:"archive-confirm",from:"archive",guardRefs:["archive-final-confirmation"]},"archive-reopen":{event:"archive-reopen",from:"archive",guardRefs:["archive-not-finalized"]},archived:{event:"archived",from:"archive",guardRefs:["verify-result-pass","archive-confirmed"]},"preset-escalate":{event:"preset-escalate",from:"build",guardRefs:["preset-workflow"]}},Fp={open:"open-complete",design:"design-complete",build:"build-complete",verify:"verify-pass"};function jS(e){return e.toISOString().slice(0,10)}function j(e,t,n,i){let r=e[n];e[n]=i,r!==i&&t.push({field:n,from:r,to:i})}function ui(e,t,n={}){let i=TS[t];if(e.phase!==i.from)throw new Error(`Cannot apply ${t}: phase is '${e.phase}', expected '${i.from}'`);let r={...e},s=[],o=n.now??new Date;if(t==="open-complete")j(r,s,"phase",r.workflow==="full"?"design":"build");else if(t==="design-complete")j(r,s,"phase","build");else if(t==="build-complete"){let a=r.verifyResult==="fail";j(r,s,"phase","verify"),j(r,s,"verifyResult","pending"),j(r,s,"branchStatus","pending"),a||j(r,s,"verificationReport",null)}else if(t==="verify-pass")j(r,s,"verifyResult","pass"),j(r,s,"verifyFailures",0),j(r,s,"phase","archive"),j(r,s,"verifiedAt",jS(o)),j(r,s,"archiveConfirmation","pending"),j(r,s,"branchStatus","pending");else if(t==="verify-fail")j(r,s,"verifyResult","fail"),j(r,s,"verifyFailures",r.verifyFailures+1),j(r,s,"phase","build"),j(r,s,"branchStatus","pending");else if(t==="preset-escalate"){if(r.workflow!=="hotfix"&&r.workflow!=="tweak")throw new Error(`Cannot apply ${t}: workflow must be hotfix or tweak, got '${r.workflow}'`);j(r,s,"workflow","full"),j(r,s,"classicProfile","full"),j(r,s,"phase","design"),j(r,s,"designDoc",null),j(r,s,"buildPause",null),j(r,s,"buildMode",null),j(r,s,"subagentDispatch",null),j(r,s,"tddMode",null),j(r,s,"reviewMode",null),j(r,s,"isolation",null),j(r,s,"boundBranch",null),j(r,s,"verifyMode",null),j(r,s,"directOverride",null)}else if(t==="archive-confirm"){if(r.verifyResult!=="pass")throw new Error(`Cannot apply ${t}: verifyResult must be pass`);if(r.archived)throw new Error(`Cannot apply ${t}: already archived`);j(r,s,"archiveConfirmation","confirmed")}else if(t==="archive-reopen"){if(r.archived)throw new Error(`Cannot apply ${t}: already archived`);j(r,s,"verifyResult","pending"),j(r,s,"verifyFailures",0),j(r,s,"phase","verify"),j(r,s,"verifiedAt",null),j(r,s,"archiveConfirmation",null),j(r,s,"branchStatus","pending")}else{if(r.verifyResult!=="pass")throw new Error(`Cannot apply ${t}: verifyResult must be pass`);if(r.archiveConfirmation!=="confirmed")throw new Error(`Cannot apply ${t}: archiveConfirmation must be confirmed`);j(r,s,"archived",!0)}return{classic:r,effects:s,definition:i}}Zc();import{randomUUID as LS}from"crypto";import{promises as vr}from"fs";import Bp from"path";var Il="comet.selection.v2",MS=16*1024;function Ao(e){return Bp.join(e,".comet","current-change.json")}function qS(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Wp(e){return e===null||typeof e=="string"}function Hp(e){let t;try{t=JSON.parse(e)}catch(n){throw new Error(`current change selection contains invalid JSON: ${n instanceof Error?n.message:String(n)}`,{cause:n})}if(!qS(t))throw new Error("current change selection must be a JSON object");if(t.version===1){if(typeof t.change!="string")throw new Error("legacy current change selection change must be a string");if(t.branch!==void 0&&!Wp(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:Il,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==Il)throw new Error(`current change selection schema must be ${Il}`);if(t.workflow!=="native"&&t.workflow!=="classic")throw new Error("current change selection workflow must be native or classic");if(typeof t.change!="string")throw new Error("current change selection change must be a string");if(!Wp(t.branch))throw new Error("current change selection branch must be a string or null");if(t.workflow==="native"&&t.branch!==null)throw new Error("Native current change selection branch must be null");return{selection:t,legacy:!1}}async function No(e){let t;try{let i=Ao(e),{bytes:r}=await Gs(i,MS,{label:"current change selection"});t=r.toString("utf8")}catch(i){if(i.code==="ENOENT")return{status:"missing"};throw new Error(`cannot read current change selection: ${i instanceof Error?i.message:String(i)}`,{cause:i})}return{status:"selected",...Hp(t)}}async function Kp(e,t){let n=Hp(JSON.stringify(t));if(n.legacy)throw new Error("cannot write a legacy current change selection");let i=Ao(e),r=`${i}.${LS()}.tmp`;await vr.mkdir(Bp.dirname(i),{recursive:!0});try{await vr.writeFile(r,`${JSON.stringify(n.selection,null,2)} -`,"utf8"),await vr.rename(r,i)}catch(s){throw await vr.rm(r,{force:!0}),s}}async function Al(e){await vr.rm(Ao(e),{force:!0})}async function Jp(e,t,n){let i=await No(e);return i.status!=="selected"||i.selection.workflow!==t||i.selection.change!==n?!1:(await Al(e),!0)}var Up=null;function Vp(e,t){let n=e;for(let i of t)n+="\0"+(typeof i=="string"?i:JSON.stringify(i));return n}function br(e,t){return(...n)=>{let i=Up;if(i===null)return t(...n);let r=Vp(`async:${e}`,n),s=i.entries.get(r);if(s)return s.value;let o=t(...n).catch(a=>{throw i.entries.delete(r),a});return i.entries.set(r,{value:o}),o}}function Nl(e,t){return(...n)=>{let i=Up;if(i===null)return t(...n);let r=Vp(`sync:${e}`,n),s=i.entries.get(r);if(s)return s.value;let o=t(...n);return i.entries.set(r,{value:o}),o}}var Tl=rt(Ue(),1);import{execFileSync as Yp}from"child_process";import{randomUUID as DS}from"crypto";import{promises as Cr}from"fs";import Gp from"path";function To(e){try{let t=Yp("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();return t&&t!=="HEAD"?t:null}catch{return null}}var FS=Nl("liveGitBranch",e=>To(e));function jl(e){try{return Yp("git",["rev-parse","--is-inside-work-tree"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()==="true"}catch{return!1}}var WS=Nl("isGitWorkTree",e=>jl(e)),BS=["current","branch","worktree"];function jo(e){return BS.includes(e)}function Ll(e){return jo(e.isolation)?e.boundBranch===null&&e.currentBranch===null&&e.gitWorkTree===!1?{status:"not-applicable"}:e.boundBranch===null?e.currentBranch===null?{status:"unbound-detached"}:{status:"needs-heal",branch:e.currentBranch}:e.currentBranch===e.boundBranch?{status:"ok"}:{status:"drift",boundBranch:e.boundBranch,currentBranch:e.currentBranch}:{status:"not-applicable"}}async function xt(e,t){let n=Gp.join(e,".comet.yaml"),i=(0,Tl.parseDocument)(await Cr.readFile(n,"utf8"),{uniqueKeys:!1});if(i.errors.length>0)throw new Error(`Invalid .comet.yaml: ${i.errors[0].message}`);let r=i.toJS()??{},s=typeof r.isolation=="string"?r.isolation:null,o=typeof r.bound_branch=="string"&&r.bound_branch!==""?r.bound_branch:null,a=jo(s),c=FS(t.cwd),l=a&&o===null&&c===null?WS(t.cwd):!0,f=Ll({isolation:s,boundBranch:o,currentBranch:c,gitWorkTree:l});return f.status==="needs-heal"&&t.heal?(await Ml(e,f.branch),{status:"healed",branch:f.branch,bindingRequired:a,currentBranch:c}):{...f,bindingRequired:a,currentBranch:c}}async function Ml(e,t){let n=Gp.join(e,".comet.yaml"),i=(0,Tl.parseDocument)(await Cr.readFile(n,"utf8"),{uniqueKeys:!1});i.set("bound_branch",t);let r=`${n}.${DS()}.tmp`;try{await Cr.writeFile(r,i.toString(),"utf8"),await Cr.rename(r,n)}catch(s){throw await Cr.rm(r,{force:!0}),s}}function zp(e){return e??"detached HEAD"}function Lo(e,t,n){return`change '${e}' is bound to branch '${t}', but current branch is '${zp(n)}'. -Next: ask the user to confirm — switch back to '${t}', or run \`comet state rebind ${e}\` after explicit confirmation.`}function kr(e,t,n){return`change '${e}' is bound to branch '${t}', but current branch is '${zp(n)}'`}function Pt(e){return`change '${e}' uses a branch-bound workspace mode but has no bound branch and HEAD is detached; checkout a branch first before continuing.`}var HS=br("readCometCurrentSelection",e=>No(e));async function Xp(e,t){en(t);let n=await Ye(t,e);if(!n.stateExists)throw new Error(`Cannot select current change '${t}': active change state not found`);let i=await B(n.directory,{migrate:!1});if(!i.classic)throw new Error(`Cannot select current change '${t}': Classic state is incomplete`);if(i.classic.archived)throw new Error(`Cannot select current change '${t}': change is archived`);return n.directory}async function Qp(e,t){let n=await Xp(e,t),i=await xt(n,{heal:!0,cwd:e});if(i.status==="drift")throw new Error(kr(t,i.boundBranch,i.currentBranch));if(i.status==="unbound-detached")throw new Error(Pt(t));let r={schema:"comet.selection.v2",workflow:"classic",change:t,branch:i.currentBranch};return await Kp(e,r),r}async function Mo(e){let t;try{t=await HS(e)}catch(s){return{status:"stale",reason:s instanceof Error?s.message:String(s)}}if(t.status==="missing")return{status:"missing"};if(t.selection.workflow!=="classic")return{status:"stale",reason:`current change '${t.selection.change}' belongs to Native, not Classic`};let n=t.selection,i;try{i=await Xp(e,n.change)}catch(s){return{status:"stale",reason:s instanceof Error?s.message:String(s)}}let r=await xt(i,{heal:!1,cwd:e});return r.status==="drift"?{status:"stale",reason:kr(n.change,r.boundBranch,r.currentBranch)}:r.status==="unbound-detached"?{status:"stale",reason:Pt(n.change)}:r.status==="ok"?{status:"selected",selection:n}:n.branch!==null&&r.currentBranch!==n.branch?{status:"stale",reason:`current change '${n.change}' was selected on branch '${n.branch}', current branch is '${r.currentBranch??"detached HEAD"}'`}:{status:"selected",selection:n}}async function Zp(e){let t;try{t=await No(e)}catch{return}t.status==="selected"&&t.selection.workflow==="classic"&&await Al(e)}async function eh(e,t){return Jp(e,"classic",t)}var US="\x1B[32m",VS="\x1B[31m",YS="\x1B[33m",Dl="\x1B[0m";function He(e){return`${US}${e}${Dl}`}function _e(e){return`${VS}${e}${Dl}`}function Sr(e){return`${YS}${e}${Dl}`}var ue=class extends Error{constructor(n,i=1){super(n);this.exitCode=i}exitCode},ql=class{stderr=[];openSpecStdout=[];openSpecStderr=[];stepsOk=0;stepsTotal=0;captureOpenSpec(t){t.stdout&&this.openSpecStdout.push(t.stdout),t.stderr&&this.openSpecStderr.push(t.stderr)}toResult(t=0){let n=this.stderr.length>0?this.stderr.join(` +`))throw new Error("Invalid project config write transaction: unexpected fields");if(i.schema!==_m)throw new Error("Invalid project config write transaction: unsupported schema");if(typeof i.id!="string"||!xm.test(i.id))throw new Error("Invalid project config write transaction: invalid id");if(typeof i.owner_pid!="number"||!Number.isSafeInteger(i.owner_pid)||i.owner_pid<=0)throw new Error("Invalid project config write transaction: invalid owner pid");if(typeof i.expected_sha256!="string"||!io.test(i.expected_sha256)||typeof i.output_sha256!="string"||!io.test(i.output_sha256))throw new Error("Invalid project config write transaction: invalid config hash");if(i.candidate!==Pm(i.id)||i.quarantine!==Om(i.id))throw new Error("Invalid project config write transaction: paths do not match its id");return{journal:i,source:t.toString("utf8")}}async function ro(e,t){try{let{bytes:n}=await U(e,t,al,{label:t});return ol(n)}catch(n){if($m(n))return null;throw n}}async function Rm(e,t,n,i){let r=await T(e,t,{label:t,expected:"file"});if(!r.exists)return!1;let s=`${t}.${JC()}.cleanup`,o=await T(e,s,{label:`${t} cleanup`,expected:"file"});if(o.exists)throw new Error(`Owned cleanup path already exists: ${s}`);if(await Qt.rename(r.target,o.target),await i?.(t,s),await ro(e,s)!==n){try{let c=await T(e,t,{label:t,expected:"file"});c.exists||(await Qt.link(o.target,c.target),await Qt.unlink(o.target))}catch{}throw new Error(`Refusing to remove modified project config transaction file: ${t}`)}return await Qt.unlink(o.target),!0}function VC(e){if(e===process.pid)return!0;try{return process.kill(e,0),!0}catch(t){return t.code!=="ESRCH"}}async function YC(e,t){let n=UC(t.journal.id),i=await T(e,n,{label:"project config write transaction cleanup",expected:"file"});if(i.exists)throw new Error("Project config write transaction cleanup path already exists");let r=await T(e,no,{label:"project config write transaction",expected:"file"});if(!r.exists)throw new Error("Project config write transaction changed before cleanup");await Qt.rename(r.target,i.target);let s=await U(e,n,al,{label:"project config write transaction cleanup"});if(ol(s.bytes)!==ol(t.source)){try{let o=await T(e,no,{label:"project config write transaction",expected:"file"});o.exists||await Qt.link(i.target,o.target)}catch{}throw new Error("Project config write transaction changed before cleanup")}await Qt.unlink(i.target)}async function Im(e,t,n,i){if(!xm.test(t))throw new Error("Invalid project config write transaction id");if(!io.test(n)||!io.test(i))throw new Error("Invalid project config write transaction hash");if(await cl(e))throw new Error("An unfinished project config write transaction exists; run comet doctor --repair");let r={schema:_m,id:t,owner_pid:process.pid,expected_sha256:n,output_sha256:i,candidate:Pm(t),quarantine:Om(t)};return await Te((await T(e,no,{label:"project config write transaction",expected:"file"})).target,`${JSON.stringify(r,null,2)} +`,{containedRoot:e,exclusive:!0}),{candidate:r.candidate,quarantine:r.quarantine}}async function so(e){let t=await cl(e);if(!t)return null;let{journal:n}=t,[i,r,s]=await Promise.all([Ct(e),ro(e,n.candidate),ro(e,n.quarantine)]);if(r!==null&&r!==n.output_sha256)throw new Error("Project config write transaction candidate changed after creation");if(s!==null&&s!==n.expected_sha256)throw new Error("Project config write transaction quarantine changed after creation");let o;return!i.exists&&s===n.expected_sha256?o="config-quarantined":i.sha256===n.output_sha256?o="published-cleanup-pending":i.exists&&i.sha256!==n.expected_sha256&&i.sha256!==n.output_sha256?o="successor-preserved-cleanup-pending":o="prepared",{id:n.id,stage:o,candidate:n.candidate,quarantine:n.quarantine,allowedRepair:"rollback-or-cleanup"}}async function oo(e,t={}){let n=await cl(e);if(!n)return!1;let{journal:i}=n;if(t.ownerId!==i.id&&VC(i.owner_pid))throw new Error(`Project config write transaction ${i.id} is still active in process ${i.owner_pid}`);if(!await so(e))return!1;let s=await Ct(e),o=await ro(e,i.quarantine);if(!s.exists){if(o!==i.expected_sha256)throw new Error("Cannot recover project config write transaction: the config and owned quarantine are missing");let a=await T(e,ae,{label:ae,expected:"file"}),c=await T(e,i.quarantine,{label:"project config write transaction quarantine",expected:"file"});try{await Qt.link(c.target,a.target)}catch(l){if(l.code!=="EEXIST")throw l}if(s=await Ct(e),!s.exists)throw new Error("Cannot recover project config write transaction: config publish failed")}return await Rm(e,i.candidate,i.output_sha256,t.testHooks?.afterOwnedFileQuarantine),s.exists&&await Rm(e,i.quarantine,i.expected_sha256,t.testHooks?.afterOwnedFileQuarantine),await YC(e,n),!0}var _m,no,al,xm,io,ll=pe(()=>{"use strict";_n();kt();Ne();_m="comet.project-config-write.v1",no=".comet/config-write-transaction.json",al=16*1024,xm=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,io=/^[0-9a-f]{64}$/});import{createHash as Am,randomUUID as GC}from"crypto";import{promises as Tm}from"fs";import ul from"path";async function fl(e,t){if(!t)return;let n=await Ct(e);if(!il(n,t))throw new Error("Project config changed before commit; rerun the operation")}async function dl(e,t,n={}){ct(t,{allowPartialProject:n.allowPartialProject??!1});let i=ul.resolve(e);if(await so(i))throw new Error("An unfinished project config write transaction exists; run comet doctor --repair");let r=n.expectedIdentity??await Ct(i);await fl(i,r);let s=await T(i,ae,{label:ae,expected:"file"}),o=GC(),a=Am("sha256").update(t).digest("hex"),c=r.exists&&r.sha256?await Im(i,o,r.sha256,a):null,l=c!==null,f=c?.candidate??`.comet/config.yaml.${o}.next`,u=ul.join(i,...f.split("/")),d=c?.quarantine??null;try{if(await Te(u,t,{containedRoot:i,exclusive:!0}),await n.beforeCommit?.(),await fl(i,r),await T(i,f,{label:"project config candidate",expected:"file"}),r.exists){if(!d)throw new Error("Project config write transaction was not created");let g=ul.join(i,...d.split("/"));if(await T(i,ae,{label:ae,expected:"file"}),(await T(i,d,{label:"project config quarantine",expected:"file"})).exists)throw new Error("Project config quarantine already exists");await Tm.rename(s.target,g);let{bytes:m}=await U(i,d,Cn,{label:"project config quarantine"});if(Am("sha256").update(m).digest("hex")!==r.sha256)throw new Error("Project config changed before final publish; successor was preserved")}else if(s.exists)throw new Error("Project config changed before final publish; successor was preserved");await n.beforePublish?.(),await T(i,f,{label:"project config candidate",expected:"file"});try{await to(u,s.target)}catch(g){throw new Error("Project config final publish failed; successor was preserved",{cause:g})}let p=await Ct(i);if(!p.exists||p.sha256!==a)throw new Error("Project config changed during final publish; successor was preserved");l&&(await oo(i,{ownerId:o}),l=!1)}catch(p){if(l)try{await oo(i,{ownerId:o})&&(l=!1)}catch{}throw p}finally{l||await zC(i,f).catch(()=>!1)}}async function zC(e,t){let n=await T(e,t,{label:t,expected:"file"});return n.exists?(await Tm.unlink(n.target),!0):!1}var ml=pe(()=>{"use strict";_n();lt();kt();Ne();ll()});var mo=pe(()=>{"use strict"});var Ym=pe(()=>{"use strict"});var gl=pe(()=>{"use strict";mo()});var Gm=pe(()=>{"use strict";mo();gl()});function Sk(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function Ek(e){let t=(0,zm.parseDocument)(e,{uniqueKeys:!0});if(t.errors.length>0)throw new Error(`Invalid global Comet config: ${t.errors[0].message}`);let n=t.toJS();if(n==null)return{};if(typeof n!="object"||Array.isArray(n))throw new Error("Invalid global Comet config: root must be a mapping");return n}function Qm(e){if(e.native?.pending_root_move)throw new Error("Global Comet config cannot contain native.pending_root_move");let t=e.native?(({pending_root_move:n,...i})=>i)(e.native):void 0;return{...e,schema:"comet.global.v1",...t?{native:t}:{}}}function Rk(e){let t=ct(JSON.stringify({...e,schema:"comet.project.v1"})).config;if(!t)throw new Error("Invalid global Comet config: workflow template is incomplete");return Qm(t)}function _k(e){let t=ct(e,{allowPartialProject:!0,allowMissingNativeFields:!0});if(!t.native&&!t.classic)return null;let n=t.native?"native":"classic",i=t.native?.language??t.classic?.language??"en",r=Xc(t.native?.artifact_root??"docs",i);return{schema:"comet.global.v1",default_workflow:n,workflows:[n],ambient_resume:t.ambient_resume,...t.native?{native:{...r.native,...t.native}}:{},...t.classic?{classic:t.classic}:{}}}function Zm(e){let t=Ek(e);if(Object.keys(t).length===0)return null;if(t.schema===void 0)return _k(e);if(t.schema!=="comet.global.v1")throw new Error("Unsupported Comet global schema");return Rk(t)}async function wl(e){try{let t=await U(e,Xm,Cn,{label:"global Comet config"});return Zm(t.bytes.toString("utf8"))}catch(t){if(Sk(t))return null;throw t}}var zm,Xm,yl=pe(()=>{"use strict";zm=st(Ue(),1);_n();lt();Ne();Xm=".comet/config.yaml"});var ep=pe(()=>{"use strict";mo();_n();Ym();Gm();lt();yl();Ne();kt();ml();ll();gl()});import{TextDecoder as xk}from"util";function tp(e){return{dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs}}function Pk(e,t){try{return new xk("utf-8",{fatal:!0}).decode(e.bytes)}catch(n){throw new Error(`${t} is not valid UTF-8`,{cause:n})}}async function vl(e,t,n,i,r={}){try{let s=await U(e,t,n,{label:i,hooks:r.hooks});return{result:s,text:Pk(s,i)}}catch(s){let o=s.code;if(o==="ENOENT"||o==="ENOTDIR")return null;throw s}}async function Rt(e,t,n,i,r={}){return(await vl(e,t,n,i,r))?.text??null}async function tn(e,t,n,i,r,s={}){if(Buffer.byteLength(n,"utf8")>i)throw new Error(`${r} exceeds ${i} bytes`);let o=await vl(e,t,i,r),a=await T(e,t,{label:r,expected:"file"});await Te(a.target,n,{containedRoot:a.projectRoot,beforeCommit:async()=>{await s.beforeCommit?.();let c=await vl(e,t,i,r);if(!(!o&&!c)){if(!o||!c)throw new Error(`${r} changed before commit`);if(o.result.realPath!==c.result.realPath||!Ae(tp(o.result.stat),tp(c.result.stat))||o.text!==c.text)throw new Error(`${r} changed before commit`)}}})}async function po(e,t,n,i,r,s={}){let o=await Rt(e,t,i,r);await tn(e,t,`${o??""}${n}`,i,r,s)}async function ho(e,t,n,i={}){let r=await T(e,t,{label:n,expected:"file"});return r.exists?sl(r.target,{containedRoot:r.projectRoot,beforeRemove:i.beforeRemove}):!1}var go=pe(()=>{"use strict";ep();rr()});var rp={};zg(rp,{RUN_STATE_FILE:()=>yo,applyRunStateToDocument:()=>bl,readRunState:()=>mr,removeRunState:()=>Cl,runStateFromDocument:()=>wo,writeRunState:()=>vo});import Ok from"path";function dr(e,t){let n=e[t];if(typeof n!="string"||n.length===0)throw new Error(`Invalid Run state: ${t} must be a non-empty string`);return n}function fr(e,t){let n=dr(e,t);if(Ok.isAbsolute(n)||/^(?:[A-Za-z]:|[\\/]|~)/u.test(n)||n.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Run state: ${t} must stay inside the change directory`);return n}function $k(e){let t=e.run_retries??"{}",n;try{n=typeof t=="string"?JSON.parse(t):t}catch(i){throw new Error("Invalid Run state: run_retries must be a JSON object",{cause:i})}if(!n||typeof n!="object"||Array.isArray(n))throw new Error("Invalid Run state: run_retries must be a JSON object");for(let i of Object.values(n))if(!Number.isInteger(i)||Number(i)<0)throw new Error("Invalid Run state: retry counts must be non-negative integers");return n}function wo(e){if(!e.run_id)return null;let t=dr(e,"run_id"),n=dr(e,"skill"),i=dr(e,"skill_version"),r=dr(e,"skill_hash"),s=fr(e,"pending_ref"),o=fr(e,"trajectory_ref"),a=fr(e,"context_ref"),c=fr(e,"artifacts_ref"),l=fr(e,"checkpoint_ref"),f=Number(e.iteration);if(!Number.isInteger(f)||f<0)throw new Error("Invalid Run state: iteration must be a non-negative integer");if(e.orchestration!=="deterministic"&&e.orchestration!=="adaptive")throw new Error("Invalid Run state: orchestration must be deterministic or adaptive");if(e.run_status!=="running"&&e.run_status!=="waiting"&&e.run_status!=="completed"&&e.run_status!=="failed")throw new Error("Invalid Run state: run_status is invalid");return{runId:t,skill:n,skillVersion:i,skillHash:r,orchestration:e.orchestration,currentStep:np(e,"current_step"),iteration:f,pending:np(e,"pending"),pendingRef:s,trajectoryRef:o,contextRef:a,artifactsRef:c,checkpointRef:l,status:e.run_status,retries:$k(e)}}function bl(e,t){t?e.run_id=t.runId:delete e.run_id}function Ik(e){return{runId:e.runId,skill:e.skill,skillVersion:e.skillVersion,skillHash:e.skillHash,orchestration:e.orchestration,currentStep:e.currentStep,iteration:e.iteration,pending:e.pending,pendingRef:e.pendingRef,trajectoryRef:e.trajectoryRef,contextRef:e.contextRef,artifactsRef:e.artifactsRef,checkpointRef:e.checkpointRef,status:e.status,retries:e.retries}}function Ak(e){let t={run_id:e.runId,skill:e.skill,skill_version:e.skillVersion,skill_hash:e.skillHash,orchestration:e.orchestration,current_step:e.currentStep,iteration:e.iteration,pending:e.pending,pending_ref:e.pendingRef,trajectory_ref:e.trajectoryRef,context_ref:e.contextRef,artifacts_ref:e.artifactsRef,checkpoint_ref:e.checkpointRef,run_status:e.status,run_retries:JSON.stringify(e.retries)};return wo(t)}async function mr(e,t={}){let n=await Rt(e,yo,ip,"Run state",t);if(n===null)return null;let i=JSON.parse(n);return Ak(i)}async function vo(e,t,n={}){await tn(e,yo,JSON.stringify(Ik(t),null,2),ip,"Run state",n)}async function Cl(e,t={}){await ho(e,yo,"Run state",t)}var np,yo,ip,pr=pe(()=>{"use strict";go();np=(e,t)=>{let n=e[t];return n==null?null:String(n)};yo=".comet/run-state.json",ip=256*1024});import{pathToFileURL as Nx}from"url";import{createHash as KS}from"crypto";import{promises as JS}from"fs";import dt from"path";import{spawnSync as nk}from"child_process";function Qg(e){return e.length>0&&/^[A-Za-z0-9@+=:,./\\_-]+$/.test(e)?e:`"${e.replace(/"/g,'""')}"`}function ku(e){return e.map(t=>Qg(t))}import{promises as Lm}from"fs";import z from"path";import{promises as Su}from"fs";async function Ri(e){try{return await Su.access(e),!0}catch(t){if(Zg(t))return!1;throw t}}async function Eu(e){try{return await Su.readdir(e)}catch(t){let n=t?.code;if(n==="ENOENT"||n==="ENOTDIR")return[];throw t}}function Zg(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}lt();kt();ml();Ne();var or=class extends Error{code="classic-layout-unavailable";constructor(t="Classic artifact layout is unavailable from .comet/config.yaml"){super(t),this.name="ClassicLayoutUnavailableError"}},jm=".comet/config.yaml";function Mm(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function ao(e){await T(e,jm,{label:jm,expected:"file"})}function Ye(e,t){let n=z.resolve(e),i=t==="docs"?z.join(n,"docs"):n,r=z.join(i,"openspec"),s=z.join(n,"docs","superpowers");return{projectRoot:n,artifactLayout:t,openSpecBase:i,openSpecRoot:r,changesDir:z.join(r,"changes"),archiveDir:z.join(r,"changes","archive"),specsDir:z.join(r,"specs"),superpowersRoot:s,superpowersSpecsDir:z.join(s,"specs"),superpowersPlansDir:z.join(s,"plans"),superpowersReportsDir:z.join(s,"reports")}}async function Zt(e){await ao(e);let t=await ut(e,{allowPartialProject:!0,allowMissingNativeFields:!0});if(!t?.config)throw new or;if(!(t.config.workflows??[t.config.default_workflow]).includes("classic"))throw new or("Classic artifact layout is unavailable because Classic is not enabled");return t.classic?.artifact_layout??"legacy"}async function qm(e){await ao(e);let t=(await ut(e))?.config;if(!t)throw new Error(".comet/config.yaml must use comet.project.v1 before migration");if(!(t.workflows??[t.default_workflow]).includes("classic"))throw new Error("Classic root move requires the Classic workflow to be enabled")}async function Dm(e,t,n={}){await ao(e);let i=await Rn(e,{allowPartialProject:!0}),r=i.document;if(!r)throw new Error(".comet/config.yaml does not exist");let s=r.value.classic;if(!s||typeof s!="object"||Array.isArray(s))throw new Error("classic must be a mapping");let o={...r.value,classic:{...s,artifact_layout:t}},a=kn(o,r.classic?.language==="zh-CN"||r.native?.language==="zh-CN"?"zh-CN":"en");ct(a,{allowPartialProject:!0}),await dl(e,a,{expectedIdentity:n.expectedIdentity??i.identity,beforeCommit:n.beforeCommit})}async function XC(e,t){return Ye(e,t??await Zt(e))}async function QC(e){try{return await Lm.lstat(e),!0}catch(t){if(Mm(t))return!1;throw t}}async function pl(e,t){let n=await XC(e,t),i=n.artifactLayout==="legacy"?"docs":"legacy",r=Ye(e,i).openSpecRoot,[s,o]=await Promise.all([T(n.projectRoot,A(n.projectRoot,n.openSpecRoot),{label:"Configured Classic OpenSpec root",expected:"directory"}),QC(r)]),a=s.exists;return{paths:n,configuredRootExists:a,alternateRoot:r,alternateRootExists:o,dualRoots:a&&o}}async function ZC(e){let t=[e.openSpecRoot,e.changesDir,e.archiveDir,e.specsDir,e.superpowersRoot,e.superpowersSpecsDir,e.superpowersPlansDir,e.superpowersReportsDir];for(let n of t){let i=A(e.projectRoot,n);await T(e.projectRoot,i,{label:`Classic managed physical path ${i}`,expected:"directory"})}}async function G(e,t){let n=await pl(e,t);if(await ZC(n.paths),!n.configuredRootExists){let i=A(n.paths.projectRoot,n.paths.openSpecRoot),r=A(n.paths.projectRoot,n.alternateRoot);throw new or(`Configured Classic OpenSpec root is missing: ${i} (alternate ${r} is ${n.alternateRootExists?"present":"missing"})`)}return n.paths}async function Ee(e,t){let n=z.join(z.resolve(e),".comet","classic-root-move.json");if(await Ri(n))throw new Error("Classic root move transaction is incomplete; inspect it with comet doctor and recover it explicitly before writing");let i=await G(e,t);if(!await Ri(i.openSpecRoot))throw new Error(`Configured Classic OpenSpec root is missing: ${A(i.projectRoot,i.openSpecRoot)}`);return i}async function le(e){let t=z.resolve(e),n=null;try{(await Lm.lstat(t)).isDirectory()||(t=z.dirname(t))}catch(i){if(!Mm(i))throw i}for(;;){z.basename(t)==="openspec"&&(n=z.dirname(t));let i=z.join(t,".comet","config.yaml"),r=!1;if(await Ri(i))try{await ao(t);let o=(await ut(t))?.value;r=!!o&&typeof o=="object"&&!Array.isArray(o)&&(o.schema==="comet.project.v1"||o.default_workflow!==void 0||o.native!==void 0)}catch{}if(r||await Ri(z.join(t,".git")))return t;let s=z.dirname(t);if(s===t)return n??z.resolve(e);t=s}}function A(e,t){return z.relative(z.resolve(e),t).replaceAll("\\","/")}var Fm=st(Ue(),1);Ne();import ek from"path";var tk=1024*1024;async function Wm(e,t){let n=t??await G(e),i=ek.join(n.openSpecRoot,"config.yaml"),r=A(n.projectRoot,i),s;try{s=(await U(n.projectRoot,r,tk,{label:"Classic OpenSpec project config",bigint:!0})).bytes.toString("utf8")}catch(l){throw l.code==="ENOENT"?new Error(`Classic OpenSpec root is unhealthy: ${r} is missing; rerun OpenSpec initialization for the configured Classic layout`,{cause:l}):new Error(`Classic OpenSpec root is unhealthy: ${l instanceof Error?l.message:String(l)}`,{cause:l})}let o=(0,Fm.parseDocument)(s,{uniqueKeys:!0});if(o.errors.length>0)throw new Error(`Classic OpenSpec root is unhealthy: ${r} is invalid YAML (${o.errors[0].message})`);let a=o.toJS();if(!a||typeof a!="object"||Array.isArray(a))throw new Error(`Classic OpenSpec root is unhealthy: ${r} must contain a mapping`);let c=a.schema;if(typeof c!="string"||c.trim()==="")throw new Error(`Classic OpenSpec root is unhealthy: ${r} must declare a non-empty schema`);return{layout:n,configPath:r,schema:c}}function ik(e){return e[0]==="--"?e.slice(1):[...e]}async function hl(e,t=process.cwd()){let n=ik(e);if(n.length===0)return{exitCode:64,stderr:"Usage: comet classic openspec -- "};let i=await le(t),r=await Ee(i);await Wm(i,r);let s=process.env.COMET_OPENSPEC||"openspec",o=process.platform==="win32",a=nk(s,o?ku(n):n,{cwd:r.openSpecBase,encoding:"utf8",shell:o,windowsHide:!0});if(a.error){let c=a.error.code;return{exitCode:c==="ENOENT"?127:70,stdout:a.stdout||void 0,stderr:a.stderr||(c==="ENOENT"?`OpenSpec CLI not found: ${s}`:a.error.message)}}return{exitCode:a.status??1,stdout:a.stdout||void 0,stderr:a.stderr||void 0}}var Bm=async e=>hl(e);import{promises as sk}from"fs";import On from"path";_n();lt();Ne();import ar from"path";var rk=2*1024*1024;function co(e,t,n){let i=ar.resolve(e),r=ar.isAbsolute(t)?ar.resolve(t):ar.resolve(i,t),s=ar.relative(i,r).replaceAll("\\","/");return{root:i,relative:Vt(s,n),target:r}}async function Y(e,t,n){let i=co(e,t,n.label);return T(i.root,i.relative,n)}async function X(e,t,n){return(await Y(e,t,{label:n.label,expected:n.expected??"any"})).exists}async function xn(e,t,n,i){return await X(e,t,{label:n,expected:"file"})?(await lo(e,t,{label:n,hooks:i})).byteLength>0:!1}async function W(e,t,n){return(await lo(e,t,n)).toString("utf8")}async function lo(e,t,n){let i=co(e,t,n.label);return(await U(i.root,i.relative,n.maxBytes??rk,{label:n.label,hooks:n.hooks})).bytes}async function Pn(e,t,n){let i=co(e,t,n);return nl(i.root,i.relative,{label:n})}async function ti(e,t,n,i){let r=co(e,t,i.label);await T(r.root,r.relative,{label:i.label,expected:"file"}),await Te(r.target,n,{containedRoot:r.root,beforeTemporaryOpen:i.beforeTemporaryOpen,beforeCommit:i.beforeCommit,exclusive:i.exclusive})}function ge(e){return e?/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e)?e.includes("..")?"Change name cannot contain '..' (path traversal not allowed)":null:`Invalid change name: '${e}' +Valid format: lowercase kebab-case (a-z, 0-9, single hyphens)`:"Change name cannot be empty"}function en(e){let t=ge(e);if(t)throw new Error(t)}function ok(e,t){return{label:A(e,t),directory:t}}async function ni(e,t,n){let i=ok(e,t);if(!(await Y(e,t,{label:n,expected:"directory"})).exists)return{change:i,exists:!1,stateExists:!1};let s=await Y(e,On.join(t,".comet.yaml"),{label:`${n} state`,expected:"file"});return{change:i,exists:!0,stateExists:s.exists}}function Hm(e,t){let n=t.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&");return new RegExp(`^\\d{4}-\\d{2}-\\d{2}-${n}$`,"u").test(e)}async function Km(e,t,n,i={}){if(!i.skipExactCompatibility){let o=await ni(e,On.join(t,n),`Classic archived change ${n}`);if(o.exists)return o.change}if(!(await Y(e,t,{label:"Classic archive directory",expected:"directory"})).exists)return null;let s=[];for(let o of await sk.readdir(t,{withFileTypes:!0})){if(!Hm(o.name,n))continue;let a=await ni(e,On.join(t,o.name),`Classic archived change ${o.name}`);a.exists&&a.stateExists&&s.push(a.change)}return s.sort((o,a)=>a.directory.localeCompare(o.directory))[0]??null}async function Ge(e,t=process.cwd()){en(e);let n=await G(t),i=await ni(n.projectRoot,On.join(n.changesDir,e),`Classic active change ${e}`);return{...i.change,exists:i.exists,stateExists:i.stateExists}}async function Jm(e,t=process.cwd()){en(e);let n=await Ee(t),i=On.join(n.changesDir,e),r=await ni(n.projectRoot,i,`Classic active change ${e}`);return r.exists||await Pn(n.projectRoot,i,`Classic active change ${e}`),r.change}async function uo(e,t=process.cwd(),n={}){en(e);let i=await G(t);if(n.preferredArchiveName!==void 0){let r=n.preferredArchiveName;if(r!==e&&!Hm(r,e))throw new Error(`Classic preferred archive name '${r}' does not belong to change '${e}'`);let s=await ni(i.projectRoot,On.join(i.archiveDir,r),`Classic preferred archived change ${r}`);return s.exists&&s.stateExists?s.change:null}return Km(i.projectRoot,i.archiveDir,e,n)}async function ii(e,t=process.cwd()){en(e);let n=await G(t),i=await ni(n.projectRoot,On.join(n.changesDir,e),`Classic active change ${e}`);if(i.exists)return i.change;let r=await Km(n.projectRoot,n.archiveDir,e);return r||i.change}import{promises as Lp}from"fs";import ve from"path";import{fileURLToPath as Ol}from"url";import{promises as ck}from"fs";import St from"path";Ne();lt();import cr from"path";function ak(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function Um(e,t,n,i){let r=Vt(n,"Classic handoff artifact pointer");if((await T(e,r,{label:"Classic handoff artifact",expected:"file"})).exists)return null;let o=await G(e),a=`${A(e,o.changesDir)}/`,l=(o.artifactLayout==="docs"?[a,"openspec/changes/"]:[a]).find(w=>r.startsWith(w));if(!l)return null;let f=r.slice(l.length).split("/");if(f.length<4||f[1]!==".comet"||f.slice(2).some(w=>w.length===0))return null;let u=f[0];en(u);let d=f.slice(2),p=cr.resolve(t);if(cr.dirname(p)!==cr.resolve(o.archiveDir))return null;let g=cr.basename(p),h=/^\d{4}-\d{2}-\d{2}-(.+)$/u.exec(g);if(g!==u&&h?.[1]!==u)return null;await T(e,A(e,p),{label:"Classic archived change directory",expected:"directory"});let m=cr.join(p,".comet",...d),y=A(e,m);try{return await U(e,y,i,{label:"Historical Classic archived handoff artifact"}),y}catch(w){if(ak(w))return null;throw w}}Ne();var Vm=2*1024*1024;function lr(e,t){return St.relative(e,t).split(St.sep).join("/")}async function ur(e,t,n,i,r){if(!n)return{code:t,satisfied:!1};let s=n.replaceAll("\\","/");if(r)return{code:t,satisfied:!1,source:s,detail:`Classic layout is unsafe or unavailable: ${r instanceof Error?r.message:String(r)}`};try{if(i){let a=i.artifactLayout==="legacy"?"docs":"legacy",c=A(e,Ye(e,a).openSpecRoot);if((s===c||s.startsWith(`${c}/`))&&(await T(e,s,{label:`${t} artifact`,expected:"file"})).exists)return{code:t,satisfied:!1,source:s,detail:"standalone OpenSpec root is not a Comet artifact root"}}let o=await Xs(e,s,{label:`${t} artifact`});return{code:t,satisfied:o,source:s,...o?{resolvedSource:s}:{}}}catch(o){return{code:t,satisfied:!1,source:s,detail:`unsafe artifact pointer outside the project or through a special path: ${o instanceof Error?o.message:String(o)}`}}}async function lk(e,t,n,i){try{i??=await G(e)}catch(s){return{code:"design.handoff",satisfied:!1,...n?{source:n.replaceAll("\\","/")}:{},detail:`Classic layout is unsafe or unavailable for handoff evidence: ${s instanceof Error?s.message:String(s)}`}}let r=await ur(e,"design.handoff",n,i);if(!n||r.satisfied||r.detail)return r;try{let s=await Um(e,t,n,Vm);return s?{...r,satisfied:!0,resolvedSource:s,detail:`resolved historical legacy pointer from archived change: ${s}`}:r}catch(s){return{...r,satisfied:!1,detail:`unsafe archived handoff fallback: ${s instanceof Error?s.message:String(s)}`}}}async function fo(e,t,n){return ur(e,t,lr(e,n))}async function uk(e,t){let n=St.join(t,"specs"),i;try{let o=lr(e,n);if(!(await T(e,o,{label:"OpenSpec delta-spec directory",expected:"directory"})).exists)return{code:"openspec.delta-spec",satisfied:!1};i=await ck.readdir(n)}catch(o){return o.code==="ENOENT"?{code:"openspec.delta-spec",satisfied:!1}:{code:"openspec.delta-spec",satisfied:!1,detail:`unsafe delta-spec path: ${o instanceof Error?o.message:String(o)}`}}let r=i.map(o=>St.join(n,o,"spec.md")),s=(await Promise.all(r.map(async o=>{try{return await Xs(e,lr(e,o),{label:"OpenSpec delta spec"})?o:null}catch{return null}}))).filter(o=>o!==null);return{code:"openspec.delta-spec",satisfied:s.length>0,source:s[0]?lr(e,s[0]):void 0,detail:`${s.length} delta spec${s.length===1?"":"s"}`}}async function fk(e,t){let n,i=lr(e,t);try{n=(await U(e,i,Vm,{label:"Classic tasks artifact"})).bytes.toString("utf8")}catch(o){return o.code==="ENOENT"?{code:"build.tasks-complete",satisfied:!1}:{code:"build.tasks-complete",satisfied:!1,source:i,detail:`unsafe tasks artifact: ${o instanceof Error?o.message:String(o)}`}}let r=[...n.matchAll(/^\s*[-*]\s+\[([ xX])\]\s+/gmu)],s=r.filter(o=>o[1].toLowerCase()==="x").length;return{code:"build.tasks-complete",satisfied:r.length>0&&s===r.length,source:i,detail:`${s} of ${r.length} tasks complete`}}function $n(e,t){return e.some(n=>n.code===t&&n.satisfied)}async function ze(e,t){let n=await le(e),i=t.classic,r=St.join(e,"proposal.md"),s=St.join(e,"design.md"),o=St.join(e,"tasks.md"),a=t.run?St.resolve(e,t.run.checkpointRef):St.join(e,".comet","checkpoint.json"),c,l;try{c=await G(n)}catch(d){l=d}let f=await Promise.all([fo(n,"openspec.proposal",r),fo(n,"openspec.design",s),fo(n,"openspec.tasks",o),uk(n,e),ur(n,"design.document",i?.designDoc??null,c,l),ur(n,"build.plan",i?.plan??null,c,l),fk(n,o),ur(n,"verification.report",i?.verificationReport??null,c,l),lk(n,e,i?.handoffContext??null,c),fo(n,"run.checkpoint",a)]),u=f.find(d=>d.code==="design.handoff");return u&&!i?.handoffHash&&(u.satisfied=!1,u.detail="handoff hash is missing"),f.push({code:"archive.confirmed",satisfied:i?.archiveConfirmation==="confirmed"}),f}import{createHash as kS,randomUUID as SS}from"crypto";import{promises as Pl}from"fs";import _t from"path";function dk(e){return e.classicProfile??e.workflow}function mk(e){return!e.buildMode||!e.tddMode||!e.isolation||!e.verifyMode?!1:e.buildMode==="subagent-driven-development"?e.subagentDispatch==="confirmed":e.buildMode==="direct"?e.directOverride===!0:!0}function pk(e){return e.buildMode==="direct"&&e.tddMode==="direct"&&e.isolation!==null&&e.verifyMode==="light"}function hk(e,t,n){if(t.verifyResult==="fail")return e==="full"?"full.build.fix":`${e}.build.execute`;if(e==="full"){if(!$n(n,"build.plan"))return"full.build.plan";if(t.buildPause==="plan-ready")return"full.build.plan-ready";if(!mk(t))return"full.build.configure"}else if(!pk(t))throw new Error(`${e} build configuration is incomplete`);return $n(n,"build.tasks-complete")?`${e}.build.complete`:`${e}.build.execute`}function gk(e,t,n){return t.verifyResult!=="pass"||!$n(n,"verification.report")?`${e}.verify.run`:`${e}.verify.branch`}function wk(e,t){if(t.verifyResult!=="pass")throw new Error("archive requires verify_result=pass");return t.archiveConfirmation==="confirmed"?`${e}.archive.execute`:`${e}.archive.confirm`}function Et(e,t){let n=dk(e);if(e.archived&&e.phase!=="archive")throw new Error("archived=true requires phase=archive");if(e.archived)return"completed";if(n!=="full"&&e.phase==="design")throw new Error(`${n} workflow cannot enter design`);switch(e.phase){case"open":return`${n}.open`;case"design":return $n(t,"design.handoff")?"full.design.document":"full.design.handoff";case"build":return hk(n,e,t);case"verify":return gk(n,e,t);case"archive":return wk(n,e)}}var Co=st(Ue(),1);_n();Ne();import wr from"path";pr();var Sl=["full","hotfix","tweak"],nn=1,op=["open","design","build","verify","archive"],Nk=["en","zh-CN"],Tk=["off","beta"],jk=["subagent-driven-development","executing-plans","direct"],Lk=["plan-ready"],Mk=["confirmed"],qk=["tdd","direct"],Dk=["off","standard","thorough"],Fk=["current","branch","worktree"],Wk=["light","full"],Bk=["pending","pass","fail"],Hk=["pending","handled"],Kk=["pending","confirmed"],rn=["workflow","language","phase","context_compression","build_mode","build_pause","subagent_dispatch","tdd_mode","review_mode","isolation","bound_branch","verify_mode","auto_transition","base_ref","design_doc","plan","verify_result","verify_failures","verification_report","branch_status","created_at","verified_at","archive_confirmation","archived","direct_override","handoff_context","handoff_hash","classic_profile","classic_migration"],hr=["run_id"],ap=new Set([...rn,...hr]),Jk=["workflow","phase","design_doc","plan","build_mode","isolation","verify_mode","verify_result","verified_at","archived"];function sp(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function ri(e,t){let n=e[t];if(n==null||n==="")return null;if(typeof n!="string")throw new Error(`Invalid Classic state: ${t} must be a string or null`);return n}function we(e,t,n,i=!0){let r=e[t];if(r==null||r===""){if(i)return null;throw new Error(`Invalid Classic state: ${t} is required`)}if(typeof r!="string"||!n.includes(r))throw new Error(`Invalid Classic state: ${t} must be one of ${n.join(", ")}${i?" or null":""}`);return r}function kl(e,t,n=!0){let i=e[t];if(i==null||i===""){if(n)return null;throw new Error(`Invalid Classic state: ${t} is required`)}if(typeof i!="boolean")throw new Error(`Invalid Classic state: ${t} must be true or false`);return i}function Uk(e,t,n=0){let i=e[t];if(i==null||i==="")return n;if(typeof i!="number"||!Number.isInteger(i)||i<0)throw new Error(`Invalid Classic state: ${t} must be a non-negative integer`);return i}function bo(e,t){let n=ri(e,t);if(n===null)return null;if(/^(?:[A-Za-z]:|[\\/]|~)/u.test(n)||n.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Classic state: ${t} must be a relative repository path`);return n}function Vk(e,t){let n=ri(e,t);if(n!==null&&!/^[a-f0-9]{64}$/u.test(n))throw new Error(`Invalid Classic state: ${t} must be a sha256 hex digest`);return n}function Yk(e){let t=e.classic_migration;if(t==null||t==="")return null;if(t!==nn)throw new Error(`Invalid Classic state: classic_migration must be ${nn}`);return t}function Gk(e){if(!rn.some(n=>sp(e,n)))return null;for(let n of Jk)if(!sp(e,n))return null;return{workflow:we(e,"workflow",Sl,!1),language:we(e,"language",Nk),phase:we(e,"phase",op,!1),contextCompression:we(e,"context_compression",Tk),buildMode:we(e,"build_mode",jk),buildPause:we(e,"build_pause",Lk),subagentDispatch:we(e,"subagent_dispatch",Mk),tddMode:we(e,"tdd_mode",qk),reviewMode:we(e,"review_mode",Dk),isolation:we(e,"isolation",Fk),boundBranch:ri(e,"bound_branch"),verifyMode:we(e,"verify_mode",Wk),autoTransition:kl(e,"auto_transition"),baseRef:ri(e,"base_ref"),designDoc:bo(e,"design_doc"),plan:bo(e,"plan"),verifyResult:we(e,"verify_result",Bk,!1),verifyFailures:Uk(e,"verify_failures"),verificationReport:bo(e,"verification_report"),branchStatus:we(e,"branch_status",Hk),createdAt:ri(e,"created_at"),verifiedAt:ri(e,"verified_at"),archiveConfirmation:we(e,"archive_confirmation",Kk),archived:kl(e,"archived",!1),directOverride:kl(e,"direct_override"),handoffContext:bo(e,"handoff_context"),handoffHash:Vk(e,"handoff_hash"),classicProfile:we(e,"classic_profile",Sl),classicMigration:Yk(e)}}function gr(e,t){let n=t??null;if(n===null&&t===void 0&&e.run_id&&e.skill)try{n=wo(e)}catch(i){let r=i instanceof Error?i.message:String(i);throw new Error(r.replace(/^Invalid Run state:/u,"Invalid Classic state:"),{cause:i})}return{classic:Gk(e),run:n,unknownKeys:Object.keys(e).filter(i=>!ap.has(i))}}function cp(e){let t=e.workflow,n=e.phase,i=e.archived,r=e.design_doc;return{workflow:typeof t=="string"&&Sl.includes(t)?t:null,phase:typeof n=="string"&&op.includes(n)?n:null,archived:i===!0,designDoc:typeof r=="string"&&r!==""?r:null,unknownKeys:Object.keys(e).filter(s=>!ap.has(s))}}function lp(e){return{workflow:e.workflow,language:e.language,phase:e.phase,context_compression:e.contextCompression,build_mode:e.buildMode,build_pause:e.buildPause,subagent_dispatch:e.subagentDispatch,tdd_mode:e.tddMode,review_mode:e.reviewMode,isolation:e.isolation,bound_branch:e.boundBranch,verify_mode:e.verifyMode,auto_transition:e.autoTransition,base_ref:e.baseRef,design_doc:e.designDoc,plan:e.plan,verify_result:e.verifyResult,verify_failures:e.verifyFailures,verification_report:e.verificationReport,branch_status:e.branchStatus,created_at:e.createdAt,verified_at:e.verifiedAt,archive_confirmation:e.archiveConfirmation,archived:e.archived,direct_override:e.directOverride,handoff_context:e.handoffContext,handoff_hash:e.handoffHash,classic_profile:e.classicProfile,classic_migration:e.classicMigration}}pr();var zk=2*1024*1024;function si(e){let t=e.toJS();if(t===null)return{};if(typeof t!="object"||Array.isArray(t))throw new Error("Invalid Classic state document: root must be a mapping");return t}function up(e,t,n){e.get(t)!==n&&e.set(t,n)}function Xk(e,t){if(t.classic)for(let[n,i]of Object.entries(lp(t.classic)))up(e,n,i);else for(let n of rn)e.delete(n);bl(e.toJS(),t.run),t.run?up(e,"run_id",t.run.runId):e.delete("run_id")}function Qk(e){let t=["skill","skill_version","skill_hash","orchestration","current_step","iteration","pending","pending_ref","trajectory_ref","context_ref","artifacts_ref","checkpoint_ref","run_status","run_retries"];for(let n of t)e.delete(n)}function Zk(e){let t=!1;for(let n of["build_command","verify_command"])e.has(n)&&(e.delete(n),t=!0);return t}async function El(e){let t;try{t=(await U(wr.dirname(e),wr.basename(e),zk,{label:"Classic state document"})).bytes.toString("utf8")}catch(i){if(i.code!=="ENOENT")throw i;return new Co.Document({})}let n=(0,Co.parseDocument)(t);if(n.errors.length>0)throw new Error(`Invalid Classic state document: ${n.errors[0].message}`);return si(n),n}async function B(e,t={}){let n=t.migrate!==!1,i=wr.join(e,".comet.yaml"),r=await El(i),s=si(r),o=Zk(r);o&&(s=si(r));let a=await mr(e);if(!a&&s.run_id&&s.skill){let{runStateFromDocument:c}=await Promise.resolve().then(()=>(pr(),rp));a=c(s),a&&n&&(await vo(e,a),Qk(r),o=!0)}return o&&n&&await Te(i,r.toString(),{containedRoot:e}),gr(si(r),a)}async function fp(e){let t=await El(wr.join(e,".comet.yaml"));return cp(si(t))}async function je(e,t,n={}){let i=wr.join(e,".comet.yaml"),r=await El(i);Xk(r,{...t,unknownKeys:t.unknownKeys??[]}),gr(si(r),t.run??null),await Te(i,r.toString(),{containedRoot:e,beforeCommit:n.beforeCommit}),t.run?await vo(e,t.run):await Cl(e)}function dp(e,t,n){return{runId:t,skill:e.definition.metadata.name,skillVersion:e.definition.metadata.version,skillHash:n,orchestration:e.definition.orchestration.mode,currentStep:e.definition.orchestration.entry??null,iteration:0,pending:null,pendingRef:".comet/pending-action.json",trajectoryRef:".comet/trajectory.jsonl",contextRef:".comet/context.md",artifactsRef:".comet/artifacts.json",checkpointRef:".comet/checkpoint.json",status:"running",retries:{}}}go();import ko from"path";var ft={trajectory:8*1024*1024,artifacts:1024*1024,context:1024*1024,pendingAction:256*1024,checkpoint:256*1024};function Xe(e,t){if(ko.isAbsolute(t))throw new Error("Run path must stay inside the change directory");let n=ko.resolve(e),i=ko.resolve(n,t);if(i!==n&&!i.startsWith(n+ko.sep))throw new Error("Run path must stay inside the change directory")}async function We(e,t,n,i={}){Xe(e,t),await po(e,t,`${JSON.stringify(n)} +`,ft.trajectory,"Run trajectory",i)}async function Le(e,t,n={}){Xe(e,t);let i=await Rt(e,t,ft.trajectory,"Run trajectory",n);return i===null?[]:i.split(/\r?\n/).map((r,s)=>({line:r,number:s+1})).filter(({line:r})=>r.length>0).map(({line:r,number:s})=>{try{return JSON.parse(r)}catch(o){throw new Error(`Invalid Trajectory event at line ${s}`,{cause:o})}})}async function oi(e,t,n={}){Xe(e,t);let i=await Rt(e,t,ft.artifacts,"Run artifacts",n);return i===null?{}:JSON.parse(i)}async function ai(e,t,n,i={}){Xe(e,t),await tn(e,t,JSON.stringify(n,null,2)+` +`,ft.artifacts,"Run artifacts",i)}async function So(e,t,n,i={}){Xe(e,t),await tn(e,t,n,ft.context,"Run context",i)}async function Eo(e,t,n={}){return Xe(e,t),Rt(e,t,ft.context,"Run context",n)}async function Ro(e,t,n,i={}){Xe(e,t),await tn(e,t,JSON.stringify(n,null,2)+` +`,ft.pendingAction,"Run pending action",i)}async function yr(e,t,n={}){Xe(e,t);let i=await Rt(e,t,ft.pendingAction,"Run pending action",n);return i===null?null:JSON.parse(i)}async function _o(e,t,n={}){Xe(e,t),await ho(e,t,"Run pending action",n)}async function ci(e,t,n,i={}){Xe(e,t),await tn(e,t,JSON.stringify(n,null,2)+` +`,ft.checkpoint,"Run checkpoint",i)}async function mp(e,t,n={}){Xe(e,t);let i=await Rt(e,t,ft.checkpoint,"Run checkpoint",n);return i===null?null:JSON.parse(i)}import{createHash as xp,randomUUID as wS}from"crypto";import{promises as re}from"fs";import te from"path";var gp=st(Ue(),1);import{promises as Rl}from"fs";import Be from"path";var eS=["invoke_skill","call_tool","handoff","ask_user","checkpoint"],tS=["deterministic","adaptive"],nS=["function","mcp","script","agent"],iS=["none","read","write","external"],rS=["progress","step","completion"],sS=["artifact_exists","state_equals"];function In(e,t,n){return new Error(`${e}: ${t} ${n}`)}function Re(e,t,n="document"){if(e===null||typeof e!="object"||Array.isArray(e))throw In(t,n,"must be an object")}function sn(e,t,n){if(!Array.isArray(e))throw In(t,n,"must be an array")}function ye(e,t,n){if(typeof e!="string")throw In(t,n,"must be a string")}function Qe(e,t,n,i){t in e&&ye(e[t],n,`${i}.${t}`)}function wp(e,t,n,i){if(t in e&&typeof e[t]!="boolean")throw In(n,`${i}.${t}`,"must be a boolean")}function on(e,t,n,i){if(typeof e!="string"||!t.includes(e))throw In(n,i,`must be one of ${t.join(", ")}`)}function xo(e,t,n){sn(e,t,n),e.forEach((i,r)=>{ye(i,t,`${n}[${r}]`)})}function pp(e,t,n){Re(e,t,n),ye(e.name,t,`${n}.name`),ye(e.description,t,`${n}.description`),wp(e,"required",t,n)}function oS(e,t,n){Re(e,t,n),ye(e.id,t,`${n}.id`),Qe(e,"source",t,n),Qe(e,"version",t,n)}function aS(e,t,n){Re(e,t,n),ye(e.id,t,`${n}.id`),ye(e.role,t,`${n}.role`),Qe(e,"instructions",t,n)}function cS(e,t,n){Re(e,t,n),ye(e.id,t,`${n}.id`),on(e.kind,nS,t,`${n}.kind`),ye(e.source,t,`${n}.source`),on(e.sideEffect,iS,t,`${n}.sideEffect`),wp(e,"requiresConfirmation",t,n)}function lS(e,t,n){Re(e,t,n),on(e.type,eS,t,`${n}.type`),Qe(e,"ref",t,n),Qe(e,"prompt",t,n),Qe(e,"question",t,n),"options"in e&&xo(e.options,t,`${n}.options`)}function uS(e,t,n){Re(e,t,n),ye(e.id,t,`${n}.id`),lS(e.action,t,`${n}.action`),Qe(e,"next",t,n),"completionEvals"in e&&xo(e.completionEvals,t,`${n}.completionEvals`)}function fS(e,t){let n="goal";Re(e,t,n),ye(e.statement,t,`${n}.statement`),sn(e.inputs,t,`${n}.inputs`),e.inputs.forEach((i,r)=>{pp(i,t,`${n}.inputs[${r}]`)}),sn(e.outputs,t,`${n}.outputs`),e.outputs.forEach((i,r)=>{pp(i,t,`${n}.outputs[${r}]`)}),xo(e.success,t,`${n}.success`)}function dS(e,t){let n="orchestration";Re(e,t,n),on(e.mode,tS,t,`${n}.mode`),Qe(e,"entry",t,n),"steps"in e&&(sn(e.steps,t,`${n}.steps`),e.steps.forEach((i,r)=>{uS(i,t,`${n}.steps[${r}]`)}))}function yp(e,t){return Re(e,t),on(e.apiVersion,["comet/v1alpha1"],t,"apiVersion"),on(e.kind,["Skill"],t,"kind"),Re(e.metadata,t,"metadata"),ye(e.metadata.name,t,"metadata.name"),ye(e.metadata.version,t,"metadata.version"),ye(e.metadata.description,t,"metadata.description"),fS(e.goal,t),dS(e.orchestration,t),sn(e.skills,t,"skills"),e.skills.forEach((n,i)=>{oS(n,t,`skills[${i}]`)}),sn(e.agents,t,"agents"),e.agents.forEach((n,i)=>{aS(n,t,`agents[${i}]`)}),sn(e.tools,t,"tools"),e.tools.forEach((n,i)=>{cS(n,t,`tools[${i}]`)}),e}function vp(e,t){Re(e,t);for(let n of["allowedSkills","allowedAgents","allowedTools","confirmationRequiredFor"])n in e&&xo(e[n],t,n);for(let n of["maxIterations","maxRetriesPerAction"])if(n in e&&(typeof e[n]!="number"||!Number.isFinite(e[n])))throw In(t,n,"must be a finite number");return e}function mS(e,t){return Re(e,t),"runtime"in e&&bp(e.runtime,t,"runtime"),e}function bp(e,t,n){return sn(e,t,n),e.forEach((i,r)=>{let s=`${n}[${r}]`;Re(i,t,s),ye(i.id,t,`${s}.id`),on(i.scope,rS,t,`${s}.scope`),on(i.type,sS,t,`${s}.type`),Qe(i,"artifact",t,s),Qe(i,"field",t,s),Qe(i,"equals",t,s)}),e}async function _l(e){let t=await Rl.readFile(e,"utf8");try{return(0,gp.parse)(t)}catch(n){let i=n instanceof Error?n.message:String(n);throw In(e,"document",i)}}async function pS(e){try{return await _l(e)}catch(t){if(t.code==="ENOENT")return null;throw t}}async function hp(e){try{return await Rl.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function hS(e){let t=Be.join(e,"checks.yaml"),n=Be.join(e,"evals.yaml"),[i,r]=await Promise.all([hp(t),hp(n)]);if(r)throw new Error(`${n}: evals.yaml is no longer supported; use checks.yaml`);return i?{document:mS(await _l(t),t)}:{document:null}}async function Cp(e){let t=Be.resolve(e.root),n=Be.resolve(e.controlRoot);e.requireSkillMarkdown&&await Rl.access(Be.join(t,"SKILL.md"));let i=Be.join(n,"skill.yaml"),r=Be.join(n,"guardrails.yaml"),s=yp(await _l(i),i),o=await pS(r),a=o===null?null:vp(o,r),c=await hS(n),l={allowedSkills:s.skills.map(f=>f.id),allowedAgents:s.agents.map(f=>f.id),allowedTools:s.tools.map(f=>f.id),maxIterations:50,maxRetriesPerAction:3,confirmationRequiredFor:s.tools.filter(f=>f.requiresConfirmation).map(f=>f.id)};return{root:t,packageKind:e.packageKind==="runtime"?"runtime":void 0,definition:s,guardrails:{...l,...a},evals:c.document?.runtime??[]}}async function kp(e){let t=Be.resolve(e);return Cp({root:t,controlRoot:Be.join(t,"comet"),packageKind:"skill",requireSkillMarkdown:!0})}async function Sp(e){let t=Be.resolve(e);return Cp({root:t,controlRoot:t,packageKind:"runtime",requireSkillMarkdown:!1})}function Ep(e,t,n=Be.join(t,"package.json")){Re(e,n);let i=e.packageKind==="runtime"?"runtime":void 0,r=yp(e.definition,n),s=vp(e.guardrails,n),o=bp(e.evals,n,"evals"),a={allowedSkills:r.skills.map(c=>c.id),allowedAgents:r.agents.map(c=>c.id),allowedTools:r.tools.map(c=>c.id),maxIterations:50,maxRetriesPerAction:3,confirmationRequiredFor:r.tools.filter(c=>c.requiresConfirmation).map(c=>c.id)};return{root:Be.resolve(t),packageKind:i,definition:r,guardrails:{...a,...s},evals:o}}import Rp from"path";function gS(e,t,n,i){e.type==="invoke_skill"&&!t.definition.skills.some(r=>r.id===e.ref)&&n.push(`step ${i} references undeclared skill: ${e.ref??"(missing)"}`),e.type==="call_tool"&&!t.definition.tools.some(r=>r.id===e.ref)&&n.push(`step ${i} references undeclared tool: ${e.ref??"(missing)"}`),e.type==="handoff"&&!t.definition.agents.some(r=>r.id===e.ref)&&n.push(`step ${i} references undeclared agent: ${e.ref??"(missing)"}`),e.type==="ask_user"&&!e.question&&n.push(`step ${i} ask_user action requires question`)}function _p(e){let t=[],{definition:n,guardrails:i,evals:r}=e;n.apiVersion!=="comet/v1alpha1"&&t.push("unsupported apiVersion"),n.kind!=="Skill"&&t.push("kind must be Skill"),n.metadata.name||t.push("metadata.name is required"),n.goal.statement||t.push("goal.statement is required"),i.maxIterations<1&&t.push("maxIterations must be at least 1"),i.maxRetriesPerAction<0&&t.push("maxRetriesPerAction must not be negative");let s=n.orchestration.steps??[];if(n.orchestration.mode==="adaptive")(n.orchestration.entry||s.length>0)&&t.push("adaptive orchestration must not define entry or steps");else{let o=new Set;for(let a of s)o.has(a.id)&&t.push(`duplicate step id: ${a.id}`),o.add(a.id),gS(a.action,e,t,a.id);(!n.orchestration.entry||!o.has(n.orchestration.entry))&&t.push(`orchestration.entry references unknown step: ${n.orchestration.entry??"(missing)"}`);for(let a of s){a.next&&!o.has(a.next)&&t.push(`step ${a.id} has unknown next step: ${a.next}`);for(let c of a.completionEvals??[])r.some(l=>l.id===c)||t.push(`step ${a.id} references unknown eval: ${c}`)}}for(let o of n.tools){if(o.kind!=="script")continue;let a=Rp.posix.normalize(o.source.replaceAll("\\","/"));(Rp.isAbsolute(o.source)||a===".."||a.startsWith("../"))&&t.push(`script tool ${o.id} must reference a relative path inside the Skill package`)}for(let o of i.allowedSkills)n.skills.some(a=>a.id===o)||t.push(`guardrails allow undeclared skill: ${o}`);for(let o of i.allowedAgents)n.agents.some(a=>a.id===o)||t.push(`guardrails allow undeclared agent: ${o}`);for(let o of i.allowedTools)n.tools.some(a=>a.id===o)||t.push(`guardrails allow undeclared tool: ${o}`);return t}function Po(e){return Array.isArray(e)?e.map(Po):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,Po(n)])):e}function yS(e){return Po({...e.packageKind==="runtime"?{packageKind:"runtime"}:{},definition:e.definition,guardrails:e.guardrails,evals:e.evals})}function vS(e){return te.posix.normalize(e.replaceAll("\\","/"))}function li(e,t,n){let i=te.relative(e,t);if(!(i===""||!te.isAbsolute(i)&&!i.startsWith(`..${te.sep}`)))throw new Error(`${n} resolves outside the Skill package`)}async function Pp(e,t,n){let i=vS(t);if(te.posix.isAbsolute(i)||i===".."||i.startsWith("../"))throw new Error(`${n} resolves outside the Skill package`);let r=te.resolve(e,...i.split("/"));li(e,r,n);let s;try{s=await re.realpath(r)}catch(o){throw o.code==="ENOENT"?new Error(`${n} does not exist: ${t}`,{cause:o}):o}if(li(e,s,n),!(await re.stat(s)).isFile())throw new Error(`${n} is not a file: ${t}`);return{path:i,content:await re.readFile(s)}}async function bS(e){let t=await re.realpath(e.root),n=e.packageKind==="runtime"?[]:[await Pp(t,"SKILL.md","SKILL.md")];for(let i of e.definition.tools)i.kind==="script"&&n.push(await Pp(t,i.source,`Script tool ${i.id}`));return n.sort((i,r)=>i.path.localeCompare(r.path))}function CS(e,t){let n=t.map(i=>({path:i.path,sha256:xp("sha256").update(i.content).digest("hex")}));return xp("sha256").update(JSON.stringify(Po({package:e,files:n}))).digest("hex")}function Ip(e){return JSON.stringify(e,null,2)+` +`}async function Ap(e){let t=yS(e),n=await bS(e);return{document:t,files:n,hash:CS(t,n)}}async function Oo(e){return(await Ap(e)).hash}async function Op(e){try{return await re.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function $p(e,t){try{if((await re.readFile(te.join(e,"sha256"),"utf8")).trim()!==t.hash)throw new Error("hash mismatch");if(await re.readFile(te.join(e,"package.json"),"utf8")!==Ip(t.document))throw new Error("package mismatch");for(let r of t.files)if(!(await re.readFile(te.join(e,...r.path.split("/")))).equals(r.content))throw new Error(`file mismatch: ${r.path}`)}catch(n){throw new Error(`Existing Skill snapshot is invalid: ${t.hash}`,{cause:n})}}async function xl(e,t){let n=await Ap(e),i=te.resolve(t,".comet","skill-snapshots"),r=te.join(i,n.hash);if(await re.mkdir(i,{recursive:!0}),await Op(r))return await $p(r,n),{hash:n.hash,snapshotDir:r};let s=te.join(i,`.tmp-${wS()}`);li(i,s,"Temporary snapshot"),li(i,r,"Published snapshot");try{await re.mkdir(s);for(let o of n.files){let a=te.join(s,...o.path.split("/"));li(s,a,`Snapshot file ${o.path}`),await re.mkdir(te.dirname(a),{recursive:!0}),await re.writeFile(a,o.content)}await re.writeFile(te.join(s,"package.json"),Ip(n.document)),await re.writeFile(te.join(s,"sha256"),n.hash+` +`),await re.rename(s,r)}catch(o){if(await Op(r)){try{await $p(r,n)}finally{await re.rm(s,{recursive:!0,force:!0})}return{hash:n.hash,snapshotDir:r}}throw await re.rm(s,{recursive:!0,force:!0}),o}return{hash:n.hash,snapshotDir:r}}async function $o(e,t){if(!/^[a-f0-9]{64}$/u.test(t))throw new Error(`Invalid Skill snapshot hash: ${t}`);let n=te.resolve(e,".comet","skill-snapshots"),i=te.join(n,t);li(n,i,"Skill snapshot");try{let r=(await re.readFile(te.join(i,"sha256"),"utf8")).trim();if(r!==t)throw new Error(`stored hash is ${r||"(empty)"}`);let s=te.join(i,"package.json"),o=JSON.parse(await re.readFile(s,"utf8")),a=Ep(o,i,s),c=_p(a);if(c.length>0)throw new Error(c.map(f=>` - ${f}`).join(` +`));let l=await Oo(a);if(l!==t)throw new Error(`calculated hash is ${l}`);return a}catch(r){throw new Error(`Skill snapshot is invalid or missing: ${t}`,{cause:r})}}async function Np(e){try{return await Pl.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Tp(e){return kS("sha256").update(e).digest("hex")}function ES(e){return Tp(JSON.stringify(Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))))}function RS(e){return e.replaceAll(".","_").replaceAll("-","_")}async function _S(e,t){let n=await le(e),i=Object.fromEntries(t.filter(o=>o.satisfied&&o.source).map(o=>[RS(o.code),o.source])),r=_t.join(e,"subagent-progress.md");await Np(r)&&(i.subagent_progress=_t.relative(n,r).split(_t.sep).join("/"));let s=t.find(o=>o.code==="design.handoff"&&o.satisfied);return s?.source&&(i.handoff_context=s.source),i}function xS(e,t,n){return[{sequence:1,timestamp:n,type:"run_started",runId:e.runId,data:{skill:e.skill,skillVersion:e.skillVersion,skillHash:e.skillHash}},{sequence:2,timestamp:n,type:"state_migrated",runId:e.runId,data:{kind:"classic",migrationVersion:nn,profile:t,source:"pre-migration"}}]}async function PS(e){await Promise.all(e.map(t=>Pl.rm(t,{recursive:!0,force:!0})))}async function jp(e,t){let n=await B(e);if(!n.classic)throw new Error("Classic migration requires a legacy state projection");let i=n.classic,r=i.classicProfile??i.workflow;if(n.run){if(i.classicMigration!==nn)throw new Error("Classic Run exists without a supported classic_migration marker");if(n.run.skill!==t.skillPackage.definition.metadata.name)throw new Error(`Classic Run skill mismatch: expected ${t.skillPackage.definition.metadata.name}, got ${n.run.skill}`);if(await Oo(t.skillPackage)!==n.run.skillHash)return await $o(e,n.run.skillHash),{classic:i,run:n.run,evidence:await ze(e,n),migrated:!1,snapshotDir:_t.join(e,".comet","skill-snapshots",n.run.skillHash)};let d=await xl(t.skillPackage,e);return{classic:i,run:n.run,evidence:await ze(e,n),migrated:!1,snapshotDir:d.snapshotDir}}let s=await ze(e,n),o=Et(i,s);if(!t.skillPackage.definition.orchestration.steps?.some(u=>u.id===o))throw new Error(`Classic Skill package does not define resolved step: ${o}`);let a=await Oo(t.skillPackage),c=_t.join(e,".comet","skill-snapshots",a),l=await Np(c),f=[];try{let u=await xl(t.skillPackage,e),d=dp(t.skillPackage,t.runId?.()??SS(),u.hash);d.currentStep=o,o==="completed"&&(d.status="completed");let p={...i,classicProfile:r,classicMigration:nn},g=await _S(e,s),h=await le(e),m=s.find(k=>k.code==="design.handoff"&&k.satisfied),y=null;m?.source&&(y=await W(h,m.resolvedSource??m.source,{label:"Classic migration handoff context",hooks:t.handoffReadHooks}),await So(e,d.contextRef,y),f.push(_t.resolve(e,d.contextRef))),await ai(e,d.artifactsRef,g),f.push(_t.resolve(e,d.artifactsRef));let w=(t.now?.()??new Date).toISOString(),C={runId:d.runId,stateVersion:1,trajectoryOffset:2,contextHash:y===null?null:Tp(y),artifactsHash:ES(g),createdAt:w};await ci(e,d.checkpointRef,C),f.push(_t.resolve(e,d.checkpointRef)),f.push(_t.resolve(e,d.trajectoryRef));for(let k of xS(d,r,w))await We(e,d.trajectoryRef,k);return await je(e,{classic:p,run:d,unknownKeys:n.unknownKeys}),{classic:p,run:d,evidence:s,migrated:!0,snapshotDir:u.snapshotDir}}catch(u){throw await PS(f),l||await Pl.rm(c,{recursive:!0,force:!0}),u}}async function OS(e){try{return(await Lp.stat(e)).isDirectory()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Io(e){try{return(await Lp.stat(e)).isFile()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function $S(e){return await OS(e)?await Io(ve.join(e,"skill.yaml"))?!0:await Io(ve.join(e,"SKILL.md"))&&await Io(ve.join(e,"comet","skill.yaml")):!1}function Mp(e){return{root:e,packageKind:"runtime",definition:{apiVersion:"comet/v1alpha1",kind:"Skill",metadata:{name:"comet-classic",version:"1",description:"Internal compatibility orchestration for classic Comet full, hotfix, and tweak workflows"},goal:{statement:"Advance or restore a classic Comet Run without changing the user command surface",inputs:[{name:"classic-state",description:"Validated ClassicState consistent with the Run projection",required:!0},{name:"evidence",description:"Structured evidence produced by the Classic Evidence collector",required:!0}],outputs:[{name:"run-state",description:"Atomically synchronized Classic and Run state",required:!0}],success:["Legacy fields and Run fields remain consistent","Every step invokes only a declared public Comet Skill","The completed state passes its completion eval"]},orchestration:{mode:"deterministic",entry:"full.open",steps:[{id:"full.open",action:{type:"invoke_skill",ref:"comet-open"},next:"full.design.handoff"},{id:"full.design.handoff",action:{type:"invoke_skill",ref:"comet-design"},next:"full.design.document"},{id:"full.design.document",action:{type:"invoke_skill",ref:"comet-design"},next:"full.build.plan"},{id:"full.build.plan",action:{type:"invoke_skill",ref:"comet-build"},next:"full.build.plan-ready"},{id:"full.build.plan-ready",action:{type:"invoke_skill",ref:"comet-build"},next:"full.build.configure"},{id:"full.build.configure",action:{type:"invoke_skill",ref:"comet-build"},next:"full.build.execute"},{id:"full.build.execute",action:{type:"invoke_skill",ref:"comet-build"},next:"full.build.complete"},{id:"full.build.complete",action:{type:"invoke_skill",ref:"comet-build"},next:"full.verify.run"},{id:"full.build.fix",action:{type:"invoke_skill",ref:"comet-build"},next:"full.build.execute"},{id:"full.verify.run",action:{type:"invoke_skill",ref:"comet-verify"},next:"full.verify.branch"},{id:"full.verify.branch",action:{type:"invoke_skill",ref:"comet-verify"},next:"full.archive.confirm"},{id:"full.archive.confirm",action:{type:"invoke_skill",ref:"comet-archive"},next:"full.archive.execute"},{id:"full.archive.execute",action:{type:"invoke_skill",ref:"comet-archive"},next:"completed"},{id:"hotfix.open",action:{type:"invoke_skill",ref:"comet-hotfix"},next:"hotfix.build.execute"},{id:"hotfix.build.execute",action:{type:"invoke_skill",ref:"comet-build"},next:"hotfix.build.complete"},{id:"hotfix.build.complete",action:{type:"invoke_skill",ref:"comet-build"},next:"hotfix.verify.run"},{id:"hotfix.verify.run",action:{type:"invoke_skill",ref:"comet-verify"},next:"hotfix.verify.branch"},{id:"hotfix.verify.branch",action:{type:"invoke_skill",ref:"comet-verify"},next:"hotfix.archive.confirm"},{id:"hotfix.archive.confirm",action:{type:"invoke_skill",ref:"comet-archive"},next:"hotfix.archive.execute"},{id:"hotfix.archive.execute",action:{type:"invoke_skill",ref:"comet-archive"},next:"completed"},{id:"tweak.open",action:{type:"invoke_skill",ref:"comet-tweak"},next:"tweak.build.execute"},{id:"tweak.build.execute",action:{type:"invoke_skill",ref:"comet-build"},next:"tweak.build.complete"},{id:"tweak.build.complete",action:{type:"invoke_skill",ref:"comet-build"},next:"tweak.verify.run"},{id:"tweak.verify.run",action:{type:"invoke_skill",ref:"comet-verify"},next:"tweak.verify.branch"},{id:"tweak.verify.branch",action:{type:"invoke_skill",ref:"comet-verify"},next:"tweak.archive.confirm"},{id:"tweak.archive.confirm",action:{type:"invoke_skill",ref:"comet-archive"},next:"tweak.archive.execute"},{id:"tweak.archive.execute",action:{type:"invoke_skill",ref:"comet-archive"},next:"completed"},{id:"completed",action:{type:"checkpoint"},completionEvals:["classic-completed"]}]},skills:[{id:"comet-open"},{id:"comet-design"},{id:"comet-build"},{id:"comet-verify"},{id:"comet-archive"},{id:"comet-hotfix"},{id:"comet-tweak"}],agents:[],tools:[]},guardrails:{allowedSkills:["comet-open","comet-design","comet-build","comet-verify","comet-archive","comet-hotfix","comet-tweak"],allowedAgents:[],allowedTools:[],maxIterations:500,maxRetriesPerAction:3,confirmationRequiredFor:[]},evals:[{id:"classic-completed",scope:"completion",type:"state_equals",field:"status",equals:"completed"}]}}async function qp(){let e=ve.dirname(Ol(import.meta.url)),t=[process.env.COMET_RUNTIME_CLASSIC_ROOT,ve.resolve(e,"..","runtime","classic"),ve.resolve(e,"..","..","comet","runtime","classic"),ve.resolve(e,"..","..","assets","skills","comet","runtime","classic"),ve.resolve("assets","skills","comet","runtime","classic"),process.env.COMET_CLASSIC_SKILL_ROOT,ve.resolve(e,"..","..","comet-classic"),ve.resolve(e,"..","..","assets","skills","comet-classic"),ve.resolve("assets","skills","comet-classic")].filter(n=>!!n);for(let n of t)if(await $S(n))return n;return null}async function Dp(e){return await Io(ve.join(e,"skill.yaml"))?Sp(e):kp(e)}async function an(e){let t=await qp();return jp(e,{skillPackage:t?await Dp(t):Mp(ve.dirname(Ol(import.meta.url)))})}async function Fp(e){let t=await B(e),n=Array.from(new Set(t.unknownKeys)).sort();if(n.length>0)throw new Error(`Invalid Classic state: unknown field(s): ${n.join(", ")}`);return an(e)}async function $l(e,t){let n=t??await B(e,{migrate:!1}),i=Array.from(new Set(n.unknownKeys)).sort();if(i.length>0)throw new Error(`Invalid Classic state: unknown field(s): ${i.join(", ")}`);if(!n.classic||!n.run)throw new Error("Classic runtime validation requires synchronized Classic and Run projections");if(n.classic.classicMigration!==nn)throw new Error("Classic Run exists without a supported classic_migration marker");let r=await qp(),s=r?await Dp(r):Mp(ve.dirname(Ol(import.meta.url)));if(n.run.skill!==s.definition.metadata.name)throw new Error(`Classic Run skill mismatch: expected ${s.definition.metadata.name}, got ${n.run.skill}`);let o=await $o(e,n.run.skillHash);if(o.definition.metadata.name!==n.run.skill)throw new Error(`Classic Run snapshot skill mismatch: expected ${n.run.skill}, got ${o.definition.metadata.name}`);let a=await ze(e,n),c=Et(n.classic,a);if(n.run.currentStep!==c)throw new Error(`Classic Run step mismatch: expected ${c}, got ${n.run.currentStep}`);return{classic:n.classic,run:n.run,evidence:a,migrated:!1,snapshotDir:ve.join(e,".comet","skill-snapshots",n.run.skillHash)}}async function cn(e,t,n,i){let r=await B(e);if(!r.classic||!r.run)throw new Error("Classic transition requires synchronized Classic and Run projections");let s=await ze(e,{classic:t,run:n,unknownKeys:r.unknownKeys}),o=Et(t,s),a={...n,currentStep:o,iteration:n.iteration+1,status:o==="completed"?"completed":"running"};await je(e,{classic:t,run:a,unknownKeys:r.unknownKeys});let c=await Le(e,a.trajectoryRef);return await We(e,a.trajectoryRef,{sequence:c.length+1,timestamp:new Date().toISOString(),type:"state_transitioned",runId:a.runId,data:{kind:"classic",fromStep:n.currentStep,toStep:o,...i}}),a}go();import IS from"path";var AS=IS.join(".comet","state-events.jsonl"),NS=8*1024*1024;async function An(e,t){let n={schemaVersion:1,timestamp:new Date().toISOString(),...t};return await po(e,AS,`${JSON.stringify(n)} +`,NS,"Classic state event log"),n}var Wp=["open-complete","design-complete","build-complete","verify-pass","verify-fail","archive-confirm","archive-reopen","archived","preset-escalate"],TS={"open-complete":{event:"open-complete",from:"open",guardRefs:["open-artifacts-present"]},"design-complete":{event:"design-complete",from:"design",guardRefs:["design-evidence-present"]},"build-complete":{event:"build-complete",from:"build",guardRefs:["build-decisions-selected"]},"verify-pass":{event:"verify-pass",from:"verify",guardRefs:["verification-report-present"]},"verify-fail":{event:"verify-fail",from:"verify",guardRefs:["verification-failed"]},"archive-confirm":{event:"archive-confirm",from:"archive",guardRefs:["archive-final-confirmation"]},"archive-reopen":{event:"archive-reopen",from:"archive",guardRefs:["archive-not-finalized"]},archived:{event:"archived",from:"archive",guardRefs:["verify-result-pass","archive-confirmed"]},"preset-escalate":{event:"preset-escalate",from:"build",guardRefs:["preset-workflow"]}},Bp={open:"open-complete",design:"design-complete",build:"build-complete",verify:"verify-pass"};function jS(e){return e.toISOString().slice(0,10)}function j(e,t,n,i){let r=e[n];e[n]=i,r!==i&&t.push({field:n,from:r,to:i})}function ui(e,t,n={}){let i=TS[t];if(e.phase!==i.from)throw new Error(`Cannot apply ${t}: phase is '${e.phase}', expected '${i.from}'`);let r={...e},s=[],o=n.now??new Date;if(t==="open-complete")j(r,s,"phase",r.workflow==="full"?"design":"build");else if(t==="design-complete")j(r,s,"phase","build");else if(t==="build-complete"){let a=r.verifyResult==="fail";j(r,s,"phase","verify"),j(r,s,"verifyResult","pending"),j(r,s,"branchStatus","pending"),a||j(r,s,"verificationReport",null)}else if(t==="verify-pass")j(r,s,"verifyResult","pass"),j(r,s,"verifyFailures",0),j(r,s,"phase","archive"),j(r,s,"verifiedAt",jS(o)),j(r,s,"archiveConfirmation","pending"),j(r,s,"branchStatus","pending");else if(t==="verify-fail")j(r,s,"verifyResult","fail"),j(r,s,"verifyFailures",r.verifyFailures+1),j(r,s,"phase","build"),j(r,s,"branchStatus","pending");else if(t==="preset-escalate"){if(r.workflow!=="hotfix"&&r.workflow!=="tweak")throw new Error(`Cannot apply ${t}: workflow must be hotfix or tweak, got '${r.workflow}'`);j(r,s,"workflow","full"),j(r,s,"classicProfile","full"),j(r,s,"phase","design"),j(r,s,"designDoc",null),j(r,s,"buildPause",null),j(r,s,"buildMode",null),j(r,s,"subagentDispatch",null),j(r,s,"tddMode",null),j(r,s,"reviewMode",null),j(r,s,"isolation",null),j(r,s,"boundBranch",null),j(r,s,"verifyMode",null),j(r,s,"directOverride",null)}else if(t==="archive-confirm"){if(r.verifyResult!=="pass")throw new Error(`Cannot apply ${t}: verifyResult must be pass`);if(r.archived)throw new Error(`Cannot apply ${t}: already archived`);j(r,s,"archiveConfirmation","confirmed")}else if(t==="archive-reopen"){if(r.archived)throw new Error(`Cannot apply ${t}: already archived`);j(r,s,"verifyResult","pending"),j(r,s,"verifyFailures",0),j(r,s,"phase","verify"),j(r,s,"verifiedAt",null),j(r,s,"archiveConfirmation",null),j(r,s,"branchStatus","pending")}else{if(r.verifyResult!=="pass")throw new Error(`Cannot apply ${t}: verifyResult must be pass`);if(r.archiveConfirmation!=="confirmed")throw new Error(`Cannot apply ${t}: archiveConfirmation must be confirmed`);j(r,s,"archived",!0)}return{classic:r,effects:s,definition:i}}Zc();import{randomUUID as LS}from"crypto";import{promises as vr}from"fs";import Kp from"path";var Il="comet.selection.v2",MS=16*1024;function Ao(e){return Kp.join(e,".comet","current-change.json")}function qS(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Hp(e){return e===null||typeof e=="string"}function Jp(e){let t;try{t=JSON.parse(e)}catch(n){throw new Error(`current change selection contains invalid JSON: ${n instanceof Error?n.message:String(n)}`,{cause:n})}if(!qS(t))throw new Error("current change selection must be a JSON object");if(t.version===1){if(typeof t.change!="string")throw new Error("legacy current change selection change must be a string");if(t.branch!==void 0&&!Hp(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:Il,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==Il)throw new Error(`current change selection schema must be ${Il}`);if(t.workflow!=="native"&&t.workflow!=="classic")throw new Error("current change selection workflow must be native or classic");if(typeof t.change!="string")throw new Error("current change selection change must be a string");if(!Hp(t.branch))throw new Error("current change selection branch must be a string or null");if(t.workflow==="native"&&t.branch!==null)throw new Error("Native current change selection branch must be null");return{selection:t,legacy:!1}}async function No(e){let t;try{let i=Ao(e),{bytes:r}=await Gs(i,MS,{label:"current change selection"});t=r.toString("utf8")}catch(i){if(i.code==="ENOENT")return{status:"missing"};throw new Error(`cannot read current change selection: ${i instanceof Error?i.message:String(i)}`,{cause:i})}return{status:"selected",...Jp(t)}}async function Up(e,t){let n=Jp(JSON.stringify(t));if(n.legacy)throw new Error("cannot write a legacy current change selection");let i=Ao(e),r=`${i}.${LS()}.tmp`;await vr.mkdir(Kp.dirname(i),{recursive:!0});try{await vr.writeFile(r,`${JSON.stringify(n.selection,null,2)} +`,"utf8"),await vr.rename(r,i)}catch(s){throw await vr.rm(r,{force:!0}),s}}async function Al(e){await vr.rm(Ao(e),{force:!0})}async function Vp(e,t,n){let i=await No(e);return i.status!=="selected"||i.selection.workflow!==t||i.selection.change!==n?!1:(await Al(e),!0)}var Yp=null;function Gp(e,t){let n=e;for(let i of t)n+="\0"+(typeof i=="string"?i:JSON.stringify(i));return n}function br(e,t){return(...n)=>{let i=Yp;if(i===null)return t(...n);let r=Gp(`async:${e}`,n),s=i.entries.get(r);if(s)return s.value;let o=t(...n).catch(a=>{throw i.entries.delete(r),a});return i.entries.set(r,{value:o}),o}}function Nl(e,t){return(...n)=>{let i=Yp;if(i===null)return t(...n);let r=Gp(`sync:${e}`,n),s=i.entries.get(r);if(s)return s.value;let o=t(...n);return i.entries.set(r,{value:o}),o}}var Tl=st(Ue(),1);import{execFileSync as zp}from"child_process";import{randomUUID as DS}from"crypto";import{promises as Cr}from"fs";import Xp from"path";function To(e){try{let t=zp("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();return t&&t!=="HEAD"?t:null}catch{return null}}var FS=Nl("liveGitBranch",e=>To(e));function jl(e){try{return zp("git",["rev-parse","--is-inside-work-tree"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()==="true"}catch{return!1}}var WS=Nl("isGitWorkTree",e=>jl(e)),BS=["current","branch","worktree"];function jo(e){return BS.includes(e)}function Ll(e){return jo(e.isolation)?e.boundBranch===null&&e.currentBranch===null&&e.gitWorkTree===!1?{status:"not-applicable"}:e.boundBranch===null?e.currentBranch===null?{status:"unbound-detached"}:{status:"needs-heal",branch:e.currentBranch}:e.currentBranch===e.boundBranch?{status:"ok"}:{status:"drift",boundBranch:e.boundBranch,currentBranch:e.currentBranch}:{status:"not-applicable"}}async function xt(e,t){let n=Xp.join(e,".comet.yaml"),i=(0,Tl.parseDocument)(await Cr.readFile(n,"utf8"),{uniqueKeys:!1});if(i.errors.length>0)throw new Error(`Invalid .comet.yaml: ${i.errors[0].message}`);let r=i.toJS()??{},s=typeof r.isolation=="string"?r.isolation:null,o=typeof r.bound_branch=="string"&&r.bound_branch!==""?r.bound_branch:null,a=jo(s),c=FS(t.cwd),l=a&&o===null&&c===null?WS(t.cwd):!0,f=Ll({isolation:s,boundBranch:o,currentBranch:c,gitWorkTree:l});return f.status==="needs-heal"&&t.heal?(await Ml(e,f.branch),{status:"healed",branch:f.branch,bindingRequired:a,currentBranch:c}):{...f,bindingRequired:a,currentBranch:c}}async function Ml(e,t){let n=Xp.join(e,".comet.yaml"),i=(0,Tl.parseDocument)(await Cr.readFile(n,"utf8"),{uniqueKeys:!1});i.set("bound_branch",t);let r=`${n}.${DS()}.tmp`;try{await Cr.writeFile(r,i.toString(),"utf8"),await Cr.rename(r,n)}catch(s){throw await Cr.rm(r,{force:!0}),s}}function Qp(e){return e??"detached HEAD"}function Lo(e,t,n){return`change '${e}' is bound to branch '${t}', but current branch is '${Qp(n)}'. +Next: ask the user to confirm — switch back to '${t}', or run \`comet state rebind ${e}\` after explicit confirmation.`}function kr(e,t,n){return`change '${e}' is bound to branch '${t}', but current branch is '${Qp(n)}'`}function Pt(e){return`change '${e}' uses a branch-bound workspace mode but has no bound branch and HEAD is detached; checkout a branch first before continuing.`}var HS=br("readCometCurrentSelection",e=>No(e));async function Zp(e,t){en(t);let n=await Ge(t,e);if(!n.stateExists)throw new Error(`Cannot select current change '${t}': active change state not found`);let i=await B(n.directory,{migrate:!1});if(!i.classic)throw new Error(`Cannot select current change '${t}': Classic state is incomplete`);if(i.classic.archived)throw new Error(`Cannot select current change '${t}': change is archived`);return n.directory}async function eh(e,t){let n=await Zp(e,t),i=await xt(n,{heal:!0,cwd:e});if(i.status==="drift")throw new Error(kr(t,i.boundBranch,i.currentBranch));if(i.status==="unbound-detached")throw new Error(Pt(t));let r={schema:"comet.selection.v2",workflow:"classic",change:t,branch:i.currentBranch};return await Up(e,r),r}async function Mo(e){let t;try{t=await HS(e)}catch(s){return{status:"stale",reason:s instanceof Error?s.message:String(s)}}if(t.status==="missing")return{status:"missing"};if(t.selection.workflow!=="classic")return{status:"stale",reason:`current change '${t.selection.change}' belongs to Native, not Classic`};let n=t.selection,i;try{i=await Zp(e,n.change)}catch(s){return{status:"stale",reason:s instanceof Error?s.message:String(s)}}let r=await xt(i,{heal:!1,cwd:e});return r.status==="drift"?{status:"stale",reason:kr(n.change,r.boundBranch,r.currentBranch)}:r.status==="unbound-detached"?{status:"stale",reason:Pt(n.change)}:r.status==="ok"?{status:"selected",selection:n}:n.branch!==null&&r.currentBranch!==n.branch?{status:"stale",reason:`current change '${n.change}' was selected on branch '${n.branch}', current branch is '${r.currentBranch??"detached HEAD"}'`}:{status:"selected",selection:n}}async function th(e){let t;try{t=await No(e)}catch{return}t.status==="selected"&&t.selection.workflow==="classic"&&await Al(e)}async function nh(e,t){return Vp(e,"classic",t)}var US="\x1B[32m",VS="\x1B[31m",YS="\x1B[33m",Dl="\x1B[0m";function He(e){return`${US}${e}${Dl}`}function _e(e){return`${VS}${e}${Dl}`}function Sr(e){return`${YS}${e}${Dl}`}var ue=class extends Error{constructor(n,i=1){super(n);this.exitCode=i}exitCode},ql=class{stderr=[];openSpecStdout=[];openSpecStderr=[];stepsOk=0;stepsTotal=0;captureOpenSpec(t){t.stdout&&this.openSpecStdout.push(t.stdout),t.stderr&&this.openSpecStderr.push(t.stderr)}toResult(t=0){let n=this.stderr.length>0?this.stderr.join(` `)+` `:"",i=this.openSpecStderr.join(""),r=i&&n&&!i.endsWith(` `)?` -`:"";return{exitCode:t,...this.openSpecStdout.length>0?{stdout:this.openSpecStdout.join("")}:{},...i||n?{stderr:`${i}${r}${n}`}:{}}}};function GS(e){let t=ge(e);if(t)throw new ue(_e(`FATAL: ${t}`))}function nh(e){return KS("sha256").update(e).digest("hex")}function zS(e){return nh(JSON.stringify(Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))))}function XS(e,t){let n=ft.relative(e,t);return n!==""&&!ft.isAbsolute(n)&&n!==".."&&!n.startsWith(`..${ft.sep}`)}function Er(e,t,n,i){if(!i)return i;let r=ft.resolve(e,i);return XS(t,r)?A(e,ft.join(n,ft.relative(t,r))):i}function QS(e,t,n,i){let r={...i};for(let s of["handoff_context","handoff_markdown"]){let o=r[s];o&&(r[s]=Er(e,t,n,o)??o)}return r}async function ZS(e,t){let n=await B(t);if(!n.classic||!n.run||!n.classic.archived)throw new ue(_e(" [FAIL] Final archived state is incomplete"));let i=[["design_doc",n.classic.designDoc],["plan",n.classic.plan],["verification_report",n.classic.verificationReport],["handoff_context",n.classic.handoffContext]],r=await oi(t,n.run.artifactsRef),s=[["artifacts.handoff_context",r.handoff_context],["artifacts.handoff_markdown",r.handoff_markdown]];for(let[o,a]of[...i,...s])if(a&&!await X(e,ft.resolve(e,a),{label:`Classic archived ${o}`,expected:"file"}))throw new ue(_e(` [FAIL] Final archived ${o} does not exist: ${a}`))}function th(e){return`${e.replace(/\n+$/u,"")} +`:"";return{exitCode:t,...this.openSpecStdout.length>0?{stdout:this.openSpecStdout.join("")}:{},...i||n?{stderr:`${i}${r}${n}`}:{}}}};function GS(e){let t=ge(e);if(t)throw new ue(_e(`FATAL: ${t}`))}function rh(e){return KS("sha256").update(e).digest("hex")}function zS(e){return rh(JSON.stringify(Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))))}function XS(e,t){let n=dt.relative(e,t);return n!==""&&!dt.isAbsolute(n)&&n!==".."&&!n.startsWith(`..${dt.sep}`)}function Er(e,t,n,i){if(!i)return i;let r=dt.resolve(e,i);return XS(t,r)?A(e,dt.join(n,dt.relative(t,r))):i}function QS(e,t,n,i){let r={...i};for(let s of["handoff_context","handoff_markdown"]){let o=r[s];o&&(r[s]=Er(e,t,n,o)??o)}return r}async function ZS(e,t){let n=await B(t);if(!n.classic||!n.run||!n.classic.archived)throw new ue(_e(" [FAIL] Final archived state is incomplete"));let i=[["design_doc",n.classic.designDoc],["plan",n.classic.plan],["verification_report",n.classic.verificationReport],["handoff_context",n.classic.handoffContext]],r=await oi(t,n.run.artifactsRef),s=[["artifacts.handoff_context",r.handoff_context],["artifacts.handoff_markdown",r.handoff_markdown]];for(let[o,a]of[...i,...s])if(a&&!await X(e,dt.resolve(e,a),{label:`Classic archived ${o}`,expected:"file"}))throw new ue(_e(` [FAIL] Final archived ${o} does not exist: ${a}`))}function ih(e){return`${e.replace(/\n+$/u,"")} `}function eE(e,t,n){let i=e.replace(/\r\n/gu,` `),r=i.split(` -`),s=r[0]==="---"?r.indexOf("---",1):-1,o=n.match(/^([^:\n]+):/u)?.[1]?.trim();if(s!==-1){let c=r.slice(1,s).filter(l=>{let f=l.match(/^([^:\n]+):/u)?.[1]?.trim();return f===void 0?!0:f!=="archived-with"&&f!==o});return c.push(`archived-with: ${t}`),n&&c.push(n),th(["---",...c,"---",...r.slice(s+1)].join(` -`))}let a=["---",`archived-with: ${t}`];return n&&a.push(n),o!=="status"&&a.push("status: final"),a.push("---"),th([...a,i].join(` +`),s=r[0]==="---"?r.indexOf("---",1):-1,o=n.match(/^([^:\n]+):/u)?.[1]?.trim();if(s!==-1){let c=r.slice(1,s).filter(l=>{let f=l.match(/^([^:\n]+):/u)?.[1]?.trim();return f===void 0?!0:f!=="archived-with"&&f!==o});return c.push(`archived-with: ${t}`),n&&c.push(n),ih(["---",...c,"---",...r.slice(s+1)].join(` +`))}let a=["---",`archived-with: ${t}`];return n&&a.push(n),o!=="status"&&a.push("status: final"),a.push("---"),ih([...a,i].join(` `))}async function tE(e,t,n){let i=await Le(e,t.trajectoryRef);i.some(r=>r.type==="recovery_reconciled"&&r.data.kind==="classic-archive"&&r.data.actionId===n)||await We(e,t.trajectoryRef,{sequence:i.length+1,timestamp:new Date().toISOString(),type:"recovery_reconciled",runId:t.runId,data:{kind:"classic-archive",actionId:n}})}async function qo(e,t,n,i,r,s){if(!await X(t,n,{label:"Classic archive annotation target",expected:"file"}))return;if(s){e.stderr.push(Sr(` [DRY-RUN] Would annotate: ${n}`)),e.stepsOk+=1,e.stepsTotal+=1;return}let o=await W(t,n,{label:"Classic archive annotation target"}),a=eE(o,i,r);await ti(t,n,a,{label:"Classic archive annotation target"}),e.stderr.push(He(` [OK] Annotated: ${n}`)),e.stepsOk+=1,e.stepsTotal+=1}async function nE(e,t){if(!(await Y(e,t,{label:"Classic main specs directory",expected:"directory"})).exists)return;let i=!1,r=await JS.readdir(t,{withFileTypes:!0});for(let s of r){if(!s.isDirectory()&&!s.isSymbolicLink())continue;let o=`${t}/${s.name}/spec.md`,a=await(async()=>await X(e,o,{label:`Classic main spec ${s.name}`,expected:"file"})?W(e,o,{label:`Classic main spec ${s.name}`}):null)();if(a===null)continue;let c=a.split(/\r?\n/u).map((l,f)=>({line:l,number:f+1})).filter(l=>/^## (ADDED|MODIFIED|REMOVED|RENAMED) Requirements$/u.test(l.line));if(c.length>0){i=!0,process.stderr.write(_e(`FATAL: delta-only section heading leaked into main spec: ${o}`)+` `);for(let l of c)process.stderr.write(`${l.number}:${l.line} -`)}}if(i)throw new ue("")}var ih=async e=>{let t=new ql,n=e[0],i=e[1]==="--dry-run";try{GS(n);let r=await le(process.cwd()),s=await Ee(r),o=await Ye(n,s.projectRoot),a=o.directory,c=A(s.projectRoot,a),f=`${new Date().toISOString().slice(0,10)}-${n}`,u=ft.join(s.archiveDir,f);t.stderr.push(`=== Comet Archive: ${n} ===`);let d=o.stateExists,p=d?null:await uo(n,s.projectRoot),g=d?a:p?.directory;if(!g||!await X(s.projectRoot,`${g}/.comet.yaml`,{label:`Classic change ${n} state`,expected:"file"}))throw new ue(_e(`FATAL: .comet.yaml not found in ${c}/`));p&&(u=p.directory,f=ft.basename(p.directory));let h=await B(g);if(!h.classic)throw new ue(_e("FATAL: archive requires Classic state"));let m=h.classic,y=m.designDoc,w=m.plan;if(m.phase!=="archive")throw new ue(_e(`FATAL: phase is '${m.phase}', expected 'archive'`));if(m.verifyResult!=="pass")throw new ue(_e(`FATAL: verify_result is '${m.verifyResult}', expected 'pass'. Run comet-verify first.`));t.stderr.push(He(" [OK] Entry state verified")),t.stepsOk+=1,t.stepsTotal+=1;let C=await Y(s.projectRoot,u,{label:`Classic archive target ${f}`,expected:"directory"});if(d&&C.exists)throw new ue(_e(`FATAL: archive target already exists: ${u}`));if(t.stderr.push(He(" [OK] Archive target available")),t.stepsOk+=1,t.stepsTotal+=1,i)t.stderr.push(Sr(` [DRY-RUN] Would run OpenSpec archive: ${n}`)),t.stepsOk+=1,t.stepsTotal+=1;else if(!m.archived||h.run?.pending){await Pn(s.projectRoot,`${g}/.comet`,"Classic change runtime directory");let k=await an(g),E=`classic-archive:${n}`,R=await yr(g,k.run.pendingRef),O=!!p||R?.id===E&&R.type==="checkpoint"&&R.ref===n;if(k.run.pending&&k.run.pending!==E)throw new ue(_e(`FATAL: another action is pending: ${k.run.pending}`));if(!O&&!m.archived&&m.archiveConfirmation!=="confirmed")throw new ue(_e(`FATAL: archive_confirmation is '${m.archiveConfirmation??"null"}', expected 'confirmed'. Run final archive confirmation first.`));if(!O){let mn={id:E,stepId:k.run.currentStep,type:"checkpoint",ref:n};await Ro(g,k.run.pendingRef,mn),await je(g,{classic:k.classic,run:{...k.run,pending:E,status:"waiting"},unknownKeys:(await B(g)).unknownKeys})}if(!p){let mn=await hl(["archive",n,"--yes"],s.projectRoot);if(t.captureOpenSpec(mn),mn.exitCode!==0)throw new ue("",mn.exitCode)}let b=await uo(n,s.projectRoot,{preferredArchiveName:f});if(!b&&!p&&(b=await uo(n,s.projectRoot,{skipExactCompatibility:!0})),!b)return t.stderr.push(_e(" [FAIL] OpenSpec archive output not found")),t.stepsTotal+=1,t.stderr.push(""),t.stderr.push(He(`Archive complete. ${t.stepsOk}/${t.stepsTotal} steps succeeded.`)),t.toResult(1);u=b.directory,f=ft.basename(b.directory),t.stderr.push(He(` [OK] OpenSpec archive completed: ${u}`)),t.stepsOk+=1,t.stepsTotal+=1,await nE(s.projectRoot,s.specsDir),t.stderr.push(He(" [OK] Main specs verified clean")),t.stepsOk+=1,t.stepsTotal+=1,y&&await qo(t,s.projectRoot,y,f,"status: final",!1),w&&await qo(t,s.projectRoot,w,f,"",!1);let L=await B(u);if(!L.classic||!L.run)throw new ue(_e(" [FAIL] archived state projection is incomplete"));let Ie={...QS(s.projectRoot,a,u,await oi(u,L.run.artifactsRef)),archive_directory:A(s.projectRoot,u)};await ai(u,L.run.artifactsRef,Ie);let Q=ui(O&&L.classic.archiveConfirmation!=="confirmed"?{...L.classic,archiveConfirmation:"confirmed"}:L.classic,"archived"),K={...Q.classic,designDoc:Er(s.projectRoot,a,u,Q.classic.designDoc),plan:Er(s.projectRoot,a,u,Q.classic.plan),verificationReport:Er(s.projectRoot,a,u,Q.classic.verificationReport),handoffContext:Er(s.projectRoot,a,u,Q.classic.handoffContext)},Ce=L.run;(L.run.currentStep!=="completed"||L.run.status!=="completed")&&(Ce=await cn(u,K,L.run,{actionId:E,archiveDirectory:A(s.projectRoot,u),event:"archived",source:"comet-archive"})),O&&await tE(u,Ce,E);let Hr=await Le(u,Ce.trajectoryRef),da=await Eo(u,Ce.contextRef),wt={runId:Ce.runId,stateVersion:Ce.iteration,trajectoryOffset:Hr.length,contextHash:da===null?null:nh(da),artifactsHash:zS(Ie),createdAt:new Date().toISOString()};await ci(u,Ce.checkpointRef,wt);let Kr={...Ce,pending:null,status:"completed"};await je(u,{classic:K,run:Kr,unknownKeys:L.unknownKeys}),await An(u,{change:f,event:"archived",source:"comet-archive",from:L.classic,to:K,effects:Q.effects}),await _o(u,Kr.pendingRef),t.stderr.push(He(" [OK] archived: true")),t.stepsOk+=1,t.stepsTotal+=1}else{if(!h.run)throw new ue(_e("FATAL: archived Classic state is missing its Run projection"));t.stderr.push(He(` [OK] OpenSpec archive completed: ${u}`)),t.stepsOk+=1,t.stepsTotal+=1,t.stderr.push(He(" [OK] Main specs verified clean")),t.stepsOk+=1,t.stepsTotal+=1,t.stderr.push(He(" [OK] archived: true")),t.stepsOk+=1,t.stepsTotal+=1}return i?(y&&await qo(t,s.projectRoot,y,f,"status: final",!0),w&&await qo(t,s.projectRoot,w,f,"",!0),t.stderr.push(Sr(` [DRY-RUN] Would set archived: true in ${u}/.comet.yaml`)),t.stepsOk+=1,t.stepsTotal+=1,t.stderr.push(Sr(" [DRY-RUN] Would verify final archive integrity")),t.stepsOk+=1,t.stepsTotal+=1):(await ZS(s.projectRoot,u),t.stderr.push(He(" [OK] Final archive integrity verified")),t.stepsOk+=1,t.stepsTotal+=1),i||await eh(s.projectRoot,n),t.stderr.push(""),t.stderr.push(i?Sr(`Dry run complete. ${t.stepsOk}/${t.stepsTotal} steps would succeed.`):He(`Archive complete. ${t.stepsOk}/${t.stepsTotal} steps succeeded.`)),t.toResult(t.stepsOkMath.max(o,a.sequence),0)+1,timestamp:new Date().toISOString(),runId:n.runId,scope:i.scope,command:i.command,exitCode:i.exitCode,cwd:sh(e,i.cwd)};return await We(t,n.trajectoryRef,{sequence:s.sequence,timestamp:s.timestamp,type:"command_check_recorded",runId:s.runId,data:{scope:s.scope,command:s.command,exitCode:s.exitCode,cwd:s.cwd}}),s}async function ah(e,t,n,i){rh(i);let r=await Le(t,n.trajectoryRef);for(let s=r.length-1;s>=0;s-=1){let o=r[s];if(o.runId!==n.runId)continue;let a=iE(e,o);if(a?.scope===i)return a}return null}var ch={"full.open":["openspec.proposal","openspec.tasks"],"full.design.handoff":["openspec.proposal","openspec.design","openspec.tasks"],"full.design.document":["design.handoff"],"full.build.plan":["openspec.tasks"],"full.build.plan-ready":["build.plan"],"full.build.configure":["build.plan"],"full.build.execute":["build.plan"],"full.build.complete":["build.tasks-complete"],"full.verify.run":["build.tasks-complete"],"full.verify.branch":["verification.report"],"full.archive.confirm":["verification.report"],"full.archive.execute":["archive.confirmed"]};function rE(e){return ch[e]?ch[e]:e.endsWith(".open")?["openspec.proposal","openspec.tasks"]:e.endsWith(".build.execute")?[]:e.endsWith(".build.complete")?["build.tasks-complete"]:e.endsWith(".verify.run")?["build.tasks-complete"]:e.endsWith(".verify.branch")?["verification.report"]:e.endsWith(".archive.confirm")?["verification.report"]:e.endsWith(".archive.execute")?["archive.confirmed"]:[]}function lh(e,t){let n=rE(e),i=n.filter(r=>!$n(t,r));return{stepId:e,passed:i.length===0,requiredEvidence:n,missingEvidence:i}}function sE(e){switch(e){case"open":return"/comet-open";case"design":return"/comet-design";case"build":return"/comet-build";case"verify":return"/comet-verify";case"archive":return"/comet-archive";default:return null}}async function uh(e,t){try{let n=await qp(e),i=await Ge(e,{classic:n.classic,run:n.run,unknownKeys:[]}),r=Et(n.classic,i);return{name:t,valid:!0,workflow:n.classic.workflow,phase:n.classic.phase,currentStep:r,nextCommand:sE(n.classic.phase),runtimeMode:"engine-projection",runtimeEval:lh(r,i),evidence:i}}catch(n){return{name:t,valid:!1,workflow:"unknown",phase:"invalid",currentStep:null,nextCommand:null,runtimeMode:"invalid",runtimeEval:null,evidence:[],error:n instanceof Error?n.message:String(n)}}}var Pr=rt(Ue(),1);import dh from"path";import{AsyncLocalStorage as oE}from"async_hooks";import{promises as fh}from"fs";import Rr from"path";var Fo=new oE;function aE(e,t){let n=Rr.relative(e,t);return n===""||!Rr.isAbsolute(n)&&n!==".."&&!n.startsWith(`..${Rr.sep}`)}async function cE(e){let t=Rr.resolve(e.invocationCwd??process.cwd()),n=Rr.resolve(e.projectRoot??await le(t)),[i,r]=await Promise.all([fh.realpath(t),fh.realpath(n)]);if(!aE(r,i))throw new Error(`Classic command invocation cwd is outside the discovered project: ${t}`);return{invocationCwd:t,projectRoot:n}}async function dt(e,t){let n=Fo.getStore();if(n)return t(n);let i=await cE(e);return Fo.run(i,()=>t(i))}function x(){let e=Fo.getStore();if(!e)throw new Error("Classic command project context is unavailable");return e.projectRoot}function Ot(){let e=Fo.getStore();if(!e)throw new Error("Classic command invocation context is unavailable");return e.invocationCwd}var lE="\x1B[32m",_r="\x1B[31m",uE="\x1B[33m",fE="\x1B[0m",dE=["workflow","phase","design_doc","plan","build_mode","isolation","verify_mode","verify_result","verified_at","archived"],mE={workflow:["full","hotfix","tweak"],language:["en","zh-CN"],phase:["open","design","build","verify","archive"],context_compression:["off","beta"],build_mode:["subagent-driven-development","executing-plans","direct"],build_pause:["plan-ready"],subagent_dispatch:["confirmed"],tdd_mode:["tdd","direct"],review_mode:["off","standard","thorough"],isolation:["current","branch","worktree"],verify_mode:["light","full"],auto_transition:["true","false"],verify_result:["pending","pass","fail"],branch_status:["pending","handled"],archive_confirmation:["pending","confirmed"],archived:["true","false"],direct_override:["true","false"],classic_profile:["full","hotfix","tweak"],classic_migration:["1"]},pE=new Set([...rn,...hr,"classic_profile","classic_migration"]);function Nn(e,t){return`${e}${t}${fE}`}function xr(e){return e==null?"":typeof e=="object"?JSON.stringify(e):String(e)}var Wo=async(e,t)=>dt(t,async()=>{let n=e[0],i=ge(n);if(i)return{exitCode:1,stderr:Nn(_r,`ERROR: ${i}`)};let r=x(),{directory:s,label:o}=await ii(n,r),a=dh.join(s,".comet.yaml"),c=[`[VALIDATE] ${o}/.comet.yaml`],l=0,f=0,u=m=>{l+=1,c.push(Nn(_r,` FAIL: ${m}`))},d=m=>{f+=1,c.push(Nn(uE,` WARN: ${m}`))},p;try{p=await W(r,a,{label:`Classic state ${o}/.comet.yaml`})}catch(m){if(m.code==="ENOENT")return u(".comet.yaml does not exist"),c.push("",Nn(_r,`${l} error(s), ${f} warning(s) — validation FAILED`)),{exitCode:1,stderr:c.join(` +`)}}if(i)throw new ue("")}var sh=async e=>{let t=new ql,n=e[0],i=e[1]==="--dry-run";try{GS(n);let r=await le(process.cwd()),s=await Ee(r),o=await Ge(n,s.projectRoot),a=o.directory,c=A(s.projectRoot,a),f=`${new Date().toISOString().slice(0,10)}-${n}`,u=dt.join(s.archiveDir,f);t.stderr.push(`=== Comet Archive: ${n} ===`);let d=o.stateExists,p=d?null:await uo(n,s.projectRoot),g=d?a:p?.directory;if(!g||!await X(s.projectRoot,`${g}/.comet.yaml`,{label:`Classic change ${n} state`,expected:"file"}))throw new ue(_e(`FATAL: .comet.yaml not found in ${c}/`));p&&(u=p.directory,f=dt.basename(p.directory));let h=await B(g);if(!h.classic)throw new ue(_e("FATAL: archive requires Classic state"));let m=h.classic,y=m.designDoc,w=m.plan;if(m.phase!=="archive")throw new ue(_e(`FATAL: phase is '${m.phase}', expected 'archive'`));if(m.verifyResult!=="pass")throw new ue(_e(`FATAL: verify_result is '${m.verifyResult}', expected 'pass'. Run comet-verify first.`));t.stderr.push(He(" [OK] Entry state verified")),t.stepsOk+=1,t.stepsTotal+=1;let C=await Y(s.projectRoot,u,{label:`Classic archive target ${f}`,expected:"directory"});if(d&&C.exists)throw new ue(_e(`FATAL: archive target already exists: ${u}`));if(t.stderr.push(He(" [OK] Archive target available")),t.stepsOk+=1,t.stepsTotal+=1,i)t.stderr.push(Sr(` [DRY-RUN] Would run OpenSpec archive: ${n}`)),t.stepsOk+=1,t.stepsTotal+=1;else if(!m.archived||h.run?.pending){await Pn(s.projectRoot,`${g}/.comet`,"Classic change runtime directory");let k=await an(g),E=`classic-archive:${n}`,R=await yr(g,k.run.pendingRef),O=!!p||R?.id===E&&R.type==="checkpoint"&&R.ref===n;if(k.run.pending&&k.run.pending!==E)throw new ue(_e(`FATAL: another action is pending: ${k.run.pending}`));if(!O&&!m.archived&&m.archiveConfirmation!=="confirmed")throw new ue(_e(`FATAL: archive_confirmation is '${m.archiveConfirmation??"null"}', expected 'confirmed'. Run final archive confirmation first.`));if(!O){let mn={id:E,stepId:k.run.currentStep,type:"checkpoint",ref:n};await Ro(g,k.run.pendingRef,mn),await je(g,{classic:k.classic,run:{...k.run,pending:E,status:"waiting"},unknownKeys:(await B(g)).unknownKeys})}if(!p){let mn=await hl(["archive",n,"--yes"],s.projectRoot);if(t.captureOpenSpec(mn),mn.exitCode!==0)throw new ue("",mn.exitCode)}let b=await uo(n,s.projectRoot,{preferredArchiveName:f});if(!b&&!p&&(b=await uo(n,s.projectRoot,{skipExactCompatibility:!0})),!b)return t.stderr.push(_e(" [FAIL] OpenSpec archive output not found")),t.stepsTotal+=1,t.stderr.push(""),t.stderr.push(He(`Archive complete. ${t.stepsOk}/${t.stepsTotal} steps succeeded.`)),t.toResult(1);u=b.directory,f=dt.basename(b.directory),t.stderr.push(He(` [OK] OpenSpec archive completed: ${u}`)),t.stepsOk+=1,t.stepsTotal+=1,await nE(s.projectRoot,s.specsDir),t.stderr.push(He(" [OK] Main specs verified clean")),t.stepsOk+=1,t.stepsTotal+=1,y&&await qo(t,s.projectRoot,y,f,"status: final",!1),w&&await qo(t,s.projectRoot,w,f,"",!1);let L=await B(u);if(!L.classic||!L.run)throw new ue(_e(" [FAIL] archived state projection is incomplete"));let Ie={...QS(s.projectRoot,a,u,await oi(u,L.run.artifactsRef)),archive_directory:A(s.projectRoot,u)};await ai(u,L.run.artifactsRef,Ie);let Q=ui(O&&L.classic.archiveConfirmation!=="confirmed"?{...L.classic,archiveConfirmation:"confirmed"}:L.classic,"archived"),K={...Q.classic,designDoc:Er(s.projectRoot,a,u,Q.classic.designDoc),plan:Er(s.projectRoot,a,u,Q.classic.plan),verificationReport:Er(s.projectRoot,a,u,Q.classic.verificationReport),handoffContext:Er(s.projectRoot,a,u,Q.classic.handoffContext)},Ce=L.run;(L.run.currentStep!=="completed"||L.run.status!=="completed")&&(Ce=await cn(u,K,L.run,{actionId:E,archiveDirectory:A(s.projectRoot,u),event:"archived",source:"comet-archive"})),O&&await tE(u,Ce,E);let Hr=await Le(u,Ce.trajectoryRef),da=await Eo(u,Ce.contextRef),yt={runId:Ce.runId,stateVersion:Ce.iteration,trajectoryOffset:Hr.length,contextHash:da===null?null:rh(da),artifactsHash:zS(Ie),createdAt:new Date().toISOString()};await ci(u,Ce.checkpointRef,yt);let Kr={...Ce,pending:null,status:"completed"};await je(u,{classic:K,run:Kr,unknownKeys:L.unknownKeys}),await An(u,{change:f,event:"archived",source:"comet-archive",from:L.classic,to:K,effects:Q.effects}),await _o(u,Kr.pendingRef),t.stderr.push(He(" [OK] archived: true")),t.stepsOk+=1,t.stepsTotal+=1}else{if(!h.run)throw new ue(_e("FATAL: archived Classic state is missing its Run projection"));t.stderr.push(He(` [OK] OpenSpec archive completed: ${u}`)),t.stepsOk+=1,t.stepsTotal+=1,t.stderr.push(He(" [OK] Main specs verified clean")),t.stepsOk+=1,t.stepsTotal+=1,t.stderr.push(He(" [OK] archived: true")),t.stepsOk+=1,t.stepsTotal+=1}return i?(y&&await qo(t,s.projectRoot,y,f,"status: final",!0),w&&await qo(t,s.projectRoot,w,f,"",!0),t.stderr.push(Sr(` [DRY-RUN] Would set archived: true in ${u}/.comet.yaml`)),t.stepsOk+=1,t.stepsTotal+=1,t.stderr.push(Sr(" [DRY-RUN] Would verify final archive integrity")),t.stepsOk+=1,t.stepsTotal+=1):(await ZS(s.projectRoot,u),t.stderr.push(He(" [OK] Final archive integrity verified")),t.stepsOk+=1,t.stepsTotal+=1),i||await nh(s.projectRoot,n),t.stderr.push(""),t.stderr.push(i?Sr(`Dry run complete. ${t.stepsOk}/${t.stepsTotal} steps would succeed.`):He(`Archive complete. ${t.stepsOk}/${t.stepsTotal} steps succeeded.`)),t.toResult(t.stepsOkMath.max(o,a.sequence),0)+1,timestamp:new Date().toISOString(),runId:n.runId,scope:i.scope,command:i.command,exitCode:i.exitCode,cwd:ah(e,i.cwd)};return await We(t,n.trajectoryRef,{sequence:s.sequence,timestamp:s.timestamp,type:"command_check_recorded",runId:s.runId,data:{scope:s.scope,command:s.command,exitCode:s.exitCode,cwd:s.cwd}}),s}async function lh(e,t,n,i){oh(i);let r=await Le(t,n.trajectoryRef);for(let s=r.length-1;s>=0;s-=1){let o=r[s];if(o.runId!==n.runId)continue;let a=iE(e,o);if(a?.scope===i)return a}return null}var uh={"full.open":["openspec.proposal","openspec.tasks"],"full.design.handoff":["openspec.proposal","openspec.design","openspec.tasks"],"full.design.document":["design.handoff"],"full.build.plan":["openspec.tasks"],"full.build.plan-ready":["build.plan"],"full.build.configure":["build.plan"],"full.build.execute":["build.plan"],"full.build.complete":["build.tasks-complete"],"full.verify.run":["build.tasks-complete"],"full.verify.branch":["verification.report"],"full.archive.confirm":["verification.report"],"full.archive.execute":["archive.confirmed"]};function rE(e){return uh[e]?uh[e]:e.endsWith(".open")?["openspec.proposal","openspec.tasks"]:e.endsWith(".build.execute")?[]:e.endsWith(".build.complete")?["build.tasks-complete"]:e.endsWith(".verify.run")?["build.tasks-complete"]:e.endsWith(".verify.branch")?["verification.report"]:e.endsWith(".archive.confirm")?["verification.report"]:e.endsWith(".archive.execute")?["archive.confirmed"]:[]}function fh(e,t){let n=rE(e),i=n.filter(r=>!$n(t,r));return{stepId:e,passed:i.length===0,requiredEvidence:n,missingEvidence:i}}function sE(e){switch(e){case"open":return"/comet-open";case"design":return"/comet-design";case"build":return"/comet-build";case"verify":return"/comet-verify";case"archive":return"/comet-archive";default:return null}}async function dh(e,t){try{let n=await Fp(e),i=await ze(e,{classic:n.classic,run:n.run,unknownKeys:[]}),r=Et(n.classic,i);return{name:t,valid:!0,workflow:n.classic.workflow,phase:n.classic.phase,currentStep:r,nextCommand:sE(n.classic.phase),runtimeMode:"engine-projection",runtimeEval:fh(r,i),evidence:i}}catch(n){return{name:t,valid:!1,workflow:"unknown",phase:"invalid",currentStep:null,nextCommand:null,runtimeMode:"invalid",runtimeEval:null,evidence:[],error:n instanceof Error?n.message:String(n)}}}var Pr=st(Ue(),1);import ph from"path";import{AsyncLocalStorage as oE}from"async_hooks";import{promises as mh}from"fs";import Rr from"path";var Fo=new oE;function aE(e,t){let n=Rr.relative(e,t);return n===""||!Rr.isAbsolute(n)&&n!==".."&&!n.startsWith(`..${Rr.sep}`)}async function cE(e){let t=Rr.resolve(e.invocationCwd??process.cwd()),n=Rr.resolve(e.projectRoot??await le(t)),[i,r]=await Promise.all([mh.realpath(t),mh.realpath(n)]);if(!aE(r,i))throw new Error(`Classic command invocation cwd is outside the discovered project: ${t}`);return{invocationCwd:t,projectRoot:n}}async function mt(e,t){let n=Fo.getStore();if(n)return t(n);let i=await cE(e);return Fo.run(i,()=>t(i))}function x(){let e=Fo.getStore();if(!e)throw new Error("Classic command project context is unavailable");return e.projectRoot}function Ot(){let e=Fo.getStore();if(!e)throw new Error("Classic command invocation context is unavailable");return e.invocationCwd}var lE="\x1B[32m",_r="\x1B[31m",uE="\x1B[33m",fE="\x1B[0m",dE=["workflow","phase","design_doc","plan","build_mode","isolation","verify_mode","verify_result","verified_at","archived"],mE={workflow:["full","hotfix","tweak"],language:["en","zh-CN"],phase:["open","design","build","verify","archive"],context_compression:["off","beta"],build_mode:["subagent-driven-development","executing-plans","direct"],build_pause:["plan-ready"],subagent_dispatch:["confirmed"],tdd_mode:["tdd","direct"],review_mode:["off","standard","thorough"],isolation:["current","branch","worktree"],verify_mode:["light","full"],auto_transition:["true","false"],verify_result:["pending","pass","fail"],branch_status:["pending","handled"],archive_confirmation:["pending","confirmed"],archived:["true","false"],direct_override:["true","false"],classic_profile:["full","hotfix","tweak"],classic_migration:["1"]},pE=new Set([...rn,...hr,"classic_profile","classic_migration"]);function Nn(e,t){return`${e}${t}${fE}`}function xr(e){return e==null?"":typeof e=="object"?JSON.stringify(e):String(e)}var Wo=async(e,t)=>mt(t,async()=>{let n=e[0],i=ge(n);if(i)return{exitCode:1,stderr:Nn(_r,`ERROR: ${i}`)};let r=x(),{directory:s,label:o}=await ii(n,r),a=ph.join(s,".comet.yaml"),c=[`[VALIDATE] ${o}/.comet.yaml`],l=0,f=0,u=m=>{l+=1,c.push(Nn(_r,` FAIL: ${m}`))},d=m=>{f+=1,c.push(Nn(uE,` WARN: ${m}`))},p;try{p=await W(r,a,{label:`Classic state ${o}/.comet.yaml`})}catch(m){if(m.code==="ENOENT")return u(".comet.yaml does not exist"),c.push("",Nn(_r,`${l} error(s), ${f} warning(s) — validation FAILED`)),{exitCode:1,stderr:c.join(` `)};throw m}let g=(0,Pr.parseDocument)(p);if(g.errors.length>0||!(0,Pr.isMap)(g.contents)){for(let m of g.errors)u(m.message);return(0,Pr.isMap)(g.contents)||u("document root must be a mapping"),c.push("",Nn(_r,`${l} error(s), ${f} warning(s) — validation FAILED`)),{exitCode:1,stderr:c.join(` -`)}}let h=g.toJS();for(let m of dE)Object.prototype.hasOwnProperty.call(h,m)||u(`missing required field '${m}'`);for(let[m,y]of Object.entries(mE)){if(!Object.prototype.hasOwnProperty.call(h,m))continue;let w=xr(h[m]);if(!w){m==="auto_transition"&&u(`${m}='' is not valid. Expected: ${y.join(" ")}`);continue}y.includes(w)||u(`${m}='${w}' is not valid. Expected: ${y.join(" ")}`)}if(Object.prototype.hasOwnProperty.call(h,"bound_branch")){let m=h.bound_branch;m!==null&&typeof m!="string"&&u(`bound_branch='${xr(m)}' is not a string or null`)}if(Object.prototype.hasOwnProperty.call(h,"verify_failures")){let m=h.verify_failures;(typeof m!="number"||!Number.isInteger(m)||m<0)&&u(`verify_failures='${xr(m)}' is not a non-negative integer`)}for(let m of["design_doc","plan","handoff_context","verification_report"]){let y=xr(h[m]);if(y){if(/^(?:[A-Za-z]:|[\\/]|~)/u.test(y)||y.split(/[\\/]/u).includes("..")){u(`${m}='${y}' must be a relative repository path`);continue}try{await X(r,dh.resolve(r,y),{label:`${m} artifact pointer`,expected:"file"})||u(`${m}='${y}' does not exist on disk`)}catch(w){u(`${m}='${y}' is unsafe: ${w instanceof Error?w.message:String(w)}`)}}}for(let m of["handoff_hash"]){let y=xr(h[m]);y&&!/^[a-f0-9]{64}$/u.test(y)&&u(`${m}='${y}' is not a sha256 hex digest`)}for(let m of Object.keys(h))pE.has(m)||d(`unknown field '${m}' found`);return c.push(""),l>0?(c.push(Nn(_r,`${l} error(s), ${f} warning(s) — validation FAILED`)),{exitCode:1,stderr:c.join(` +`)}}let h=g.toJS();for(let m of dE)Object.prototype.hasOwnProperty.call(h,m)||u(`missing required field '${m}'`);for(let[m,y]of Object.entries(mE)){if(!Object.prototype.hasOwnProperty.call(h,m))continue;let w=xr(h[m]);if(!w){m==="auto_transition"&&u(`${m}='' is not valid. Expected: ${y.join(" ")}`);continue}y.includes(w)||u(`${m}='${w}' is not valid. Expected: ${y.join(" ")}`)}if(Object.prototype.hasOwnProperty.call(h,"bound_branch")){let m=h.bound_branch;m!==null&&typeof m!="string"&&u(`bound_branch='${xr(m)}' is not a string or null`)}if(Object.prototype.hasOwnProperty.call(h,"verify_failures")){let m=h.verify_failures;(typeof m!="number"||!Number.isInteger(m)||m<0)&&u(`verify_failures='${xr(m)}' is not a non-negative integer`)}for(let m of["design_doc","plan","handoff_context","verification_report"]){let y=xr(h[m]);if(y){if(/^(?:[A-Za-z]:|[\\/]|~)/u.test(y)||y.split(/[\\/]/u).includes("..")){u(`${m}='${y}' must be a relative repository path`);continue}try{await X(r,ph.resolve(r,y),{label:`${m} artifact pointer`,expected:"file"})||u(`${m}='${y}' does not exist on disk`)}catch(w){u(`${m}='${y}' is unsafe: ${w instanceof Error?w.message:String(w)}`)}}}for(let m of["handoff_hash"]){let y=xr(h[m]);y&&!/^[a-f0-9]{64}$/u.test(y)&&u(`${m}='${y}' is not a sha256 hex digest`)}for(let m of Object.keys(h))pE.has(m)||d(`unknown field '${m}' found`);return c.push(""),l>0?(c.push(Nn(_r,`${l} error(s), ${f} warning(s) — validation FAILED`)),{exitCode:1,stderr:c.join(` `)}):(c.push(Nn(lE,`0 errors, ${f} warning(s) — validation PASSED`)),{exitCode:0,stderr:c.join(` -`)})});yl();Ct();import hE from"os";import Bo from"path";function gE(e={}){let t=e.cwd??process.cwd(),n=e.homeDir??hE.homedir(),i=[{file:Bo.resolve(t,".comet","config.yaml"),source:".comet/config.yaml",scope:"project"},{file:Bo.resolve(n,".comet","config.yaml"),source:"~/.comet/config.yaml",scope:"global"}];return i.filter((r,s)=>i.findIndex(o=>o.file===r.file)===s)}async function Or(e,t={}){for(let n of gE(t)){let i=Bo.dirname(Bo.dirname(n.file)),r=n.scope==="global"?(await wl(i))?.classic:(await lt(i,{allowPartialProject:!0}))?.value.classic;if(!r||typeof r!="object"||Array.isArray(r))continue;let s=r[e];if(s!=null)return{value:String(s),source:n.source}}return null}Ct();var vE="\x1B[32m",bE="\x1B[31m",CE="\x1B[33m",Hl="\x1B[0m",kE=["open","design","build","verify","archive"],SE={open:"=== Guard: open → next ===",design:"=== Guard: design → build ===",build:"=== Guard: build → verify ===",verify:"=== Guard: verify → archive ===",archive:"=== Guard: archive completeness ==="},EE={open:" [APPLY] .comet.yaml updated: phase=PLACEHOLDER",design:" [APPLY] .comet.yaml updated: phase=build",build:" [APPLY] .comet.yaml updated: phase=verify, verify_result=pending",verify:" [APPLY] .comet.yaml updated: phase=archive, verify_result=pass"},RE={branchStatus:"branch_status",phase:"phase",verificationReport:"verification_report",verifiedAt:"verified_at",verifyResult:"verify_result"};function fi(e){return`${vE}${e}${Hl}`}function $t(e){return`${bE}${e}${Hl}`}function _E(e){return`${CE}${e}${Hl}`}function xE(e){return RE[e]??String(e)}function PE(e){return e===null?"null":e===void 0?"":typeof e=="object"?JSON.stringify(e):String(e)}var Qe=class extends Error{constructor(n,i=1){super(n);this.exitCode=i}exitCode},Bl=class{stderr=[];diagnostics;toResult(t=0){return{exitCode:t,...this.diagnostics?{stdout:JSON.stringify({diagnostics:this.diagnostics})+` +`)})});yl();kt();import hE from"os";import Bo from"path";function gE(e={}){let t=e.cwd??process.cwd(),n=e.homeDir??hE.homedir(),i=[{file:Bo.resolve(t,".comet","config.yaml"),source:".comet/config.yaml",scope:"project"},{file:Bo.resolve(n,".comet","config.yaml"),source:"~/.comet/config.yaml",scope:"global"}];return i.filter((r,s)=>i.findIndex(o=>o.file===r.file)===s)}async function Or(e,t={}){for(let n of gE(t)){let i=Bo.dirname(Bo.dirname(n.file)),r=n.scope==="global"?(await wl(i))?.classic:(await ut(i,{allowPartialProject:!0}))?.value.classic;if(!r||typeof r!="object"||Array.isArray(r))continue;let s=r[e];if(s!=null)return{value:String(s),source:n.source}}return null}kt();var vE="\x1B[32m",bE="\x1B[31m",CE="\x1B[33m",Hl="\x1B[0m",kE=["open","design","build","verify","archive"],SE={open:"=== Guard: open → next ===",design:"=== Guard: design → build ===",build:"=== Guard: build → verify ===",verify:"=== Guard: verify → archive ===",archive:"=== Guard: archive completeness ==="},EE={open:" [APPLY] .comet.yaml updated: phase=PLACEHOLDER",design:" [APPLY] .comet.yaml updated: phase=build",build:" [APPLY] .comet.yaml updated: phase=verify, verify_result=pending",verify:" [APPLY] .comet.yaml updated: phase=archive, verify_result=pass"},RE={branchStatus:"branch_status",phase:"phase",verificationReport:"verification_report",verifiedAt:"verified_at",verifyResult:"verify_result"};function fi(e){return`${vE}${e}${Hl}`}function $t(e){return`${bE}${e}${Hl}`}function _E(e){return`${CE}${e}${Hl}`}function xE(e){return RE[e]??String(e)}function PE(e){return e===null?"null":e===void 0?"":typeof e=="object"?JSON.stringify(e):String(e)}var Ze=class extends Error{constructor(n,i=1){super(n);this.exitCode=i}exitCode},Bl=class{stderr=[];diagnostics;toResult(t=0){return{exitCode:t,...this.diagnostics?{stdout:JSON.stringify({diagnostics:this.diagnostics})+` `}:{},...this.stderr.length>0?{stderr:this.stderr.join(` `)+` -`}:{}}}};async function se(e){let t=x();return X(t,e,{label:`Classic guard path ${J.relative(t,J.resolve(t,e)).replaceAll("\\","/")}`})}async function fe(e){let t=x();return xn(t,e,`Classic guard file ${J.relative(t,J.resolve(t,e)).replaceAll("\\","/")}`)}function OE(e){let t=ge(e);if(t)throw new Qe($t(`ERROR: ${t}`))}async function $E(e){return(await ii(e,x())).directory}async function H(e,t){let n=J.join(e,".comet.yaml"),i=(0,hh.parseDocument)(await W(x(),n,{label:`Classic state ${e}/.comet.yaml`}),{uniqueKeys:!1});if(i.errors.length>0)throw new Qe(`ERROR: Invalid .comet.yaml: ${i.errors[0].message}`);let s=i.toJS()[t];return s==null?"":typeof s=="object"?JSON.stringify(s):String(s)}async function IE(e,t){let n=await H(t,e);return n&&n!=="null"?n:(await Or(e,{cwd:x()}))?.value??""}async function AE(e){let t=await IE("language",e);if(!t)return"en";if(t==="en"||t==="zh-CN")return t;throw new Error(`configured language '${t}' is invalid; expected en or zh-CN.`)}function NE(e){let t=[],n=!1;for(let i of e.split(/\r?\n/u)){if(/^\s*```/u.test(i)){n=!n;continue}n||t.push(i)}return t.join(` -`)}function TE(e){return e.match(/[\u4e00-\u9fff]/gu)?.length??0}function jE(e){return e.match(/[A-Za-z][A-Za-z0-9_-]{2,}/gu)?.length??0}async function mt(e,t){let n=await AE(e),i=NE(await W(x(),t,{label:`Classic language-check artifact ${t}`})),r=TE(i),s=jE(i);return n==="zh-CN"&&r<20&&s>=20?P(`configured language is zh-CN, but ${t} appears to be English-dominant (cjk_chars=${r}, english_words=${s}). +`}:{}}}};async function se(e){let t=x();return X(t,e,{label:`Classic guard path ${J.relative(t,J.resolve(t,e)).replaceAll("\\","/")}`})}async function fe(e){let t=x();return xn(t,e,`Classic guard file ${J.relative(t,J.resolve(t,e)).replaceAll("\\","/")}`)}function OE(e){let t=ge(e);if(t)throw new Ze($t(`ERROR: ${t}`))}async function $E(e){return(await ii(e,x())).directory}async function H(e,t){let n=J.join(e,".comet.yaml"),i=(0,wh.parseDocument)(await W(x(),n,{label:`Classic state ${e}/.comet.yaml`}),{uniqueKeys:!1});if(i.errors.length>0)throw new Ze(`ERROR: Invalid .comet.yaml: ${i.errors[0].message}`);let s=i.toJS()[t];return s==null?"":typeof s=="object"?JSON.stringify(s):String(s)}async function IE(e,t){let n=await H(t,e);return n&&n!=="null"?n:(await Or(e,{cwd:x()}))?.value??""}async function AE(e){let t=await IE("language",e);if(!t)return"en";if(t==="en"||t==="zh-CN")return t;throw new Error(`configured language '${t}' is invalid; expected en or zh-CN.`)}function NE(e){let t=[],n=!1;for(let i of e.split(/\r?\n/u)){if(/^\s*```/u.test(i)){n=!n;continue}n||t.push(i)}return t.join(` +`)}function TE(e){return e.match(/[\u4e00-\u9fff]/gu)?.length??0}function jE(e){return e.match(/[A-Za-z][A-Za-z0-9_-]{2,}/gu)?.length??0}async function pt(e,t){let n=await AE(e),i=NE(await W(x(),t,{label:`Classic language-check artifact ${t}`})),r=TE(i),s=jE(i);return n==="zh-CN"&&r<20&&s>=20?P(`configured language is zh-CN, but ${t} appears to be English-dominant (cjk_chars=${r}, english_words=${s}). Next: regenerate or rewrite this artifact in Chinese while preserving necessary technical terms.`):n==="en"&&r>20&&r>s?P(`configured language is en, but ${t} appears to be Chinese-dominant (cjk_chars=${r}, english_words=${s}). -Next: regenerate or rewrite this artifact in English while preserving necessary technical terms.`):N()}async function gh(e){return ph("sha256").update(await lo(x(),e,{label:`Classic handoff source ${e}`})).digest("hex")}async function Kl(e){let t=A(x(),e),n=[`${t}/proposal.md`,`${t}/design.md`,`${t}/tasks.md`],i=`${t}/specs`;if(await se(i)){await Y(x(),i,{label:`Classic delta-spec directory ${i}`,expected:"directory"});for(let r of(await yE.readdir(i)).sort()){let s=`${i}/${r}/spec.md`;await se(s)&&n.push(s)}}return n}async function LE(e){let t=[];for(let n of await Kl(e))await se(n)&&t.push(`path:${n}`,`sha256:${await gh(n)}`);return ph("sha256").update(t.join(` -`)).digest("hex")}async function ME(e,t){if(!await se(e))throw new Qe($t(`FATAL: change directory not found: ${e}`));if(!await se(J.join(e,".comet.yaml")))throw new Qe($t(`FATAL: .comet.yaml not found in ${e}`));await Y(x(),J.join(e,".comet"),{label:`Classic runtime directory for ${t}`,expected:"directory"});let n=await Wo([t],{json:!1});if(n.exitCode!==0)throw n.stderr&&process.stderr.write(n.stderr.endsWith(` +Next: regenerate or rewrite this artifact in English while preserving necessary technical terms.`):N()}async function yh(e){return gh("sha256").update(await lo(x(),e,{label:`Classic handoff source ${e}`})).digest("hex")}async function Kl(e){let t=A(x(),e),n=[`${t}/proposal.md`,`${t}/design.md`,`${t}/tasks.md`],i=`${t}/specs`;if(await se(i)){await Y(x(),i,{label:`Classic delta-spec directory ${i}`,expected:"directory"});for(let r of(await yE.readdir(i)).sort()){let s=`${i}/${r}/spec.md`;await se(s)&&n.push(s)}}return n}async function LE(e){let t=[];for(let n of await Kl(e))await se(n)&&t.push(`path:${n}`,`sha256:${await yh(n)}`);return gh("sha256").update(t.join(` +`)).digest("hex")}async function ME(e,t){if(!await se(e))throw new Ze($t(`FATAL: change directory not found: ${e}`));if(!await se(J.join(e,".comet.yaml")))throw new Ze($t(`FATAL: .comet.yaml not found in ${e}`));await Y(x(),J.join(e,".comet"),{label:`Classic runtime directory for ${t}`,expected:"directory"});let n=await Wo([t],{json:!1});if(n.exitCode!==0)throw n.stderr&&process.stderr.write(n.stderr.endsWith(` `)?n.stderr:`${n.stderr} -`),new Qe($t("FATAL: .comet.yaml schema validation failed"));let i=await B(e),r=Array.from(new Set(i.unknownKeys)).sort();if(r.length>0)throw new Qe($t(`FATAL: .comet.yaml has unknown field(s): ${r.join(", ")}`))}function qE(e,t){if(t.passed){if(e.stderr.push(fi(` [PASS] ${t.description}`)),t.detail)for(let n of t.detail.split(` +`),new Ze($t("FATAL: .comet.yaml schema validation failed"));let i=await B(e),r=Array.from(new Set(i.unknownKeys)).sort();if(r.length>0)throw new Ze($t(`FATAL: .comet.yaml has unknown field(s): ${r.join(", ")}`))}function qE(e,t){if(t.passed){if(e.stderr.push(fi(` [PASS] ${t.description}`)),t.detail)for(let n of t.detail.split(` `))e.stderr.push(fi(` ${n}`))}else if(e.stderr.push($t(` [FAIL] ${t.description}`)),t.detail)for(let n of t.detail.split(` -`))e.stderr.push($t(` ${n}`))}function I(e,t){return async()=>{try{let n=await t();return{description:e,passed:n.passed,detail:("detail"in n?n.detail:"")??""}}catch(n){return{description:e,passed:!1,detail:n instanceof Error?n.message:String(n)}}}}function N(e){return{passed:!0,...e?{detail:e}:{}}}function P(e){return{passed:!1,detail:e}}async function di(e,t){let n=!1;for(let i of t){let r=await i();qE(e,r),r.passed||(n=!0)}return n}var DE=["package.json with a build script","pom.xml","Cargo.toml"];async function FE(e){try{let t=await lt(x(),{allowPartialProject:!0});return t?Object.prototype.hasOwnProperty.call(t.value,e):!1}catch(t){throw new Error(`.comet/config.yaml is invalid YAML (${t instanceof Error?t.message:String(t)}); cannot check for removed "${e}" field. Fix the config and retry.`,{cause:t})}}function WE(e){return{status:1,output:`${e} has been removed from .comet/config.yaml. Delete this field and run any required ${e==="build_command"?"build":"verification"} command manually before retrying.`}}function BE(e){let t=wE(e,{shell:!0,cwd:Ot(),encoding:"utf8",timeout:3e5});return{status:t.status??1,output:`${t.stdout??""}${t.stderr??""}`.replace(/\n+$/u,"")}}function $r(e){return J.resolve(Ot(),e)}async function HE(){let e=$r("package.json");return await se(e)&&typeof JSON.parse(await W(x(),e,{label:"package.json"})).scripts?.build=="string"?"npm run build":await se($r("pom.xml"))?process.platform==="win32"?await se($r("mvnw.cmd"))?"mvnw.cmd compile -q":"mvn.cmd compile -q":await se($r("mvnw"))?"./mvnw compile -q":"mvn compile -q":await se($r("Cargo.toml"))?"cargo build":null}function mh(e){return`Evidence: recorded command-check at ${e.timestamp}; command: ${e.command}; cwd: ${e.cwd}`}function Fl(e,t,n){return`comet state record-check ${e} ${t} --command "${n}" --exit-code 0`}async function wh(e,t,n,i){if(process.env.COMET_SKIP_BUILD==="1")return{status:0,output:"SKIPPED via COMET_SKIP_BUILD=1"};let r=i==="build"?["build_command"]:["verify_command","build_command"];for(let a of r)if(await FE(a))return WE(a);let s=i==="build"?await HE():null;if(s)return BE(s);let o=await ah(x(),e,n,i);return o?o.exitCode!==0?{status:o.exitCode,output:`Latest recorded ${i} check failed with exit code ${o.exitCode}. -${mh(o)} +`))e.stderr.push($t(` ${n}`))}function I(e,t){return async()=>{try{let n=await t();return{description:e,passed:n.passed,detail:("detail"in n?n.detail:"")??""}}catch(n){return{description:e,passed:!1,detail:n instanceof Error?n.message:String(n)}}}}function N(e){return{passed:!0,...e?{detail:e}:{}}}function P(e){return{passed:!1,detail:e}}async function di(e,t){let n=!1;for(let i of t){let r=await i();qE(e,r),r.passed||(n=!0)}return n}var DE=["package.json with a build script","pom.xml","Cargo.toml"];async function FE(e){try{let t=await ut(x(),{allowPartialProject:!0});return t?Object.prototype.hasOwnProperty.call(t.value,e):!1}catch(t){throw new Error(`.comet/config.yaml is invalid YAML (${t instanceof Error?t.message:String(t)}); cannot check for removed "${e}" field. Fix the config and retry.`,{cause:t})}}function WE(e){return{status:1,output:`${e} has been removed from .comet/config.yaml. Delete this field and run any required ${e==="build_command"?"build":"verification"} command manually before retrying.`}}function BE(e){let t=wE(e,{shell:!0,cwd:Ot(),encoding:"utf8",timeout:3e5});return{status:t.status??1,output:`${t.stdout??""}${t.stderr??""}`.replace(/\n+$/u,"")}}function $r(e){return J.resolve(Ot(),e)}async function HE(){let e=$r("package.json");return await se(e)&&typeof JSON.parse(await W(x(),e,{label:"package.json"})).scripts?.build=="string"?"npm run build":await se($r("pom.xml"))?process.platform==="win32"?await se($r("mvnw.cmd"))?"mvnw.cmd compile -q":"mvn.cmd compile -q":await se($r("mvnw"))?"./mvnw compile -q":"mvn compile -q":await se($r("Cargo.toml"))?"cargo build":null}function hh(e){return`Evidence: recorded command-check at ${e.timestamp}; command: ${e.command}; cwd: ${e.cwd}`}function Fl(e,t,n){return`comet state record-check ${e} ${t} --command "${n}" --exit-code 0`}async function vh(e,t,n,i){if(process.env.COMET_SKIP_BUILD==="1")return{status:0,output:"SKIPPED via COMET_SKIP_BUILD=1"};let r=i==="build"?["build_command"]:["verify_command","build_command"];for(let a of r)if(await FE(a))return WE(a);let s=i==="build"?await HE():null;if(s)return BE(s);let o=await lh(x(),e,n,i);return o?o.exitCode!==0?{status:o.exitCode,output:`Latest recorded ${i} check failed with exit code ${o.exitCode}. +${hh(o)} Next: rerun the command successfully, then record it with: -${Fl(t,i,o.command)}`}:{status:0,output:mh(o)}:{status:1,output:i==="build"?`No inferred build command or recorded build check. Detection searched: ${DE.join(", ")}. +${Fl(t,i,o.command)}`}:{status:0,output:hh(o)}:{status:1,output:i==="build"?`No inferred build command or recorded build check. Detection searched: ${DE.join(", ")}. Next: run the required command, then record it with: ${Fl(t,i,"")}`:`No recorded verify check. Next: run the required verification command, then record it with: @@ -217,7 +217,7 @@ Next: complete or explicitly remove unfinished tasks, then mark tasks.md with '- Next: restore the Superpowers plan file or update .comet.yaml plan before leaving build.`);let i=(await W(x(),t,{label:`Classic plan ${t}`})).split(/\r?\n/u).map((r,s)=>({line:r,number:s+1})).filter(r=>/^\s*- \[ \]/u.test(r.line));return i.length>0?P(`Unfinished Superpowers plan tasks: ${i.map(r=>`${r.number}:${r.line}`).join(` `)} -Next: check off corresponding completed plan tasks, then commit the plan update.`):N()}async function Ul(e,t){let n;try{n=await xt(e,{heal:!0,cwd:Ot()})}catch(i){throw new Qe(`ERROR: ${i instanceof Error?i.message:String(i)}`)}switch(n.status){case"drift":return P(Lo(t,n.boundBranch,n.currentBranch));case"unbound-detached":return P(Pt(t));case"healed":return N(`bound_branch lazily set to ${n.branch}`);case"needs-heal":case"ok":case"not-applicable":return N();default:{let i=n;throw new Error(`unhandled branch binding status: ${JSON.stringify(i)}`)}}}async function UE(e,t){let n=await H(e,"isolation");return n==="current"||n==="branch"||n==="worktree"?N():P(`isolation must be current, branch, or worktree, got '${n||"null"}' +Next: check off corresponding completed plan tasks, then commit the plan update.`):N()}async function Ul(e,t){let n;try{n=await xt(e,{heal:!0,cwd:Ot()})}catch(i){throw new Ze(`ERROR: ${i instanceof Error?i.message:String(i)}`)}switch(n.status){case"drift":return P(Lo(t,n.boundBranch,n.currentBranch));case"unbound-detached":return P(Pt(t));case"healed":return N(`bound_branch lazily set to ${n.branch}`);case"needs-heal":case"ok":case"not-applicable":return N();default:{let i=n;throw new Error(`unhandled branch binding status: ${JSON.stringify(i)}`)}}}async function UE(e,t){let n=await H(e,"isolation");return n==="current"||n==="branch"||n==="worktree"?N():P(`isolation must be current, branch, or worktree, got '${n||"null"}' Next: choose a valid workspace mode, prepare it when needed, then run: comet state set ${t} isolation `)}async function VE(e,t){let n=await H(e,"build_mode");return["subagent-driven-development","executing-plans","direct"].includes(n)?N():P(`build_mode must be selected before leaving build, got '${n||"null"}' Next: ask the user to choose an execution mode, then run: @@ -236,63 +236,63 @@ Next: regenerate the design handoff with comet handoff ${t} design --write.`);le Expected handoff_hash: ${i} Actual handoff_hash: ${r} Next: run comet handoff ${t} design --write so Superpowers receives the current OpenSpec context.`);let s=`${n.replace(/\.json$/u,"")}.md`;return await fe(s)?N():P(`design handoff markdown is missing or empty: ${s} -Next: regenerate the design handoff with comet handoff ${t} design --write.`)}async function iR(e){let t=await H(e,"handoff_context");if(!t||t==="null")return P("handoff_context is missing from .comet.yaml");let n=`${t.replace(/\.json$/u,"")}.md`;if(!await fe(n))return P(`design handoff markdown is missing or empty: ${n}`);let i=await W(x(),n,{label:`Classic handoff markdown ${n}`}),r=new Set(i.split(/\r?\n/u)),s=[];/^Generated-by: comet-handoff\.sh$/mu.test(i)||s.push("handoff markdown is missing Generated-by marker"),/^- Mode: (compact|full|beta)$/mu.test(i)||s.push("handoff markdown is missing Mode marker");for(let o of await Kl(e))await se(o)&&(r.has(`- Source: ${o}`)||s.push(`handoff markdown is missing source reference: ${o}`),r.has(`- SHA256: ${await gh(o)}`)||s.push(`handoff markdown is missing current sha256 for: ${o}`));return s.length===0?N():P(s.join(` -`))}async function yh(e){return await H(e,"context_compression")||"off"}async function rR(e){if(await yh(e)!=="beta")return N();let t=await H(e,"handoff_context");if(!t||t==="null")return P("handoff_context is missing from .comet.yaml");if(!await fe(t))return P(`spec-context.json is missing or empty: ${t}`);let n=await W(x(),t,{label:`Classic handoff context ${t}`}),i=[],r;try{r=JSON.parse(n)}catch(a){return P(`spec-context.json invalid JSON: ${a instanceof Error?a.message:String(a)}`)}if(!r||typeof r!="object"||Array.isArray(r))return P("spec-context.json root must be an object");let s=r;typeof s.change!="string"&&i.push("spec-context.json missing 'change' field"),typeof s.phase!="string"&&i.push("spec-context.json missing 'phase' field"),s.mode!=="beta"&&i.push("spec-context.json mode is not beta"),typeof s.context_hash!="string"&&i.push("spec-context.json missing 'context_hash' field"),Array.isArray(s.files)||i.push("spec-context.json missing 'files' field");let o=Array.isArray(s.files)?s.files.filter(a=>!!a&&typeof a=="object"&&!Array.isArray(a)):[];for(let a of await Kl(e))await se(a)&&(o.some(c=>c.path===a&&typeof c.sha256=="string")||i.push(`spec-context.json missing source file reference: ${a}`));return i.length===0?N():P(i.join(` -`))}async function sR(e,t){let n=await H(t,"workflow"),i=[I("proposal.md exists and non-empty",async()=>await fe(J.join(t,"proposal.md"))?N():P("")),I("proposal.md matches configured language",()=>mt(t,J.join(t,"proposal.md"))),I("tasks.md exists and non-empty",async()=>await fe(J.join(t,"tasks.md"))?N():P("")),I("tasks.md matches configured language",()=>mt(t,J.join(t,"tasks.md"))),I("tasks.md has at least one task",async()=>await KE(t)?N():P(""))];return n==="full"&&i.splice(1,0,I("design.md exists and non-empty",async()=>await fe(J.join(t,"design.md"))?N():P("")),I("design.md matches configured language",()=>mt(t,J.join(t,"design.md")))),di(e,i)}async function oR(e,t,n){let i=await H(t,"design_doc"),r=await H(t,"workflow"),s=[I("proposal.md exists",async()=>await fe(J.join(t,"proposal.md"))?N():P("")),I("proposal.md matches configured language",()=>mt(t,J.join(t,"proposal.md"))),I("design.md exists",async()=>await fe(J.join(t,"design.md"))?N():P("")),I("design.md matches configured language",()=>mt(t,J.join(t,"design.md"))),I("tasks.md exists",async()=>await fe(J.join(t,"tasks.md"))?N():P("")),I("tasks.md matches configured language",()=>mt(t,J.join(t,"tasks.md"))),I("design handoff context exists",()=>nR(t,n)),I("design handoff markdown is traceable",()=>iR(t))];await yh(t)==="beta"&&s.push(I("beta spec-context.json is structurally valid",()=>rR(t))),r==="full"&&s.push(I("design_doc is recorded for full workflow",()=>tR(t,n)));let o=await di(e,s);return i&&i!=="null"?o=await di(e,[I(`Design Doc (${i}) exists`,async()=>await fe(i)?N():P("")),I("Design Doc matches configured language",()=>mt(t,i)),I("Design Doc frontmatter links current change",async()=>await fe(i)&&await Wl(i,"comet_change",n)?N():P("")),I("Design Doc declares technical design role",async()=>await fe(i)&&await Wl(i,"role","technical-design")?N():P("")),I("Design Doc declares OpenSpec as canonical spec",async()=>await fe(i)&&await Wl(i,"canonical_spec","openspec")?N():P(""))])||o:r!=="full"&&e.stderr.push(_E(" [WARN] No design_doc recorded in .comet.yaml (optional for hotfix/tweak)")),o}async function aR(e,t,n,i){return di(e,[I("bound branch matches workspace mode",()=>Ul(t,n)),I("isolation selected",()=>UE(t,n)),I("build_mode selected",()=>VE(t,n)),I("build_mode allowed for workflow",()=>YE(t)),I("subagent dispatch confirmed",()=>GE(t,n)),I("tdd_mode selected",()=>zE(t,n)),I("review_mode selected",()=>XE(t,n)),I("tasks.md all tasks checked",()=>Jl(t)),I("Superpowers plan all tasks checked",()=>JE(t)),I("proposal.md exists",async()=>await fe(J.join(t,"proposal.md"))?N():P("")),I("proposal.md matches configured language",()=>mt(t,J.join(t,"proposal.md"))),I("Superpowers plan matches configured language",async()=>{let r=await H(t,"plan");return!r||r==="null"||!await se(r)?N():mt(t,r)}),I("Build passes",async()=>{let r=await wh(t,n,i,"build");return r.status===0?N(r.output):P(r.output)})])}async function cR(e,t,n,i){return di(e,[I("bound branch matches workspace mode",()=>Ul(t,n)),I("tasks.md all tasks checked",()=>Jl(t)),I("Verification passes",async()=>{let r=await wh(t,n,i,"verify");return r.status===0?N(r.output):P(r.output)}),I("verification_report exists",async()=>await QE(t)?N():P("")),I("verification_report matches configured language",async()=>{let r=await H(t,"verification_report");return!r||r==="null"||!await se(r)?N():mt(t,r)})])}async function lR(e,t,n){return di(e,[I("bound branch matches workspace mode",()=>Ul(t,n)),I("archived is true",async()=>await eR(t)?N():P("")),I("proposal.md exists",async()=>await fe(J.join(t,"proposal.md"))?N():P("")),I("design.md exists",async()=>await fe(J.join(t,"design.md"))?N():P("")),I("tasks.md all tasks checked",()=>Jl(t)),I("branch_status=handled",async()=>await ZE(t)?N():P(""))])}async function uR(e,t,n,i){let r=Fp[i];if(!r)return;let s=await an(n),o=ui(s.classic,r);await cn(n,o.classic,s.run,{event:r,phase:i,source:"comet-guard"}),await An(n,{change:t,event:r,source:"comet-guard",from:s.classic,to:o.classic,effects:o.effects});for(let l of o.effects)e.stderr.push(fi(`[SET] ${xE(l.field)}=${PE(l.to)}`));e.stderr.push(fi(`[TRANSITION] ${r}`));let a=EE[i],c=i==="open"?a.replace("PLACEHOLDER",o.classic.phase):a;e.stderr.push(fi(c))}var vh=async(e,t)=>dt(t,async()=>{let n=new Bl,[i,r,s]=e;try{if(OE(i),!r||!kE.includes(r))throw new Qe(`${$t(`Unknown phase: ${r??""}`)} -Valid phases: open, design, build, verify, archive`);await Ee(x());let o=await $E(i);await ME(o,i);let a=await an(o),c=await uh(o,i);t.json&&(n.diagnostics={change:i,phase:r,currentStep:c.currentStep,runtimeEval:c.runtimeEval}),n.stderr.push(SE[r]);let l;return r==="open"?l=await sR(n,o):r==="design"?l=await oR(n,o,i):r==="build"?l=await aR(n,o,i,a.run):r==="verify"?l=await cR(n,o,i,a.run):l=await lR(n,o,i),l?(n.stderr.push(""),n.stderr.push($t("BLOCKED — fix failing checks before proceeding to next phase")),n.toResult(1)):(n.stderr.push(""),n.stderr.push(fi("ALL CHECKS PASSED — ready for next phase")),s==="--apply"&&await uR(n,i,o,r),n.toResult(0))}catch(o){if(o instanceof Qe){for(let a of o.message.split(` -`))n.stderr.push(a);return n.toResult(o.exitCode)}throw o}});var _h=rt(Ue(),1);import{createHash as Sh}from"crypto";import{promises as Eh}from"fs";import Rh from"path";var fR="\x1B[32m",dR="\x1B[31m",mR="\x1B[33m",Yl="\x1B[0m";function ln(e){return`${fR}${e}${Yl}`}function xe(e){return`${dR}${e}${Yl}`}function pR(e){return`${mR}${e}${Yl}`}var de=class extends Error{constructor(n,i=1){super(n);this.exitCode=i}exitCode},Vl=class{stdout=[];stderr=[];toResult(t=0){return{exitCode:t,...this.stdout.length>0?{stdout:this.stdout.join(` +Next: regenerate the design handoff with comet handoff ${t} design --write.`)}async function iR(e){let t=await H(e,"handoff_context");if(!t||t==="null")return P("handoff_context is missing from .comet.yaml");let n=`${t.replace(/\.json$/u,"")}.md`;if(!await fe(n))return P(`design handoff markdown is missing or empty: ${n}`);let i=await W(x(),n,{label:`Classic handoff markdown ${n}`}),r=new Set(i.split(/\r?\n/u)),s=[];/^Generated-by: comet-handoff\.sh$/mu.test(i)||s.push("handoff markdown is missing Generated-by marker"),/^- Mode: (compact|full|beta)$/mu.test(i)||s.push("handoff markdown is missing Mode marker");for(let o of await Kl(e))await se(o)&&(r.has(`- Source: ${o}`)||s.push(`handoff markdown is missing source reference: ${o}`),r.has(`- SHA256: ${await yh(o)}`)||s.push(`handoff markdown is missing current sha256 for: ${o}`));return s.length===0?N():P(s.join(` +`))}async function bh(e){return await H(e,"context_compression")||"off"}async function rR(e){if(await bh(e)!=="beta")return N();let t=await H(e,"handoff_context");if(!t||t==="null")return P("handoff_context is missing from .comet.yaml");if(!await fe(t))return P(`spec-context.json is missing or empty: ${t}`);let n=await W(x(),t,{label:`Classic handoff context ${t}`}),i=[],r;try{r=JSON.parse(n)}catch(a){return P(`spec-context.json invalid JSON: ${a instanceof Error?a.message:String(a)}`)}if(!r||typeof r!="object"||Array.isArray(r))return P("spec-context.json root must be an object");let s=r;typeof s.change!="string"&&i.push("spec-context.json missing 'change' field"),typeof s.phase!="string"&&i.push("spec-context.json missing 'phase' field"),s.mode!=="beta"&&i.push("spec-context.json mode is not beta"),typeof s.context_hash!="string"&&i.push("spec-context.json missing 'context_hash' field"),Array.isArray(s.files)||i.push("spec-context.json missing 'files' field");let o=Array.isArray(s.files)?s.files.filter(a=>!!a&&typeof a=="object"&&!Array.isArray(a)):[];for(let a of await Kl(e))await se(a)&&(o.some(c=>c.path===a&&typeof c.sha256=="string")||i.push(`spec-context.json missing source file reference: ${a}`));return i.length===0?N():P(i.join(` +`))}async function sR(e,t){let n=await H(t,"workflow"),i=[I("proposal.md exists and non-empty",async()=>await fe(J.join(t,"proposal.md"))?N():P("")),I("proposal.md matches configured language",()=>pt(t,J.join(t,"proposal.md"))),I("tasks.md exists and non-empty",async()=>await fe(J.join(t,"tasks.md"))?N():P("")),I("tasks.md matches configured language",()=>pt(t,J.join(t,"tasks.md"))),I("tasks.md has at least one task",async()=>await KE(t)?N():P(""))];return n==="full"&&i.splice(1,0,I("design.md exists and non-empty",async()=>await fe(J.join(t,"design.md"))?N():P("")),I("design.md matches configured language",()=>pt(t,J.join(t,"design.md")))),di(e,i)}async function oR(e,t,n){let i=await H(t,"design_doc"),r=await H(t,"workflow"),s=[I("proposal.md exists",async()=>await fe(J.join(t,"proposal.md"))?N():P("")),I("proposal.md matches configured language",()=>pt(t,J.join(t,"proposal.md"))),I("design.md exists",async()=>await fe(J.join(t,"design.md"))?N():P("")),I("design.md matches configured language",()=>pt(t,J.join(t,"design.md"))),I("tasks.md exists",async()=>await fe(J.join(t,"tasks.md"))?N():P("")),I("tasks.md matches configured language",()=>pt(t,J.join(t,"tasks.md"))),I("design handoff context exists",()=>nR(t,n)),I("design handoff markdown is traceable",()=>iR(t))];await bh(t)==="beta"&&s.push(I("beta spec-context.json is structurally valid",()=>rR(t))),r==="full"&&s.push(I("design_doc is recorded for full workflow",()=>tR(t,n)));let o=await di(e,s);return i&&i!=="null"?o=await di(e,[I(`Design Doc (${i}) exists`,async()=>await fe(i)?N():P("")),I("Design Doc matches configured language",()=>pt(t,i)),I("Design Doc frontmatter links current change",async()=>await fe(i)&&await Wl(i,"comet_change",n)?N():P("")),I("Design Doc declares technical design role",async()=>await fe(i)&&await Wl(i,"role","technical-design")?N():P("")),I("Design Doc declares OpenSpec as canonical spec",async()=>await fe(i)&&await Wl(i,"canonical_spec","openspec")?N():P(""))])||o:r!=="full"&&e.stderr.push(_E(" [WARN] No design_doc recorded in .comet.yaml (optional for hotfix/tweak)")),o}async function aR(e,t,n,i){return di(e,[I("bound branch matches workspace mode",()=>Ul(t,n)),I("isolation selected",()=>UE(t,n)),I("build_mode selected",()=>VE(t,n)),I("build_mode allowed for workflow",()=>YE(t)),I("subagent dispatch confirmed",()=>GE(t,n)),I("tdd_mode selected",()=>zE(t,n)),I("review_mode selected",()=>XE(t,n)),I("tasks.md all tasks checked",()=>Jl(t)),I("Superpowers plan all tasks checked",()=>JE(t)),I("proposal.md exists",async()=>await fe(J.join(t,"proposal.md"))?N():P("")),I("proposal.md matches configured language",()=>pt(t,J.join(t,"proposal.md"))),I("Superpowers plan matches configured language",async()=>{let r=await H(t,"plan");return!r||r==="null"||!await se(r)?N():pt(t,r)}),I("Build passes",async()=>{let r=await vh(t,n,i,"build");return r.status===0?N(r.output):P(r.output)})])}async function cR(e,t,n,i){return di(e,[I("bound branch matches workspace mode",()=>Ul(t,n)),I("tasks.md all tasks checked",()=>Jl(t)),I("Verification passes",async()=>{let r=await vh(t,n,i,"verify");return r.status===0?N(r.output):P(r.output)}),I("verification_report exists",async()=>await QE(t)?N():P("")),I("verification_report matches configured language",async()=>{let r=await H(t,"verification_report");return!r||r==="null"||!await se(r)?N():pt(t,r)})])}async function lR(e,t,n){return di(e,[I("bound branch matches workspace mode",()=>Ul(t,n)),I("archived is true",async()=>await eR(t)?N():P("")),I("proposal.md exists",async()=>await fe(J.join(t,"proposal.md"))?N():P("")),I("design.md exists",async()=>await fe(J.join(t,"design.md"))?N():P("")),I("tasks.md all tasks checked",()=>Jl(t)),I("branch_status=handled",async()=>await ZE(t)?N():P(""))])}async function uR(e,t,n,i){let r=Bp[i];if(!r)return;let s=await an(n),o=ui(s.classic,r);await cn(n,o.classic,s.run,{event:r,phase:i,source:"comet-guard"}),await An(n,{change:t,event:r,source:"comet-guard",from:s.classic,to:o.classic,effects:o.effects});for(let l of o.effects)e.stderr.push(fi(`[SET] ${xE(l.field)}=${PE(l.to)}`));e.stderr.push(fi(`[TRANSITION] ${r}`));let a=EE[i],c=i==="open"?a.replace("PLACEHOLDER",o.classic.phase):a;e.stderr.push(fi(c))}var Ch=async(e,t)=>mt(t,async()=>{let n=new Bl,[i,r,s]=e;try{if(OE(i),!r||!kE.includes(r))throw new Ze(`${$t(`Unknown phase: ${r??""}`)} +Valid phases: open, design, build, verify, archive`);await Ee(x());let o=await $E(i);await ME(o,i);let a=await an(o),c=await dh(o,i);t.json&&(n.diagnostics={change:i,phase:r,currentStep:c.currentStep,runtimeEval:c.runtimeEval}),n.stderr.push(SE[r]);let l;return r==="open"?l=await sR(n,o):r==="design"?l=await oR(n,o,i):r==="build"?l=await aR(n,o,i,a.run):r==="verify"?l=await cR(n,o,i,a.run):l=await lR(n,o,i),l?(n.stderr.push(""),n.stderr.push($t("BLOCKED — fix failing checks before proceeding to next phase")),n.toResult(1)):(n.stderr.push(""),n.stderr.push(fi("ALL CHECKS PASSED — ready for next phase")),s==="--apply"&&await uR(n,i,o,r),n.toResult(0))}catch(o){if(o instanceof Ze){for(let a of o.message.split(` +`))n.stderr.push(a);return n.toResult(o.exitCode)}throw o}});var Ph=st(Ue(),1);import{createHash as Rh}from"crypto";import{promises as _h}from"fs";import xh from"path";var fR="\x1B[32m",dR="\x1B[31m",mR="\x1B[33m",Yl="\x1B[0m";function ln(e){return`${fR}${e}${Yl}`}function xe(e){return`${dR}${e}${Yl}`}function pR(e){return`${mR}${e}${Yl}`}var de=class extends Error{constructor(n,i=1){super(n);this.exitCode=i}exitCode},Vl=class{stdout=[];stderr=[];toResult(t=0){return{exitCode:t,...this.stdout.length>0?{stdout:this.stdout.join(` `)+` `}:{},...this.stderr.length>0?{stderr:this.stderr.join(` `)+` -`}:{}}}};async function un(e,t,n){return await X(e,t,{label:n,expected:"file"})?W(e,t,{label:n}):null}async function Ho(e,t,n,i){await ti(e,t,n,{label:i})}function hR(e){let t=ge(e);if(t)throw new de(xe(`ERROR: ${t}`))}function It(e){return Sh("sha256").update(e).digest("hex")}function xh(e){return It(JSON.stringify(Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))))}async function Ir(e,t){let n=[`${t}/proposal.md`,`${t}/design.md`,`${t}/tasks.md`],i=`${t}/specs`;if((await Y(e,i,{label:"Classic handoff specs directory",expected:"directory"})).exists){let s=(await Eh.readdir(i,{withFileTypes:!0})).sort((o,a)=>o.name.localeCompare(a.name));for(let o of s){if(!o.isDirectory()&&!o.isSymbolicLink())continue;let a=`${i}/${o.name}/spec.md`;(await Y(e,`${i}/${o.name}`,{label:`Classic handoff spec directory ${o.name}`,expected:"directory"})).exists&&await X(e,a,{label:`Classic handoff spec ${o.name}`,expected:"file"})&&n.push(a)}}return n}function mi(e,t,n){let i=Rh.relative(e,n).replaceAll("\\","/");return`${t}/${i}`}async function bh(e,t,n){let i=[];for(let r of await Ir(e,t)){let s=mi(t,n,r),o=await un(e,r,`Classic handoff source ${s}`);o!==null&&i.push(`path:${s}`,`sha256:${It(o)}`)}return Sh("sha256").update(i.join(` -`)).digest("hex")}function Ch(e){return e.replace(/\\/gu,"\\\\").replace(/"/gu,'\\"')}function Ph(e){return(e.match(/\n/gu)??[]).length}function gR(e,t){let n=0;for(let i=0;iu.name.localeCompare(d.name));for(let u of f){if(!u.isDirectory()&&!u.isSymbolicLink())continue;let d=`${a}/${u.name}/spec.md`,p=await un(e,d,`Classic handoff spec ${u.name}`);p!==null&&(c=!0,o.push(...await vR(mi(t,n,d),p)))}}c||o.push("No delta spec files found.",""),o.push("Full source files remain canonical. If a required heading or scenario is missing here, regenerate the handoff or read the source spec directly. Supporting files (proposal, design, tasks) are referenced by hash only."),await Ho(e,s,o.join(` +`}:{}}}};async function un(e,t,n){return await X(e,t,{label:n,expected:"file"})?W(e,t,{label:n}):null}async function Ho(e,t,n,i){await ti(e,t,n,{label:i})}function hR(e){let t=ge(e);if(t)throw new de(xe(`ERROR: ${t}`))}function It(e){return Rh("sha256").update(e).digest("hex")}function Oh(e){return It(JSON.stringify(Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))))}async function Ir(e,t){let n=[`${t}/proposal.md`,`${t}/design.md`,`${t}/tasks.md`],i=`${t}/specs`;if((await Y(e,i,{label:"Classic handoff specs directory",expected:"directory"})).exists){let s=(await _h.readdir(i,{withFileTypes:!0})).sort((o,a)=>o.name.localeCompare(a.name));for(let o of s){if(!o.isDirectory()&&!o.isSymbolicLink())continue;let a=`${i}/${o.name}/spec.md`;(await Y(e,`${i}/${o.name}`,{label:`Classic handoff spec directory ${o.name}`,expected:"directory"})).exists&&await X(e,a,{label:`Classic handoff spec ${o.name}`,expected:"file"})&&n.push(a)}}return n}function mi(e,t,n){let i=xh.relative(e,n).replaceAll("\\","/");return`${t}/${i}`}async function kh(e,t,n){let i=[];for(let r of await Ir(e,t)){let s=mi(t,n,r),o=await un(e,r,`Classic handoff source ${s}`);o!==null&&i.push(`path:${s}`,`sha256:${It(o)}`)}return Rh("sha256").update(i.join(` +`)).digest("hex")}function Sh(e){return e.replace(/\\/gu,"\\\\").replace(/"/gu,'\\"')}function $h(e){return(e.match(/\n/gu)??[]).length}function gR(e,t){let n=0;for(let i=0;iu.name.localeCompare(d.name));for(let u of f){if(!u.isDirectory()&&!u.isSymbolicLink())continue;let d=`${a}/${u.name}/spec.md`,p=await un(e,d,`Classic handoff spec ${u.name}`);p!==null&&(c=!0,o.push(...await vR(mi(t,n,d),p)))}}c||o.push("No delta spec files found.",""),o.push("Full source files remain canonical. If a required heading or scenario is missing here, regenerate the handoff or read the source spec directly. Supporting files (proposal, design, tasks) are referenced by hash only."),await Ho(e,s,o.join(` `),"Classic handoff spec markdown output")}async function CR(e,t,n,i,r,s){let o=[];for(let a of await Ir(e,t)){let c=mi(t,n,a),l=await un(e,a,`Classic handoff source ${c}`);if(l===null)continue;let f=/\/specs\/[^/]+\/spec\.md$/u.test(c)?"spec":"supporting";o.push({path:c,sha256:It(l),role:f})}await Ho(e,s,`${JSON.stringify({change:i,phase:"design",mode:"beta",canonical_spec:"openspec",generated_by:"comet-handoff.sh",context_hash:r,files:o},null,2)} -`,"Classic handoff spec JSON output")}async function kh(e,t,n){let i=Rh.join(t,".comet.yaml"),r=(0,_h.parseDocument)(await W(e,i,{label:"Classic change state"}),{uniqueKeys:!1});if(r.errors.length>0)throw new de(`ERROR: Invalid .comet.yaml: ${r.errors[0].message}`);let o=r.toJS()[n];return o==null?"":typeof o=="object"?JSON.stringify(o):String(o)}async function kR(e,t,n){let i=await Le(e,t.trajectoryRef);i.some(s=>s.type==="recovery_reconciled"&&s.data.kind==="classic-handoff"&&s.data.actionId===n)||await We(e,t.trajectoryRef,{sequence:i.length+1,timestamp:new Date().toISOString(),type:"recovery_reconciled",runId:t.runId,data:{kind:"classic-handoff",actionId:n}})}async function SR(e,t,n,i,r,s,o,a){let[c,l,f]=await Promise.all([Eo(t,n.contextRef),oi(t,n.artifactsRef),fp(t,n.checkpointRef)]),[u,d]=await Promise.all([un(e,r,"Classic handoff JSON output"),un(e,s,"Classic handoff markdown output")]);return u===null||d===null||c!==d||l.handoff_context!==o||l.handoff_markdown!==a?!1:f?.runId===n.runId&&f.contextHash===(c===null?null:It(c))&&f.artifactsHash===xh(l)&&i.length===64}var Oh=async(e,t)=>dt(t,async()=>{let n=new Vl,[i,r,s,o]=e;try{hR(i);let a=await Ee(x()),c=await Ye(i,a.projectRoot),l=c.directory,f=A(a.projectRoot,l);if(r==="--hash-only"){if(!c.exists)throw new de(xe(`ERROR: change directory not found: ${f}`));for(let pn of["proposal.md","design.md","tasks.md"])if(!await xn(a.projectRoot,`${l}/${pn}`,`Classic handoff source ${pn}`))throw new de(xe(`ERROR: required file missing or empty: ${f}/${pn}`));return n.stdout.push(await bh(a.projectRoot,l,f)),n.toResult(0)}if(r!=="design"||s!=="--write")throw new de(xe("Usage: comet-handoff.mjs design --write [--full]"));let u;if(o===void 0||o==="")u="compact";else if(o==="--full")u="full";else throw new de(xe("Usage: comet-handoff.mjs design --write [--full]"));if(!c.exists)throw new de(xe(`ERROR: change directory not found: ${f}`));if(!c.stateExists)throw new de(xe(`ERROR: .comet.yaml not found at ${f}/.comet.yaml`));if(await kh(a.projectRoot,l,"phase")!=="design")throw new de(xe("ERROR: design handoff requires phase: design"));for(let pn of["proposal.md","design.md","tasks.md"])if(!await xn(a.projectRoot,`${l}/${pn}`,`Classic handoff source ${pn}`))throw new de(xe(`ERROR: required OpenSpec artifact missing or empty: ${f}/${pn}`));let d=`${l}/.comet/handoff`;await Y(a.projectRoot,`${l}/.comet`,{label:"Classic change runtime directory",expected:"directory"}),await Y(a.projectRoot,d,{label:"Classic handoff directory",expected:"directory"});let p=await kh(a.projectRoot,l,"context_compression")||"off",g,h;if(p==="off")g=`${d}/design-context.json`,h=`${d}/design-context.md`;else if(p==="beta")u==="full"&&n.stderr.push(pR("[HANDOFF] --full is ignored in beta mode; spec files are projected verbatim")),u="beta",g=`${d}/spec-context.json`,h=`${d}/spec-context.md`;else throw new de([xe(`ERROR: invalid context_compression: ${p}`),xe("Valid values: off, beta")].join(` -`));let m=A(a.projectRoot,g),y=A(a.projectRoot,h),w=await bh(a.projectRoot,l,f),C=`classic-handoff:${w}`,k=await B(l);if(!k.classic)throw new de(xe("ERROR: design handoff requires Classic state"));let E=k.run?await yr(l,k.run.pendingRef):null,R=E?.id===C&&E.type==="handoff"&&E.ref===w;if(k.classic.handoffHash&&k.classic.handoffHash!==w&&!R)throw new de(xe(`ERROR: stale handoff detected: source hash ${w} does not match completed hash ${k.classic.handoffHash}`));await Pn(a.projectRoot,`${l}/.comet`,"Classic change runtime directory"),await Pn(a.projectRoot,d,"Classic handoff directory");let O=await an(l),b=await yr(l,O.run.pendingRef),L=b?.id===C&&b.type==="handoff"&&b.ref===w;if(O.run.pending&&O.run.pending!==C)throw new de(xe(`ERROR: another action is pending: ${O.run.pending}`));if(O.classic.handoffHash===w&&O.classic.handoffContext===m&&!O.run.pending&&!b&&await SR(a.projectRoot,l,O.run,w,g,h,m,y))return n.stderr.push(ln(`[HANDOFF] wrote ${m}`)),n.stderr.push(ln(`[HANDOFF] wrote ${y}`)),n.stderr.push(ln(`[HANDOFF] handoff_hash=${w}`)),n.toResult(0);let Ie={id:C,stepId:O.run.currentStep,type:"handoff",ref:w};await Ro(l,O.run.pendingRef,Ie);let Q={...O.run,pending:C,status:"waiting"};await je(l,{classic:O.classic,run:Q,unknownKeys:(await B(l)).unknownKeys}),u==="beta"?(await bR(a.projectRoot,l,f,i,w,h),await CR(a.projectRoot,l,f,i,w,g)):(await wR(a.projectRoot,l,f,i,u,w,h),await yR(a.projectRoot,l,f,i,u,w,g));let K=await W(a.projectRoot,h,{label:"Classic handoff markdown output"});await So(l,Q.contextRef,K);let Ce={...await oi(l,Q.artifactsRef),handoff_context:m,handoff_markdown:y};await ai(l,Q.artifactsRef,Ce);let Hr={...O.classic,handoffContext:m,handoffHash:w},wt={...Q.currentStep==="full.design.handoff"?await cn(l,Hr,Q,{actionId:C,kind:"classic-handoff"}):Q,pending:null,status:"running"};(R||L)&&await kR(l,wt,C);let Kr=await Le(l,wt.trajectoryRef),mn={runId:wt.runId,stateVersion:wt.iteration,trajectoryOffset:Kr.length,contextHash:It(K),artifactsHash:xh(Ce),createdAt:new Date().toISOString()};return await ci(l,wt.checkpointRef,mn),await je(l,{classic:Hr,run:wt,unknownKeys:(await B(l)).unknownKeys}),await _o(l,wt.pendingRef),n.stderr.push(ln(`[SET] handoff_context=${g}`)),n.stderr.push(ln(`[SET] handoff_hash=${w}`)),n.stderr.push(ln(`[HANDOFF] wrote ${m}`)),n.stderr.push(ln(`[HANDOFF] wrote ${y}`)),n.stderr.push(ln(`[HANDOFF] handoff_hash=${w}`)),n.toResult(0)}catch(a){if(a instanceof de){for(let c of a.message.split(` -`))n.stderr.push(c);return n.toResult(a.exitCode)}throw a}});import{promises as Jo,readFileSync as RR}from"fs";import qe from"path";import{promises as Gl}from"fs";import Me from"path";function $h(e,t){let n=Me.relative(e,t);return n===""||n!==".."&&!n.startsWith(`..${Me.sep}`)&&!Me.isAbsolute(n)}async function ER(e){let t=Me.resolve(e),n=Me.parse(t).root,i=[],r=t;for(;r&&r!==n;)try{let s=await Gl.realpath(r);return Me.join(s,...i.reverse())}catch(s){let o=s.code;if(o!=="ENOENT"&&o!=="ENOTDIR")throw s;i.push(Me.basename(r)),r=Me.dirname(r)}try{let s=await Gl.realpath(n);return Me.join(s,...i.reverse())}catch{return null}}async function Ih(e,t){let n=Me.resolve(e),i=await Gl.realpath(n),r=[],s=[];for(let o of t){let a=Me.isAbsolute(o)?Me.resolve(o):Me.resolve(n,o),c=await ER(a);((c?$h(i,c):$h(n,a))?r:s).push(o)}return{projectTargets:r,externalTargets:s}}import Tn from"node:path";async function Ko(e,t){if(!t||t==="null")return{status:"missing",recordedPath:null};let n=await z(e),i=Tn.resolve(e,t),r=Tn.relative(n.superpowersPlansDir,i);return Tn.isAbsolute(t)||!r||r.startsWith(`..${Tn.sep}`)||Tn.isAbsolute(r)||r.includes(Tn.sep)||Tn.extname(r).toLowerCase()!==".md"?{status:"broken",recordedPath:t}:await X(e,t,{label:`Classic build plan ${t}`,expected:"file"})?{status:"ready",recordedPath:t}:{status:"broken",recordedPath:t}}function Ze(e,t){return{exitCode:e,stderr:t+` -`}}function pt(e){return Ze(0,`[COMET-HOOK] allowed: ${e}`)}function _R(){if(process.env.FILE_PATH)return process.env.FILE_PATH;if(process.stdin.isTTY)return"";let e=RR(0,"utf8");if(!e)return"";try{let t=JSON.parse(e);return typeof t.tool_input?.file_path=="string"?t.tool_input.file_path:""}catch{return""}}function Nr(e){return e.replaceAll("\\","/").replace(/\/+/gu,"/")}function jn(e){let t=Nr(e);return process.platform==="win32"?t.toLowerCase():t}function xR(e){let t=e.indexOf("--project-root"),n=t>=0?e[t+1]:void 0;return qe.resolve(n&&!n.startsWith("--")?n:process.cwd())}function Ah(e,t){let n=Nr(qe.relative(t,e));return n===""?"":n.startsWith("../")||n===".."||qe.isAbsolute(n)?null:n}async function PR(e){let t=qe.resolve(e),n=qe.parse(t).root,i=[],r=t;for(;r&&r!==n;)try{let s=await Jo.realpath(r);return qe.join(s,...i.reverse())}catch(s){let o=s.code;if(o!=="ENOENT"&&o!=="ENOTDIR")throw s;i.push(qe.basename(r)),r=qe.dirname(r)}try{let s=await Jo.realpath(n);return qe.join(s,...i.reverse())}catch{return null}}async function OR(e,t){let n=qe.isAbsolute(e)?e:qe.resolve(t,e),i=Nr(n),r=Ah(n,t);if(r!==null)return r;try{let s=await PR(n),o=await Jo.realpath(t);if(s){let a=Ah(s,o);if(a!==null)return a;i=Nr(s)}}catch{if(!qe.isAbsolute(e))return Nr(e).replace(/^\.\//u,"")}return i.replace(/^\.\//u,"")}async function Lh(e){try{let t=await B(e,{migrate:!1}),n=Array.from(new Set(t.unknownKeys)).sort();if(n.length>0)throw new Error(`Invalid Classic state: unknown field(s): ${n.join(", ")}`);if(!t.classic)throw new Error("Classic state projection is unavailable");return{changeDir:e,phase:t.classic.phase,classic:t.classic,archived:t.classic.archived}}catch(t){let n=await lp(e);return n.phase?{changeDir:e,phase:n.phase,classic:null,archived:n.archived,invalidState:t instanceof Error&&t.message.includes("unknown field")}:null}}async function $R(e){let t=(await z(e)).changesDir,n=[];if(!(await Y(e,t,{label:"Classic changes directory",expected:"directory"})).exists)return n;for(let r of(await Jo.readdir(t,{withFileTypes:!0})).sort((s,o)=>s.name.localeCompare(o.name))){if(r.name==="archive"||ge(r.name))continue;let s=await Ye(r.name,e);if(!s.exists||!s.stateExists)continue;let o=await Lh(s.directory);!o||o.archived||n.push(o)}return n}var zl=br("classicActiveChanges",e=>$R(e)),Mh=br("classicPlanReadiness",Ko);function qh(e,t){return`${A(e,t.superpowersRoot)}/`}function Dh(e,t){return jn(e).startsWith(jn(t))}function IR(e,t){return[{prefix:`${A(e,t.superpowersSpecsDir)}/`,field:"designDoc",wireField:"design_doc",phase:"design"},{prefix:`${A(e,t.superpowersPlansDir)}/`,field:"plan",wireField:"plan",phase:"build"},{prefix:`${A(e,t.superpowersReportsDir)}/`,field:"verificationReport",wireField:"verification_report",phase:"verify"}]}function AR(e,t){let n=jn(e),i=t.find(s=>n.startsWith(jn(s.prefix)));if(!i)return null;let r=n.slice(jn(i.prefix).length);return!r||r.includes("/")||!r.endsWith(".md")?null:i}function Fh(e,t){return e.classic?.[t.field]??null}function NR(e,t){return e.classic!==null&&e.phase===t.phase&&!Fh(e,t)}async function Nh(e,t,n){return NR(t,n)?!0:n.field!=="plan"||t.phase!=="build"?!1:(await Mh(e,t.classic?.plan??null)).status==="broken"}function Wh(e){return e.phase==="design"||e.phase==="build"||e.phase==="verify"}function At(e){return e.changeDir?qe.basename(e.changeDir):null}var TR=new Set(["design","plan","verify","verification","verification-report","report"]);function Th(e){return e.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}function jR(e,t){return[t.classic?.designDoc,t.classic?.plan,t.classic?.verificationReport].some(i=>i&&jn(i)===jn(e))}function LR(e,t){let i=(e.split("/").at(-1)??e).replace(/\.[^.]+$/u,"");if(i===t)return!0;let r=[...TR].map(Th).join("|");return new RegExp(`(^|[-_.])${Th(t)}[-_.](${r})$`,"u").test(i)}async function MR(e,t){let n=await zl(t),i=n.find(o=>jR(e,o));if(i)return{governing:i,match:"recorded"};let s=n.filter(Wh).filter(o=>{let a=At(o);return a!==null&&LR(e,a)}).sort((o,a)=>(At(a)?.length??0)-(At(o)?.length??0))[0];return s?{governing:s,match:"named"}:null}async function jh(e,t,n){let i=await zl(e);if(i.length===0)return null;if(n)return i.find(o=>At(o)===n)??{blockedResult:Ar(t,`selected change '${n}' is no longer active`)};let r=await Mo(e);if(r.status==="stale")return{blockedResult:Ar(t,r.reason)};if(r.status==="selected"){let s=i.find(o=>At(o)===r.selection.change);return s||{blockedResult:Ar(t,`selected change '${r.selection.change}' is no longer active`)}}if(i.length===1){let s=i[0];if(s.changeDir!==null){let o=await xt(s.changeDir,{heal:!1,cwd:e}),a=At(s)??"unknown";if(o.status==="drift")return{blockedResult:Ar(t,kr(a,o.boundBranch,o.currentBranch))};if(o.status==="unbound-detached")return{blockedResult:Ar(t,Pt(a))}}return s}return{blockedResult:VR(t,i.map(s=>At(s)).filter(Boolean))}}async function qR(e,t,n,i){let r=`${A(t,n.changesDir)}/`;if(e.startsWith(r)){let s=e.slice(r.length),[o]=s.split("/");if(o&&o!=="archive"){let a=await Ye(o,t);if(a.stateExists){let c=await Lh(a.directory);return c||{changeDir:a.directory,phase:"open",classic:null,archived:!1}}return{changeDir:a.directory,phase:"open",classic:null,archived:!1}}}if(Dh(e,qh(t,n))){let s=await MR(e,t);if(s?.match==="recorded")return{...s.governing,superpowersArtifact:"matched"};let o=AR(e,IR(t,n));if(s)return o?{...s.governing,superpowersArtifact:await Nh(t,s.governing,o)?"matched":"unmatched",superpowersSlot:o}:{...s.governing,superpowersArtifact:"matched"};if(o){let l=await jh(t,e,i);return!l||"blockedResult"in l?l:{...l,superpowersArtifact:await Nh(t,l,o)?"matched":"unmatched",superpowersSlot:o}}let a=await zl(t),c=i?a.find(l=>At(l)===i)??null:a[0]??null;return c?{...c,superpowersArtifact:"unmatched"}:null}return jh(t,e,i)}function DR(e){return!e.includes("/")&&e.endsWith(".md")}function FR(e){return e.startsWith(".comet/")||e.includes("/.comet/")}function WR(e){return e===".superpowers"||e.startsWith(".superpowers/")}function BR(e,t,n){if(!e.startsWith(n))return null;let i=e.endsWith("/.comet.yaml")||e.endsWith("/.openspec.yaml"),r=e.endsWith("/proposal.md")||e.endsWith("/design.md")||e.endsWith("/tasks.md"),s=e.includes("/.comet/"),o=e.includes("/specs/");return t==="open"&&(r||i||s||o)?`${e} (phase: open, openspec artifacts)`:t==="design"&&(r||i||s||o)?`${e} (phase: design, handoff/spec)`:t==="build"&&(e.endsWith("/tasks.md")||i||o)?`${e} (phase: build, spec/tasks)`:t==="verify"&&(e.endsWith("/tasks.md")||i)?`${e} (phase: verify, tasks/state)`:t==="archive"&&i?`${e} (phase: archive, state)`:null}function HR(e,t){let n=t==="open"?[" BLOCKED: source writes are not allowed during open"," This phase does not allow source writes"," ALLOWED: create proposal/design/tasks artifacts and run guard"," NEXT: finish clarification and artifacts, then run guard --apply"]:t==="design"?[" BLOCKED: source writes are not allowed during design"," This phase does not allow source writes"," ALLOWED: run brainstorming, create the Design Doc, and run guard"," NEXT: finish the Design Doc, then run comet guard design --apply to enter build"]:[" BLOCKED: source writes are not allowed during archive"," This phase does not allow source writes"," ALLOWED: confirm archive state and run the archive script"];return Ze(2,["","╔══════════════════════════════════════════╗","║ COMET PHASE GUARD — WRITE BLOCKED ║","╚══════════════════════════════════════════╝","",` Current phase: ${t}`,` Target file: ${e}`,"",...n,""].join(` -`))}function KR(e){return Ze(2,["","╔══════════════════════════════════════════╗","║ COMET PHASE GUARD — WRITE BLOCKED ║","╚══════════════════════════════════════════╝",""," Current phase: build (workflow: full), but design_doc is empty",` Target file: ${e}`,""," BLOCKED: full workflow source writes require a recorded Design Doc"," This phase does not allow source writes until design_doc is recorded"," NEXT: return to design, create/link the Design Doc, then run guard again",""].join(` -`))}function JR(e,t,n,i,r){let s=At(t)??"",o=n.status==="missing",a=o?"classic-build-plan-missing":"classic-build-plan-broken",c=o?"plan is not recorded":"the recorded plan path does not resolve to a file",l=o?[]:[`RECORDED_PLAN: ${n.recordedPath}`],f=t.changeDir?A(i,t.changeDir):"",u=A(i,r.superpowersPlansDir),d=o?`comet state set ${s} plan `:`comet state set ${s} plan `,p=o?["2. Load the Superpowers writing-plans Skill.",`3. Read the Design Doc path from "comet state get ${s} design_doc" and read ${f}/tasks.md.`,`4. Create the implementation plan under ${u}/.`,"5. Record the plan path:",` ${d}`]:[`2. Restore the plan file at ${n.recordedPath}, or load the Superpowers writing-plans Skill and create a replacement under ${u}/.`,"3. When creating a replacement, record its path:",` ${d}`];return Ze(2,["","╔══════════════════════════════════════════╗","║ COMET PHASE GUARD — WRITE BLOCKED ║","╚══════════════════════════════════════════╝","",`ERROR_CODE: ${a}`,`CHANGE: ${s}`,"WORKFLOW: full","PHASE: build",`TARGET: ${e}`,`STATE: ${c}`,...l,"","BLOCKED: project source writes require a ready Superpowers implementation plan.","","ALLOWED_RECOVERY_WRITES:",`- ${u}/.md`,"- Comet state updates performed by the comet CLI",`- ${f} artifacts allowed by the build phase`,"","RECOVERY:",`1. Invoke /comet-build for ${s} and resume Step 1.`,...p,`${o?"6":"4"}. Verify recovery:`,` comet state check ${s} build --recover`,"","SUCCESS: plan is reported as DONE and recovery advances beyond plan creation.",`RETRY: retry the original Write/Edit for ${e} only after SUCCESS.`,"PROHIBITED: do not treat tasks.md as the implementation plan or write project source before SUCCESS.","If writing-plans is unavailable, stop and report the missing Skill instead of bypassing this check.",""].join(` -`))}function UR(e,t){let n=t.superpowersSlot,i=n?Fh(t,n):null,r=n?t.phase!==n.phase?[` BLOCKED: ${n.wireField} cannot be first-written in phase ${t.phase}`,` Expected phase: ${n.phase}`," NEXT: resume the matching Comet phase or use an already recorded artifact path"]:i?[` BLOCKED: ${n.wireField} is already recorded for this change`,` Recorded path: ${i}`," NEXT: write the recorded artifact or explicitly correct the state path"]:[" BLOCKED: standard Superpowers artifact state is incomplete"," NEXT: validate the active change state, then retry the matching phase"]:[" BLOCKED: unmatched Superpowers artifact"," This docs/superpowers/ path does not match any active change artifact"," NEXT: use a recorded artifact path or a standard phase artifact directory"];return Ze(2,["","╔══════════════════════════════════════════╗","║ COMET PHASE GUARD — WRITE BLOCKED ║","╚══════════════════════════════════════════╝","",` Current phase: ${t.phase}`,` Target file: ${e}`,"",...r,""].join(` -`))}function VR(e,t){return Ze(2,["","╔══════════════════════════════════════════╗","║ COMET PHASE GUARD — WRITE BLOCKED ║","╚══════════════════════════════════════════╝",""," BLOCKED: multiple active changes require a current change",` Target file: ${e}`,` Active changes: ${t.join(", ")}`,""," NEXT: run comet state select , then retry the source write",""].join(` -`))}function Ar(e,t){return Ze(2,["","╔══════════════════════════════════════════╗","║ COMET PHASE GUARD — WRITE BLOCKED ║","╚══════════════════════════════════════════╝",""," BLOCKED: current change selection is stale or invalid",` Target file: ${e}`,` Reason: ${t}`,""," NEXT: run comet state select , then retry the source write",""].join(` -`))}async function YR(e,t,n,i=Ih){try{if((await i(e,[t])).projectTargets.length===0)return pt(`${t} (outside guarded project)`)}catch(l){return Ze(2,[`[COMET-HOOK] blocked: scope could not be determined safely for ${t}.`,`REASON: ${l instanceof Error?l.message:String(l)}`,"NEXT: verify that the project root is accessible, then retry the write."].join(` -`))}let r=await OR(t,e),s;try{s=await Ee(e)}catch(l){return Ze(2,`[COMET-HOOK] blocked: ${l instanceof Error?l.message:String(l)}`)}if(FR(r))return pt(`${r} (whitelist: comet config)`);if(WR(r))return pt(`${r} (whitelist: superpowers workspace)`);if(r==="CLAUDE.md"||r==="CHANGELOG.md"||r==="README.md"||DR(r))return pt(`${r} (whitelist: root markdown)`);let o;try{o=await qR(r,e,s,n)}catch(l){return Ze(2,`[COMET-HOOK] blocked: ${l instanceof Error?l.message:String(l)}`)}if(!o)return pt("no active comet change");if("blockedResult"in o)return o.blockedResult;if(o.archived)return pt(`${r} (own change archived)`);let a=o.phase,c=BR(r,a,`${A(e,s.openSpecRoot)}/`);if(c)return pt(c);if(Dh(r,qh(e,s))){if(o.superpowersArtifact==="matched"&&Wh(o))return pt(`${r} (phase: ${a}, superpowers)`);if(o.superpowersArtifact==="unmatched")return UR(r,o)}if(o.invalidState)return Ze(2,`[COMET-HOOK] blocked: active Classic state is invalid; repair .comet.yaml before writing ${r}`);if(a==="build"&&o.classic?.workflow==="full"&&!o.classic.designDoc)return KR(r);if(a==="build"&&o.classic?.workflow==="full"){let l=await Mh(e,o.classic.plan);if(l.status!=="ready")return JR(r,o,l,e,s)}return a==="build"||a==="verify"?pt(`${r} (phase: ${a})`):HR(r,a)}var Bh=async e=>{let t=xR(e),n=_R();return n?YR(t,n):pt("no file path in tool input")};var GR="comet.intent.v1";var zR=["start_change","resume_change","fix_bug","make_tweak","ask_question","unknown"],XR=["change_id","workflow","file_path","command","capability","bug_signal","risk_signal"],QR=["start","resume","continue","fix","modify","create","verify","archive","question","unknown"],Hh=["full","hotfix","tweak"],ZR=["small","medium","large","unknown"],e_=["full","hotfix","tweak","resume","ask_user","out_of_scope"],t_=["comet-open","comet-hotfix","comet-tweak","comet-design","comet-build","comet-verify","comet-archive"],n_=["user","repo","state"],gi=class extends Error{constructor(n){super(`Invalid CometIntentFrame: +`,"Classic handoff spec JSON output")}async function Eh(e,t,n){let i=xh.join(t,".comet.yaml"),r=(0,Ph.parseDocument)(await W(e,i,{label:"Classic change state"}),{uniqueKeys:!1});if(r.errors.length>0)throw new de(`ERROR: Invalid .comet.yaml: ${r.errors[0].message}`);let o=r.toJS()[n];return o==null?"":typeof o=="object"?JSON.stringify(o):String(o)}async function kR(e,t,n){let i=await Le(e,t.trajectoryRef);i.some(s=>s.type==="recovery_reconciled"&&s.data.kind==="classic-handoff"&&s.data.actionId===n)||await We(e,t.trajectoryRef,{sequence:i.length+1,timestamp:new Date().toISOString(),type:"recovery_reconciled",runId:t.runId,data:{kind:"classic-handoff",actionId:n}})}async function SR(e,t,n,i,r,s,o,a){let[c,l,f]=await Promise.all([Eo(t,n.contextRef),oi(t,n.artifactsRef),mp(t,n.checkpointRef)]),[u,d]=await Promise.all([un(e,r,"Classic handoff JSON output"),un(e,s,"Classic handoff markdown output")]);return u===null||d===null||c!==d||l.handoff_context!==o||l.handoff_markdown!==a?!1:f?.runId===n.runId&&f.contextHash===(c===null?null:It(c))&&f.artifactsHash===Oh(l)&&i.length===64}var Ih=async(e,t)=>mt(t,async()=>{let n=new Vl,[i,r,s,o]=e;try{hR(i);let a=await Ee(x()),c=await Ge(i,a.projectRoot),l=c.directory,f=A(a.projectRoot,l);if(r==="--hash-only"){if(!c.exists)throw new de(xe(`ERROR: change directory not found: ${f}`));for(let pn of["proposal.md","design.md","tasks.md"])if(!await xn(a.projectRoot,`${l}/${pn}`,`Classic handoff source ${pn}`))throw new de(xe(`ERROR: required file missing or empty: ${f}/${pn}`));return n.stdout.push(await kh(a.projectRoot,l,f)),n.toResult(0)}if(r!=="design"||s!=="--write")throw new de(xe("Usage: comet-handoff.mjs design --write [--full]"));let u;if(o===void 0||o==="")u="compact";else if(o==="--full")u="full";else throw new de(xe("Usage: comet-handoff.mjs design --write [--full]"));if(!c.exists)throw new de(xe(`ERROR: change directory not found: ${f}`));if(!c.stateExists)throw new de(xe(`ERROR: .comet.yaml not found at ${f}/.comet.yaml`));if(await Eh(a.projectRoot,l,"phase")!=="design")throw new de(xe("ERROR: design handoff requires phase: design"));for(let pn of["proposal.md","design.md","tasks.md"])if(!await xn(a.projectRoot,`${l}/${pn}`,`Classic handoff source ${pn}`))throw new de(xe(`ERROR: required OpenSpec artifact missing or empty: ${f}/${pn}`));let d=`${l}/.comet/handoff`;await Y(a.projectRoot,`${l}/.comet`,{label:"Classic change runtime directory",expected:"directory"}),await Y(a.projectRoot,d,{label:"Classic handoff directory",expected:"directory"});let p=await Eh(a.projectRoot,l,"context_compression")||"off",g,h;if(p==="off")g=`${d}/design-context.json`,h=`${d}/design-context.md`;else if(p==="beta")u==="full"&&n.stderr.push(pR("[HANDOFF] --full is ignored in beta mode; spec files are projected verbatim")),u="beta",g=`${d}/spec-context.json`,h=`${d}/spec-context.md`;else throw new de([xe(`ERROR: invalid context_compression: ${p}`),xe("Valid values: off, beta")].join(` +`));let m=A(a.projectRoot,g),y=A(a.projectRoot,h),w=await kh(a.projectRoot,l,f),C=`classic-handoff:${w}`,k=await B(l);if(!k.classic)throw new de(xe("ERROR: design handoff requires Classic state"));let E=k.run?await yr(l,k.run.pendingRef):null,R=E?.id===C&&E.type==="handoff"&&E.ref===w;if(k.classic.handoffHash&&k.classic.handoffHash!==w&&!R)throw new de(xe(`ERROR: stale handoff detected: source hash ${w} does not match completed hash ${k.classic.handoffHash}`));await Pn(a.projectRoot,`${l}/.comet`,"Classic change runtime directory"),await Pn(a.projectRoot,d,"Classic handoff directory");let O=await an(l),b=await yr(l,O.run.pendingRef),L=b?.id===C&&b.type==="handoff"&&b.ref===w;if(O.run.pending&&O.run.pending!==C)throw new de(xe(`ERROR: another action is pending: ${O.run.pending}`));if(O.classic.handoffHash===w&&O.classic.handoffContext===m&&!O.run.pending&&!b&&await SR(a.projectRoot,l,O.run,w,g,h,m,y))return n.stderr.push(ln(`[HANDOFF] wrote ${m}`)),n.stderr.push(ln(`[HANDOFF] wrote ${y}`)),n.stderr.push(ln(`[HANDOFF] handoff_hash=${w}`)),n.toResult(0);let Ie={id:C,stepId:O.run.currentStep,type:"handoff",ref:w};await Ro(l,O.run.pendingRef,Ie);let Q={...O.run,pending:C,status:"waiting"};await je(l,{classic:O.classic,run:Q,unknownKeys:(await B(l)).unknownKeys}),u==="beta"?(await bR(a.projectRoot,l,f,i,w,h),await CR(a.projectRoot,l,f,i,w,g)):(await wR(a.projectRoot,l,f,i,u,w,h),await yR(a.projectRoot,l,f,i,u,w,g));let K=await W(a.projectRoot,h,{label:"Classic handoff markdown output"});await So(l,Q.contextRef,K);let Ce={...await oi(l,Q.artifactsRef),handoff_context:m,handoff_markdown:y};await ai(l,Q.artifactsRef,Ce);let Hr={...O.classic,handoffContext:m,handoffHash:w},yt={...Q.currentStep==="full.design.handoff"?await cn(l,Hr,Q,{actionId:C,kind:"classic-handoff"}):Q,pending:null,status:"running"};(R||L)&&await kR(l,yt,C);let Kr=await Le(l,yt.trajectoryRef),mn={runId:yt.runId,stateVersion:yt.iteration,trajectoryOffset:Kr.length,contextHash:It(K),artifactsHash:Oh(Ce),createdAt:new Date().toISOString()};return await ci(l,yt.checkpointRef,mn),await je(l,{classic:Hr,run:yt,unknownKeys:(await B(l)).unknownKeys}),await _o(l,yt.pendingRef),n.stderr.push(ln(`[SET] handoff_context=${g}`)),n.stderr.push(ln(`[SET] handoff_hash=${w}`)),n.stderr.push(ln(`[HANDOFF] wrote ${m}`)),n.stderr.push(ln(`[HANDOFF] wrote ${y}`)),n.stderr.push(ln(`[HANDOFF] handoff_hash=${w}`)),n.toResult(0)}catch(a){if(a instanceof de){for(let c of a.message.split(` +`))n.stderr.push(c);return n.toResult(a.exitCode)}throw a}});import{promises as Jo,readFileSync as RR}from"fs";import qe from"path";import{promises as Gl}from"fs";import Me from"path";function Ah(e,t){let n=Me.relative(e,t);return n===""||n!==".."&&!n.startsWith(`..${Me.sep}`)&&!Me.isAbsolute(n)}async function ER(e){let t=Me.resolve(e),n=Me.parse(t).root,i=[],r=t;for(;r&&r!==n;)try{let s=await Gl.realpath(r);return Me.join(s,...i.reverse())}catch(s){let o=s.code;if(o!=="ENOENT"&&o!=="ENOTDIR")throw s;i.push(Me.basename(r)),r=Me.dirname(r)}try{let s=await Gl.realpath(n);return Me.join(s,...i.reverse())}catch{return null}}async function Nh(e,t){let n=Me.resolve(e),i=await Gl.realpath(n),r=[],s=[];for(let o of t){let a=Me.isAbsolute(o)?Me.resolve(o):Me.resolve(n,o),c=await ER(a);((c?Ah(i,c):Ah(n,a))?r:s).push(o)}return{projectTargets:r,externalTargets:s}}import Tn from"node:path";async function Ko(e,t){if(!t||t==="null")return{status:"missing",recordedPath:null};let n=await G(e),i=Tn.resolve(e,t),r=Tn.relative(n.superpowersPlansDir,i);return Tn.isAbsolute(t)||!r||r.startsWith(`..${Tn.sep}`)||Tn.isAbsolute(r)||r.includes(Tn.sep)||Tn.extname(r).toLowerCase()!==".md"?{status:"broken",recordedPath:t}:await X(e,t,{label:`Classic build plan ${t}`,expected:"file"})?{status:"ready",recordedPath:t}:{status:"broken",recordedPath:t}}function et(e,t){return{exitCode:e,stderr:t+` +`}}function ht(e){return et(0,`[COMET-HOOK] allowed: ${e}`)}function _R(){if(process.env.FILE_PATH)return process.env.FILE_PATH;if(process.stdin.isTTY)return"";let e=RR(0,"utf8");if(!e)return"";try{let t=JSON.parse(e);return typeof t.tool_input?.file_path=="string"?t.tool_input.file_path:""}catch{return""}}function Nr(e){return e.replaceAll("\\","/").replace(/\/+/gu,"/")}function jn(e){let t=Nr(e);return process.platform==="win32"?t.toLowerCase():t}function xR(e){let t=e.indexOf("--project-root"),n=t>=0?e[t+1]:void 0;return qe.resolve(n&&!n.startsWith("--")?n:process.cwd())}function Th(e,t){let n=Nr(qe.relative(t,e));return n===""?"":n.startsWith("../")||n===".."||qe.isAbsolute(n)?null:n}async function PR(e){let t=qe.resolve(e),n=qe.parse(t).root,i=[],r=t;for(;r&&r!==n;)try{let s=await Jo.realpath(r);return qe.join(s,...i.reverse())}catch(s){let o=s.code;if(o!=="ENOENT"&&o!=="ENOTDIR")throw s;i.push(qe.basename(r)),r=qe.dirname(r)}try{let s=await Jo.realpath(n);return qe.join(s,...i.reverse())}catch{return null}}async function OR(e,t){let n=qe.isAbsolute(e)?e:qe.resolve(t,e),i=Nr(n),r=Th(n,t);if(r!==null)return r;try{let s=await PR(n),o=await Jo.realpath(t);if(s){let a=Th(s,o);if(a!==null)return a;i=Nr(s)}}catch{if(!qe.isAbsolute(e))return Nr(e).replace(/^\.\//u,"")}return i.replace(/^\.\//u,"")}async function qh(e){try{let t=await B(e,{migrate:!1}),n=Array.from(new Set(t.unknownKeys)).sort();if(n.length>0)throw new Error(`Invalid Classic state: unknown field(s): ${n.join(", ")}`);if(!t.classic)throw new Error("Classic state projection is unavailable");return{changeDir:e,phase:t.classic.phase,classic:t.classic,archived:t.classic.archived}}catch(t){let n=await fp(e);return n.phase?{changeDir:e,phase:n.phase,classic:null,archived:n.archived,invalidState:t instanceof Error&&t.message.includes("unknown field")}:null}}async function $R(e){let t=(await G(e)).changesDir,n=[];if(!(await Y(e,t,{label:"Classic changes directory",expected:"directory"})).exists)return n;for(let r of(await Jo.readdir(t,{withFileTypes:!0})).sort((s,o)=>s.name.localeCompare(o.name))){if(r.name==="archive"||ge(r.name))continue;let s=await Ge(r.name,e);if(!s.exists||!s.stateExists)continue;let o=await qh(s.directory);!o||o.archived||n.push(o)}return n}var zl=br("classicActiveChanges",e=>$R(e)),Dh=br("classicPlanReadiness",Ko);function Fh(e,t){return`${A(e,t.superpowersRoot)}/`}function Wh(e,t){return jn(e).startsWith(jn(t))}function IR(e,t){return[{prefix:`${A(e,t.superpowersSpecsDir)}/`,field:"designDoc",wireField:"design_doc",phase:"design"},{prefix:`${A(e,t.superpowersPlansDir)}/`,field:"plan",wireField:"plan",phase:"build"},{prefix:`${A(e,t.superpowersReportsDir)}/`,field:"verificationReport",wireField:"verification_report",phase:"verify"}]}function AR(e,t){let n=jn(e),i=t.find(s=>n.startsWith(jn(s.prefix)));if(!i)return null;let r=n.slice(jn(i.prefix).length);return!r||r.includes("/")||!r.endsWith(".md")?null:i}function Bh(e,t){return e.classic?.[t.field]??null}function NR(e,t){return e.classic!==null&&e.phase===t.phase&&!Bh(e,t)}async function jh(e,t,n){return NR(t,n)?!0:n.field!=="plan"||t.phase!=="build"?!1:(await Dh(e,t.classic?.plan??null)).status==="broken"}function Hh(e){return e.phase==="design"||e.phase==="build"||e.phase==="verify"}function At(e){return e.changeDir?qe.basename(e.changeDir):null}var TR=new Set(["design","plan","verify","verification","verification-report","report"]);function Lh(e){return e.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}function jR(e,t){return[t.classic?.designDoc,t.classic?.plan,t.classic?.verificationReport].some(i=>i&&jn(i)===jn(e))}function LR(e,t){let i=(e.split("/").at(-1)??e).replace(/\.[^.]+$/u,"");if(i===t)return!0;let r=[...TR].map(Lh).join("|");return new RegExp(`(^|[-_.])${Lh(t)}[-_.](${r})$`,"u").test(i)}async function MR(e,t){let n=await zl(t),i=n.find(o=>jR(e,o));if(i)return{governing:i,match:"recorded"};let s=n.filter(Hh).filter(o=>{let a=At(o);return a!==null&&LR(e,a)}).sort((o,a)=>(At(a)?.length??0)-(At(o)?.length??0))[0];return s?{governing:s,match:"named"}:null}async function Mh(e,t,n){let i=await zl(e);if(i.length===0)return null;if(n)return i.find(o=>At(o)===n)??{blockedResult:Ar(t,`selected change '${n}' is no longer active`)};let r=await Mo(e);if(r.status==="stale")return{blockedResult:Ar(t,r.reason)};if(r.status==="selected"){let s=i.find(o=>At(o)===r.selection.change);return s||{blockedResult:Ar(t,`selected change '${r.selection.change}' is no longer active`)}}if(i.length===1){let s=i[0];if(s.changeDir!==null){let o=await xt(s.changeDir,{heal:!1,cwd:e}),a=At(s)??"unknown";if(o.status==="drift")return{blockedResult:Ar(t,kr(a,o.boundBranch,o.currentBranch))};if(o.status==="unbound-detached")return{blockedResult:Ar(t,Pt(a))}}return s}return{blockedResult:VR(t,i.map(s=>At(s)).filter(Boolean))}}async function qR(e,t,n,i){let r=`${A(t,n.changesDir)}/`;if(e.startsWith(r)){let s=e.slice(r.length),[o]=s.split("/");if(o&&o!=="archive"){let a=await Ge(o,t);if(a.stateExists){let c=await qh(a.directory);return c||{changeDir:a.directory,phase:"open",classic:null,archived:!1}}return{changeDir:a.directory,phase:"open",classic:null,archived:!1}}}if(Wh(e,Fh(t,n))){let s=await MR(e,t);if(s?.match==="recorded")return{...s.governing,superpowersArtifact:"matched"};let o=AR(e,IR(t,n));if(s)return o?{...s.governing,superpowersArtifact:await jh(t,s.governing,o)?"matched":"unmatched",superpowersSlot:o}:{...s.governing,superpowersArtifact:"matched"};if(o){let l=await Mh(t,e,i);return!l||"blockedResult"in l?l:{...l,superpowersArtifact:await jh(t,l,o)?"matched":"unmatched",superpowersSlot:o}}let a=await zl(t),c=i?a.find(l=>At(l)===i)??null:a[0]??null;return c?{...c,superpowersArtifact:"unmatched"}:null}return Mh(t,e,i)}function DR(e){return!e.includes("/")&&e.endsWith(".md")}function FR(e){return e.startsWith(".comet/")||e.includes("/.comet/")}function WR(e){return e===".superpowers"||e.startsWith(".superpowers/")}function BR(e,t,n){if(!e.startsWith(n))return null;let i=e.endsWith("/.comet.yaml")||e.endsWith("/.openspec.yaml"),r=e.endsWith("/proposal.md")||e.endsWith("/design.md")||e.endsWith("/tasks.md"),s=e.includes("/.comet/"),o=e.includes("/specs/");return t==="open"&&(r||i||s||o)?`${e} (phase: open, openspec artifacts)`:t==="design"&&(r||i||s||o)?`${e} (phase: design, handoff/spec)`:t==="build"&&(e.endsWith("/tasks.md")||i||o)?`${e} (phase: build, spec/tasks)`:t==="verify"&&(e.endsWith("/tasks.md")||i)?`${e} (phase: verify, tasks/state)`:t==="archive"&&i?`${e} (phase: archive, state)`:null}function HR(e,t){let n=t==="open"?[" BLOCKED: source writes are not allowed during open"," This phase does not allow source writes"," ALLOWED: create proposal/design/tasks artifacts and run guard"," NEXT: finish clarification and artifacts, then run guard --apply"]:t==="design"?[" BLOCKED: source writes are not allowed during design"," This phase does not allow source writes"," ALLOWED: run brainstorming, create the Design Doc, and run guard"," NEXT: finish the Design Doc, then run comet guard design --apply to enter build"]:[" BLOCKED: source writes are not allowed during archive"," This phase does not allow source writes"," ALLOWED: confirm archive state and run the archive script"];return et(2,["","╔══════════════════════════════════════════╗","║ COMET PHASE GUARD — WRITE BLOCKED ║","╚══════════════════════════════════════════╝","",` Current phase: ${t}`,` Target file: ${e}`,"",...n,""].join(` +`))}function KR(e){return et(2,["","╔══════════════════════════════════════════╗","║ COMET PHASE GUARD — WRITE BLOCKED ║","╚══════════════════════════════════════════╝",""," Current phase: build (workflow: full), but design_doc is empty",` Target file: ${e}`,""," BLOCKED: full workflow source writes require a recorded Design Doc"," This phase does not allow source writes until design_doc is recorded"," NEXT: return to design, create/link the Design Doc, then run guard again",""].join(` +`))}function JR(e,t,n,i,r){let s=At(t)??"",o=n.status==="missing",a=o?"classic-build-plan-missing":"classic-build-plan-broken",c=o?"plan is not recorded":"the recorded plan path does not resolve to a file",l=o?[]:[`RECORDED_PLAN: ${n.recordedPath}`],f=t.changeDir?A(i,t.changeDir):"",u=A(i,r.superpowersPlansDir),d=o?`comet state set ${s} plan `:`comet state set ${s} plan `,p=o?["2. Load the Superpowers writing-plans Skill.",`3. Read the Design Doc path from "comet state get ${s} design_doc" and read ${f}/tasks.md.`,`4. Create the implementation plan under ${u}/.`,"5. Record the plan path:",` ${d}`]:[`2. Restore the plan file at ${n.recordedPath}, or load the Superpowers writing-plans Skill and create a replacement under ${u}/.`,"3. When creating a replacement, record its path:",` ${d}`];return et(2,["","╔══════════════════════════════════════════╗","║ COMET PHASE GUARD — WRITE BLOCKED ║","╚══════════════════════════════════════════╝","",`ERROR_CODE: ${a}`,`CHANGE: ${s}`,"WORKFLOW: full","PHASE: build",`TARGET: ${e}`,`STATE: ${c}`,...l,"","BLOCKED: project source writes require a ready Superpowers implementation plan.","","ALLOWED_RECOVERY_WRITES:",`- ${u}/.md`,"- Comet state updates performed by the comet CLI",`- ${f} artifacts allowed by the build phase`,"","RECOVERY:",`1. Invoke /comet-build for ${s} and resume Step 1.`,...p,`${o?"6":"4"}. Verify recovery:`,` comet state check ${s} build --recover`,"","SUCCESS: plan is reported as DONE and recovery advances beyond plan creation.",`RETRY: retry the original Write/Edit for ${e} only after SUCCESS.`,"PROHIBITED: do not treat tasks.md as the implementation plan or write project source before SUCCESS.","If writing-plans is unavailable, stop and report the missing Skill instead of bypassing this check.",""].join(` +`))}function UR(e,t){let n=t.superpowersSlot,i=n?Bh(t,n):null,r=n?t.phase!==n.phase?[` BLOCKED: ${n.wireField} cannot be first-written in phase ${t.phase}`,` Expected phase: ${n.phase}`," NEXT: resume the matching Comet phase or use an already recorded artifact path"]:i?[` BLOCKED: ${n.wireField} is already recorded for this change`,` Recorded path: ${i}`," NEXT: write the recorded artifact or explicitly correct the state path"]:[" BLOCKED: standard Superpowers artifact state is incomplete"," NEXT: validate the active change state, then retry the matching phase"]:[" BLOCKED: unmatched Superpowers artifact"," This docs/superpowers/ path does not match any active change artifact"," NEXT: use a recorded artifact path or a standard phase artifact directory"];return et(2,["","╔══════════════════════════════════════════╗","║ COMET PHASE GUARD — WRITE BLOCKED ║","╚══════════════════════════════════════════╝","",` Current phase: ${t.phase}`,` Target file: ${e}`,"",...r,""].join(` +`))}function VR(e,t){return et(2,["","╔══════════════════════════════════════════╗","║ COMET PHASE GUARD — WRITE BLOCKED ║","╚══════════════════════════════════════════╝",""," BLOCKED: multiple active changes require a current change",` Target file: ${e}`,` Active changes: ${t.join(", ")}`,""," NEXT: run comet state select , then retry the source write",""].join(` +`))}function Ar(e,t){return et(2,["","╔══════════════════════════════════════════╗","║ COMET PHASE GUARD — WRITE BLOCKED ║","╚══════════════════════════════════════════╝",""," BLOCKED: current change selection is stale or invalid",` Target file: ${e}`,` Reason: ${t}`,""," NEXT: run comet state select , then retry the source write",""].join(` +`))}async function YR(e,t,n,i=Nh){try{if((await i(e,[t])).projectTargets.length===0)return ht(`${t} (outside guarded project)`)}catch(l){return et(2,[`[COMET-HOOK] blocked: scope could not be determined safely for ${t}.`,`REASON: ${l instanceof Error?l.message:String(l)}`,"NEXT: verify that the project root is accessible, then retry the write."].join(` +`))}let r=await OR(t,e),s;try{s=await Ee(e)}catch(l){return et(2,`[COMET-HOOK] blocked: ${l instanceof Error?l.message:String(l)}`)}if(FR(r))return ht(`${r} (whitelist: comet config)`);if(WR(r))return ht(`${r} (whitelist: superpowers workspace)`);if(r==="CLAUDE.md"||r==="CHANGELOG.md"||r==="README.md"||DR(r))return ht(`${r} (whitelist: root markdown)`);let o;try{o=await qR(r,e,s,n)}catch(l){return et(2,`[COMET-HOOK] blocked: ${l instanceof Error?l.message:String(l)}`)}if(!o)return ht("no active comet change");if("blockedResult"in o)return o.blockedResult;if(o.archived)return ht(`${r} (own change archived)`);let a=o.phase,c=BR(r,a,`${A(e,s.openSpecRoot)}/`);if(c)return ht(c);if(Wh(r,Fh(e,s))){if(o.superpowersArtifact==="matched"&&Hh(o))return ht(`${r} (phase: ${a}, superpowers)`);if(o.superpowersArtifact==="unmatched")return UR(r,o)}if(o.invalidState)return et(2,`[COMET-HOOK] blocked: active Classic state is invalid; repair .comet.yaml before writing ${r}`);if(a==="build"&&o.classic?.workflow==="full"&&!o.classic.designDoc)return KR(r);if(a==="build"&&o.classic?.workflow==="full"){let l=await Dh(e,o.classic.plan);if(l.status!=="ready")return JR(r,o,l,e,s)}return a==="build"||a==="verify"?ht(`${r} (phase: ${a})`):HR(r,a)}var Kh=async e=>{let t=xR(e),n=_R();return n?YR(t,n):ht("no file path in tool input")};var GR="comet.intent.v1";var zR=["start_change","resume_change","fix_bug","make_tweak","ask_question","unknown"],XR=["change_id","workflow","file_path","command","capability","bug_signal","risk_signal"],QR=["start","resume","continue","fix","modify","create","verify","archive","question","unknown"],Jh=["full","hotfix","tweak"],ZR=["small","medium","large","unknown"],e_=["full","hotfix","tweak","resume","ask_user","out_of_scope"],t_=["comet-open","comet-hotfix","comet-tweak","comet-design","comet-build","comet-verify","comet-archive"],n_=["user","repo","state"],gi=class extends Error{constructor(n){super(`Invalid CometIntentFrame: ${n.map(i=>`- ${i}`).join(` -`)}`);this.issues=n}issues};function Pe(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function fn(e,t,n,i){return typeof e!="string"||!t.includes(e)?(i.push(`${n} must be one of: ${t.join(", ")}`),null):e}function Xl(e,t,n,i){return e==null?null:fn(e,t,n,i)}function pi(e,t,n){return typeof e!="string"||e.trim()===""?(n.push(`${t} must be a non-empty string`),""):e}function Ql(e,t,n){return e==null?null:typeof e!="string"||e.trim()===""?(n.push(`${t} must be a non-empty string or null`),null):e}function hi(e,t,n){return e==null?null:typeof e!="boolean"?(n.push(`${t} must be boolean or null`),null):e}function Kh(e,t,n){return typeof e!="number"||Number.isNaN(e)||e<0||e>1?(n.push(`${t} must be a number between 0 and 1`),0):e}function i_(e,t,n){return typeof e!="number"||!Number.isInteger(e)||e<0?(n.push(`${t} must be a non-negative integer`),0):e}function r_(e){let t=[];if(!Pe(e))throw new gi(["frame must be an object"]);let n=Pe(e.intent)?e.intent:{};Pe(e.intent)||t.push("intent must be an object");let i=Pe(e.slots)?e.slots:{};Pe(e.slots)||t.push("slots must be an object");let r=Pe(e.context)?e.context:{};Pe(e.context)||t.push("context must be an object");let s=Pe(e.proposed_route)?e.proposed_route:{};Pe(e.proposed_route)||t.push("proposed_route must be an object");let o=e.entities===void 0?[]:Array.isArray(e.entities)?e.entities:[];e.entities!==void 0&&!Array.isArray(e.entities)&&t.push("entities must be an array");let a=Array.isArray(e.evidence)?e.evidence:[];Array.isArray(e.evidence)||t.push("evidence must be an array");let c={schema_version:fn(e.schema_version,[GR],"schema_version",t),utterance:pi(e.utterance,"utterance",t),locale:e.locale===void 0?"unknown":pi(e.locale,"locale",t),intent:{name:fn(n.name,zR,"intent.name",t)??"unknown",confidence:Kh(n.confidence,"intent.confidence",t)},entities:o.map((l,f)=>{let u=Pe(l)?l:{};return Pe(l)||t.push(`entities[${f}] must be an object`),{type:fn(u.type,XR,`entities[${f}].type`,t)??"risk_signal",value:pi(u.value,`entities[${f}].value`,t),text:pi(u.text,`entities[${f}].text`,t)}}),slots:{requested_action:fn(i.requested_action,QR,"slots.requested_action",t)??"unknown",workflow_candidate:Xl(i.workflow_candidate,Hh,"slots.workflow_candidate",t),user_explicit_workflow:Xl(i.user_explicit_workflow,Hh,"slots.user_explicit_workflow",t),change_id:Ql(i.change_id,"slots.change_id",t),target_area:Ql(i.target_area,"slots.target_area",t),scope:i.scope===void 0?"unknown":fn(i.scope,ZR,"slots.scope",t)??"unknown",existing_behavior:hi(i.existing_behavior,"slots.existing_behavior",t),new_capability:hi(i.new_capability,"slots.new_capability",t),public_api_change:hi(i.public_api_change,"slots.public_api_change",t),schema_change:hi(i.schema_change,"slots.schema_change",t),cross_module_change:hi(i.cross_module_change,"slots.cross_module_change",t)},context:{active_changes_count:i_(r.active_changes_count,"context.active_changes_count",t),active_change_names:Pe(r)?Array.isArray(r.active_change_names)?r.active_change_names.every(l=>typeof l=="string")?r.active_change_names:(t.push("context.active_change_names must only contain strings"),[]):(t.push("context.active_change_names must be an array"),[]):[],dirty_worktree:hi(r.dirty_worktree,"context.dirty_worktree",t)},evidence:a.map((l,f)=>{let u=Pe(l)?l:{};return Pe(l)||t.push(`evidence[${f}] must be an object`),{field:pi(u.field,`evidence[${f}].field`,t),quote:pi(u.quote,`evidence[${f}].quote`,t),source:fn(u.source,n_,`evidence[${f}].source`,t)??"user"}}),proposed_route:{name:fn(s.name,e_,"proposed_route.name",t)??"ask_user",next_skill:Xl(s.next_skill,t_,"proposed_route.next_skill",t),confidence:Kh(s.confidence,"proposed_route.confidence",t),requires_confirmation:typeof s.requires_confirmation=="boolean"?s.requires_confirmation:!0,fallback_reason:Ql(s.fallback_reason,"proposed_route.fallback_reason",t)}};if(t.length>0)throw new gi(t);return c}function Zl(e,t){return e.evidence.some(n=>n.field===t&&n.quote.trim()!=="")}function Jh(e){return e.slots.new_capability===!0||e.slots.public_api_change===!0||e.slots.schema_change===!0||e.slots.cross_module_change===!0}function Ln(e,t,n=null){return{name:e,next_skill:{full:"comet-open",hotfix:"comet-hotfix",tweak:"comet-tweak",resume:null,ask_user:null,out_of_scope:null}[e],confidence:t,requires_confirmation:e==="ask_user"||e==="out_of_scope",fallback_reason:n}}function Tr(e){return Ln("ask_user",.5,e)}function Uh(e,t){return Ln(e,t)}function Vh(e){let t=r_(e),n=[],i=t.intent.confidence,r;return t.intent.confidence<.7?r=Tr(`intent confidence ${t.intent.confidence} is below ${.7}`):(t.intent.name==="resume_change"||t.slots.requested_action==="resume"||t.slots.requested_action==="continue")&&!t.slots.change_id&&t.context.active_changes_count>1?r=Tr("multiple active changes require an explicit change_id"):(t.intent.name==="resume_change"||t.slots.requested_action==="resume"||t.slots.requested_action==="continue")&&t.slots.change_id?r=t.context.active_change_names.includes(t.slots.change_id)?Ln("resume",i):Tr(`change_id '${t.slots.change_id}' is not in active_change_names`):t.intent.name==="ask_question"||t.slots.requested_action==="question"?r=Ln("out_of_scope",i,"user asked a question without requesting a Comet workflow"):t.slots.user_explicit_workflow&&t.slots.user_explicit_workflow!=="full"&&Jh(t)?r=Tr(`explicit workflow '${t.slots.user_explicit_workflow}' conflicts with risk signals`):t.slots.user_explicit_workflow?r=Uh(t.slots.user_explicit_workflow,i):Jh(t)?r=Ln("full",i):t.intent.name==="fix_bug"&&t.slots.existing_behavior===!0&&Zl(t,"slots.workflow_candidate")?r=Ln("hotfix",i):t.intent.name==="make_tweak"&&t.slots.workflow_candidate==="tweak"&&Zl(t,"slots.workflow_candidate")?r=Ln("tweak",i):t.slots.workflow_candidate&&Zl(t,"slots.workflow_candidate")?r=Uh(t.slots.workflow_candidate,i):r=Tr("workflow_candidate evidence is missing or route is ambiguous"),r.name!==t.proposed_route.name&&n.push(`agent proposed_route '${t.proposed_route.name}' normalized to '${r.name}'`),r.next_skill!==t.proposed_route.next_skill&&n.push(`agent proposed_route next_skill '${t.proposed_route.next_skill}' normalized to '${r.next_skill}'`),r.requires_confirmation!==t.proposed_route.requires_confirmation&&n.push(`agent proposed_route requires_confirmation '${t.proposed_route.requires_confirmation}' normalized to '${r.requires_confirmation}'`),r.fallback_reason!==t.proposed_route.fallback_reason&&n.push(`agent proposed_route fallback_reason '${t.proposed_route.fallback_reason}' normalized to '${r.fallback_reason}'`),{route:r,diagnostics:n,normalizedFrame:{...t,route:r}}}function Uo(e,t,n){return{exitCode:e,...t===void 0?{}:{stdout:t},...n===void 0?{}:{stderr:n}}}function Yh(){return Uo(64,void 0,`Usage: comet-intent.mjs route -Usage: comet-intent.mjs route --stdin`)}async function s_(){let e=[];for await(let t of process.stdin)e.push(Buffer.isBuffer(t)?t:Buffer.from(String(t)));return Buffer.concat(e).toString("utf8")}var Gh=async(e,t)=>{let[n,i]=e;if(n!=="route")return Yh();let r=i==="--stdin"?await s_():i;if(!r)return Yh();try{let s=Vh(JSON.parse(r));return Uo(0,`${JSON.stringify(s,null,2)} -`)}catch(s){if(s instanceof SyntaxError)return Uo(1,void 0,`Invalid JSON: ${s.message}`);if(s instanceof gi)return Uo(1,void 0,s.message);throw s}};import{spawn as o_}from"child_process";var wi="comet.resume_probe.v1";function zh(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function a_(e){if(!zh(e))throw new Error("Invalid CometResumeProbeInput: input must be an object");if(e.schema_version!==wi)throw new Error(`Invalid CometResumeProbeInput: schema_version must be ${wi}`);if(typeof e.utterance!="string")throw new Error("Invalid CometResumeProbeInput: utterance must be a string");let t=zh(e.agent_context)?e.agent_context:{};return{schema_version:wi,utterance:e.utterance,locale:typeof e.locale=="string"?e.locale:"unknown",agent_context:{non_trivial_work:t.non_trivial_work===!0,already_in_comet_flow:t.already_in_comet_flow===!0}}}function Oe(e,t,n,i,r=[]){return{schema_version:wi,action:e,changeName:t?.name??null,phase:t?.phase??null,nextCommand:e==="auto_resume"||e==="ask_user"?t?.nextCommand??null:null,confidence:n,reason:i,evidence:r}}async function c_(e,t,n){return await X(e,t,{label:n,expected:"file"})?W(e,t,{label:n}):""}async function Xh(e,t,n){let i=["proposal.md","design.md","tasks.md"],r=[n.name,n.workflow,n.phase];for(let s of i)r.push(await c_(e,`${t}/${s}`,`Classic change ${n.name} ${s}`));return r.join(` -`).toLowerCase()}function l_(e){switch(e){case"open":return"/comet-open";case"design":return"/comet-design";case"build":return"/comet-build";case"verify":return"/comet-verify";case"archive":return"/comet-archive";default:return null}}function u_(e,t,n){let i=n.classic,r=n.unknownKeys.filter(s=>s!=="run_id");return i?r.length>0?{name:t,valid:!1,workflow:i.workflow,phase:i.phase,currentStep:null,nextCommand:null,runtimeMode:"invalid",runtimeEval:null,evidence:[],error:`unknown field(s): ${r.join(", ")}`}:{name:t,valid:!0,workflow:i.workflow,phase:i.phase,currentStep:null,nextCommand:l_(i.phase),runtimeMode:"engine-projection",runtimeEval:null,evidence:[]}:{name:t,valid:!1,workflow:"unknown",phase:"invalid",currentStep:null,nextCommand:null,runtimeMode:"invalid",runtimeEval:null,evidence:[],error:`${e} does not contain valid Comet state`}}async function f_(e,t){return await X(e,`${t}/proposal.md`,{label:"Classic proposal",expected:"file"})||await X(e,`${t}/design.md`,{label:"Classic design",expected:"file"})||await X(e,`${t}/tasks.md`,{label:"Classic tasks",expected:"file"})}async function d_(e){let t=(await z(e)).changesDir;if(!(await Y(e,t,{label:"Classic changes directory",expected:"directory"})).exists)return[];let i=await Eu(t),r=[];for(let s of i){if(s==="archive"||ge(s))continue;let o=await Ye(s,e);if(!o.exists)continue;let a=o.directory;if(!o.stateExists){if(!await f_(e,a))continue;let m={name:s,workflow:"unknown",phase:"invalid",nextCommand:null,diagnostic:{name:s,valid:!1,workflow:"unknown",phase:"invalid",currentStep:null,nextCommand:null,runtimeMode:"invalid",runtimeEval:null,evidence:[],error:"missing Comet state"},buildPause:null,hasClassicProjection:!1,verifyResult:null,text:"",missingCometState:!0};m.text=await Xh(e,a,m),r.push(m);continue}let l=await B(a,{migrate:!1}),f=l.classic,u=u_(a,s,l),d=!!f,p=f?.phase??u.phase,g=f?.workflow??u.workflow;if(p==="archive"||f?.archived)continue;let h={name:s,workflow:g,phase:p,nextCommand:u.nextCommand,diagnostic:u,buildPause:f?.buildPause??null,hasClassicProjection:d,verifyResult:f?.verifyResult??null,text:"",missingCometState:!1};h.text=await Xh(e,a,h),r.push(h)}return r}var m_=["continue","resume","carry on","finish","run it","commit","verify","archive","继续","接着","恢复","跑完","提交","验证","归档","修刚才"],p_=["what","why","how","explain","summarize","reliable","靠谱吗","是什么","为什么","解释","总结","取名","命名"],h_=new Set(["add","build","cache","change","code","design","docs","file","fix","implement","plan","readme","task","test","update","修改","更新","修复","添加","文档","任务","计划","实现"]),g_=["do not resume","don't resume","without comet","skip comet","不要恢复","不走 comet","不要走 comet","直接解释","只回答"];function eu(e,t){return t.some(n=>e.includes(n))}function Qh(e){return e.missingCometState||!e.hasClassicProjection||!e.diagnostic.valid||e.phase==="archive"||e.verifyResult==="fail"||e.diagnostic.runtimeEval&&!e.diagnostic.runtimeEval.passed?!0:e.phase!=="build"?!1:e.buildPause==="plan-ready"}function w_(e,t){let n=e.toLowerCase(),i=[];n.includes(t.name.toLowerCase())&&i.push({source:"user",quote:t.name});let r=t.text.split(/[^a-zA-Z0-9_\-\u4e00-\u9fff/]+/u).map(o=>o.trim().toLowerCase()).filter(o=>o.length>=4&&!h_.has(o)),s=[...new Set(r.filter(o=>n.includes(o)))].slice(0,3);for(let o of s)i.push({source:"repo",quote:o});return i}async function y_(e){return new Promise(t=>{let n=o_("git",["status","--short","--untracked-files=all"],{cwd:e,stdio:["ignore","pipe","ignore"],shell:!1}),i=[];n.stdout.on("data",r=>{i.push(Buffer.isBuffer(r)?r:Buffer.from(String(r)))}),n.on("error",()=>t([])),n.on("exit",r=>{if(r!==0){t([]);return}let s=Buffer.concat(i).toString("utf8").split(/\r?\n/u).map(o=>o.trim()).filter(Boolean);t(s)})})}async function Zh(e,t){let n=a_(t),i=n.utterance.trim(),r=i.toLowerCase();if(n.agent_context.already_in_comet_flow)return Oe("out_of_scope",null,"low","already in Comet flow");if(eu(r,g_))return Oe("out_of_scope",null,"low","user opted out of Comet resume",[{source:"user",quote:i}]);let s=await d_(e);if(s.length===0)return Oe("none",null,"none","no active Comet changes");let o=await y_(e);if(s.length>1){let u=s.find(d=>r.includes(d.name.toLowerCase()));return u?o.length>0?Oe("ask_user",u,"low","uncommitted worktree changes require attribution",[{source:"repo",quote:`${o.length} dirty file(s)`}]):Qh(u)?Oe("ask_user",u,"low","active change is at a decision point"):Oe("auto_resume",u,"high","request names an active change",[{source:"user",quote:u.name}]):Oe("ask_user",null,"low","multiple active changes require a change name")}let[a]=s;if(o.length>0)return Oe("ask_user",a,"low","uncommitted worktree changes require attribution",[{source:"repo",quote:`${o.length} dirty file(s)`}]);if(Qh(a))return a.missingCometState?Oe("ask_user",a,"low","active OpenSpec change is missing Comet state"):Oe("ask_user",a,"low","active change is at a decision point",[{source:"state",quote:`phase: ${a.phase}`}]);let c=eu(r,m_);if(!n.agent_context.non_trivial_work&&eu(r,p_)&&!c)return Oe("out_of_scope",a,"low","user asked a question without workflow work");let f=w_(i,a);return c||f.length>0?Oe("auto_resume",a,"high","single active change and request is related",[{source:"state",quote:`phase: ${a.phase}`},...f]):n.agent_context.non_trivial_work?Oe("ask_user",a,"low","single active change exists but request looks unrelated"):Oe("out_of_scope",a,"low","request is not workflow work")}function Vo(e,t,n){return{exitCode:e,...t===void 0?{}:{stdout:t},...n===void 0?{}:{stderr:n}}}function eg(){return Vo(64,void 0,`Usage: comet-resume-probe.mjs probe -Usage: comet-resume-probe.mjs probe --stdin`)}async function v_(){let e=[];for await(let t of process.stdin)e.push(Buffer.isBuffer(t)?t:Buffer.from(String(t)));return Buffer.concat(e).toString("utf8")}function b_(e){return{schema_version:wi,utterance:e,locale:"unknown",agent_context:{non_trivial_work:!0,already_in_comet_flow:!1}}}function C_(e){try{return JSON.parse(e)}catch{return b_(e)}}var tg=async(e,t)=>dt(t,async()=>{let[n,i]=e;if(n!=="probe")return eg();let r=i==="--stdin",s=r?await v_():i;if(!s)return eg();try{let o=r?C_(s):JSON.parse(s),a=await Zh(x(),o);return Vo(0,`${JSON.stringify(a,null,2)} -`)}catch(o){return o instanceof SyntaxError?Vo(1,void 0,`Invalid JSON: ${o.message}`):Vo(1,void 0,o instanceof Error?o.message:String(o))}});rr();ct();Ct();Ne();import{createHash as Dr,randomUUID as na}from"crypto";import{promises as ne}from"fs";import $ from"path";var su=".comet/classic-root-move.json",ou=".comet/transactions/classic-root-move//openspec",cg=["handoff hashes","Run state","checkpoints","trajectory","archived evidence and artifact pointers"],lg=["approved plan ID still matches layout, source identity and manifest, target identity, and configuration","no pending root-move recovery transaction","target remains absent or the bound empty directory","source, target, staging, transaction, and config paths remain protected"],Qo=5e4,Xo=512*1024*1024,ng=16*1024*1024,ht=/^[a-f0-9]{64}$/u,ug=/^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/u,fg=Symbol("ClassicRootMoveJournalClaim");function tt(e,t){return $.relative(e,t).replaceAll("\\","/")}async function Si(e,t,n,i="directory"){await T(e,tt(e,t),{label:`Classic root move physical path ${n}`,expected:i})}function dg(e,t){return Ae(e,t)}async function $e(e,t,n){let i=$.resolve(e),r=$.resolve(t),s=$.relative(i,r);if($.isAbsolute(s)||s===".."||s.startsWith(`..${$.sep}`))throw new Error(`${n} must stay inside the project root`);r!==i&&await Si(e,t,n,"directory");let o=[i],a=i;for(let l of s.split($.sep).filter(Boolean))a=$.join(a,l),o.push(a);let c=[];for(let l of o){let f=await ne.lstat(l,{bigint:!0});if(!f.isDirectory()||f.isSymbolicLink())throw new Error(`${n} crosses a symbolic link or junction`);c.push({path:l,identity:Fn(f),stat:f})}return{entries:c}}async function V(e,t){for(let n of e.entries){let i=await ne.lstat(n.path,{bigint:!0});if(!i.isDirectory()||i.isSymbolicLink()||!dg(n.identity,Fn(i)))throw new Error(`${t} changed after inspection`)}}async function k_(e,t,n,i){let r=await $e(e,t,n);await i?.afterDirectoryInspect?.(n),await V(r,n);let s=await ne.readdir(t,{withFileTypes:!0});return await V(r,n),s}async function qn(e,t,n){try{return await $e(e,t,n),!0}catch(i){if(i.code==="ENOENT")return!1;throw i}}async function yi(e,t,n,i){let r=$.resolve(e),s=$.resolve(t),o=$.relative(r,s);if($.isAbsolute(o)||o===".."||o.startsWith(`..${$.sep}`))throw new Error(`${n} must stay inside the project root`);let a=r;for(let c of o.split($.sep).filter(Boolean)){let l=$.join(a,c);try{let f=await ne.lstat(l,{bigint:!0});if(!f.isDirectory()||f.isSymbolicLink())throw new Error(`${n} crosses a symbolic link or junction`)}catch(f){if(f.code!=="ENOENT")throw f;let u=await $e(e,a,n),d=`create-directory:${tt(e,l)}`;await i?.beforeMutation?.(d),await V(u,n);try{await ne.mkdir(l)}catch(g){if(g.code!=="EEXIST")throw g}await V(u,n);let p=await ne.lstat(l,{bigint:!0});if(!p.isDirectory()||p.isSymbolicLink())throw new Error(`${n} changed while creating a directory`,{cause:f})}a=l}await Si(e,t,n,"directory")}async function Ei(e,t,n){let i=await ne.lstat(e,{bigint:!0});if(i.isSymbolicLink()||(t==="file"?!i.isFile():!i.isDirectory()))throw new Error(`${n} must be a real ${t}`);return i}async function et(e,t,n){let i=await ne.lstat(e,{bigint:!0}),r=t.isDirectory()?dg(Fn(t),Fn(i)):sa(t,i);if(i.isSymbolicLink()||i.isFile()!==t.isFile()||i.isDirectory()!==t.isDirectory()||!r)throw new Error(`${n} changed after inspection`)}async function au(e,t,n,i,r){let s=`Classic root move ${i}`,o=await $e(e,$.dirname(t),s);await r?.beforeMutation?.(i),await V(o,s);let a=await ne.open(t,"wx");try{await V(o,s),await a.writeFile(n),await a.sync()}finally{await a.close()}await V(o,s),await Si(e,t,s,"file")}async function ia(e,t,n,i,r){let s=`Classic root move ${i}`,o=await $e(e,$.dirname(t),s),a=await $e(e,$.dirname(n),s),c=await Ei(t,"file",s);await r?.beforeMutation?.(i),await V(o,s),await V(a,s),await et(t,c,s),await ne.link(t,n),await V(o,s),await V(a,s),await et(n,c,s)}async function ig(e,t,n,i,r,s={}){let o=`Classic root move ${i}`,a=await $e(e,$.dirname(t),o),c=await $e(e,$.dirname(n),o),l=await Ei(t,(await ne.lstat(t)).isDirectory()?"directory":"file",o);if(s.replaceTarget)s.expectedTargetIdentity&&await et(n,s.expectedTargetIdentity,o);else if((await T(e,tt(e,n),{label:o,expected:"any"})).exists)throw new Error(`${o} target already exists`);await r?.beforeMutation?.(i),await V(a,o),await V(c,o),await et(t,l,o),s.expectedTargetIdentity&&await et(n,s.expectedTargetIdentity,o),await s.validateTarget?.(),await ne.rename(t,n),await V(a,o),await V(c,o),await et(n,l,o)}async function Dn(e,t,n,i,r={}){let s=`Classic root move ${n}`,o;try{o=await Ei(t,"file",s)}catch(c){if(c.code==="ENOENT")return!1;throw c}r.expectedIdentity&&await et(t,r.expectedIdentity,s);let a=await $e(e,$.dirname(t),s);return await i?.beforeMutation?.(n),await V(a,s),await et(t,o,s),r.expectedIdentity&&await et(t,r.expectedIdentity,s),await r.validateTarget?.(),await ne.unlink(t),await V(a,s),!0}async function Zo(e,t,n,i,r){let s=`Classic root move ${n}`,o;try{o=await Ei(t,"directory",s)}catch(l){if(l.code==="ENOENT")return!1;throw l}if(r&&!cu(ta(o,`Classic root move ${n}`),r))throw new Error(`Classic root move ${n} changed after migration preflight`);let a=await $e(e,$.dirname(t),s);await i?.beforeMutation?.(n),await V(a,s),await et(t,o,s);let c=await ne.readdir(t);if(await V(a,s),await et(t,o,s),c.length>0)throw new Error(`${s} directory is not empty`);return await ne.rmdir(t),await V(a,s),!0}async function ra(e,t){let n=kt(e,"legacy"),i=kt(e,"docs"),r=$.join(e,".comet","transactions","classic-root-move"),s=[[$.join(e,".comet"),".comet","directory"],[$.join(e,".comet","config.yaml"),".comet/config.yaml","file"],[n.openSpecRoot,"openspec","directory"],[$.dirname(i.openSpecRoot),"docs","directory"],[i.openSpecRoot,"docs/openspec","directory"],[$.join(e,".comet","transactions"),".comet/transactions","directory"],[r,".comet/transactions/classic-root-move","directory"]];if(t){let o=$.join(r,t);s.push([o,`transaction ${t}`,"directory"],[$.join(o,"openspec"),`transaction ${t} staging`,"directory"],[$.join(o,"legacy-source"),`transaction ${t} quarantine`,"directory"])}for(let[o,a,c]of s)await Si(e,o,a,c)}async function mg(e,t,n,i){let r=Bn(e);await yi(e,$.dirname(r),"Classic root move journal parent",i);let s=`${r}.${na()}.tmp`,o=JSON.stringify(n,null,2)+` -`,a;try{await au(e,s,o,"update-journal-temp",i);let c=await Ei(s,"file","Classic root move updated journal");a=await Cg(e,t,"update-journal-commit",i);try{await ia(e,s,r,"update-journal-publish",i)}catch(u){throw new Error("Classic root move journal publish failed; a successor journal was preserved",{cause:u})}let l=await Ci(e),f=l?ki(l):null;if(!l||l.id!==n.id||l.stage!==n.stage||l.planId!==n.planId||l.schema!==n.schema||!f||f.contentHash!==vi(Buffer.from(o))||!sa(c,f.fileIdentity))throw new Error("Classic root move journal ownership changed while updating");return await Dn(e,a.file,"cleanup-update-journal-quarantine",i,{expectedIdentity:ki(a.journal).fileIdentity}),a=void 0,l}catch(c){throw a&&await bg(e,a,"restore-update-journal",i).catch(()=>!1),c}finally{await Dn(e,s,"cleanup-update-journal-temp").catch(()=>!1)}}async function S_(e,t,n,i){await yi(e,$.dirname(t),"Classic root move journal parent",i);let r=`${t}.${na()}.tmp`;try{await au(e,r,JSON.stringify(n,null,2)+` -`,"create-journal-temp",i),await ia(e,r,t,"create-journal-commit",i)}catch(s){throw s.code==="EEXIST"?new Error("Classic root move is incomplete; use comet doctor --repair --strategy continue|rollback",{cause:s}):s}finally{await Dn(e,r,"cleanup-create-journal-temp").catch(()=>!1)}}function pg(e){return Dr("sha256").update(JSON.stringify({directories:e.directories,files:e.files,totalBytes:e.totalBytes})).digest("hex")}function Lr(e,t){return et?1:0}function Yo(e,t){return e.every((n,i)=>i===0||t(e[i-1],n)<=0)}function hg(e){return Dr("sha256").update(JSON.stringify({source:e.source,target:e.target,staging:e.staging,artifactLayout:e.artifactLayout,sourceIdentity:e.sourceIdentity,targetInitialIdentity:e.targetInitialIdentity,targetInitialState:e.targetInitialState,fileCount:e.fileCount,directoryCount:e.directoryCount,totalBytes:e.totalBytes,manifestHash:e.manifestHash,configPath:e.configPath,originalConfigHash:e.originalConfigHash,expectedConfigHash:e.expectedConfigHash})).digest("hex")}function E_(e){return Dr("sha256").update(JSON.stringify({source:e.source,target:e.target,staging:ou,targetInitialState:e.targetInitialState,fileCount:e.fileCount,directoryCount:e.directoryCount,totalBytes:e.totalBytes,manifestHash:e.manifestHash,configPath:e.configPath,originalConfigHash:e.originalConfigHash,expectedConfigHash:e.expectedConfigHash})).digest("hex")}function ea(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function nu(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function R_(e){return"mtimeNs"in e&&typeof e.mtimeNs=="bigint"?e.mtimeNs:e.mtimeMs}function Fn(e){return{dev:e.dev,ino:e.ino,birthtime:ea(e)}}function jr(e){return String(e)}function ta(e,t){let n=Fn(e);if(!Sn(n,n))throw new Error(`${t} filesystem does not expose a stable device and file identity; refusing an auditable root move`);return{dev:jr(e.dev),ino:jr(e.ino),birthtime:jr(ea(e)),ctime:jr(nu(e)),mtime:jr(R_(e))}}function __(e,t,n){return t.entries.map(i=>{let r=ta(i.stat,n);return{path:tt(e,i.path)||".",dev:r.dev,ino:r.ino,birthtime:r.birthtime}})}function cu(e,t){return JSON.stringify(e)===JSON.stringify(t)}function gg(e,t){return e.length===t.length&&e.every((n,i)=>cu(n,t[i]))}async function iu(e,t,n){let i=await $e(e,t,n);return await V(i,n),__(e,i,n)}function sa(e,t){let n=Fn(e),i=Fn(t);return Sn(n,i)?Ae(n,i):Ae(n,i)&&ea(e)===ea(t)&&nu(e)===nu(t)&&e.size===t.size}function vi(e){return Dr("sha256").update(e).digest("hex")}async function Mr(e,t,n,i,r){let s=await U(e,tt(e,t),n,{label:i,bigint:!0});if(r&&!sa(r,s.stat))throw new Error(`${i} changed while reading`);if(BigInt(s.stat.size)!==BigInt(s.bytes.byteLength))throw new Error(`${i} changed while reading`);return s.bytes}async function wg(e){let t=await Rn(e,{allowPartialProject:!0});if(!t.document||!t.identity.exists||!t.identity.sha256)throw new Error(".comet/config.yaml does not exist");return t}async function lu(e){return(await wg(e)).identity.sha256}function x_(e){let t=e.value.classic;if(!t||typeof t!="object"||Array.isArray(t))throw new Error("classic must be a mapping");let n=kn({...e.value,classic:{...t,artifact_layout:"docs"}},e.classic?.language==="zh-CN"||e.native?.language==="zh-CN"?"zh-CN":"en");return Dr("sha256").update(n).digest("hex")}async function oa(e,t,n){let i=[],r=[],s=0;async function o(c,l){await Si(e,c,l||tt(e,t),"directory");let f=await k_(e,c,`tree:${l||tt(e,t)}`,n);for(let u of f.sort((d,p)=>Lr(d.name,p.name))){let d=$.join(c,u.name),p=l?`${l}/${u.name}`:u.name,g=await ne.lstat(d,{bigint:!0});if(g.isSymbolicLink())throw new Error(`Classic root move does not support symbolic links or junctions: ${p}`);if(g.isDirectory()){i.push(p),await o(d,p);continue}if(!g.isFile())throw new Error(`Classic root move supports only regular files and directories: ${p}`);if(await n?.afterSourceFileInspect?.(p),r.length+1>Qo)throw new Error(`Classic root move exceeds ${Qo} files`);let h=Xo-s,m=await Mr(e,d,Math.max(1,h),`Classic root move source file ${p}`,g);if(s+=m.byteLength,s>Xo)throw new Error(`Classic root move exceeds ${Xo} bytes`);r.push({path:p,size:m.byteLength,hash:vi(m)})}}await o(t,""),i.sort(Lr),r.sort((c,l)=>Lr(c.path,l.path));let a={directories:i,files:r,totalBytes:s};return{...a,hash:pg(a)}}function uu(e,t){return e.hash===t.hash}async function P_(e,t,n){try{let i=await $e(e,t,"docs-target"),r=i.entries.at(-1);if(!r)throw new Error("Classic docs target identity is unavailable");let s=ta(r.stat,"Classic docs target");await n?.afterDirectoryInspect?.("docs-target"),await V(i,"docs-target");let o=await ne.readdir(t,{withFileTypes:!0});await V(i,"docs-target");let c=(await $e(e,t,"docs-target")).entries.at(-1),l=c?ta(c.stat,"Classic docs target"):null;if(!l||!cu(s,l))throw new Error("Classic docs target changed after inspection");return o.length>0?{state:"non-empty",conflicts:["Classic docs target is not empty"],identity:l}:{state:"empty",conflicts:[],identity:l}}catch(i){if(i.code==="ENOENT")return{state:"missing",conflicts:[],identity:null};throw i}}async function O_(e){if(await Lm(e),await Zt(e)!=="legacy")throw new Error("Classic root move requires classic.artifact_layout: legacy")}async function ru(e,t={}){if(await ra(e),await O_(e),await Zt(e)!=="legacy")throw new Error("Classic root move requires the legacy layout");let n=kt(e,"legacy"),i=kt(e,"docs");if(!await qn(e,n.openSpecRoot,"Classic legacy root"))throw new Error("Classic legacy root does not exist: openspec/");let r=await iu(e,n.openSpecRoot,"Classic legacy root identity"),s=await oa(e,n.openSpecRoot,t.testHooks),o=await iu(e,n.openSpecRoot,"Classic legacy root identity");if(!gg(r,o))throw new Error("Classic legacy root identity changed during migration preflight");let a=await P_(e,i.openSpecRoot,t.testHooks),c=await wg(e);await t.testHooks?.afterConfigSnapshot?.();let l=c.identity.sha256,f=x_(c.document),u={source:tt(e,n.openSpecRoot),target:tt(e,i.openSpecRoot),staging:ou,artifactLayout:"legacy",sourceIdentity:o,targetInitialIdentity:a.identity,targetInitialState:a.state,fileCount:s.files.length,directoryCount:s.directories.length,totalBytes:s.totalBytes,manifestHash:s.hash,configPath:ae,originalConfigHash:l,expectedConfigHash:f};return{manifest:s,plan:{projectRoot:e,...u,configHash:l,planId:hg(u),fileSummary:s.files.map(d=>({...d})),configChange:{from:"legacy",to:"docs"},conflicts:a.conflicts,blockers:[],pendingRecovery:null,historicalPointersPreserved:[...cg],applyPreconditions:[...lg],allowedRecoveryStrategies:[],readyToApply:a.conflicts.length===0}}}async function $_(e,t,n,i,r){await yi(e,n,"Classic root move staging root",r);for(let s of i.directories)await yi(e,$.join(n,...s.split("/")),`Classic root move staging directory ${s}`,r);for(let s of i.files){await r?.beforeSourceFileCopy?.(s.path);let o=$.join(t,...s.path.split("/")),a=await Mr(e,o,Math.max(1,s.size),`Classic root move source file ${s.path}`);if(a.byteLength!==s.size||vi(a)!==s.hash)throw new Error("Classic legacy root changed after migration preflight");let c=$.join(n,...s.path.split("/"));if(await yi(e,$.dirname(c),`Classic root move staging parent ${s.path}`,r),(await T(e,tt(e,c),{label:`Classic root move staging file ${s.path}`,expected:"file"})).exists)throw new Error("Classic root move staging changed after migration preflight");await au(e,c,a,`copy-file:${s.path}`,r);let f=await Mr(e,c,Math.max(1,s.size),`Classic root move staging file ${s.path}`);if(f.byteLength!==s.size||vi(f)!==s.hash)throw new Error("Classic root move staging verification failed")}}function Bn(e){return $.join(e,...su.split("/"))}function D(e){return new Error(`invalid Classic root move journal: ${e}`)}function bi(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw D(`${t} must be an object`);return e}function Wn(e,t,n){let i=Object.keys(e).sort(),r=[...t].sort();if(JSON.stringify(i)!==JSON.stringify(r))throw D(`${n} fields are invalid`)}function rg(e,t){if(typeof e!="string"||e.length===0||e.includes("\\"))throw D(`${t} is invalid`);let n=e.split("/");if($.posix.isAbsolute(e)||n.some(i=>i===""||i==="."||i==="..")||$.posix.normalize(e)!==e)throw D(`${t} must stay inside the migration tree`);return e}function yg(e){let t=bi(e,"manifest");if(Wn(t,["directories","files","totalBytes","hash"],"manifest"),!Array.isArray(t.directories)||!Array.isArray(t.files)||!Number.isSafeInteger(t.totalBytes)||t.totalBytes<0||t.totalBytes>Xo||typeof t.hash!="string"||!ht.test(t.hash))throw D("manifest shape is invalid");let n=t.directories.map((f,u)=>rg(f,`manifest path directories[${u}]`)),i=t.files.map((f,u)=>{let d=bi(f,`manifest.files[${u}]`);Wn(d,["path","size","hash"],`manifest.files[${u}]`);let p=rg(d.path,`manifest path files[${u}]`);if(!Number.isSafeInteger(d.size)||d.size<0||typeof d.hash!="string"||!ht.test(d.hash))throw D(`manifest.files[${u}] is invalid`);return{path:p,size:d.size,hash:d.hash}});if(i.length>Qo)throw D(`manifest exceeds ${Qo} files`);let r=i.map(f=>f.path),s=new Set(n).size!==n.length||new Set(r).size!==r.length,o=Yo(n,Lr)&&Yo(r,Lr)||Yo(n,(f,u)=>f.localeCompare(u))&&Yo(r,(f,u)=>f.localeCompare(u));if(s||!o)throw D("manifest paths must be unique and sorted");let a=i.reduce((f,u)=>f+u.size,0);if(a!==t.totalBytes)throw D("manifest totalBytes does not match its files");let c={directories:n,files:i,totalBytes:a},l=pg(c);if(l!==t.hash)throw D("manifest hash is invalid");return{...c,hash:l}}function vg(e,t){let n=bi(e,t);Wn(n,["dev","ino","birthtime"],t);let i=/^-?[0-9]+$/u;for(let r of["dev","ino","birthtime"])if(typeof n[r]!="string"||!i.test(n[r]))throw D(`${t}.${r} is invalid`);if(n.dev==="0"||n.ino==="0")throw D(`${t} does not contain a stable filesystem identity`);return{dev:n.dev,ino:n.ino,birthtime:n.birthtime}}function I_(e,t){let n=bi(e,t);Wn(n,["dev","ino","birthtime","ctime","mtime"],t);let i=vg({dev:n.dev,ino:n.ino,birthtime:n.birthtime},t),r=/^-?[0-9]+$/u;if(typeof n.ctime!="string"||!r.test(n.ctime)||typeof n.mtime!="string"||!r.test(n.mtime))throw D(`${t} timestamps are invalid`);return{...i,ctime:n.ctime,mtime:n.mtime}}function A_(e){if(!Array.isArray(e)||e.length!==2)throw D("sourceIdentity must bind the project root and openspec root");let t=[".","openspec"];return e.map((n,i)=>{let r=bi(n,`sourceIdentity[${i}]`);if(Wn(r,["path","dev","ino","birthtime"],`sourceIdentity[${i}]`),r.path!==t[i])throw D(`sourceIdentity[${i}].path is invalid`);let s={dev:r.dev,ino:r.ino,birthtime:r.birthtime};return{path:t[i],...vg(s,`sourceIdentity[${i}]`)}})}function N_(e){if(Wn(e,["schema","id","stage","source","target","staging","configPath","originalConfigHash","expectedConfigHash","planId","targetInitialState","manifest"],"root"),typeof e.id!="string"||!ug.test(e.id))throw D("id is invalid");if(e.stage!=="copying"&&e.stage!=="ready"&&e.stage!=="switched"&&e.stage!=="configured")throw D("stage is invalid");let t=`.comet/transactions/classic-root-move/${e.id}/openspec`;if(e.source!=="openspec"||e.target!=="docs/openspec"||e.staging!==t)throw D("source, target, and staging must use the managed project paths");if(e.configPath!==ae||typeof e.originalConfigHash!="string"||!ht.test(e.originalConfigHash)||typeof e.expectedConfigHash!="string"||!ht.test(e.expectedConfigHash)||typeof e.planId!="string"||!ht.test(e.planId))throw D("config path, config hashes, or planId is invalid");if(e.targetInitialState!=="missing"&&e.targetInitialState!=="empty")throw D("targetInitialState is invalid");let n=e.targetInitialState,i=yg(e.manifest),r={source:e.source,target:e.target,targetInitialState:n,fileCount:i.files.length,directoryCount:i.directories.length,totalBytes:i.totalBytes,manifestHash:i.hash,configPath:e.configPath,originalConfigHash:e.originalConfigHash,expectedConfigHash:e.expectedConfigHash};if(E_(r)!==e.planId)throw D("planId does not match the bound config and tree");return{schema:"comet.classic-root-move.v1",id:e.id,stage:e.stage,source:e.source,target:e.target,staging:e.staging,configPath:e.configPath,originalConfigHash:e.originalConfigHash,expectedConfigHash:e.expectedConfigHash,planId:e.planId,targetInitialState:n,manifest:i}}function T_(e){if(Wn(e,["schema","id","stage","source","target","staging","artifactLayout","sourceIdentity","targetInitialIdentity","configPath","originalConfigHash","expectedConfigHash","planId","approvedPlanId","targetInitialState","manifest"],"root"),typeof e.id!="string"||!ug.test(e.id))throw D("id is invalid");if(e.stage!=="locked"&&e.stage!=="copying"&&e.stage!=="ready"&&e.stage!=="switched"&&e.stage!=="configured")throw D("stage is invalid");let t=`.comet/transactions/classic-root-move/${e.id}/openspec`;if(e.source!=="openspec"||e.target!=="docs/openspec"||e.staging!==t)throw D("source, target, and staging must use the managed project paths");if(e.artifactLayout!=="legacy")throw D("artifactLayout must be legacy");let n=A_(e.sourceIdentity);if(e.configPath!==ae||typeof e.originalConfigHash!="string"||!ht.test(e.originalConfigHash)||typeof e.expectedConfigHash!="string"||!ht.test(e.expectedConfigHash)||typeof e.planId!="string"||!ht.test(e.planId)||typeof e.approvedPlanId!="string"||!ht.test(e.approvedPlanId))throw D("config path, config hashes, planId, or approvedPlanId is invalid");let i=e.targetInitialState;if(i!=="missing"&&i!=="empty"&&!(e.stage==="locked"&&i==="non-empty"))throw D("targetInitialState is invalid");let r=e.targetInitialIdentity===null?null:I_(e.targetInitialIdentity,"targetInitialIdentity");if(i==="missing"&&r!==null||i!=="missing"&&r===null)throw D("targetInitialIdentity does not match targetInitialState");let s=yg(e.manifest),o={source:e.source,target:e.target,staging:ou,artifactLayout:"legacy",sourceIdentity:n,targetInitialIdentity:r,targetInitialState:i,fileCount:s.files.length,directoryCount:s.directories.length,totalBytes:s.totalBytes,manifestHash:s.hash,configPath:e.configPath,originalConfigHash:e.originalConfigHash,expectedConfigHash:e.expectedConfigHash};if(hg(o)!==e.planId)throw D("planId does not match the bound config and tree");if(e.stage!=="locked"&&e.approvedPlanId!==e.planId)throw D("approvedPlanId does not match the executable plan");return{schema:"comet.classic-root-move.v2",id:e.id,stage:e.stage,source:e.source,target:e.target,staging:e.staging,artifactLayout:"legacy",sourceIdentity:n,targetInitialIdentity:r,configPath:e.configPath,originalConfigHash:e.originalConfigHash,expectedConfigHash:e.expectedConfigHash,planId:e.planId,approvedPlanId:e.approvedPlanId,targetInitialState:i,manifest:s}}function j_(e){let t=bi(e,"root");if(t.schema==="comet.classic-root-move.v1")return N_(t);if(t.schema==="comet.classic-root-move.v2")return T_(t);throw D("schema is unsupported")}async function Ci(e,t){return fu(e,Bn(e),su,t?.afterJournalInspect)}async function fu(e,t,n,i){await Si(e,t,n,"file");try{let r=await ne.lstat(t,{bigint:!0});if(!r.isFile()||r.isSymbolicLink()||r.size>BigInt(ng))throw D("journal must be a bounded regular file");await i?.();let s=await Mr(e,t,ng,"Classic root move journal",r),o=j_(JSON.parse(s.toString("utf8")));return Object.defineProperty(o,fg,{value:{fileIdentity:r,contentHash:vi(s)},enumerable:!1}),o}catch(r){if(r.code==="ENOENT")return null;throw r}}function ki(e){let t=e[fg];if(!t)throw new Error("Classic root move journal has no ownership claim");return t}function du(e,t){let n=ki(e),i=ki(t);return sa(n.fileIdentity,i.fileIdentity)&&n.contentHash===i.contentHash&&e.schema===t.schema&&e.id===t.id&&e.stage===t.stage&&e.planId===t.planId}async function sg(e,t){let n=await fu(e,Bn(e),su);if(!n||!du(t,n))throw new Error("Classic root move journal ownership changed")}async function bg(e,t,n,i){let r=Bn(e);try{await ia(e,t.file,r,`${n}-publish`,i)}catch(o){if(o.code==="EEXIST")return!1;throw o}let s=await Ci(e);if(!s||!du(t.journal,s))throw new Error("Classic root move journal ownership changed while restoring quarantine");return await Dn(e,t.file,`${n}-cleanup-quarantine`,i,{expectedIdentity:ki(t.journal).fileIdentity}),!0}async function Cg(e,t,n,i){let r=Bn(e),s=`${r}.${t.id}.${na()}.quarantine`;await sg(e,t);let o=await $e(e,$.dirname(r),`Classic root move ${n} quarantine`);await i?.beforeMutation?.(`${n}-quarantine`),await V(o,`Classic root move ${n} quarantine`),await sg(e,t),await ne.rename(r,s),await V(o,`Classic root move ${n} quarantine`);let a=await fu(e,s,tt(e,s)).catch(async c=>{throw await og(e,s,`${n}-restore-unverified`,i).catch(()=>!1),new Error("Classic root move journal ownership changed while quarantining",{cause:c})});if(!a||!du(t,a))throw await og(e,s,`${n}-restore-successor`,i).catch(()=>!1),new Error("Classic root move journal ownership changed while quarantining");return await i?.afterJournalQuarantine?.(n),{file:s,journal:a}}async function og(e,t,n,i){let r=Bn(e),s;try{s=await Ei(t,"file",`Classic root move ${n}`)}catch(o){if(o.code==="ENOENT")return!1;throw o}try{await ia(e,t,r,`${n}-publish`,i)}catch(o){if(o.code==="EEXIST")return!1;throw o}return await Dn(e,t,`${n}-cleanup-quarantine`,i,{expectedIdentity:s}),!0}async function kg(e,t,n,i){let r=await Cg(e,t,n,i);try{if(!await Dn(e,r.file,`${n}-quarantined`,i,{expectedIdentity:ki(r.journal).fileIdentity}))throw new Error("Classic root move quarantined journal disappeared before removal");return!0}catch(s){throw await bg(e,r,`${n}-restore`,i).catch(()=>!1),s}}async function Go(e,t,n,i){if(t.schema==="comet.classic-root-move.v1"&&n==="locked")throw new Error("Legacy Classic root move journals do not support the locked stage");let r={...t,stage:n};return mg(e,t,r,i)}function Sg(e,t){let n={legacy:kt(e,"legacy"),docs:kt(e,"docs")},i=$.join(e,".comet","transactions","classic-root-move",t.id);return{source:n.legacy.openSpecRoot,target:n.docs.openSpecRoot,staging:$.join(i,"openspec"),quarantine:$.join(i,"legacy-source"),transactionRoot:i}}async function qr(e,t,n){if(!await qn(e,t,"Classic root move tree"))return"missing";try{return uu(await oa(e,t),n)?"match":"mismatch"}catch{return"mismatch"}}async function mu(e,t,n){if(!await qn(e,t,"Classic root move target"))return"missing";try{let i=await oa(e,t);return uu(i,n)?"match":i.directories.length===0&&i.files.length===0?"empty":"mismatch"}catch{return"mismatch"}}async function Eg(e,t,n){if(!await qn(e,t,"Classic root move manifest tree"))return{status:"missing"};try{let i=await oa(e,t);if(uu(i,n))return{status:"complete",actual:i};let r=new Set(n.directories),s=new Map(n.files.map(o=>[o.path,o]));if(i.directories.some(o=>!r.has(o)))return{status:"mismatch"};for(let o of i.files){let a=s.get(o.path);if(!a||a.size!==o.size||a.hash!==o.hash)return{status:"mismatch"}}return{status:"partial",actual:i}}catch{return{status:"mismatch"}}}async function L_(e,t,n,i,r="remove-quarantine"){let s=await Eg(e,t,n);if(s.status==="missing")return;if(s.status==="mismatch"||!s.actual)throw new Error("Classic quarantine contains unknown or changed content; files were preserved");for(let a of s.actual.files){let c=$.join(t,...a.path.split("/")),l;try{l=await ne.lstat(c,{bigint:!0})}catch(u){if(u.code==="ENOENT")continue;throw u}let f=l.isFile()&&!l.isSymbolicLink()?await Mr(e,c,Math.max(1,a.size),`Classic root move quarantine file ${a.path}`,l):null;if(!f||f.byteLength!==a.size||vi(f)!==a.hash)throw new Error("Classic quarantine contains unknown or changed content; files were preserved");await Dn(e,c,`${r}-file:${a.path}`,i)}let o=[...s.actual.directories].sort((a,c)=>{let l=c.split("/").length-a.split("/").length;return l===0?c.localeCompare(a):l});for(let a of o){let c=$.join(t,...a.split("/"));await Zo(e,c,`${r}-directory:${a}`,i)}await Zo(e,t,`${r}-root`,i)}async function M_(e,t,n,i){let r=await mu(e,t,n.manifest);if(n.targetInitialState==="missing"){if(r!=="missing")throw new Error("Classic docs target changed after migration preflight");return}if(r==="empty"){if(n.schema==="comet.classic-root-move.v2"&&!n.targetInitialIdentity)throw new Error("Classic docs target identity is missing from the approved plan");await Zo(e,t,"remove-empty-target",i,n.schema==="comet.classic-root-move.v2"?n.targetInitialIdentity??void 0:void 0);return}if(r!=="missing")throw new Error("Classic docs target changed after migration preflight")}async function zo(e,t,n){if(n.schema==="comet.classic-root-move.v1")return;let i=await iu(e,t,"Classic legacy root identity");if(!gg(i,n.sourceIdentity))throw new Error("Classic legacy root identity changed after migration preflight")}async function tu(e,t){if(await lu(e)!==t.originalConfigHash)throw new Error("Classic project config changed after migration preflight");if(await Zt(e)!=="legacy")throw new Error("Classic project config changed after migration preflight")}async function ag(e,t){if(await lu(e)!==t.expectedConfigHash)throw new Error("Classic project config does not match the expected post-switch config hash");if(await Zt(e)!=="docs")throw new Error("Classic project config does not match the expected post-switch config hash")}async function Mn(e,t,n,i){if(await qr(e,t,n)!=="match")throw new Error(i)}async function q_(e,t,n){if(t.stage==="locked")throw new Error("Classic root move locked preflight must be approved before execution");await ra(e,t.id);let{source:i,target:r,staging:s,quarantine:o,transactionRoot:a}=Sg(e,t),c=t;if(c.stage==="copying"){await tu(e,c),await zo(e,i,c),await Mn(e,i,c.manifest,"Classic legacy root changed after migration preflight"),await M_(e,r,c,n);let l=await qr(e,s,c.manifest);if(l==="mismatch")throw new Error("Classic root move staging changed after migration preflight");l==="missing"&&await $_(e,i,s,c.manifest,n),await Mn(e,s,c.manifest,"Classic root move staging verification failed"),c=await Go(e,c,"ready",n)}if(c.stage==="ready"){await tu(e,c),await zo(e,i,c),await Mn(e,i,c.manifest,"Classic legacy root changed after migration preflight");let l=await qr(e,s,c.manifest),f=await mu(e,r,c.manifest);if(l==="missing"&&f==="match")c=await Go(e,c,"switched",n);else{if(l!=="match")throw new Error("Classic root move staging changed after migration preflight");if(f==="mismatch"||f==="empty")throw new Error("Classic docs target changed after migration preflight");f==="missing"&&(await yi(e,$.dirname(r),"Classic docs target parent",n),await ig(e,s,r,"rename-staging-target",n),c=await Go(e,c,"switched",n))}}if(c.stage==="switched"){await zo(e,i,c),await Mn(e,i,c.manifest,"Classic legacy root changed before config switch"),await Mn(e,r,c.manifest,"Classic docs target verification failed after switch");let l=await Zt(e);if(l==="legacy")await tu(e,c),await Mm(e,"docs",{expectedIdentity:{exists:!0,sha256:c.originalConfigHash}});else if(l!=="docs")throw new Error("Classic project config changed after migration preflight");await ag(e,c),c=await Go(e,c,"configured",n)}if(c.stage!=="configured")throw new Error(`Unsupported Classic root move stage: ${c.stage}`);if(await ag(e,c),await Mn(e,r,c.manifest,"Classic docs target verification failed after config switch"),await qn(e,i,"Classic legacy root")){if(await zo(e,i,c),await Mn(e,i,c.manifest,"Classic legacy root changed before cleanup; both roots were preserved"),await qn(e,o,"Classic root move quarantine"))throw new Error("Classic root move quarantine conflicts with the legacy root");await ig(e,i,o,"rename-source-quarantine",n)}await qn(e,o,"Classic root move quarantine")&&await L_(e,o,c.manifest,n),await Zo(e,a,"remove-transaction-root",n),await kg(e,c,"remove-journal",n)}async function D_(e,t){if(await ra(e,t.id),t.stage==="locked")return{allowedStrategies:["rollback"],reason:"the locked apply preflight was not approved for execution"};let{source:n,target:i,staging:r,quarantine:s}=Sg(e,t),o=await Zt(e),a=await lu(e),c=o==="legacy"&&a===t.originalConfigHash,l=o==="docs"&&a===t.expectedConfigHash,[f,u,d,p]=await Promise.all([qr(e,n,t.manifest),mu(e,i,t.manifest),qr(e,r,t.manifest),Eg(e,s,t.manifest)]),g=p.status;if(f==="mismatch")return{allowedStrategies:[],reason:"Classic legacy root changed after migration preflight"};if(u==="mismatch")return{allowedStrategies:[],reason:"Classic docs target changed after migration preflight"};if(d==="mismatch")return{allowedStrategies:[],reason:"Classic staging changed after migration preflight"};if(g==="mismatch")return{allowedStrategies:[],reason:"Classic quarantine contains unknown or changed content"};if(t.stage==="configured"||o==="docs")return l?u==="match"&&(f==="match"&&g==="missing"||f==="missing"&&(g==="missing"||g==="complete"||g==="partial"))?{allowedStrategies:["continue"]}:{allowedStrategies:[],reason:"the configured migration trees are incomplete"}:{allowedStrategies:[],reason:"project config does not match the expected post-switch config hash"};if(!c)return{allowedStrategies:[],reason:"project config changed after migration preflight"};let h=f==="match",m=d==="match"||d==="missing",y=u==="match"||u==="missing"||t.targetInitialState==="empty"&&u==="empty";return!h||!m||!y||g!=="missing"?{allowedStrategies:[],reason:"the migration trees are not recoverable"}:{allowedStrategies:["continue","rollback"]}}async function Rg(e,t={}){let n=await le(e),i=await Ci(n,t.testHooks);if(i){let r=await F_(n);if(!r)throw new Error("Classic root move journal disappeared during inspection");return{projectRoot:n,source:i.source,target:i.target,staging:i.staging,artifactLayout:"legacy",sourceIdentity:i.schema==="comet.classic-root-move.v2"?i.sourceIdentity.map(s=>({...s})):[],targetInitialIdentity:i.schema==="comet.classic-root-move.v2"&&i.targetInitialIdentity?{...i.targetInitialIdentity}:null,fileCount:i.manifest.files.length,directoryCount:i.manifest.directories.length,totalBytes:i.manifest.totalBytes,manifestHash:i.manifest.hash,configPath:i.configPath,configHash:i.originalConfigHash,originalConfigHash:i.originalConfigHash,expectedConfigHash:i.expectedConfigHash,planId:i.planId,fileSummary:i.manifest.files.map(s=>({...s})),configChange:{from:"legacy",to:"docs"},conflicts:r.reason?[r.reason]:[],blockers:[`pending Classic root move: ${i.id} at ${i.stage}`],pendingRecovery:r,historicalPointersPreserved:[...cg],applyPreconditions:[...lg],allowedRecoveryStrategies:[...r.allowedStrategies],targetInitialState:i.targetInitialState,readyToApply:!1}}return(await ru(n,t)).plan}async function _g(e,t={}){let n=await le(e),i=await Ci(n,t.testHooks);if(i)throw new Error(`Classic root move ${i.id} is incomplete; use comet doctor --repair --strategy continue|rollback`);let r=await ru(n),s=t.planId??r.plan.planId;if(!ht.test(s))throw new Error("Classic root move apply received an invalid internal plan ID");let o=na();await ra(n,o);let a={schema:"comet.classic-root-move.v2",id:o,stage:"locked",source:r.plan.source,target:r.plan.target,staging:`.comet/transactions/classic-root-move/${o}/openspec`,artifactLayout:r.plan.artifactLayout,sourceIdentity:r.plan.sourceIdentity.map(f=>({...f})),targetInitialIdentity:r.plan.targetInitialIdentity?{...r.plan.targetInitialIdentity}:null,configPath:ae,originalConfigHash:r.plan.originalConfigHash,expectedConfigHash:r.plan.expectedConfigHash,planId:r.plan.planId,approvedPlanId:s,targetInitialState:r.plan.targetInitialState,manifest:r.manifest};await S_(n,Bn(n),a,t.testHooks);let c=await Ci(n);if(!c||c.id!==o||c.stage!=="locked")throw new Error("Classic root move lock ownership changed before locked preflight");let l=!1;try{let f=await ru(n,t),u=f.plan;if(u.planId!==s)throw new Error(`Classic root move plan changed since dry-run: approved ${s}, current ${u.planId}`);if(!u.readyToApply)throw new Error(`Classic root move apply is blocked: ${[...u.conflicts,...u.blockers].join("; ")}`);if(u.targetInitialState==="non-empty")throw new Error("Classic root move apply is blocked: Classic docs target is not empty");let d={schema:"comet.classic-root-move.v2",id:o,stage:"copying",source:u.source,target:u.target,staging:`.comet/transactions/classic-root-move/${o}/openspec`,artifactLayout:u.artifactLayout,sourceIdentity:u.sourceIdentity.map(g=>({...g})),targetInitialIdentity:u.targetInitialIdentity?{...u.targetInitialIdentity}:null,configPath:ae,originalConfigHash:u.originalConfigHash,expectedConfigHash:u.expectedConfigHash,planId:u.planId,approvedPlanId:s,targetInitialState:u.targetInitialState,manifest:f.manifest},p=await mg(n,c,d,t.testHooks);return l=!0,await q_(n,p,t.testHooks),{...u,staging:d.staging}}catch(f){throw l||await kg(n,c,"remove-rejected-lock",t.testHooks).catch(()=>!1),f}}async function F_(e,t={}){let n=await Ci(e,t.testHooks);if(!n)return null;let i=await D_(e,n);return{id:n.id,stage:n.stage,source:n.source,target:n.target,staging:n.staging,planId:n.planId,...i}}Ct();function xg(e="en"){return{exitCode:64,stderr:e==="zh-CN"?"用法:comet classic root show | comet classic root move docs --dry-run | comet classic root move docs --apply":"Usage: comet classic root show | comet classic root move docs --dry-run | comet classic root move docs --apply"}}function W_(e){return e?.classic?.language==="en"?"en":"zh-CN"}function B_(e,t){let n=e instanceof Error?e.message:String(e);return t==="en"?n:n==="invalid Classic root move journal: manifest paths must be unique and sorted"?"Classic 根目录迁移失败:迁移记录中的清单路径必须唯一且按顺序排列":n.startsWith("invalid Classic root move journal:")?"Classic 根目录迁移失败:迁移记录格式或内容无效,请运行 comet doctor 检查恢复状态":"Classic 根目录迁移失败:迁移过程中发生错误,请运行 comet doctor 检查迁移状态"}function Pg(e,t,n="en"){let i=n==="zh-CN",r=d=>d.length>0?d.join("; "):i?"无":"none",s=d=>{if(!i)return d;let p=/^pending Classic root move: (.+) at (.+)$/u.exec(d);return p?`存在待恢复的 Classic 根目录迁移:${p[1]},阶段 ${p[2]}`:{"Classic docs target is not empty":"docs 目标目录非空","the locked apply preflight was not approved for execution":"已锁定的迁移预检尚未获准执行","Classic legacy root changed after migration preflight":"迁移预检后 legacy 根目录发生变化","Classic docs target changed after migration preflight":"迁移预检后 docs 目标目录发生变化","Classic staging changed after migration preflight":"迁移预检后暂存目录发生变化","Classic quarantine contains unknown or changed content":"隔离目录包含未知或已变化的内容","project config does not match the expected post-switch config hash":"项目配置与切换后的预期配置哈希不一致","the configured migration trees are incomplete":"已切换配置对应的迁移目录不完整","project config changed after migration preflight":"迁移预检后项目配置发生变化","the migration trees are not recoverable":"迁移目录当前无法安全恢复"}[d]??"迁移状态存在无法识别的冲突,请运行 comet doctor 检查恢复状态"},o=(d,p)=>p.length===0?[`${d}: ${i?"无":"none"}`]:[`${d}:`,...p.map(g=>`- ${s(g)}`)],a=i?{missing:"缺失",empty:"空目录","non-empty":"非空目录"}[e.targetInitialState]:e.targetInitialState,c=i?"handoff 哈希;运行状态;检查点;轨迹;已归档证据与产物指针":e.historicalPointersPreserved.join("; "),l=i?"内部迁移身份仍与布局、源目录、清单、目标目录和配置一致;不存在待恢复的根迁移事务;目标仍然缺失或为已绑定的空目录;所有迁移路径仍受保护":e.applyPreconditions.join("; "),f=i?e.allowedRecoveryStrategies.map(d=>d==="continue"?"继续":"回滚"):e.allowedRecoveryStrategies,u=[t==="dry-run"?i?"Classic 根目录迁移现状":"Classic root move status":i?"Classic 根目录迁移完成":"Classic root move complete",...t==="dry-run"?[i?"说明:仅查看现状,未修改任何文件。":"Note: Inspection only; no files were changed."]:[],`${i?"源目录":"source"}: ${e.source}`,`${i?"目标目录":"target"}: ${e.target}`,`${i?"暂存目录":"staging"}: ${e.staging}`,`${i?"当前布局":"artifact layout"}: ${e.artifactLayout}`,`${i?"源目录身份":"source identity"}: ${JSON.stringify(e.sourceIdentity)}`,`${i?"目标初始身份":"target initial identity"}: ${e.targetInitialIdentity?JSON.stringify(e.targetInitialIdentity):i?"缺失":"missing"}`,`${i?"文件数":"files"}: ${e.fileCount}`,`${i?"目录数":"directories"}: ${e.directoryCount}`,`${i?"总字节数":"bytes"}: ${e.totalBytes}`,`${i?"清单哈希":"manifest"}: ${e.manifestHash}`,...e.fileSummary.map(d=>`${i?"文件":"file"}: ${d.path} ${d.size} ${d.hash}`),`${i?"配置变更":"config change"}: ${e.configChange.from} -> ${e.configChange.to}`,`${i?"配置路径":"config path"}: ${e.configPath}`,`${i?"配置哈希":"config"}: ${e.configHash}`,`${i?"原配置哈希":"original config"}: ${e.originalConfigHash}`,`${i?"预期配置哈希":"expected config"}: ${e.expectedConfigHash}`,`${i?"目标初始状态":"target initial state"}: ${a}`,...o(i?"冲突":"conflicts",e.conflicts),...o(i?"阻塞项":"blockers",e.blockers),`${i?"待恢复事务":"pending recovery"}: ${e.pendingRecovery?`${e.pendingRecovery.id} ${i?"位于阶段":"at"} ${e.pendingRecovery.stage}`:i?"无":"none"}`,`${i?"保留历史指针":"historical pointers preserved"}: ${c}`,`${i?"执行前提":"apply preconditions"}: ${l}`,`${i?"允许的恢复策略":"allowed recovery strategies"}: ${r(f)}`,`${i?"可执行迁移":"ready to apply"}: ${e.readyToApply?i?"是":"yes":i?"否":"no"}`];return t==="dry-run"?u.push(e.readyToApply?i?"下一步:运行 comet classic root move docs --apply 执行迁移。":"Next: run comet classic root move docs --apply to apply the migration.":i?"下一步:请先解决上述冲突或阻塞项。":"Next: resolve the conflicts or blockers above before applying."):u.push(i?"结果:迁移已完成。":"Result: Migration completed."),`${u.join(` +`)}`);this.issues=n}issues};function Pe(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function fn(e,t,n,i){return typeof e!="string"||!t.includes(e)?(i.push(`${n} must be one of: ${t.join(", ")}`),null):e}function Xl(e,t,n,i){return e==null?null:fn(e,t,n,i)}function pi(e,t,n){return typeof e!="string"||e.trim()===""?(n.push(`${t} must be a non-empty string`),""):e}function Ql(e,t,n){return e==null?null:typeof e!="string"||e.trim()===""?(n.push(`${t} must be a non-empty string or null`),null):e}function hi(e,t,n){return e==null?null:typeof e!="boolean"?(n.push(`${t} must be boolean or null`),null):e}function Uh(e,t,n){return typeof e!="number"||Number.isNaN(e)||e<0||e>1?(n.push(`${t} must be a number between 0 and 1`),0):e}function i_(e,t,n){return typeof e!="number"||!Number.isInteger(e)||e<0?(n.push(`${t} must be a non-negative integer`),0):e}function r_(e){let t=[];if(!Pe(e))throw new gi(["frame must be an object"]);let n=Pe(e.intent)?e.intent:{};Pe(e.intent)||t.push("intent must be an object");let i=Pe(e.slots)?e.slots:{};Pe(e.slots)||t.push("slots must be an object");let r=Pe(e.context)?e.context:{};Pe(e.context)||t.push("context must be an object");let s=Pe(e.proposed_route)?e.proposed_route:{};Pe(e.proposed_route)||t.push("proposed_route must be an object");let o=e.entities===void 0?[]:Array.isArray(e.entities)?e.entities:[];e.entities!==void 0&&!Array.isArray(e.entities)&&t.push("entities must be an array");let a=Array.isArray(e.evidence)?e.evidence:[];Array.isArray(e.evidence)||t.push("evidence must be an array");let c={schema_version:fn(e.schema_version,[GR],"schema_version",t),utterance:pi(e.utterance,"utterance",t),locale:e.locale===void 0?"unknown":pi(e.locale,"locale",t),intent:{name:fn(n.name,zR,"intent.name",t)??"unknown",confidence:Uh(n.confidence,"intent.confidence",t)},entities:o.map((l,f)=>{let u=Pe(l)?l:{};return Pe(l)||t.push(`entities[${f}] must be an object`),{type:fn(u.type,XR,`entities[${f}].type`,t)??"risk_signal",value:pi(u.value,`entities[${f}].value`,t),text:pi(u.text,`entities[${f}].text`,t)}}),slots:{requested_action:fn(i.requested_action,QR,"slots.requested_action",t)??"unknown",workflow_candidate:Xl(i.workflow_candidate,Jh,"slots.workflow_candidate",t),user_explicit_workflow:Xl(i.user_explicit_workflow,Jh,"slots.user_explicit_workflow",t),change_id:Ql(i.change_id,"slots.change_id",t),target_area:Ql(i.target_area,"slots.target_area",t),scope:i.scope===void 0?"unknown":fn(i.scope,ZR,"slots.scope",t)??"unknown",existing_behavior:hi(i.existing_behavior,"slots.existing_behavior",t),new_capability:hi(i.new_capability,"slots.new_capability",t),public_api_change:hi(i.public_api_change,"slots.public_api_change",t),schema_change:hi(i.schema_change,"slots.schema_change",t),cross_module_change:hi(i.cross_module_change,"slots.cross_module_change",t)},context:{active_changes_count:i_(r.active_changes_count,"context.active_changes_count",t),active_change_names:Pe(r)?Array.isArray(r.active_change_names)?r.active_change_names.every(l=>typeof l=="string")?r.active_change_names:(t.push("context.active_change_names must only contain strings"),[]):(t.push("context.active_change_names must be an array"),[]):[],dirty_worktree:hi(r.dirty_worktree,"context.dirty_worktree",t)},evidence:a.map((l,f)=>{let u=Pe(l)?l:{};return Pe(l)||t.push(`evidence[${f}] must be an object`),{field:pi(u.field,`evidence[${f}].field`,t),quote:pi(u.quote,`evidence[${f}].quote`,t),source:fn(u.source,n_,`evidence[${f}].source`,t)??"user"}}),proposed_route:{name:fn(s.name,e_,"proposed_route.name",t)??"ask_user",next_skill:Xl(s.next_skill,t_,"proposed_route.next_skill",t),confidence:Uh(s.confidence,"proposed_route.confidence",t),requires_confirmation:typeof s.requires_confirmation=="boolean"?s.requires_confirmation:!0,fallback_reason:Ql(s.fallback_reason,"proposed_route.fallback_reason",t)}};if(t.length>0)throw new gi(t);return c}function Zl(e,t){return e.evidence.some(n=>n.field===t&&n.quote.trim()!=="")}function Vh(e){return e.slots.new_capability===!0||e.slots.public_api_change===!0||e.slots.schema_change===!0||e.slots.cross_module_change===!0}function Ln(e,t,n=null){return{name:e,next_skill:{full:"comet-open",hotfix:"comet-hotfix",tweak:"comet-tweak",resume:null,ask_user:null,out_of_scope:null}[e],confidence:t,requires_confirmation:e==="ask_user"||e==="out_of_scope",fallback_reason:n}}function Tr(e){return Ln("ask_user",.5,e)}function Yh(e,t){return Ln(e,t)}function Gh(e){let t=r_(e),n=[],i=t.intent.confidence,r;return t.intent.confidence<.7?r=Tr(`intent confidence ${t.intent.confidence} is below ${.7}`):(t.intent.name==="resume_change"||t.slots.requested_action==="resume"||t.slots.requested_action==="continue")&&!t.slots.change_id&&t.context.active_changes_count>1?r=Tr("multiple active changes require an explicit change_id"):(t.intent.name==="resume_change"||t.slots.requested_action==="resume"||t.slots.requested_action==="continue")&&t.slots.change_id?r=t.context.active_change_names.includes(t.slots.change_id)?Ln("resume",i):Tr(`change_id '${t.slots.change_id}' is not in active_change_names`):t.intent.name==="ask_question"||t.slots.requested_action==="question"?r=Ln("out_of_scope",i,"user asked a question without requesting a Comet workflow"):t.slots.user_explicit_workflow&&t.slots.user_explicit_workflow!=="full"&&Vh(t)?r=Tr(`explicit workflow '${t.slots.user_explicit_workflow}' conflicts with risk signals`):t.slots.user_explicit_workflow?r=Yh(t.slots.user_explicit_workflow,i):Vh(t)?r=Ln("full",i):t.intent.name==="fix_bug"&&t.slots.existing_behavior===!0&&Zl(t,"slots.workflow_candidate")?r=Ln("hotfix",i):t.intent.name==="make_tweak"&&t.slots.workflow_candidate==="tweak"&&Zl(t,"slots.workflow_candidate")?r=Ln("tweak",i):t.slots.workflow_candidate&&Zl(t,"slots.workflow_candidate")?r=Yh(t.slots.workflow_candidate,i):r=Tr("workflow_candidate evidence is missing or route is ambiguous"),r.name!==t.proposed_route.name&&n.push(`agent proposed_route '${t.proposed_route.name}' normalized to '${r.name}'`),r.next_skill!==t.proposed_route.next_skill&&n.push(`agent proposed_route next_skill '${t.proposed_route.next_skill}' normalized to '${r.next_skill}'`),r.requires_confirmation!==t.proposed_route.requires_confirmation&&n.push(`agent proposed_route requires_confirmation '${t.proposed_route.requires_confirmation}' normalized to '${r.requires_confirmation}'`),r.fallback_reason!==t.proposed_route.fallback_reason&&n.push(`agent proposed_route fallback_reason '${t.proposed_route.fallback_reason}' normalized to '${r.fallback_reason}'`),{route:r,diagnostics:n,normalizedFrame:{...t,route:r}}}function Uo(e,t,n){return{exitCode:e,...t===void 0?{}:{stdout:t},...n===void 0?{}:{stderr:n}}}function zh(){return Uo(64,void 0,`Usage: comet-intent.mjs route +Usage: comet-intent.mjs route --stdin`)}async function s_(){let e=[];for await(let t of process.stdin)e.push(Buffer.isBuffer(t)?t:Buffer.from(String(t)));return Buffer.concat(e).toString("utf8")}var Xh=async(e,t)=>{let[n,i]=e;if(n!=="route")return zh();let r=i==="--stdin"?await s_():i;if(!r)return zh();try{let s=Gh(JSON.parse(r));return Uo(0,`${JSON.stringify(s,null,2)} +`)}catch(s){if(s instanceof SyntaxError)return Uo(1,void 0,`Invalid JSON: ${s.message}`);if(s instanceof gi)return Uo(1,void 0,s.message);throw s}};import{spawn as o_}from"child_process";var wi="comet.resume_probe.v1";function Qh(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function a_(e){if(!Qh(e))throw new Error("Invalid CometResumeProbeInput: input must be an object");if(e.schema_version!==wi)throw new Error(`Invalid CometResumeProbeInput: schema_version must be ${wi}`);if(typeof e.utterance!="string")throw new Error("Invalid CometResumeProbeInput: utterance must be a string");let t=Qh(e.agent_context)?e.agent_context:{};return{schema_version:wi,utterance:e.utterance,locale:typeof e.locale=="string"?e.locale:"unknown",agent_context:{non_trivial_work:t.non_trivial_work===!0,already_in_comet_flow:t.already_in_comet_flow===!0}}}function Oe(e,t,n,i,r=[]){return{schema_version:wi,action:e,changeName:t?.name??null,phase:t?.phase??null,nextCommand:e==="auto_resume"||e==="ask_user"?t?.nextCommand??null:null,confidence:n,reason:i,evidence:r}}async function c_(e,t,n){return await X(e,t,{label:n,expected:"file"})?W(e,t,{label:n}):""}async function Zh(e,t,n){let i=["proposal.md","design.md","tasks.md"],r=[n.name,n.workflow,n.phase];for(let s of i)r.push(await c_(e,`${t}/${s}`,`Classic change ${n.name} ${s}`));return r.join(` +`).toLowerCase()}function l_(e){switch(e){case"open":return"/comet-open";case"design":return"/comet-design";case"build":return"/comet-build";case"verify":return"/comet-verify";case"archive":return"/comet-archive";default:return null}}function u_(e,t,n){let i=n.classic,r=n.unknownKeys.filter(s=>s!=="run_id");return i?r.length>0?{name:t,valid:!1,workflow:i.workflow,phase:i.phase,currentStep:null,nextCommand:null,runtimeMode:"invalid",runtimeEval:null,evidence:[],error:`unknown field(s): ${r.join(", ")}`}:{name:t,valid:!0,workflow:i.workflow,phase:i.phase,currentStep:null,nextCommand:l_(i.phase),runtimeMode:"engine-projection",runtimeEval:null,evidence:[]}:{name:t,valid:!1,workflow:"unknown",phase:"invalid",currentStep:null,nextCommand:null,runtimeMode:"invalid",runtimeEval:null,evidence:[],error:`${e} does not contain valid Comet state`}}async function f_(e,t){return await X(e,`${t}/proposal.md`,{label:"Classic proposal",expected:"file"})||await X(e,`${t}/design.md`,{label:"Classic design",expected:"file"})||await X(e,`${t}/tasks.md`,{label:"Classic tasks",expected:"file"})}async function d_(e){let t=(await G(e)).changesDir;if(!(await Y(e,t,{label:"Classic changes directory",expected:"directory"})).exists)return[];let i=await Eu(t),r=[];for(let s of i){if(s==="archive"||ge(s))continue;let o=await Ge(s,e);if(!o.exists)continue;let a=o.directory;if(!o.stateExists){if(!await f_(e,a))continue;let m={name:s,workflow:"unknown",phase:"invalid",nextCommand:null,diagnostic:{name:s,valid:!1,workflow:"unknown",phase:"invalid",currentStep:null,nextCommand:null,runtimeMode:"invalid",runtimeEval:null,evidence:[],error:"missing Comet state"},buildPause:null,hasClassicProjection:!1,verifyResult:null,text:"",missingCometState:!0};m.text=await Zh(e,a,m),r.push(m);continue}let l=await B(a,{migrate:!1}),f=l.classic,u=u_(a,s,l),d=!!f,p=f?.phase??u.phase,g=f?.workflow??u.workflow;if(p==="archive"||f?.archived)continue;let h={name:s,workflow:g,phase:p,nextCommand:u.nextCommand,diagnostic:u,buildPause:f?.buildPause??null,hasClassicProjection:d,verifyResult:f?.verifyResult??null,text:"",missingCometState:!1};h.text=await Zh(e,a,h),r.push(h)}return r}var m_=["continue","resume","carry on","finish","run it","commit","verify","archive","继续","接着","恢复","跑完","提交","验证","归档","修刚才"],p_=["what","why","how","explain","summarize","reliable","靠谱吗","是什么","为什么","解释","总结","取名","命名"],h_=new Set(["add","build","cache","change","code","design","docs","file","fix","implement","plan","readme","task","test","update","修改","更新","修复","添加","文档","任务","计划","实现"]),g_=["do not resume","don't resume","without comet","skip comet","不要恢复","不走 comet","不要走 comet","直接解释","只回答"];function eu(e,t){return t.some(n=>e.includes(n))}function eg(e){return e.missingCometState||!e.hasClassicProjection||!e.diagnostic.valid||e.phase==="archive"||e.verifyResult==="fail"||e.diagnostic.runtimeEval&&!e.diagnostic.runtimeEval.passed?!0:e.phase!=="build"?!1:e.buildPause==="plan-ready"}function w_(e,t){let n=e.toLowerCase(),i=[];n.includes(t.name.toLowerCase())&&i.push({source:"user",quote:t.name});let r=t.text.split(/[^a-zA-Z0-9_\-\u4e00-\u9fff/]+/u).map(o=>o.trim().toLowerCase()).filter(o=>o.length>=4&&!h_.has(o)),s=[...new Set(r.filter(o=>n.includes(o)))].slice(0,3);for(let o of s)i.push({source:"repo",quote:o});return i}async function y_(e){return new Promise(t=>{let n=o_("git",["status","--short","--untracked-files=all"],{cwd:e,stdio:["ignore","pipe","ignore"],shell:!1}),i=[];n.stdout.on("data",r=>{i.push(Buffer.isBuffer(r)?r:Buffer.from(String(r)))}),n.on("error",()=>t([])),n.on("exit",r=>{if(r!==0){t([]);return}let s=Buffer.concat(i).toString("utf8").split(/\r?\n/u).map(o=>o.trim()).filter(Boolean);t(s)})})}async function tg(e,t){let n=a_(t),i=n.utterance.trim(),r=i.toLowerCase();if(n.agent_context.already_in_comet_flow)return Oe("out_of_scope",null,"low","already in Comet flow");if(eu(r,g_))return Oe("out_of_scope",null,"low","user opted out of Comet resume",[{source:"user",quote:i}]);let s=await d_(e);if(s.length===0)return Oe("none",null,"none","no active Comet changes");let o=await y_(e);if(s.length>1){let u=s.find(d=>r.includes(d.name.toLowerCase()));return u?o.length>0?Oe("ask_user",u,"low","uncommitted worktree changes require attribution",[{source:"repo",quote:`${o.length} dirty file(s)`}]):eg(u)?Oe("ask_user",u,"low","active change is at a decision point"):Oe("auto_resume",u,"high","request names an active change",[{source:"user",quote:u.name}]):Oe("ask_user",null,"low","multiple active changes require a change name")}let[a]=s;if(o.length>0)return Oe("ask_user",a,"low","uncommitted worktree changes require attribution",[{source:"repo",quote:`${o.length} dirty file(s)`}]);if(eg(a))return a.missingCometState?Oe("ask_user",a,"low","active OpenSpec change is missing Comet state"):Oe("ask_user",a,"low","active change is at a decision point",[{source:"state",quote:`phase: ${a.phase}`}]);let c=eu(r,m_);if(!n.agent_context.non_trivial_work&&eu(r,p_)&&!c)return Oe("out_of_scope",a,"low","user asked a question without workflow work");let f=w_(i,a);return c||f.length>0?Oe("auto_resume",a,"high","single active change and request is related",[{source:"state",quote:`phase: ${a.phase}`},...f]):n.agent_context.non_trivial_work?Oe("ask_user",a,"low","single active change exists but request looks unrelated"):Oe("out_of_scope",a,"low","request is not workflow work")}function Vo(e,t,n){return{exitCode:e,...t===void 0?{}:{stdout:t},...n===void 0?{}:{stderr:n}}}function ng(){return Vo(64,void 0,`Usage: comet-resume-probe.mjs probe +Usage: comet-resume-probe.mjs probe --stdin`)}async function v_(){let e=[];for await(let t of process.stdin)e.push(Buffer.isBuffer(t)?t:Buffer.from(String(t)));return Buffer.concat(e).toString("utf8")}function b_(e){return{schema_version:wi,utterance:e,locale:"unknown",agent_context:{non_trivial_work:!0,already_in_comet_flow:!1}}}function C_(e){try{return JSON.parse(e)}catch{return b_(e)}}var ig=async(e,t)=>mt(t,async()=>{let[n,i]=e;if(n!=="probe")return ng();let r=i==="--stdin",s=r?await v_():i;if(!s)return ng();try{let o=r?C_(s):JSON.parse(s),a=await tg(x(),o);return Vo(0,`${JSON.stringify(a,null,2)} +`)}catch(o){return o instanceof SyntaxError?Vo(1,void 0,`Invalid JSON: ${o.message}`):Vo(1,void 0,o instanceof Error?o.message:String(o))}});rr();lt();kt();Ne();import{createHash as Dr,randomUUID as na}from"crypto";import{promises as ne}from"fs";import $ from"path";var su=".comet/classic-root-move.json",ou=".comet/transactions/classic-root-move//openspec",ug=["handoff hashes","Run state","checkpoints","trajectory","archived evidence and artifact pointers"],fg=["approved plan ID still matches layout, source identity and manifest, target identity, and configuration","no pending root-move recovery transaction","target remains absent or the bound empty directory","source, target, staging, transaction, and config paths remain protected"],Qo=5e4,Xo=512*1024*1024,rg=16*1024*1024,gt=/^[a-f0-9]{64}$/u,dg=/^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/u,mg=Symbol("ClassicRootMoveJournalClaim");function nt(e,t){return $.relative(e,t).replaceAll("\\","/")}async function Si(e,t,n,i="directory"){await T(e,nt(e,t),{label:`Classic root move physical path ${n}`,expected:i})}function pg(e,t){return Ae(e,t)}async function $e(e,t,n){let i=$.resolve(e),r=$.resolve(t),s=$.relative(i,r);if($.isAbsolute(s)||s===".."||s.startsWith(`..${$.sep}`))throw new Error(`${n} must stay inside the project root`);r!==i&&await Si(e,t,n,"directory");let o=[i],a=i;for(let l of s.split($.sep).filter(Boolean))a=$.join(a,l),o.push(a);let c=[];for(let l of o){let f=await ne.lstat(l,{bigint:!0});if(!f.isDirectory()||f.isSymbolicLink())throw new Error(`${n} crosses a symbolic link or junction`);c.push({path:l,identity:Fn(f),stat:f})}return{entries:c}}async function V(e,t){for(let n of e.entries){let i=await ne.lstat(n.path,{bigint:!0});if(!i.isDirectory()||i.isSymbolicLink()||!pg(n.identity,Fn(i)))throw new Error(`${t} changed after inspection`)}}async function k_(e,t,n,i){let r=await $e(e,t,n);await i?.afterDirectoryInspect?.(n),await V(r,n);let s=await ne.readdir(t,{withFileTypes:!0});return await V(r,n),s}async function qn(e,t,n){try{return await $e(e,t,n),!0}catch(i){if(i.code==="ENOENT")return!1;throw i}}async function yi(e,t,n,i){let r=$.resolve(e),s=$.resolve(t),o=$.relative(r,s);if($.isAbsolute(o)||o===".."||o.startsWith(`..${$.sep}`))throw new Error(`${n} must stay inside the project root`);let a=r;for(let c of o.split($.sep).filter(Boolean)){let l=$.join(a,c);try{let f=await ne.lstat(l,{bigint:!0});if(!f.isDirectory()||f.isSymbolicLink())throw new Error(`${n} crosses a symbolic link or junction`)}catch(f){if(f.code!=="ENOENT")throw f;let u=await $e(e,a,n),d=`create-directory:${nt(e,l)}`;await i?.beforeMutation?.(d),await V(u,n);try{await ne.mkdir(l)}catch(g){if(g.code!=="EEXIST")throw g}await V(u,n);let p=await ne.lstat(l,{bigint:!0});if(!p.isDirectory()||p.isSymbolicLink())throw new Error(`${n} changed while creating a directory`,{cause:f})}a=l}await Si(e,t,n,"directory")}async function Ei(e,t,n){let i=await ne.lstat(e,{bigint:!0});if(i.isSymbolicLink()||(t==="file"?!i.isFile():!i.isDirectory()))throw new Error(`${n} must be a real ${t}`);return i}async function tt(e,t,n){let i=await ne.lstat(e,{bigint:!0}),r=t.isDirectory()?pg(Fn(t),Fn(i)):sa(t,i);if(i.isSymbolicLink()||i.isFile()!==t.isFile()||i.isDirectory()!==t.isDirectory()||!r)throw new Error(`${n} changed after inspection`)}async function au(e,t,n,i,r){let s=`Classic root move ${i}`,o=await $e(e,$.dirname(t),s);await r?.beforeMutation?.(i),await V(o,s);let a=await ne.open(t,"wx");try{await V(o,s),await a.writeFile(n),await a.sync()}finally{await a.close()}await V(o,s),await Si(e,t,s,"file")}async function ia(e,t,n,i,r){let s=`Classic root move ${i}`,o=await $e(e,$.dirname(t),s),a=await $e(e,$.dirname(n),s),c=await Ei(t,"file",s);await r?.beforeMutation?.(i),await V(o,s),await V(a,s),await tt(t,c,s),await ne.link(t,n),await V(o,s),await V(a,s),await tt(n,c,s)}async function sg(e,t,n,i,r,s={}){let o=`Classic root move ${i}`,a=await $e(e,$.dirname(t),o),c=await $e(e,$.dirname(n),o),l=await Ei(t,(await ne.lstat(t)).isDirectory()?"directory":"file",o);if(s.replaceTarget)s.expectedTargetIdentity&&await tt(n,s.expectedTargetIdentity,o);else if((await T(e,nt(e,n),{label:o,expected:"any"})).exists)throw new Error(`${o} target already exists`);await r?.beforeMutation?.(i),await V(a,o),await V(c,o),await tt(t,l,o),s.expectedTargetIdentity&&await tt(n,s.expectedTargetIdentity,o),await s.validateTarget?.(),await ne.rename(t,n),await V(a,o),await V(c,o),await tt(n,l,o)}async function Dn(e,t,n,i,r={}){let s=`Classic root move ${n}`,o;try{o=await Ei(t,"file",s)}catch(c){if(c.code==="ENOENT")return!1;throw c}r.expectedIdentity&&await tt(t,r.expectedIdentity,s);let a=await $e(e,$.dirname(t),s);return await i?.beforeMutation?.(n),await V(a,s),await tt(t,o,s),r.expectedIdentity&&await tt(t,r.expectedIdentity,s),await r.validateTarget?.(),await ne.unlink(t),await V(a,s),!0}async function Zo(e,t,n,i,r){let s=`Classic root move ${n}`,o;try{o=await Ei(t,"directory",s)}catch(l){if(l.code==="ENOENT")return!1;throw l}if(r&&!cu(ta(o,`Classic root move ${n}`),r))throw new Error(`Classic root move ${n} changed after migration preflight`);let a=await $e(e,$.dirname(t),s);await i?.beforeMutation?.(n),await V(a,s),await tt(t,o,s);let c=await ne.readdir(t);if(await V(a,s),await tt(t,o,s),c.length>0)throw new Error(`${s} directory is not empty`);return await ne.rmdir(t),await V(a,s),!0}async function ra(e,t){let n=Ye(e,"legacy"),i=Ye(e,"docs"),r=$.join(e,".comet","transactions","classic-root-move"),s=[[$.join(e,".comet"),".comet","directory"],[$.join(e,".comet","config.yaml"),".comet/config.yaml","file"],[n.openSpecRoot,"openspec","directory"],[$.dirname(i.openSpecRoot),"docs","directory"],[i.openSpecRoot,"docs/openspec","directory"],[$.join(e,".comet","transactions"),".comet/transactions","directory"],[r,".comet/transactions/classic-root-move","directory"]];if(t){let o=$.join(r,t);s.push([o,`transaction ${t}`,"directory"],[$.join(o,"openspec"),`transaction ${t} staging`,"directory"],[$.join(o,"legacy-source"),`transaction ${t} quarantine`,"directory"])}for(let[o,a,c]of s)await Si(e,o,a,c)}async function hg(e,t,n,i){let r=Bn(e);await yi(e,$.dirname(r),"Classic root move journal parent",i);let s=`${r}.${na()}.tmp`,o=JSON.stringify(n,null,2)+` +`,a;try{await au(e,s,o,"update-journal-temp",i);let c=await Ei(s,"file","Classic root move updated journal");a=await Sg(e,t,"update-journal-commit",i);try{await ia(e,s,r,"update-journal-publish",i)}catch(u){throw new Error("Classic root move journal publish failed; a successor journal was preserved",{cause:u})}let l=await Ci(e),f=l?ki(l):null;if(!l||l.id!==n.id||l.stage!==n.stage||l.planId!==n.planId||l.schema!==n.schema||!f||f.contentHash!==vi(Buffer.from(o))||!sa(c,f.fileIdentity))throw new Error("Classic root move journal ownership changed while updating");return await Dn(e,a.file,"cleanup-update-journal-quarantine",i,{expectedIdentity:ki(a.journal).fileIdentity}),a=void 0,l}catch(c){throw a&&await kg(e,a,"restore-update-journal",i).catch(()=>!1),c}finally{await Dn(e,s,"cleanup-update-journal-temp").catch(()=>!1)}}async function S_(e,t,n,i){await yi(e,$.dirname(t),"Classic root move journal parent",i);let r=`${t}.${na()}.tmp`;try{await au(e,r,JSON.stringify(n,null,2)+` +`,"create-journal-temp",i),await ia(e,r,t,"create-journal-commit",i)}catch(s){throw s.code==="EEXIST"?new Error("Classic root move is incomplete; use comet doctor --repair --strategy continue|rollback",{cause:s}):s}finally{await Dn(e,r,"cleanup-create-journal-temp").catch(()=>!1)}}function gg(e){return Dr("sha256").update(JSON.stringify({directories:e.directories,files:e.files,totalBytes:e.totalBytes})).digest("hex")}function Lr(e,t){return et?1:0}function Yo(e,t){return e.every((n,i)=>i===0||t(e[i-1],n)<=0)}function wg(e){return Dr("sha256").update(JSON.stringify({source:e.source,target:e.target,staging:e.staging,artifactLayout:e.artifactLayout,sourceIdentity:e.sourceIdentity,targetInitialIdentity:e.targetInitialIdentity,targetInitialState:e.targetInitialState,fileCount:e.fileCount,directoryCount:e.directoryCount,totalBytes:e.totalBytes,manifestHash:e.manifestHash,configPath:e.configPath,originalConfigHash:e.originalConfigHash,expectedConfigHash:e.expectedConfigHash})).digest("hex")}function E_(e){return Dr("sha256").update(JSON.stringify({source:e.source,target:e.target,staging:ou,targetInitialState:e.targetInitialState,fileCount:e.fileCount,directoryCount:e.directoryCount,totalBytes:e.totalBytes,manifestHash:e.manifestHash,configPath:e.configPath,originalConfigHash:e.originalConfigHash,expectedConfigHash:e.expectedConfigHash})).digest("hex")}function ea(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function nu(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function R_(e){return"mtimeNs"in e&&typeof e.mtimeNs=="bigint"?e.mtimeNs:e.mtimeMs}function Fn(e){return{dev:e.dev,ino:e.ino,birthtime:ea(e)}}function jr(e){return String(e)}function ta(e,t){let n=Fn(e);if(!Sn(n,n))throw new Error(`${t} filesystem does not expose a stable device and file identity; refusing an auditable root move`);return{dev:jr(e.dev),ino:jr(e.ino),birthtime:jr(ea(e)),ctime:jr(nu(e)),mtime:jr(R_(e))}}function __(e,t,n){return t.entries.map(i=>{let r=ta(i.stat,n);return{path:nt(e,i.path)||".",dev:r.dev,ino:r.ino,birthtime:r.birthtime}})}function cu(e,t){return JSON.stringify(e)===JSON.stringify(t)}function yg(e,t){return e.length===t.length&&e.every((n,i)=>cu(n,t[i]))}async function iu(e,t,n){let i=await $e(e,t,n);return await V(i,n),__(e,i,n)}function sa(e,t){let n=Fn(e),i=Fn(t);return Sn(n,i)?Ae(n,i):Ae(n,i)&&ea(e)===ea(t)&&nu(e)===nu(t)&&e.size===t.size}function vi(e){return Dr("sha256").update(e).digest("hex")}async function Mr(e,t,n,i,r){let s=await U(e,nt(e,t),n,{label:i,bigint:!0});if(r&&!sa(r,s.stat))throw new Error(`${i} changed while reading`);if(BigInt(s.stat.size)!==BigInt(s.bytes.byteLength))throw new Error(`${i} changed while reading`);return s.bytes}async function vg(e){let t=await Rn(e,{allowPartialProject:!0});if(!t.document||!t.identity.exists||!t.identity.sha256)throw new Error(".comet/config.yaml does not exist");return t}async function lu(e){return(await vg(e)).identity.sha256}function x_(e){let t=e.value.classic;if(!t||typeof t!="object"||Array.isArray(t))throw new Error("classic must be a mapping");let n=kn({...e.value,classic:{...t,artifact_layout:"docs"}},e.classic?.language==="zh-CN"||e.native?.language==="zh-CN"?"zh-CN":"en");return Dr("sha256").update(n).digest("hex")}async function oa(e,t,n){let i=[],r=[],s=0;async function o(c,l){await Si(e,c,l||nt(e,t),"directory");let f=await k_(e,c,`tree:${l||nt(e,t)}`,n);for(let u of f.sort((d,p)=>Lr(d.name,p.name))){let d=$.join(c,u.name),p=l?`${l}/${u.name}`:u.name,g=await ne.lstat(d,{bigint:!0});if(g.isSymbolicLink())throw new Error(`Classic root move does not support symbolic links or junctions: ${p}`);if(g.isDirectory()){i.push(p),await o(d,p);continue}if(!g.isFile())throw new Error(`Classic root move supports only regular files and directories: ${p}`);if(await n?.afterSourceFileInspect?.(p),r.length+1>Qo)throw new Error(`Classic root move exceeds ${Qo} files`);let h=Xo-s,m=await Mr(e,d,Math.max(1,h),`Classic root move source file ${p}`,g);if(s+=m.byteLength,s>Xo)throw new Error(`Classic root move exceeds ${Xo} bytes`);r.push({path:p,size:m.byteLength,hash:vi(m)})}}await o(t,""),i.sort(Lr),r.sort((c,l)=>Lr(c.path,l.path));let a={directories:i,files:r,totalBytes:s};return{...a,hash:gg(a)}}function uu(e,t){return e.hash===t.hash}async function P_(e,t,n){try{let i=await $e(e,t,"docs-target"),r=i.entries.at(-1);if(!r)throw new Error("Classic docs target identity is unavailable");let s=ta(r.stat,"Classic docs target");await n?.afterDirectoryInspect?.("docs-target"),await V(i,"docs-target");let o=await ne.readdir(t,{withFileTypes:!0});await V(i,"docs-target");let c=(await $e(e,t,"docs-target")).entries.at(-1),l=c?ta(c.stat,"Classic docs target"):null;if(!l||!cu(s,l))throw new Error("Classic docs target changed after inspection");return o.length>0?{state:"non-empty",conflicts:["Classic docs target is not empty"],identity:l}:{state:"empty",conflicts:[],identity:l}}catch(i){if(i.code==="ENOENT")return{state:"missing",conflicts:[],identity:null};throw i}}async function O_(e){if(await qm(e),await Zt(e)!=="legacy")throw new Error("Classic root move requires classic.artifact_layout: legacy")}async function ru(e,t={}){if(await ra(e),await O_(e),await Zt(e)!=="legacy")throw new Error("Classic root move requires the legacy layout");let n=Ye(e,"legacy"),i=Ye(e,"docs");if(!await qn(e,n.openSpecRoot,"Classic legacy root"))throw new Error("Classic legacy root does not exist: openspec/");let r=await iu(e,n.openSpecRoot,"Classic legacy root identity"),s=await oa(e,n.openSpecRoot,t.testHooks),o=await iu(e,n.openSpecRoot,"Classic legacy root identity");if(!yg(r,o))throw new Error("Classic legacy root identity changed during migration preflight");let a=await P_(e,i.openSpecRoot,t.testHooks),c=await vg(e);await t.testHooks?.afterConfigSnapshot?.();let l=c.identity.sha256,f=x_(c.document),u={source:nt(e,n.openSpecRoot),target:nt(e,i.openSpecRoot),staging:ou,artifactLayout:"legacy",sourceIdentity:o,targetInitialIdentity:a.identity,targetInitialState:a.state,fileCount:s.files.length,directoryCount:s.directories.length,totalBytes:s.totalBytes,manifestHash:s.hash,configPath:ae,originalConfigHash:l,expectedConfigHash:f};return{manifest:s,plan:{projectRoot:e,...u,configHash:l,planId:wg(u),fileSummary:s.files.map(d=>({...d})),configChange:{from:"legacy",to:"docs"},conflicts:a.conflicts,blockers:[],pendingRecovery:null,historicalPointersPreserved:[...ug],applyPreconditions:[...fg],allowedRecoveryStrategies:[],readyToApply:a.conflicts.length===0}}}async function $_(e,t,n,i,r){await yi(e,n,"Classic root move staging root",r);for(let s of i.directories)await yi(e,$.join(n,...s.split("/")),`Classic root move staging directory ${s}`,r);for(let s of i.files){await r?.beforeSourceFileCopy?.(s.path);let o=$.join(t,...s.path.split("/")),a=await Mr(e,o,Math.max(1,s.size),`Classic root move source file ${s.path}`);if(a.byteLength!==s.size||vi(a)!==s.hash)throw new Error("Classic legacy root changed after migration preflight");let c=$.join(n,...s.path.split("/"));if(await yi(e,$.dirname(c),`Classic root move staging parent ${s.path}`,r),(await T(e,nt(e,c),{label:`Classic root move staging file ${s.path}`,expected:"file"})).exists)throw new Error("Classic root move staging changed after migration preflight");await au(e,c,a,`copy-file:${s.path}`,r);let f=await Mr(e,c,Math.max(1,s.size),`Classic root move staging file ${s.path}`);if(f.byteLength!==s.size||vi(f)!==s.hash)throw new Error("Classic root move staging verification failed")}}function Bn(e){return $.join(e,...su.split("/"))}function D(e){return new Error(`invalid Classic root move journal: ${e}`)}function bi(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw D(`${t} must be an object`);return e}function Wn(e,t,n){let i=Object.keys(e).sort(),r=[...t].sort();if(JSON.stringify(i)!==JSON.stringify(r))throw D(`${n} fields are invalid`)}function og(e,t){if(typeof e!="string"||e.length===0||e.includes("\\"))throw D(`${t} is invalid`);let n=e.split("/");if($.posix.isAbsolute(e)||n.some(i=>i===""||i==="."||i==="..")||$.posix.normalize(e)!==e)throw D(`${t} must stay inside the migration tree`);return e}function bg(e){let t=bi(e,"manifest");if(Wn(t,["directories","files","totalBytes","hash"],"manifest"),!Array.isArray(t.directories)||!Array.isArray(t.files)||!Number.isSafeInteger(t.totalBytes)||t.totalBytes<0||t.totalBytes>Xo||typeof t.hash!="string"||!gt.test(t.hash))throw D("manifest shape is invalid");let n=t.directories.map((f,u)=>og(f,`manifest path directories[${u}]`)),i=t.files.map((f,u)=>{let d=bi(f,`manifest.files[${u}]`);Wn(d,["path","size","hash"],`manifest.files[${u}]`);let p=og(d.path,`manifest path files[${u}]`);if(!Number.isSafeInteger(d.size)||d.size<0||typeof d.hash!="string"||!gt.test(d.hash))throw D(`manifest.files[${u}] is invalid`);return{path:p,size:d.size,hash:d.hash}});if(i.length>Qo)throw D(`manifest exceeds ${Qo} files`);let r=i.map(f=>f.path),s=new Set(n).size!==n.length||new Set(r).size!==r.length,o=Yo(n,Lr)&&Yo(r,Lr)||Yo(n,(f,u)=>f.localeCompare(u))&&Yo(r,(f,u)=>f.localeCompare(u));if(s||!o)throw D("manifest paths must be unique and sorted");let a=i.reduce((f,u)=>f+u.size,0);if(a!==t.totalBytes)throw D("manifest totalBytes does not match its files");let c={directories:n,files:i,totalBytes:a},l=gg(c);if(l!==t.hash)throw D("manifest hash is invalid");return{...c,hash:l}}function Cg(e,t){let n=bi(e,t);Wn(n,["dev","ino","birthtime"],t);let i=/^-?[0-9]+$/u;for(let r of["dev","ino","birthtime"])if(typeof n[r]!="string"||!i.test(n[r]))throw D(`${t}.${r} is invalid`);if(n.dev==="0"||n.ino==="0")throw D(`${t} does not contain a stable filesystem identity`);return{dev:n.dev,ino:n.ino,birthtime:n.birthtime}}function I_(e,t){let n=bi(e,t);Wn(n,["dev","ino","birthtime","ctime","mtime"],t);let i=Cg({dev:n.dev,ino:n.ino,birthtime:n.birthtime},t),r=/^-?[0-9]+$/u;if(typeof n.ctime!="string"||!r.test(n.ctime)||typeof n.mtime!="string"||!r.test(n.mtime))throw D(`${t} timestamps are invalid`);return{...i,ctime:n.ctime,mtime:n.mtime}}function A_(e){if(!Array.isArray(e)||e.length!==2)throw D("sourceIdentity must bind the project root and openspec root");let t=[".","openspec"];return e.map((n,i)=>{let r=bi(n,`sourceIdentity[${i}]`);if(Wn(r,["path","dev","ino","birthtime"],`sourceIdentity[${i}]`),r.path!==t[i])throw D(`sourceIdentity[${i}].path is invalid`);let s={dev:r.dev,ino:r.ino,birthtime:r.birthtime};return{path:t[i],...Cg(s,`sourceIdentity[${i}]`)}})}function N_(e){if(Wn(e,["schema","id","stage","source","target","staging","configPath","originalConfigHash","expectedConfigHash","planId","targetInitialState","manifest"],"root"),typeof e.id!="string"||!dg.test(e.id))throw D("id is invalid");if(e.stage!=="copying"&&e.stage!=="ready"&&e.stage!=="switched"&&e.stage!=="configured")throw D("stage is invalid");let t=`.comet/transactions/classic-root-move/${e.id}/openspec`;if(e.source!=="openspec"||e.target!=="docs/openspec"||e.staging!==t)throw D("source, target, and staging must use the managed project paths");if(e.configPath!==ae||typeof e.originalConfigHash!="string"||!gt.test(e.originalConfigHash)||typeof e.expectedConfigHash!="string"||!gt.test(e.expectedConfigHash)||typeof e.planId!="string"||!gt.test(e.planId))throw D("config path, config hashes, or planId is invalid");if(e.targetInitialState!=="missing"&&e.targetInitialState!=="empty")throw D("targetInitialState is invalid");let n=e.targetInitialState,i=bg(e.manifest),r={source:e.source,target:e.target,targetInitialState:n,fileCount:i.files.length,directoryCount:i.directories.length,totalBytes:i.totalBytes,manifestHash:i.hash,configPath:e.configPath,originalConfigHash:e.originalConfigHash,expectedConfigHash:e.expectedConfigHash};if(E_(r)!==e.planId)throw D("planId does not match the bound config and tree");return{schema:"comet.classic-root-move.v1",id:e.id,stage:e.stage,source:e.source,target:e.target,staging:e.staging,configPath:e.configPath,originalConfigHash:e.originalConfigHash,expectedConfigHash:e.expectedConfigHash,planId:e.planId,targetInitialState:n,manifest:i}}function T_(e){if(Wn(e,["schema","id","stage","source","target","staging","artifactLayout","sourceIdentity","targetInitialIdentity","configPath","originalConfigHash","expectedConfigHash","planId","approvedPlanId","targetInitialState","manifest"],"root"),typeof e.id!="string"||!dg.test(e.id))throw D("id is invalid");if(e.stage!=="locked"&&e.stage!=="copying"&&e.stage!=="ready"&&e.stage!=="switched"&&e.stage!=="configured")throw D("stage is invalid");let t=`.comet/transactions/classic-root-move/${e.id}/openspec`;if(e.source!=="openspec"||e.target!=="docs/openspec"||e.staging!==t)throw D("source, target, and staging must use the managed project paths");if(e.artifactLayout!=="legacy")throw D("artifactLayout must be legacy");let n=A_(e.sourceIdentity);if(e.configPath!==ae||typeof e.originalConfigHash!="string"||!gt.test(e.originalConfigHash)||typeof e.expectedConfigHash!="string"||!gt.test(e.expectedConfigHash)||typeof e.planId!="string"||!gt.test(e.planId)||typeof e.approvedPlanId!="string"||!gt.test(e.approvedPlanId))throw D("config path, config hashes, planId, or approvedPlanId is invalid");let i=e.targetInitialState;if(i!=="missing"&&i!=="empty"&&!(e.stage==="locked"&&i==="non-empty"))throw D("targetInitialState is invalid");let r=e.targetInitialIdentity===null?null:I_(e.targetInitialIdentity,"targetInitialIdentity");if(i==="missing"&&r!==null||i!=="missing"&&r===null)throw D("targetInitialIdentity does not match targetInitialState");let s=bg(e.manifest),o={source:e.source,target:e.target,staging:ou,artifactLayout:"legacy",sourceIdentity:n,targetInitialIdentity:r,targetInitialState:i,fileCount:s.files.length,directoryCount:s.directories.length,totalBytes:s.totalBytes,manifestHash:s.hash,configPath:e.configPath,originalConfigHash:e.originalConfigHash,expectedConfigHash:e.expectedConfigHash};if(wg(o)!==e.planId)throw D("planId does not match the bound config and tree");if(e.stage!=="locked"&&e.approvedPlanId!==e.planId)throw D("approvedPlanId does not match the executable plan");return{schema:"comet.classic-root-move.v2",id:e.id,stage:e.stage,source:e.source,target:e.target,staging:e.staging,artifactLayout:"legacy",sourceIdentity:n,targetInitialIdentity:r,configPath:e.configPath,originalConfigHash:e.originalConfigHash,expectedConfigHash:e.expectedConfigHash,planId:e.planId,approvedPlanId:e.approvedPlanId,targetInitialState:i,manifest:s}}function j_(e){let t=bi(e,"root");if(t.schema==="comet.classic-root-move.v1")return N_(t);if(t.schema==="comet.classic-root-move.v2")return T_(t);throw D("schema is unsupported")}async function Ci(e,t){return fu(e,Bn(e),su,t?.afterJournalInspect)}async function fu(e,t,n,i){await Si(e,t,n,"file");try{let r=await ne.lstat(t,{bigint:!0});if(!r.isFile()||r.isSymbolicLink()||r.size>BigInt(rg))throw D("journal must be a bounded regular file");await i?.();let s=await Mr(e,t,rg,"Classic root move journal",r),o=j_(JSON.parse(s.toString("utf8")));return Object.defineProperty(o,mg,{value:{fileIdentity:r,contentHash:vi(s)},enumerable:!1}),o}catch(r){if(r.code==="ENOENT")return null;throw r}}function ki(e){let t=e[mg];if(!t)throw new Error("Classic root move journal has no ownership claim");return t}function du(e,t){let n=ki(e),i=ki(t);return sa(n.fileIdentity,i.fileIdentity)&&n.contentHash===i.contentHash&&e.schema===t.schema&&e.id===t.id&&e.stage===t.stage&&e.planId===t.planId}async function ag(e,t){let n=await fu(e,Bn(e),su);if(!n||!du(t,n))throw new Error("Classic root move journal ownership changed")}async function kg(e,t,n,i){let r=Bn(e);try{await ia(e,t.file,r,`${n}-publish`,i)}catch(o){if(o.code==="EEXIST")return!1;throw o}let s=await Ci(e);if(!s||!du(t.journal,s))throw new Error("Classic root move journal ownership changed while restoring quarantine");return await Dn(e,t.file,`${n}-cleanup-quarantine`,i,{expectedIdentity:ki(t.journal).fileIdentity}),!0}async function Sg(e,t,n,i){let r=Bn(e),s=`${r}.${t.id}.${na()}.quarantine`;await ag(e,t);let o=await $e(e,$.dirname(r),`Classic root move ${n} quarantine`);await i?.beforeMutation?.(`${n}-quarantine`),await V(o,`Classic root move ${n} quarantine`),await ag(e,t),await ne.rename(r,s),await V(o,`Classic root move ${n} quarantine`);let a=await fu(e,s,nt(e,s)).catch(async c=>{throw await cg(e,s,`${n}-restore-unverified`,i).catch(()=>!1),new Error("Classic root move journal ownership changed while quarantining",{cause:c})});if(!a||!du(t,a))throw await cg(e,s,`${n}-restore-successor`,i).catch(()=>!1),new Error("Classic root move journal ownership changed while quarantining");return await i?.afterJournalQuarantine?.(n),{file:s,journal:a}}async function cg(e,t,n,i){let r=Bn(e),s;try{s=await Ei(t,"file",`Classic root move ${n}`)}catch(o){if(o.code==="ENOENT")return!1;throw o}try{await ia(e,t,r,`${n}-publish`,i)}catch(o){if(o.code==="EEXIST")return!1;throw o}return await Dn(e,t,`${n}-cleanup-quarantine`,i,{expectedIdentity:s}),!0}async function Eg(e,t,n,i){let r=await Sg(e,t,n,i);try{if(!await Dn(e,r.file,`${n}-quarantined`,i,{expectedIdentity:ki(r.journal).fileIdentity}))throw new Error("Classic root move quarantined journal disappeared before removal");return!0}catch(s){throw await kg(e,r,`${n}-restore`,i).catch(()=>!1),s}}async function Go(e,t,n,i){if(t.schema==="comet.classic-root-move.v1"&&n==="locked")throw new Error("Legacy Classic root move journals do not support the locked stage");let r={...t,stage:n};return hg(e,t,r,i)}function Rg(e,t){let n={legacy:Ye(e,"legacy"),docs:Ye(e,"docs")},i=$.join(e,".comet","transactions","classic-root-move",t.id);return{source:n.legacy.openSpecRoot,target:n.docs.openSpecRoot,staging:$.join(i,"openspec"),quarantine:$.join(i,"legacy-source"),transactionRoot:i}}async function qr(e,t,n){if(!await qn(e,t,"Classic root move tree"))return"missing";try{return uu(await oa(e,t),n)?"match":"mismatch"}catch{return"mismatch"}}async function mu(e,t,n){if(!await qn(e,t,"Classic root move target"))return"missing";try{let i=await oa(e,t);return uu(i,n)?"match":i.directories.length===0&&i.files.length===0?"empty":"mismatch"}catch{return"mismatch"}}async function _g(e,t,n){if(!await qn(e,t,"Classic root move manifest tree"))return{status:"missing"};try{let i=await oa(e,t);if(uu(i,n))return{status:"complete",actual:i};let r=new Set(n.directories),s=new Map(n.files.map(o=>[o.path,o]));if(i.directories.some(o=>!r.has(o)))return{status:"mismatch"};for(let o of i.files){let a=s.get(o.path);if(!a||a.size!==o.size||a.hash!==o.hash)return{status:"mismatch"}}return{status:"partial",actual:i}}catch{return{status:"mismatch"}}}async function L_(e,t,n,i,r="remove-quarantine"){let s=await _g(e,t,n);if(s.status==="missing")return;if(s.status==="mismatch"||!s.actual)throw new Error("Classic quarantine contains unknown or changed content; files were preserved");for(let a of s.actual.files){let c=$.join(t,...a.path.split("/")),l;try{l=await ne.lstat(c,{bigint:!0})}catch(u){if(u.code==="ENOENT")continue;throw u}let f=l.isFile()&&!l.isSymbolicLink()?await Mr(e,c,Math.max(1,a.size),`Classic root move quarantine file ${a.path}`,l):null;if(!f||f.byteLength!==a.size||vi(f)!==a.hash)throw new Error("Classic quarantine contains unknown or changed content; files were preserved");await Dn(e,c,`${r}-file:${a.path}`,i)}let o=[...s.actual.directories].sort((a,c)=>{let l=c.split("/").length-a.split("/").length;return l===0?c.localeCompare(a):l});for(let a of o){let c=$.join(t,...a.split("/"));await Zo(e,c,`${r}-directory:${a}`,i)}await Zo(e,t,`${r}-root`,i)}async function M_(e,t,n,i){let r=await mu(e,t,n.manifest);if(n.targetInitialState==="missing"){if(r!=="missing")throw new Error("Classic docs target changed after migration preflight");return}if(r==="empty"){if(n.schema==="comet.classic-root-move.v2"&&!n.targetInitialIdentity)throw new Error("Classic docs target identity is missing from the approved plan");await Zo(e,t,"remove-empty-target",i,n.schema==="comet.classic-root-move.v2"?n.targetInitialIdentity??void 0:void 0);return}if(r!=="missing")throw new Error("Classic docs target changed after migration preflight")}async function zo(e,t,n){if(n.schema==="comet.classic-root-move.v1")return;let i=await iu(e,t,"Classic legacy root identity");if(!yg(i,n.sourceIdentity))throw new Error("Classic legacy root identity changed after migration preflight")}async function tu(e,t){if(await lu(e)!==t.originalConfigHash)throw new Error("Classic project config changed after migration preflight");if(await Zt(e)!=="legacy")throw new Error("Classic project config changed after migration preflight")}async function lg(e,t){if(await lu(e)!==t.expectedConfigHash)throw new Error("Classic project config does not match the expected post-switch config hash");if(await Zt(e)!=="docs")throw new Error("Classic project config does not match the expected post-switch config hash")}async function Mn(e,t,n,i){if(await qr(e,t,n)!=="match")throw new Error(i)}async function q_(e,t,n){if(t.stage==="locked")throw new Error("Classic root move locked preflight must be approved before execution");await ra(e,t.id);let{source:i,target:r,staging:s,quarantine:o,transactionRoot:a}=Rg(e,t),c=t;if(c.stage==="copying"){await tu(e,c),await zo(e,i,c),await Mn(e,i,c.manifest,"Classic legacy root changed after migration preflight"),await M_(e,r,c,n);let l=await qr(e,s,c.manifest);if(l==="mismatch")throw new Error("Classic root move staging changed after migration preflight");l==="missing"&&await $_(e,i,s,c.manifest,n),await Mn(e,s,c.manifest,"Classic root move staging verification failed"),c=await Go(e,c,"ready",n)}if(c.stage==="ready"){await tu(e,c),await zo(e,i,c),await Mn(e,i,c.manifest,"Classic legacy root changed after migration preflight");let l=await qr(e,s,c.manifest),f=await mu(e,r,c.manifest);if(l==="missing"&&f==="match")c=await Go(e,c,"switched",n);else{if(l!=="match")throw new Error("Classic root move staging changed after migration preflight");if(f==="mismatch"||f==="empty")throw new Error("Classic docs target changed after migration preflight");f==="missing"&&(await yi(e,$.dirname(r),"Classic docs target parent",n),await sg(e,s,r,"rename-staging-target",n),c=await Go(e,c,"switched",n))}}if(c.stage==="switched"){await zo(e,i,c),await Mn(e,i,c.manifest,"Classic legacy root changed before config switch"),await Mn(e,r,c.manifest,"Classic docs target verification failed after switch");let l=await Zt(e);if(l==="legacy")await tu(e,c),await Dm(e,"docs",{expectedIdentity:{exists:!0,sha256:c.originalConfigHash}});else if(l!=="docs")throw new Error("Classic project config changed after migration preflight");await lg(e,c),c=await Go(e,c,"configured",n)}if(c.stage!=="configured")throw new Error(`Unsupported Classic root move stage: ${c.stage}`);if(await lg(e,c),await Mn(e,r,c.manifest,"Classic docs target verification failed after config switch"),await qn(e,i,"Classic legacy root")){if(await zo(e,i,c),await Mn(e,i,c.manifest,"Classic legacy root changed before cleanup; both roots were preserved"),await qn(e,o,"Classic root move quarantine"))throw new Error("Classic root move quarantine conflicts with the legacy root");await sg(e,i,o,"rename-source-quarantine",n)}await qn(e,o,"Classic root move quarantine")&&await L_(e,o,c.manifest,n),await Zo(e,a,"remove-transaction-root",n),await Eg(e,c,"remove-journal",n)}async function D_(e,t){if(await ra(e,t.id),t.stage==="locked")return{allowedStrategies:["rollback"],reason:"the locked apply preflight was not approved for execution"};let{source:n,target:i,staging:r,quarantine:s}=Rg(e,t),o=await Zt(e),a=await lu(e),c=o==="legacy"&&a===t.originalConfigHash,l=o==="docs"&&a===t.expectedConfigHash,[f,u,d,p]=await Promise.all([qr(e,n,t.manifest),mu(e,i,t.manifest),qr(e,r,t.manifest),_g(e,s,t.manifest)]),g=p.status;if(f==="mismatch")return{allowedStrategies:[],reason:"Classic legacy root changed after migration preflight"};if(u==="mismatch")return{allowedStrategies:[],reason:"Classic docs target changed after migration preflight"};if(d==="mismatch")return{allowedStrategies:[],reason:"Classic staging changed after migration preflight"};if(g==="mismatch")return{allowedStrategies:[],reason:"Classic quarantine contains unknown or changed content"};if(t.stage==="configured"||o==="docs")return l?u==="match"&&(f==="match"&&g==="missing"||f==="missing"&&(g==="missing"||g==="complete"||g==="partial"))?{allowedStrategies:["continue"]}:{allowedStrategies:[],reason:"the configured migration trees are incomplete"}:{allowedStrategies:[],reason:"project config does not match the expected post-switch config hash"};if(!c)return{allowedStrategies:[],reason:"project config changed after migration preflight"};let h=f==="match",m=d==="match"||d==="missing",y=u==="match"||u==="missing"||t.targetInitialState==="empty"&&u==="empty";return!h||!m||!y||g!=="missing"?{allowedStrategies:[],reason:"the migration trees are not recoverable"}:{allowedStrategies:["continue","rollback"]}}async function xg(e,t={}){let n=await le(e),i=await Ci(n,t.testHooks);if(i){let r=await F_(n);if(!r)throw new Error("Classic root move journal disappeared during inspection");return{projectRoot:n,source:i.source,target:i.target,staging:i.staging,artifactLayout:"legacy",sourceIdentity:i.schema==="comet.classic-root-move.v2"?i.sourceIdentity.map(s=>({...s})):[],targetInitialIdentity:i.schema==="comet.classic-root-move.v2"&&i.targetInitialIdentity?{...i.targetInitialIdentity}:null,fileCount:i.manifest.files.length,directoryCount:i.manifest.directories.length,totalBytes:i.manifest.totalBytes,manifestHash:i.manifest.hash,configPath:i.configPath,configHash:i.originalConfigHash,originalConfigHash:i.originalConfigHash,expectedConfigHash:i.expectedConfigHash,planId:i.planId,fileSummary:i.manifest.files.map(s=>({...s})),configChange:{from:"legacy",to:"docs"},conflicts:r.reason?[r.reason]:[],blockers:[`pending Classic root move: ${i.id} at ${i.stage}`],pendingRecovery:r,historicalPointersPreserved:[...ug],applyPreconditions:[...fg],allowedRecoveryStrategies:[...r.allowedStrategies],targetInitialState:i.targetInitialState,readyToApply:!1}}return(await ru(n,t)).plan}async function Pg(e,t={}){let n=await le(e),i=await Ci(n,t.testHooks);if(i)throw new Error(`Classic root move ${i.id} is incomplete; use comet doctor --repair --strategy continue|rollback`);let r=await ru(n),s=t.planId??r.plan.planId;if(!gt.test(s))throw new Error("Classic root move apply received an invalid internal plan ID");let o=na();await ra(n,o);let a={schema:"comet.classic-root-move.v2",id:o,stage:"locked",source:r.plan.source,target:r.plan.target,staging:`.comet/transactions/classic-root-move/${o}/openspec`,artifactLayout:r.plan.artifactLayout,sourceIdentity:r.plan.sourceIdentity.map(f=>({...f})),targetInitialIdentity:r.plan.targetInitialIdentity?{...r.plan.targetInitialIdentity}:null,configPath:ae,originalConfigHash:r.plan.originalConfigHash,expectedConfigHash:r.plan.expectedConfigHash,planId:r.plan.planId,approvedPlanId:s,targetInitialState:r.plan.targetInitialState,manifest:r.manifest};await S_(n,Bn(n),a,t.testHooks);let c=await Ci(n);if(!c||c.id!==o||c.stage!=="locked")throw new Error("Classic root move lock ownership changed before locked preflight");let l=!1;try{let f=await ru(n,t),u=f.plan;if(u.planId!==s)throw new Error(`Classic root move plan changed since dry-run: approved ${s}, current ${u.planId}`);if(!u.readyToApply)throw new Error(`Classic root move apply is blocked: ${[...u.conflicts,...u.blockers].join("; ")}`);if(u.targetInitialState==="non-empty")throw new Error("Classic root move apply is blocked: Classic docs target is not empty");let d={schema:"comet.classic-root-move.v2",id:o,stage:"copying",source:u.source,target:u.target,staging:`.comet/transactions/classic-root-move/${o}/openspec`,artifactLayout:u.artifactLayout,sourceIdentity:u.sourceIdentity.map(g=>({...g})),targetInitialIdentity:u.targetInitialIdentity?{...u.targetInitialIdentity}:null,configPath:ae,originalConfigHash:u.originalConfigHash,expectedConfigHash:u.expectedConfigHash,planId:u.planId,approvedPlanId:s,targetInitialState:u.targetInitialState,manifest:f.manifest},p=await hg(n,c,d,t.testHooks);return l=!0,await q_(n,p,t.testHooks),{...u,staging:d.staging}}catch(f){throw l||await Eg(n,c,"remove-rejected-lock",t.testHooks).catch(()=>!1),f}}async function F_(e,t={}){let n=await Ci(e,t.testHooks);if(!n)return null;let i=await D_(e,n);return{id:n.id,stage:n.stage,source:n.source,target:n.target,staging:n.staging,planId:n.planId,...i}}kt();function Og(e="en"){return{exitCode:64,stderr:e==="zh-CN"?"用法:comet classic root show | comet classic root move docs --dry-run | comet classic root move docs --apply":"Usage: comet classic root show | comet classic root move docs --dry-run | comet classic root move docs --apply"}}function W_(e){return e?.classic?.language==="en"?"en":"zh-CN"}function B_(e,t){let n=e instanceof Error?e.message:String(e);return t==="en"?n:n==="invalid Classic root move journal: manifest paths must be unique and sorted"?"Classic 根目录迁移失败:迁移记录中的清单路径必须唯一且按顺序排列":n.startsWith("invalid Classic root move journal:")?"Classic 根目录迁移失败:迁移记录格式或内容无效,请运行 comet doctor 检查恢复状态":"Classic 根目录迁移失败:迁移过程中发生错误,请运行 comet doctor 检查迁移状态"}function $g(e,t,n="en"){let i=n==="zh-CN",r=d=>d.length>0?d.join("; "):i?"无":"none",s=d=>{if(!i)return d;let p=/^pending Classic root move: (.+) at (.+)$/u.exec(d);return p?`存在待恢复的 Classic 根目录迁移:${p[1]},阶段 ${p[2]}`:{"Classic docs target is not empty":"docs 目标目录非空","the locked apply preflight was not approved for execution":"已锁定的迁移预检尚未获准执行","Classic legacy root changed after migration preflight":"迁移预检后 legacy 根目录发生变化","Classic docs target changed after migration preflight":"迁移预检后 docs 目标目录发生变化","Classic staging changed after migration preflight":"迁移预检后暂存目录发生变化","Classic quarantine contains unknown or changed content":"隔离目录包含未知或已变化的内容","project config does not match the expected post-switch config hash":"项目配置与切换后的预期配置哈希不一致","the configured migration trees are incomplete":"已切换配置对应的迁移目录不完整","project config changed after migration preflight":"迁移预检后项目配置发生变化","the migration trees are not recoverable":"迁移目录当前无法安全恢复"}[d]??"迁移状态存在无法识别的冲突,请运行 comet doctor 检查恢复状态"},o=(d,p)=>p.length===0?[`${d}: ${i?"无":"none"}`]:[`${d}:`,...p.map(g=>`- ${s(g)}`)],a=i?{missing:"缺失",empty:"空目录","non-empty":"非空目录"}[e.targetInitialState]:e.targetInitialState,c=i?"handoff 哈希;运行状态;检查点;轨迹;已归档证据与产物指针":e.historicalPointersPreserved.join("; "),l=i?"内部迁移身份仍与布局、源目录、清单、目标目录和配置一致;不存在待恢复的根迁移事务;目标仍然缺失或为已绑定的空目录;所有迁移路径仍受保护":e.applyPreconditions.join("; "),f=i?e.allowedRecoveryStrategies.map(d=>d==="continue"?"继续":"回滚"):e.allowedRecoveryStrategies,u=[t==="dry-run"?i?"Classic 根目录迁移现状":"Classic root move status":i?"Classic 根目录迁移完成":"Classic root move complete",...t==="dry-run"?[i?"说明:仅查看现状,未修改任何文件。":"Note: Inspection only; no files were changed."]:[],`${i?"源目录":"source"}: ${e.source}`,`${i?"目标目录":"target"}: ${e.target}`,`${i?"暂存目录":"staging"}: ${e.staging}`,`${i?"当前布局":"artifact layout"}: ${e.artifactLayout}`,`${i?"源目录身份":"source identity"}: ${JSON.stringify(e.sourceIdentity)}`,`${i?"目标初始身份":"target initial identity"}: ${e.targetInitialIdentity?JSON.stringify(e.targetInitialIdentity):i?"缺失":"missing"}`,`${i?"文件数":"files"}: ${e.fileCount}`,`${i?"目录数":"directories"}: ${e.directoryCount}`,`${i?"总字节数":"bytes"}: ${e.totalBytes}`,`${i?"清单哈希":"manifest"}: ${e.manifestHash}`,...e.fileSummary.map(d=>`${i?"文件":"file"}: ${d.path} ${d.size} ${d.hash}`),`${i?"配置变更":"config change"}: ${e.configChange.from} -> ${e.configChange.to}`,`${i?"配置路径":"config path"}: ${e.configPath}`,`${i?"配置哈希":"config"}: ${e.configHash}`,`${i?"原配置哈希":"original config"}: ${e.originalConfigHash}`,`${i?"预期配置哈希":"expected config"}: ${e.expectedConfigHash}`,`${i?"目标初始状态":"target initial state"}: ${a}`,...o(i?"冲突":"conflicts",e.conflicts),...o(i?"阻塞项":"blockers",e.blockers),`${i?"待恢复事务":"pending recovery"}: ${e.pendingRecovery?`${e.pendingRecovery.id} ${i?"位于阶段":"at"} ${e.pendingRecovery.stage}`:i?"无":"none"}`,`${i?"保留历史指针":"historical pointers preserved"}: ${c}`,`${i?"执行前提":"apply preconditions"}: ${l}`,`${i?"允许的恢复策略":"allowed recovery strategies"}: ${r(f)}`,`${i?"可执行迁移":"ready to apply"}: ${e.readyToApply?i?"是":"yes":i?"否":"no"}`];return t==="dry-run"?u.push(e.readyToApply?i?"下一步:运行 comet classic root move docs --apply 执行迁移。":"Next: run comet classic root move docs --apply to apply the migration.":i?"下一步:请先解决上述冲突或阻塞项。":"Next: resolve the conflicts or blockers above before applying."):u.push(i?"结果:迁移已完成。":"Result: Migration completed."),`${u.join(` `)} `}function H_(e,t,n){let i=A(e.projectRoot,e.openSpecRoot);return n==="zh-CN"?[t==="dry-run"?"Classic 根目录迁移现状":"Classic 根目录迁移完成",`当前布局: ${e.artifactLayout}`,`Classic 根目录: ${i}`,t==="dry-run"?"说明:项目已经使用 docs/openspec,仅查看现状,未修改任何文件。":"结果:项目已经使用 docs/openspec,无需重复迁移,未修改任何文件。"].join(` `)+` `:[t==="dry-run"?"Classic root move status":"Classic root move complete",`current layout: ${e.artifactLayout}`,`Classic root: ${i}`,t==="dry-run"?"Note: The project already uses docs/openspec. Inspection only; no files were changed.":"Result: The project already uses docs/openspec. No migration was needed and no files were changed."].join(` `)+` -`}var Og=async e=>{let[t,n,i,...r]=e;if(t==="show"&&n===void 0){let f=await le(process.cwd()),u=await z(f);return{exitCode:0,stdout:JSON.stringify({schema:"comet.classic-layout.v1",artifactLayout:u.artifactLayout,openSpecRoot:A(f,u.openSpecRoot),changesRoot:A(f,u.changesDir),archiveRoot:A(f,u.archiveDir),specsRoot:A(f,u.specsDir),superpowersRoot:A(f,u.superpowersRoot)})+` -`}}if(t!=="move"||n!=="docs")return xg();let s=await le(process.cwd()),o=await rl(s),a=W_(o);if(i!=="--dry-run"&&i!=="--apply"||r.length>0)return xg(a);let c=await z(s),l=i==="--dry-run"?"dry-run":"complete";if(c.artifactLayout==="docs")return{exitCode:0,stdout:H_(c,l,a)};try{if(i==="--dry-run"){let u=await Rg(s);return{exitCode:0,stdout:Pg(u,"dry-run",a)}}let f=await _g(s);return{exitCode:0,stdout:Pg(f,"complete",a)}}catch(f){return{exitCode:70,stderr:B_(f,a)}}};var Br=rt(Ue(),1);import{spawnSync as K_}from"child_process";import{promises as J_}from"fs";import q from"path";pr();var U_="\x1B[32m",V_="\x1B[31m",Y_="\x1B[33m",yu="\x1B[0m",Fr=["full","hotfix","tweak"],vu=["open","design","build","verify","archive"],Ig=["en","zh-CN"],G_=Dp,hu=new Set([...hr,"archive_confirmation","verify_failures","classic_profile","classic_migration","bound_branch"]),z_=new Set(rn.filter(e=>!hu.has(e))),X_={workflow:Fr,phase:vu,context_compression:["off","beta"],build_mode:["subagent-driven-development","executing-plans","direct"],build_pause:["null","plan-ready"],subagent_dispatch:["null","confirmed"],tdd_mode:["tdd","direct"],review_mode:["off","standard","thorough"],isolation:["current","branch","worktree"],verify_mode:["light","full"],auto_transition:["true","false"],verify_result:["pending","pass","fail"],branch_status:["pending","handled"],archive_confirmation:["pending","confirmed"],archived:["true","false"],direct_override:["true","false"],classic_profile:Fr,classic_migration:["1"]},Q_=new Set(["design_doc","plan","verification_report","handoff_context"]),Z_={archived:"archived",branchStatus:"branch_status",classicProfile:"classic_profile",designDoc:"design_doc",language:"language",phase:"phase",verificationReport:"verification_report",verifiedAt:"verified_at",archiveConfirmation:"archive_confirmation",verifyResult:"verify_result",verifyFailures:"verify_failures",workflow:"workflow"},Wr=class extends Error{constructor(n,i=1){super(n);this.exitCode=i}exitCode},ca=class{stdout=[];stderr=[];result(t=0){return{exitCode:t,...this.stdout.length>0?{stdout:this.stdout.join(` +`}var Ig=async e=>{let[t,n,i,...r]=e;if(t==="show"&&n===void 0){let f=await le(process.cwd()),u=await G(f),d=await pl(f,u.artifactLayout);return{exitCode:0,stdout:JSON.stringify({schema:"comet.classic-layout.v1",artifactLayout:u.artifactLayout,openSpecRoot:A(f,u.openSpecRoot),alternateRoot:A(f,d.alternateRoot),configuredRootExists:d.configuredRootExists,alternateRootExists:d.alternateRootExists,dualRoots:d.dualRoots,changesRoot:A(f,u.changesDir),archiveRoot:A(f,u.archiveDir),specsRoot:A(f,u.specsDir),superpowersRoot:A(f,u.superpowersRoot)})+` +`}}if(t!=="move"||n!=="docs")return Og();let s=await le(process.cwd()),o=await rl(s),a=W_(o);if(i!=="--dry-run"&&i!=="--apply"||r.length>0)return Og(a);let c=await G(s),l=i==="--dry-run"?"dry-run":"complete";if(c.artifactLayout==="docs")return{exitCode:0,stdout:H_(c,l,a)};try{if(i==="--dry-run"){let u=await xg(s);return{exitCode:0,stdout:$g(u,"dry-run",a)}}let f=await Pg(s);return{exitCode:0,stdout:$g(f,"complete",a)}}catch(f){return{exitCode:70,stderr:B_(f,a)}}};var Br=st(Ue(),1);import{spawnSync as K_}from"child_process";import{promises as J_}from"fs";import q from"path";pr();var U_="\x1B[32m",V_="\x1B[31m",Y_="\x1B[33m",yu="\x1B[0m",Fr=["full","hotfix","tweak"],vu=["open","design","build","verify","archive"],Ng=["en","zh-CN"],G_=Wp,hu=new Set([...hr,"archive_confirmation","verify_failures","classic_profile","classic_migration","bound_branch"]),z_=new Set(rn.filter(e=>!hu.has(e))),X_={workflow:Fr,phase:vu,context_compression:["off","beta"],build_mode:["subagent-driven-development","executing-plans","direct"],build_pause:["null","plan-ready"],subagent_dispatch:["null","confirmed"],tdd_mode:["tdd","direct"],review_mode:["off","standard","thorough"],isolation:["current","branch","worktree"],verify_mode:["light","full"],auto_transition:["true","false"],verify_result:["pending","pass","fail"],branch_status:["pending","handled"],archive_confirmation:["pending","confirmed"],archived:["true","false"],direct_override:["true","false"],classic_profile:Fr,classic_migration:["1"]},Q_=new Set(["design_doc","plan","verification_report","handoff_context"]),Z_={archived:"archived",branchStatus:"branch_status",classicProfile:"classic_profile",designDoc:"design_doc",language:"language",phase:"phase",verificationReport:"verification_report",verifiedAt:"verified_at",archiveConfirmation:"archive_confirmation",verifyResult:"verify_result",verifyFailures:"verify_failures",workflow:"workflow"},Wr=class extends Error{constructor(n,i=1){super(n);this.exitCode=i}exitCode},ca=class{stdout=[];stderr=[];result(t=0){return{exitCode:t,...this.stdout.length>0?{stdout:this.stdout.join(` `)+` `}:{},...this.stderr.length>0?{stderr:this.stderr.join(` -`)}:{}}}};function nt(e){return`${U_}${e}${yu}`}function gu(e){return`${V_}${e}${yu}`}function $g(e){return`${Y_}${e}${yu}`}function S(e){throw new Wr(e)}function it(e){let t=ge(e);t&&S(`ERROR: ${t}`)}function ua(e,t){t.includes(e)||S(`ERROR: Invalid value: '${e}' -Valid values: ${t.join(" ")}`)}function la(e,t){if(Ig.includes(e))return e;S(`ERROR: Invalid language from ${t}: '${e}' -Valid values: en, zh-CN`)}function Ag(e,t){!e||e==="null"||(/^(?:[A-Za-z]:|[\\/]|~)/u.test(e)&&S(`ERROR: ${t} must be a relative path within the repo: '${e}'`),e.split(/[\\/]/u).includes("..")&&S(`ERROR: ${t} cannot contain '..' (path traversal not allowed): '${e}'`))}async function me(e){let t=x();return X(t,e,{label:`Classic project path ${q.relative(t,q.resolve(t,e)).replaceAll("\\","/")}`})}async function Lt(e){let t=x();return xn(t,e,`Classic project file ${q.relative(t,q.resolve(t,e)).replaceAll("\\","/")}`)}async function ex(e){return ii(e,x())}async function fa(e){let t,n=x();try{t=await W(n,e,{label:`Classic state ${q.relative(n,e).replaceAll("\\","/")}`})}catch(r){throw r.code==="ENOENT"&&S(`ERROR: .comet.yaml not found at ${q.relative(n,e).replaceAll("\\","/")}`),r}let i=(0,Br.parseDocument)(t,{uniqueKeys:!1});return i.errors.length>0&&S(`ERROR: Invalid .comet.yaml: ${i.errors[0].message}`),i}async function bu(e,t){await ti(x(),e,t,{label:"Classic state write target"})}function wu(e){return e===null?"null":e===void 0?"":typeof e=="object"?JSON.stringify(e):String(e)}function Ng(e){return Z_[e]??String(e)}function Tg(e){return e===null?"null":wu(e)}function be(e,t,n,i){let r=e[t];return typeof r=="string"&&n.includes(r)?r:i}function Nt(e,t){let n=e[t];return n==null||n===""?null:typeof n=="string"?n:String(n)}function pu(e,t){let n=e[t];return n==null||n===""?null:typeof n=="boolean"?n:n==="true"?!0:n==="false"?!1:null}function tx(e,t,n=0){let i=e[t];return typeof i=="number"&&Number.isInteger(i)&&i>=0?i:n}function nx(e){let t=be(e,"workflow",Fr,"full");return{workflow:t,language:be(e,"language",Ig,null),phase:be(e,"phase",vu,"open"),contextCompression:be(e,"context_compression",["off","beta"],null),buildMode:be(e,"build_mode",["subagent-driven-development","executing-plans","direct"],null),buildPause:be(e,"build_pause",["plan-ready"],null),subagentDispatch:be(e,"subagent_dispatch",["confirmed"],null),tddMode:be(e,"tdd_mode",["tdd","direct"],null),reviewMode:be(e,"review_mode",["off","standard","thorough"],null),isolation:be(e,"isolation",["current","branch","worktree"],null),boundBranch:Nt(e,"bound_branch"),verifyMode:be(e,"verify_mode",["light","full"],null),autoTransition:pu(e,"auto_transition"),baseRef:Nt(e,"base_ref"),designDoc:Nt(e,"design_doc"),plan:Nt(e,"plan"),verifyResult:be(e,"verify_result",["pending","pass","fail"],"pending"),verifyFailures:tx(e,"verify_failures"),verificationReport:Nt(e,"verification_report"),branchStatus:be(e,"branch_status",["pending","handled"],null),createdAt:Nt(e,"created_at"),verifiedAt:Nt(e,"verified_at"),archiveConfirmation:be(e,"archive_confirmation",["pending","confirmed"],null),archived:pu(e,"archived")??!1,directOverride:pu(e,"direct_override"),handoffContext:Nt(e,"handoff_context"),handoffHash:Nt(e,"handoff_hash"),classicProfile:be(e,"classic_profile",Fr,t),classicMigration:typeof e.classic_migration=="number"?e.classic_migration:null}}async function Cu(e){return(await Or(e,{cwd:x()}))?.value??null}async function jg(){if(process.env.COMET_LANGUAGE)return la(process.env.COMET_LANGUAGE,"COMET_LANGUAGE");let e=await Or("language",{cwd:x()});return e?la(e.value,e.source):"en"}async function ix(){let e=process.env.COMET_CONTEXT_COMPRESSION??await Cu("context_compression")??"off";return["off","beta"].includes(e)||S(`ERROR: Invalid context_compression: '${e}' -Valid values: off, beta`),e}async function Lg(){let e=process.env.COMET_AUTO_TRANSITION??await Cu("auto_transition")??"true";return["true","false"].includes(e)||S(`ERROR: Invalid auto_transition: '${e}' +`)}:{}}}};function it(e){return`${U_}${e}${yu}`}function gu(e){return`${V_}${e}${yu}`}function Ag(e){return`${Y_}${e}${yu}`}function S(e){throw new Wr(e)}function rt(e){let t=ge(e);t&&S(`ERROR: ${t}`)}function ua(e,t){t.includes(e)||S(`ERROR: Invalid value: '${e}' +Valid values: ${t.join(" ")}`)}function la(e,t){if(Ng.includes(e))return e;S(`ERROR: Invalid language from ${t}: '${e}' +Valid values: en, zh-CN`)}function Tg(e,t){!e||e==="null"||(/^(?:[A-Za-z]:|[\\/]|~)/u.test(e)&&S(`ERROR: ${t} must be a relative path within the repo: '${e}'`),e.split(/[\\/]/u).includes("..")&&S(`ERROR: ${t} cannot contain '..' (path traversal not allowed): '${e}'`))}async function me(e){let t=x();return X(t,e,{label:`Classic project path ${q.relative(t,q.resolve(t,e)).replaceAll("\\","/")}`})}async function Lt(e){let t=x();return xn(t,e,`Classic project file ${q.relative(t,q.resolve(t,e)).replaceAll("\\","/")}`)}async function ex(e){return ii(e,x())}async function fa(e){let t,n=x();try{t=await W(n,e,{label:`Classic state ${q.relative(n,e).replaceAll("\\","/")}`})}catch(r){throw r.code==="ENOENT"&&S(`ERROR: .comet.yaml not found at ${q.relative(n,e).replaceAll("\\","/")}`),r}let i=(0,Br.parseDocument)(t,{uniqueKeys:!1});return i.errors.length>0&&S(`ERROR: Invalid .comet.yaml: ${i.errors[0].message}`),i}async function bu(e,t){await ti(x(),e,t,{label:"Classic state write target"})}function wu(e){return e===null?"null":e===void 0?"":typeof e=="object"?JSON.stringify(e):String(e)}function jg(e){return Z_[e]??String(e)}function Lg(e){return e===null?"null":wu(e)}function be(e,t,n,i){let r=e[t];return typeof r=="string"&&n.includes(r)?r:i}function Nt(e,t){let n=e[t];return n==null||n===""?null:typeof n=="string"?n:String(n)}function pu(e,t){let n=e[t];return n==null||n===""?null:typeof n=="boolean"?n:n==="true"?!0:n==="false"?!1:null}function tx(e,t,n=0){let i=e[t];return typeof i=="number"&&Number.isInteger(i)&&i>=0?i:n}function nx(e){let t=be(e,"workflow",Fr,"full");return{workflow:t,language:be(e,"language",Ng,null),phase:be(e,"phase",vu,"open"),contextCompression:be(e,"context_compression",["off","beta"],null),buildMode:be(e,"build_mode",["subagent-driven-development","executing-plans","direct"],null),buildPause:be(e,"build_pause",["plan-ready"],null),subagentDispatch:be(e,"subagent_dispatch",["confirmed"],null),tddMode:be(e,"tdd_mode",["tdd","direct"],null),reviewMode:be(e,"review_mode",["off","standard","thorough"],null),isolation:be(e,"isolation",["current","branch","worktree"],null),boundBranch:Nt(e,"bound_branch"),verifyMode:be(e,"verify_mode",["light","full"],null),autoTransition:pu(e,"auto_transition"),baseRef:Nt(e,"base_ref"),designDoc:Nt(e,"design_doc"),plan:Nt(e,"plan"),verifyResult:be(e,"verify_result",["pending","pass","fail"],"pending"),verifyFailures:tx(e,"verify_failures"),verificationReport:Nt(e,"verification_report"),branchStatus:be(e,"branch_status",["pending","handled"],null),createdAt:Nt(e,"created_at"),verifiedAt:Nt(e,"verified_at"),archiveConfirmation:be(e,"archive_confirmation",["pending","confirmed"],null),archived:pu(e,"archived")??!1,directOverride:pu(e,"direct_override"),handoffContext:Nt(e,"handoff_context"),handoffHash:Nt(e,"handoff_hash"),classicProfile:be(e,"classic_profile",Fr,t),classicMigration:typeof e.classic_migration=="number"?e.classic_migration:null}}async function Cu(e){return(await Or(e,{cwd:x()}))?.value??null}async function Mg(){if(process.env.COMET_LANGUAGE)return la(process.env.COMET_LANGUAGE,"COMET_LANGUAGE");let e=await Or("language",{cwd:x()});return e?la(e.value,e.source):"en"}async function ix(){let e=process.env.COMET_CONTEXT_COMPRESSION??await Cu("context_compression")??"off";return["off","beta"].includes(e)||S(`ERROR: Invalid context_compression: '${e}' +Valid values: off, beta`),e}async function qg(){let e=process.env.COMET_AUTO_TRANSITION??await Cu("auto_transition")??"true";return["true","false"].includes(e)||S(`ERROR: Invalid auto_transition: '${e}' Valid values: true, false`),e}async function rx(){let e=process.env.COMET_REVIEW_MODE??await Cu("review_mode")??"standard";return["null","off","standard","thorough"].includes(e)||S(`ERROR: Invalid review_mode: '${e}' -Valid values: off, standard, thorough`),e==="null"?null:e}function Mg(e){let t=K_("git",e,{encoding:"utf8"});return t.status===0?t.stdout.trim():null}async function gt(e){let t=await ex(e);return await Y(x(),q.join(t.directory,".comet"),{label:`Classic runtime directory for ${e}`,expected:"directory"}),{...t,file:q.join(t.directory,".comet.yaml")}}async function _(e,t){let{file:n}=await gt(e),s=(await fa(n)).toJS()[t];return t==="language"?s==null||s===""?jg():la(wu(s),".comet.yaml"):t==="auto_transition"&&(s==null||s==="")?Lg():wu(s)}function qg(e,t){let n=(0,Br.parseDocument)(`${e}: ${t} -`);return n.errors.length>0&&S(`ERROR: Invalid value: '${t}'`),n.get(e)}async function sx(e,t){if(e==="language"){la(t,"language");return}let n=X_[e];n&&ua(t,n),Q_.has(e)&&(Ag(t,e),t&&t!=="null"&&await Y(x(),t,{label:`${e} artifact pointer`,expected:"file"})),(e==="skill_hash"||e==="handoff_hash")&&!/^[a-f0-9]{64}$/u.test(t)&&S(`ERROR: ${e} must be a sha256 hex digest`),e==="iteration"&&!/^[0-9]+$/u.test(t)&&S("ERROR: iteration must be a non-negative integer")}async function Dg(e,t,n,i,r={}){hu.has(n)&&!r.machineOwned&&S(`ERROR: '${n}' is a machine-owned field and cannot be set directly`),!z_.has(n)&&!hu.has(n)&&S(`ERROR: Unknown field: '${n}'`),n==="phase"&&!r.internal&&process.env.COMET_FORCE_PHASE!=="1"&&S(`ERROR: Setting 'phase' directly is not allowed; it bypasses state machine evidence checks. +Valid values: off, standard, thorough`),e==="null"?null:e}function Dg(e){let t=K_("git",e,{encoding:"utf8"});return t.status===0?t.stdout.trim():null}async function wt(e){let t=await ex(e);return await Y(x(),q.join(t.directory,".comet"),{label:`Classic runtime directory for ${e}`,expected:"directory"}),{...t,file:q.join(t.directory,".comet.yaml")}}async function _(e,t){let{file:n}=await wt(e),s=(await fa(n)).toJS()[t];return t==="language"?s==null||s===""?Mg():la(wu(s),".comet.yaml"):t==="auto_transition"&&(s==null||s==="")?qg():wu(s)}function Fg(e,t){let n=(0,Br.parseDocument)(`${e}: ${t} +`);return n.errors.length>0&&S(`ERROR: Invalid value: '${t}'`),n.get(e)}async function sx(e,t){if(e==="language"){la(t,"language");return}let n=X_[e];n&&ua(t,n),Q_.has(e)&&(Tg(t,e),t&&t!=="null"&&await Y(x(),t,{label:`${e} artifact pointer`,expected:"file"})),(e==="skill_hash"||e==="handoff_hash")&&!/^[a-f0-9]{64}$/u.test(t)&&S(`ERROR: ${e} must be a sha256 hex digest`),e==="iteration"&&!/^[0-9]+$/u.test(t)&&S("ERROR: iteration must be a non-negative integer")}async function Wg(e,t,n,i,r={}){hu.has(n)&&!r.machineOwned&&S(`ERROR: '${n}' is a machine-owned field and cannot be set directly`),!z_.has(n)&&!hu.has(n)&&S(`ERROR: Unknown field: '${n}'`),n==="phase"&&!r.internal&&process.env.COMET_FORCE_PHASE!=="1"&&S(`ERROR: Setting 'phase' directly is not allowed; it bypasses state machine evidence checks. Use: comet-state.mjs transition - Repair-only escape hatch: COMET_FORCE_PHASE=1 comet-state.mjs set phase `),await sx(n,i);let{file:s,directory:o}=await gt(t),a=await fa(s),c=a.toJS()??{};if(a.set(n,qg(n,i)),n==="isolation")if(jo(i)){let u=typeof c.isolation=="string"?c.isolation:null,d=c.bound_branch;if(!(typeof d=="string"&&d!=="")||u!==i){let g=Ot(),h=To(g),m=Ll({isolation:i,boundBranch:null,currentBranch:h,gitWorkTree:h===null?jl(g):!0});m.status==="needs-heal"?a.set("bound_branch",m.branch):m.status==="unbound-detached"?S(`ERROR: cannot bind isolation=${i} while HEAD is detached; checkout a branch first`):a.set("bound_branch",null)}}else a.set("bound_branch",null);let l=await mr(o),f=gr(a.toJS(),l);if(f.run){f.classic||S("ERROR: migrated Run is missing its Classic projection");let u=await Ge(o,f),d=Et(f.classic,u),p=d!==f.run.currentStep,g={...f.run,currentStep:d,iteration:f.run.iteration+(p?1:0),status:d==="completed"?"completed":"running"};if(await je(o,{classic:f.classic,run:g,unknownKeys:f.unknownKeys}),p){let h=await Le(o,g.trajectoryRef);await We(o,g.trajectoryRef,{sequence:h.length+1,timestamp:new Date().toISOString(),type:"state_transitioned",runId:g.runId,data:{kind:"classic-config",field:n,fromStep:f.run.currentStep,toStep:d}})}}else await bu(s,a.toString());n==="phase"&&!r.internal&&e.stderr.push($g("WARNING: Setting 'phase' directly bypasses state machine constraints."),$g(" Consider using: comet-state.mjs transition ")),e.stderr.push(nt(`[SET] ${n}=${i}`))}async function ox(e,t,n){it(t),ua(n,Fr);let i=await Hm(t,x()),{label:r,directory:s}=i,o=q.join(s,".comet.yaml");await me(o)&&S(`ERROR: .comet.yaml already exists at ${r}/.comet.yaml`);let a=n!=="full",c=a?"off":await rx(),l=new Br.Document({workflow:n,language:await jg(),phase:"open",context_compression:await ix(),build_mode:a?"direct":null,build_pause:null,subagent_dispatch:null,tdd_mode:a?"direct":null,review_mode:c,isolation:null,verify_mode:a?"light":null,auto_transition:await Lg()==="true",base_ref:Mg(["rev-parse","--verify","HEAD"]),design_doc:null,plan:null,verify_result:"pending",verify_failures:0,verification_report:null,branch_status:"pending",created_at:new Date().toISOString().slice(0,10),verified_at:null,archive_confirmation:null,archived:!1});await bu(o,l.toString()),e.stdout.push(nt(`Initialized: ${r}/.comet.yaml (workflow=${n})`))}async function Tt(e,t){let n=await _(e,"phase");n!==t&&S(`ERROR: Cannot transition '${e}': expected phase ${t}, got ${n}`)}async function ax(e){let t=await _(e,"workflow"),n=await _(e,"build_mode"),i=await _(e,"isolation"),r=await _(e,"direct_override"),s=await _(e,"subagent_dispatch"),o=await _(e,"tdd_mode"),a=await _(e,"review_mode");["current","branch","worktree"].includes(i)||S(`ERROR: Cannot transition '${e}': isolation must be current, branch, or worktree, got '${i||"null"}'`),["subagent-driven-development","executing-plans","direct"].includes(n)||S(`ERROR: Cannot transition '${e}': build_mode must be selected before leaving build, got '${n||"null"}'`),n==="direct"&&!["hotfix","tweak"].includes(t)&&r!=="true"&&S(`ERROR: Cannot transition '${e}': build_mode=direct is only allowed for hotfix/tweak unless direct_override=true`),n==="subagent-driven-development"&&s!=="confirmed"&&S(`ERROR: Cannot transition '${e}': subagent_dispatch must be confirmed before using build_mode=subagent-driven-development`),t==="full"&&(!o||o==="null")&&S(`ERROR: Cannot transition '${e}': tdd_mode must be selected before leaving build (full workflow)`),t==="full"&&!["off","standard","thorough"].includes(a)&&S(`ERROR: Cannot transition '${e}': review_mode must be selected before leaving build (full workflow); review_mode must be off, standard, or thorough, got '${a||"null"}'`)}async function cx(e){let{directory:t}=await gt(e),n=await _(e,"workflow");for(let i of["proposal.md","tasks.md"])await Lt(q.join(t,i))||S(`ERROR: Cannot transition '${e}': ${i} must exist and be non-empty before leaving open`);n==="full"&&!await Lt(q.join(t,"design.md"))&&S(`ERROR: Cannot transition '${e}': design.md must exist and be non-empty before leaving open`)}async function lx(e){let t=await _(e,"design_doc");(!t||t==="null"||!await Lt(q.resolve(t)))&&S(`ERROR: Cannot transition '${e}': design_doc must point to an existing Design Doc before leaving design`)}async function ux(e,t){let n=q.join(e,".comet.yaml"),i=await fa(n);for(let r of t){let s=Ng(r.field);i.set(s,qg(s,Tg(r.to)))}await bu(n,i.toString())}async function fx(e,t,n){let{directory:i}=await gt(t),r=await B(i),s=r.classic,o=!1;if(!s){r.run&&S("ERROR: Classic state projection is missing");let c=await fa(q.join(i,".comet.yaml"));s=nx(c.toJS()),o=!0}let a=ui(s,n);r.run?await cn(i,a.classic,r.run,{event:n,source:"comet-state"}):o?await ux(i,a.effects):await je(i,{classic:a.classic,run:null,unknownKeys:r.unknownKeys}),await An(i,{change:t,event:n,source:"comet-state",from:s,to:a.classic,effects:a.effects});for(let c of a.effects)e.stderr.push(nt(`[SET] ${Ng(c.field)}=${Tg(c.to)}`));e.stderr.push(nt(`[TRANSITION] ${n}`))}async function dx(e,t,n){if(it(t),ua(n,G_),n==="open-complete")await Tt(t,"open"),await cx(t);else if(n==="design-complete")await Tt(t,"design"),await lx(t);else if(n==="build-complete")await Tt(t,"build"),await ax(t);else if(n==="verify-pass"){await Tt(t,"verify");let i=await _(t,"verification_report");(!i||!await me(q.resolve(i)))&&S(`ERROR: Cannot transition '${t}': verification_report must point to an existing report file`)}else if(n==="verify-fail")await Tt(t,"verify");else if(n==="archive-confirm")await Tt(t,"archive"),await _(t,"verify_result")!=="pass"&&S(`ERROR: Cannot transition '${t}': verify_result must be pass before archiving`),await _(t,"archived")==="true"&&S(`ERROR: Cannot transition '${t}': already archived`);else if(n==="preset-escalate"){await Tt(t,"build");let i=await _(t,"workflow");["hotfix","tweak"].includes(i)||S(`ERROR: Cannot transition '${t}': preset-escalate only applies to hotfix/tweak, got workflow='${i}'`)}else n==="archive-reopen"?(await Tt(t,"archive"),await _(t,"archived")==="true"&&S(`ERROR: Cannot transition '${t}': already archived`)):(await Tt(t,"archive"),await _(t,"verify_result")!=="pass"&&S(`ERROR: Cannot transition '${t}': verify_result must be pass before archiving`),await _(t,"archive_confirmation")!=="confirmed"&&S(`ERROR: Cannot transition '${t}': archive_confirmation must be confirmed before archiving`));await fx(e,t,n)}async function mx(e,t){it(t);let{file:n,label:i}=await gt(t);await me(n)||S(`ERROR: .comet.yaml not found at ${i}/.comet.yaml`);let r=await _(t,"phase"),s=await _(t,"workflow"),o=await _(t,"auto_transition");if(await _(t,"archived")==="true"){e.stdout.push("NEXT: done");return}let a=r==="open"?"comet-open":r==="design"?"comet-design":r==="verify"?"comet-verify":r==="archive"?"comet-archive":r==="build"?s==="hotfix"?"comet-hotfix":s==="tweak"?"comet-tweak":"comet-build":null;a||S(`ERROR: Cannot resolve next step for '${t}': unknown phase '${r||"null"}'`),e.stdout.push(`NEXT: ${o==="false"?"manual":"auto"}`,`SKILL: ${a}`),o==="false"&&e.stdout.push(`HINT: phase is '${r}'; run /${a} manually to continue`)}async function px(e,t,n){Ag(t,"task file"),n||S("ERROR: Task text cannot be empty");let i=q.resolve(x(),t);await me(i)||S(`ERROR: Task file not found: ${t}`);let s=(await W(x(),i,{label:"Classic task-checkoff file"})).split(/\r?\n/u).filter(a=>[`- [ ] ${n}`,`- [x] ${n}`,`- [X] ${n}`].includes(a)),o=s.filter(a=>/^- \[[xX]\] /u.test(a));s.length!==1&&S(`ERROR: task text must appear exactly once in ${t} (found ${s.length}): ${n}`),o.length!==1&&S(`ERROR: task is not checked in ${t}: ${n}`),e.stdout.push("TASK_CHECKOFF: PASS",`FILE: ${t}`,`TASK: ${n}`)}async function hx(e,t,n){it(t),ua(n,vu);let{file:i,directory:r,label:s}=await gt(t);e.stdout.push(`=== Entry Check: comet-${n} ===`),await me(i)||S(`ERROR: .comet.yaml not found at ${s}/.comet.yaml`);let o=!1,a=u=>e.stdout.push(` ${nt("[PASS]")} ${u}`),c=u=>{e.stdout.push(` ${gu("[FAIL]")} ${u}`),o=!0},l=async(u,d)=>{let p=await _(t,u);(p===d?a:c)(`${u}=${p} (expected: ${d})`)};if(a(".comet.yaml exists"),await l("phase",n),n==="design"){await l("workflow","full");let u=await _(t,"design_doc");(!u||u==="null"?a:c)(u?`design_doc=${u} (expected: empty/null)`:"design_doc is empty/null");for(let d of["proposal.md","design.md","tasks.md"])(await Lt(q.join(r,d))?a:c)(`${d} ${await Lt(q.join(r,d))?"non-empty":"missing or empty"}`)}else if(n==="build"){let u=await _(t,"workflow"),d=await _(t,"design_doc");u==="full"?(d&&d!=="null"&&await me(q.resolve(d))?a:c)(`design_doc=${d} (expected: non-null and file exists)`):a(`workflow=${u} (design_doc not required)`);for(let p of["proposal.md","tasks.md"])(await Lt(q.join(r,p))?a:c)(`${p} ${await Lt(q.join(r,p))?"non-empty":"missing or empty"}`)}else if(n==="verify"){let u=await _(t,"verify_result");(["","null","pending"].includes(u)?a:c)(`verify_result=${u} (expected: pending or null)`)}else if(n==="archive"){await l("verify_result","pass");let u=await _(t,"archived");(u!=="true"?a:c)(`archived=${u} (expected: not true)`)}let f=await xt(r,{heal:!0,cwd:Ot()});if(f.bindingRequired)switch(f.status){case"drift":c(Lo(t,f.boundBranch,f.currentBranch));break;case"unbound-detached":c(Pt(t));break;case"healed":a(`bound_branch lazily set to ${f.branch}`);break;case"needs-heal":case"ok":case"not-applicable":a("bound_branch matches current branch");break;default:{let u=f;throw new Error(`unhandled branch binding status: ${JSON.stringify(u)}`)}}if(e.stdout.push(""),o)throw e.stderr.push(gu("BLOCKED — fix failing checks before proceeding")),new Wr("",1);e.stderr.push(nt("ALL CHECKS PASSED — ready to proceed"))}async function he(e,t,n){return!t||t==="null"?` - ${e}: PENDING`:n&&!await me(q.resolve(n))?` - ${e}: BROKEN (path ${t} does not exist)`:` - ${e}: DONE (${t})`}async function gx(e,t){e.stdout.push(" Artifacts:");let n=0;for(let i of["proposal.md","design.md","tasks.md"]){let r=await Lt(q.join(t,i));r&&(n+=1),e.stdout.push(` - ${i}: ${r?"DONE":"PENDING"}`)}e.stdout.push("",n===3?"Recovery action: All artifacts complete. Run /comet-open user confirmation, then guard to transition.":n===0?"Recovery action: No artifacts created yet. Start from /comet-open Step 1 (explore and clarify).":"Recovery action: Some artifacts incomplete. Resume /comet-open from the first missing artifact.")}async function wx(e,t,n){e.stdout.push(" Artifacts:");for(let o of["proposal.md","design.md","tasks.md"])e.stdout.push(` - ${o}: ${await Lt(q.join(n,o))?"DONE":"MISSING (unexpected in design phase)"}`);let i=await _(t,"handoff_context"),r=await _(t,"handoff_hash"),s=await _(t,"design_doc");e.stdout.push(""," Design progress:",await he("handoff_context",i,i),await he("handoff_hash",r),await he("design_doc",s,s),""),s&&s!=="null"&&await me(q.resolve(s))?e.stdout.push("Recovery action: Design Doc already created and linked. Run guard to transition to build."):i&&i!=="null"&&await me(q.resolve(i))?e.stdout.push("Recovery action: Handoff generated but Design Doc not yet created. Resume from brainstorming confirmation (Step 1c)."):e.stdout.push("Recovery action: No handoff generated yet. Start from Step 1a (generate handoff package).")}async function yx(e,t,n,i){let r=await _(t,"isolation"),s=await _(t,"build_mode"),o=await _(t,"build_pause"),a=await _(t,"subagent_dispatch"),c=await _(t,"tdd_mode"),l=await _(t,"review_mode"),f=await _(t,"plan"),u=await Ko(x(),f),d=[" Build decisions:",await he("isolation",r),await he("build_mode",s),await he("build_pause",o),await he("tdd_mode",c),await he("review_mode",l)];(s==="subagent-driven-development"||a&&a!=="null")&&d.push(await he("subagent_dispatch",a)),e.stdout.push(...d,""," Plan:",await he("plan",f,f),"");let p=q.join(n,"tasks.md");if(!await me(p)){e.stdout.push(" Tasks: tasks.md MISSING","","Recovery action: tasks.md missing. Verify change directory integrity.");return}let g=(await W(x(),p,{label:"Classic change tasks"})).split(/\r?\n/u),h=g.filter(R=>/^\s*- \[[ xX]\] /u.test(R)).length,m=g.filter(R=>/^\s*- \[[xX]\] /u.test(R)).length,y=h-m,w=0,C=0;if(u.status==="ready"){let R=(await W(x(),f,{label:"Classic build plan"})).split(/\r?\n/u);w=R.filter(O=>/^\s*- \[[ xX]\] /u.test(O)).length,C=R.filter(O=>/^\s*- \[[xX]\] /u.test(O)).length}let k=w-C;e.stdout.push(` Tasks: ${m}/${h} done, ${y} pending`),w>0&&e.stdout.push(` Plan tasks: ${C}/${w} done, ${k} pending`),e.stdout.push("");let E=vx(t,q.relative(x(),n).replaceAll("\\","/"),i,r,s,o,a,c,l,u,y,k);e.stdout.push(E)}function dn(e){return!e||e==="null"}function vx(e,t,n,i,r,s,o,a,c,l,f,u){let d=l.status==="ready",p=n==="full"&&(dn(a)||dn(c));return s==="plan-ready"&&d&&(dn(i)||dn(r)||p)?n==="full"?"Recovery action: Plan-ready pause detected. Ask the user whether to continue, then choose isolation, build mode, TDD mode, and review mode without regenerating the plan.":"Recovery action: Plan-ready pause detected. Ask the user whether to continue, then choose isolation and build mode without regenerating the plan.":n==="full"&&!d?bx(e,t,l):s==="plan-ready"?r==="subagent-driven-development"&&(f>0||u>0)?o==="confirmed"?"Recovery action: Plan-ready pause is stale because build decisions are already selected. Clear build_pause to null, then inspect the first unchecked task (OpenSpec or plan additions) against recent git history/diff. If implemented, check it off; otherwise dispatch a subagent. Do not execute the pending task directly in the main window.":"Recovery action: Plan-ready pause is stale and selected subagent execution is not recorded. Run comet state set subagent_dispatch confirmed, then continue from the first unchecked task through subagent execution.":f>0||u>0?"Recovery action: Plan-ready pause is stale because build decisions are already selected. Clear build_pause to null, then continue from the first unchecked task.":"Recovery action: Plan-ready pause is stale and all tasks are done. Clear build_pause to null, then run guard to transition to verify.":dn(i)?"Recovery action: Isolation not selected. Use the current platform's user confirmation mechanism to ask user for branch/worktree choice.":dn(r)?"Recovery action: Build mode not selected. Use the current platform's user confirmation mechanism to ask user for execution method.":n==="full"&&dn(a)?"Recovery action: TDD mode not selected. Use the current platform's user confirmation mechanism to ask user for tdd or direct.":n==="full"&&dn(c)?"Recovery action: Review mode not selected. Use the current platform's user confirmation mechanism to ask user for off, standard, or thorough.":f>0?r==="subagent-driven-development"?o==="confirmed"?"Recovery action: Read tasks.md and the Superpowers plan (which may include additions beyond OpenSpec), then inspect the first unchecked task against recent git history/diff. If implemented, check it off; otherwise dispatch a subagent. Do not execute the pending task directly in the main window.":"Recovery action: Selected subagent execution is not recorded. Run comet state set subagent_dispatch confirmed, then continue from the first unchecked task through subagent execution.":"Recovery action: Read tasks.md and continue from first unchecked task.":u>0?r==="subagent-driven-development"?o==="confirmed"?"Recovery action: Read the Superpowers plan, then inspect the first unchecked Superpowers plan task against recent git history/diff. If implemented, check it off; otherwise dispatch a subagent. Do not execute the pending task directly in the main window.":"Recovery action: Selected subagent execution is not recorded. Run comet state set subagent_dispatch confirmed, then continue from the first unchecked task through subagent execution.":"Recovery action: Read the Superpowers plan and continue from the first unchecked plan task.":"Recovery action: All tasks done. Run guard to transition to verify."}function bx(e,t,n){let i=n.status==="missing",r=i?"classic-build-plan-missing":"classic-build-plan-broken",s=i?"plan is not recorded":"the recorded plan path does not resolve to a file",o=i?[]:[`RECORDED_PLAN: ${n.recordedPath}`],a=i?`comet state set ${e} plan `:`comet state set ${e} plan `,c=i?["2. Load the Superpowers writing-plans Skill.",`3. Read the Design Doc path from "comet state get ${e} design_doc" and read ${t}/tasks.md.`,"4. Create the implementation plan under docs/superpowers/plans/.","5. Record the plan path:",` ${a}`]:[`2. Restore the plan file at ${n.recordedPath}, or load the Superpowers writing-plans Skill and create a replacement under docs/superpowers/plans/.`,"3. When creating a replacement, record its path:",` ${a}`];return["COMET_RECOVERY: required",`ERROR_CODE: ${r}`,`CHANGE: ${e}`,"WORKFLOW: full","PHASE: build",`STATE: ${s}`,...o,"","ALLOWED_RECOVERY_WRITES:","- docs/superpowers/plans/.md","- Comet state updates performed by the comet CLI",`- ${t} artifacts allowed by the build phase`,"","RECOVERY:",`1. Resume /comet-build for ${e} and return to Step 1.`,...c,`${i?"6":"4"}. Verify recovery:`,` comet state check ${e} build --recover`,"","SUCCESS: plan is reported as DONE and recovery no longer returns classic-build-plan-missing or classic-build-plan-broken.","RETRY: resume build configuration or retry the blocked Write/Edit only after SUCCESS.","PROHIBITED: do not execute tasks.md or write project source before SUCCESS; tasks.md is not a substitute for the implementation plan.","If writing-plans is unavailable, stop and report the missing Skill instead of bypassing this recovery."].join(` -`)}async function Cx(e,t){let n=await _(t,"verify_result"),i=await _(t,"verify_failures"),r=await _(t,"verify_mode"),s=await _(t,"verification_report"),o=await _(t,"branch_status");e.stdout.push(" Verification:",await he("verify_result",n),` - verify_failures: ${i||"0"}`,await he("verify_mode",r),await he("verification_report",s,s),o==="handled"?" - branch_status: LEGACY (handled before archive; archive still owns final closure)":" - branch_status: DEFERRED (handled after the archive commit)","",n==="pass"?"Recovery action: Verification complete. Continue to archive; branch handling happens after archive changes are committed.":n==="fail"?"Recovery action: Verification failed and rolled back to build. Resume from /comet-build.":"Recovery action: Verification not yet started or in progress. Run scale assessment then verify.")}async function kx(e,t){let n=await _(t,"archive_confirmation");e.stdout.push(" Archive:",await he("verify_result",await _(t,"verify_result")),await he("archive_confirmation",n),await he("archived",await _(t,"archived")),"",n==="confirmed"?"Recovery action: Archive is confirmed. Run /comet-archive to complete archiving.":"Recovery action: Ask for final archive confirmation in /comet-archive before running the archive command.")}async function Sx(e,t){it(t);let{file:n,directory:i,label:r}=await gt(t);await me(n)||S(`ERROR: .comet.yaml not found at ${r}/.comet.yaml`);let s=await _(t,"phase"),o=await _(t,"workflow");e.stdout.push(`=== Recovery Context: ${t} ===`,`Phase: ${s}`,`Workflow: ${o}`,"","State fields:"),s==="open"?await gx(e,i):s==="design"?await wx(e,t,i):s==="build"?await yx(e,t,i,o):s==="verify"?await Cx(e,t):s==="archive"?await kx(e,t):S(`ERROR: Unknown phase: ${s}`),e.stdout.push("","=== End Recovery Context ===")}async function Ex(e,t){it(t);let{file:n,directory:i,label:r}=await gt(t);await me(n)||S(`ERROR: .comet.yaml not found at ${r}/.comet.yaml`);let s=q.join(i,"tasks.md"),o=await me(s)?(await W(x(),s,{label:"Classic scale task file"})).split(/\r?\n/u).filter(g=>/^- \[/u.test(g)).length:0,a=q.join(i,"specs"),c=0;if(await me(a))for(let g of await J_.readdir(a))await me(q.join(a,g,"spec.md"))&&(c+=1);let l=await _(t,"plan"),f="";l&&l!=="null"&&await me(l)&&(f=(await W(x(),l,{label:"Classic scale plan"})).match(/^base-ref:\s*(.+)$/mu)?.[1].trim()??""),f||(f=await _(t,"base_ref"));let u=Mg(["diff","--name-only",...f&&f!=="null"?[`${f}...HEAD`]:["HEAD"]]),d=u?u.split(/\r?\n/u).filter(Boolean).length:0,p=o>3||c>1||d>8?"full":"light";await Dg(new ca,t,"verify_mode",p),e.stderr.push(`=== Scale Assessment: ${t} ===`,` Tasks: ${o} (threshold: 3)`,` Delta specs: ${c} capabilities (threshold: 1)`,` Changed files: ${d} (threshold: 8)`,` → Result: ${p}`,nt(`[SCALE] verify_mode=${p}`))}function Rx(e){let t,n,i;for(let r=0;r' to establish the first binding`);let r=To(Ot());r===null&&S("ERROR: cannot rebind while HEAD is detached; checkout a branch first");let s=await B(n);s.classic||S("ERROR: Classic state projection is missing"),await Ml(n,r);let o={...s.classic,boundBranch:r};await An(n,{change:t,event:"rebind",source:"comet-state",from:s.classic,to:o,effects:[{field:"boundBranch",from:i,to:r}]}),e.stderr.push(nt(`[REBIND] bound_branch: ${i} → ${r}`))}async function Ix(e){let t=await Mo(x());if(t.status==="selected"){e.stdout.push(t.selection.change);return}t.status==="missing"&&S(`ERROR: no current change selected + Repair-only escape hatch: COMET_FORCE_PHASE=1 comet-state.mjs set phase `),await sx(n,i);let{file:s,directory:o}=await wt(t),a=await fa(s),c=a.toJS()??{};if(a.set(n,Fg(n,i)),n==="isolation")if(jo(i)){let u=typeof c.isolation=="string"?c.isolation:null,d=c.bound_branch;if(!(typeof d=="string"&&d!=="")||u!==i){let g=Ot(),h=To(g),m=Ll({isolation:i,boundBranch:null,currentBranch:h,gitWorkTree:h===null?jl(g):!0});m.status==="needs-heal"?a.set("bound_branch",m.branch):m.status==="unbound-detached"?S(`ERROR: cannot bind isolation=${i} while HEAD is detached; checkout a branch first`):a.set("bound_branch",null)}}else a.set("bound_branch",null);let l=await mr(o),f=gr(a.toJS(),l);if(f.run){f.classic||S("ERROR: migrated Run is missing its Classic projection");let u=await ze(o,f),d=Et(f.classic,u),p=d!==f.run.currentStep,g={...f.run,currentStep:d,iteration:f.run.iteration+(p?1:0),status:d==="completed"?"completed":"running"};if(await je(o,{classic:f.classic,run:g,unknownKeys:f.unknownKeys}),p){let h=await Le(o,g.trajectoryRef);await We(o,g.trajectoryRef,{sequence:h.length+1,timestamp:new Date().toISOString(),type:"state_transitioned",runId:g.runId,data:{kind:"classic-config",field:n,fromStep:f.run.currentStep,toStep:d}})}}else await bu(s,a.toString());n==="phase"&&!r.internal&&e.stderr.push(Ag("WARNING: Setting 'phase' directly bypasses state machine constraints."),Ag(" Consider using: comet-state.mjs transition ")),e.stderr.push(it(`[SET] ${n}=${i}`))}async function ox(e,t,n){rt(t),ua(n,Fr);let i=await Jm(t,x()),{label:r,directory:s}=i,o=q.join(s,".comet.yaml");await me(o)&&S(`ERROR: .comet.yaml already exists at ${r}/.comet.yaml`);let a=n!=="full",c=a?"off":await rx(),l=new Br.Document({workflow:n,language:await Mg(),phase:"open",context_compression:await ix(),build_mode:a?"direct":null,build_pause:null,subagent_dispatch:null,tdd_mode:a?"direct":null,review_mode:c,isolation:null,verify_mode:a?"light":null,auto_transition:await qg()==="true",base_ref:Dg(["rev-parse","--verify","HEAD"]),design_doc:null,plan:null,verify_result:"pending",verify_failures:0,verification_report:null,branch_status:"pending",created_at:new Date().toISOString().slice(0,10),verified_at:null,archive_confirmation:null,archived:!1});await bu(o,l.toString()),e.stdout.push(it(`Initialized: ${r}/.comet.yaml (workflow=${n})`))}async function Tt(e,t){let n=await _(e,"phase");n!==t&&S(`ERROR: Cannot transition '${e}': expected phase ${t}, got ${n}`)}async function ax(e){let t=await _(e,"workflow"),n=await _(e,"build_mode"),i=await _(e,"isolation"),r=await _(e,"direct_override"),s=await _(e,"subagent_dispatch"),o=await _(e,"tdd_mode"),a=await _(e,"review_mode");["current","branch","worktree"].includes(i)||S(`ERROR: Cannot transition '${e}': isolation must be current, branch, or worktree, got '${i||"null"}'`),["subagent-driven-development","executing-plans","direct"].includes(n)||S(`ERROR: Cannot transition '${e}': build_mode must be selected before leaving build, got '${n||"null"}'`),n==="direct"&&!["hotfix","tweak"].includes(t)&&r!=="true"&&S(`ERROR: Cannot transition '${e}': build_mode=direct is only allowed for hotfix/tweak unless direct_override=true`),n==="subagent-driven-development"&&s!=="confirmed"&&S(`ERROR: Cannot transition '${e}': subagent_dispatch must be confirmed before using build_mode=subagent-driven-development`),t==="full"&&(!o||o==="null")&&S(`ERROR: Cannot transition '${e}': tdd_mode must be selected before leaving build (full workflow)`),t==="full"&&!["off","standard","thorough"].includes(a)&&S(`ERROR: Cannot transition '${e}': review_mode must be selected before leaving build (full workflow); review_mode must be off, standard, or thorough, got '${a||"null"}'`)}async function cx(e){let{directory:t}=await wt(e),n=await _(e,"workflow");for(let i of["proposal.md","tasks.md"])await Lt(q.join(t,i))||S(`ERROR: Cannot transition '${e}': ${i} must exist and be non-empty before leaving open`);n==="full"&&!await Lt(q.join(t,"design.md"))&&S(`ERROR: Cannot transition '${e}': design.md must exist and be non-empty before leaving open`)}async function lx(e){let t=await _(e,"design_doc");(!t||t==="null"||!await Lt(q.resolve(t)))&&S(`ERROR: Cannot transition '${e}': design_doc must point to an existing Design Doc before leaving design`)}async function ux(e,t){let n=q.join(e,".comet.yaml"),i=await fa(n);for(let r of t){let s=jg(r.field);i.set(s,Fg(s,Lg(r.to)))}await bu(n,i.toString())}async function fx(e,t,n){let{directory:i}=await wt(t),r=await B(i),s=r.classic,o=!1;if(!s){r.run&&S("ERROR: Classic state projection is missing");let c=await fa(q.join(i,".comet.yaml"));s=nx(c.toJS()),o=!0}let a=ui(s,n);r.run?await cn(i,a.classic,r.run,{event:n,source:"comet-state"}):o?await ux(i,a.effects):await je(i,{classic:a.classic,run:null,unknownKeys:r.unknownKeys}),await An(i,{change:t,event:n,source:"comet-state",from:s,to:a.classic,effects:a.effects});for(let c of a.effects)e.stderr.push(it(`[SET] ${jg(c.field)}=${Lg(c.to)}`));e.stderr.push(it(`[TRANSITION] ${n}`))}async function dx(e,t,n){if(rt(t),ua(n,G_),n==="open-complete")await Tt(t,"open"),await cx(t);else if(n==="design-complete")await Tt(t,"design"),await lx(t);else if(n==="build-complete")await Tt(t,"build"),await ax(t);else if(n==="verify-pass"){await Tt(t,"verify");let i=await _(t,"verification_report");(!i||!await me(q.resolve(i)))&&S(`ERROR: Cannot transition '${t}': verification_report must point to an existing report file`)}else if(n==="verify-fail")await Tt(t,"verify");else if(n==="archive-confirm")await Tt(t,"archive"),await _(t,"verify_result")!=="pass"&&S(`ERROR: Cannot transition '${t}': verify_result must be pass before archiving`),await _(t,"archived")==="true"&&S(`ERROR: Cannot transition '${t}': already archived`);else if(n==="preset-escalate"){await Tt(t,"build");let i=await _(t,"workflow");["hotfix","tweak"].includes(i)||S(`ERROR: Cannot transition '${t}': preset-escalate only applies to hotfix/tweak, got workflow='${i}'`)}else n==="archive-reopen"?(await Tt(t,"archive"),await _(t,"archived")==="true"&&S(`ERROR: Cannot transition '${t}': already archived`)):(await Tt(t,"archive"),await _(t,"verify_result")!=="pass"&&S(`ERROR: Cannot transition '${t}': verify_result must be pass before archiving`),await _(t,"archive_confirmation")!=="confirmed"&&S(`ERROR: Cannot transition '${t}': archive_confirmation must be confirmed before archiving`));await fx(e,t,n)}async function mx(e,t){rt(t);let{file:n,label:i}=await wt(t);await me(n)||S(`ERROR: .comet.yaml not found at ${i}/.comet.yaml`);let r=await _(t,"phase"),s=await _(t,"workflow"),o=await _(t,"auto_transition");if(await _(t,"archived")==="true"){e.stdout.push("NEXT: done");return}let a=r==="open"?"comet-open":r==="design"?"comet-design":r==="verify"?"comet-verify":r==="archive"?"comet-archive":r==="build"?s==="hotfix"?"comet-hotfix":s==="tweak"?"comet-tweak":"comet-build":null;a||S(`ERROR: Cannot resolve next step for '${t}': unknown phase '${r||"null"}'`),e.stdout.push(`NEXT: ${o==="false"?"manual":"auto"}`,`SKILL: ${a}`),o==="false"&&e.stdout.push(`HINT: phase is '${r}'; run /${a} manually to continue`)}async function px(e,t,n){Tg(t,"task file"),n||S("ERROR: Task text cannot be empty");let i=q.resolve(x(),t);await me(i)||S(`ERROR: Task file not found: ${t}`);let s=(await W(x(),i,{label:"Classic task-checkoff file"})).split(/\r?\n/u).filter(a=>[`- [ ] ${n}`,`- [x] ${n}`,`- [X] ${n}`].includes(a)),o=s.filter(a=>/^- \[[xX]\] /u.test(a));s.length!==1&&S(`ERROR: task text must appear exactly once in ${t} (found ${s.length}): ${n}`),o.length!==1&&S(`ERROR: task is not checked in ${t}: ${n}`),e.stdout.push("TASK_CHECKOFF: PASS",`FILE: ${t}`,`TASK: ${n}`)}async function hx(e,t,n){rt(t),ua(n,vu);let{file:i,directory:r,label:s}=await wt(t);e.stdout.push(`=== Entry Check: comet-${n} ===`),await me(i)||S(`ERROR: .comet.yaml not found at ${s}/.comet.yaml`);let o=!1,a=u=>e.stdout.push(` ${it("[PASS]")} ${u}`),c=u=>{e.stdout.push(` ${gu("[FAIL]")} ${u}`),o=!0},l=async(u,d)=>{let p=await _(t,u);(p===d?a:c)(`${u}=${p} (expected: ${d})`)};if(a(".comet.yaml exists"),await l("phase",n),n==="design"){await l("workflow","full");let u=await _(t,"design_doc");(!u||u==="null"?a:c)(u?`design_doc=${u} (expected: empty/null)`:"design_doc is empty/null");for(let d of["proposal.md","design.md","tasks.md"])(await Lt(q.join(r,d))?a:c)(`${d} ${await Lt(q.join(r,d))?"non-empty":"missing or empty"}`)}else if(n==="build"){let u=await _(t,"workflow"),d=await _(t,"design_doc");u==="full"?(d&&d!=="null"&&await me(q.resolve(d))?a:c)(`design_doc=${d} (expected: non-null and file exists)`):a(`workflow=${u} (design_doc not required)`);for(let p of["proposal.md","tasks.md"])(await Lt(q.join(r,p))?a:c)(`${p} ${await Lt(q.join(r,p))?"non-empty":"missing or empty"}`)}else if(n==="verify"){let u=await _(t,"verify_result");(["","null","pending"].includes(u)?a:c)(`verify_result=${u} (expected: pending or null)`)}else if(n==="archive"){await l("verify_result","pass");let u=await _(t,"archived");(u!=="true"?a:c)(`archived=${u} (expected: not true)`)}let f=await xt(r,{heal:!0,cwd:Ot()});if(f.bindingRequired)switch(f.status){case"drift":c(Lo(t,f.boundBranch,f.currentBranch));break;case"unbound-detached":c(Pt(t));break;case"healed":a(`bound_branch lazily set to ${f.branch}`);break;case"needs-heal":case"ok":case"not-applicable":a("bound_branch matches current branch");break;default:{let u=f;throw new Error(`unhandled branch binding status: ${JSON.stringify(u)}`)}}if(e.stdout.push(""),o)throw e.stderr.push(gu("BLOCKED — fix failing checks before proceeding")),new Wr("",1);e.stderr.push(it("ALL CHECKS PASSED — ready to proceed"))}async function he(e,t,n){return!t||t==="null"?` - ${e}: PENDING`:n&&!await me(q.resolve(n))?` - ${e}: BROKEN (path ${t} does not exist)`:` - ${e}: DONE (${t})`}async function gx(e,t){e.stdout.push(" Artifacts:");let n=0;for(let i of["proposal.md","design.md","tasks.md"]){let r=await Lt(q.join(t,i));r&&(n+=1),e.stdout.push(` - ${i}: ${r?"DONE":"PENDING"}`)}e.stdout.push("",n===3?"Recovery action: All artifacts complete. Run /comet-open user confirmation, then guard to transition.":n===0?"Recovery action: No artifacts created yet. Start from /comet-open Step 1 (explore and clarify).":"Recovery action: Some artifacts incomplete. Resume /comet-open from the first missing artifact.")}async function wx(e,t,n){e.stdout.push(" Artifacts:");for(let o of["proposal.md","design.md","tasks.md"])e.stdout.push(` - ${o}: ${await Lt(q.join(n,o))?"DONE":"MISSING (unexpected in design phase)"}`);let i=await _(t,"handoff_context"),r=await _(t,"handoff_hash"),s=await _(t,"design_doc");e.stdout.push(""," Design progress:",await he("handoff_context",i,i),await he("handoff_hash",r),await he("design_doc",s,s),""),s&&s!=="null"&&await me(q.resolve(s))?e.stdout.push("Recovery action: Design Doc already created and linked. Run guard to transition to build."):i&&i!=="null"&&await me(q.resolve(i))?e.stdout.push("Recovery action: Handoff generated but Design Doc not yet created. Resume from brainstorming confirmation (Step 1c)."):e.stdout.push("Recovery action: No handoff generated yet. Start from Step 1a (generate handoff package).")}async function yx(e,t,n,i){let r=await _(t,"isolation"),s=await _(t,"build_mode"),o=await _(t,"build_pause"),a=await _(t,"subagent_dispatch"),c=await _(t,"tdd_mode"),l=await _(t,"review_mode"),f=await _(t,"plan"),u=await Ko(x(),f),d=[" Build decisions:",await he("isolation",r),await he("build_mode",s),await he("build_pause",o),await he("tdd_mode",c),await he("review_mode",l)];(s==="subagent-driven-development"||a&&a!=="null")&&d.push(await he("subagent_dispatch",a)),e.stdout.push(...d,""," Plan:",await he("plan",f,f),"");let p=q.join(n,"tasks.md");if(!await me(p)){e.stdout.push(" Tasks: tasks.md MISSING","","Recovery action: tasks.md missing. Verify change directory integrity.");return}let g=(await W(x(),p,{label:"Classic change tasks"})).split(/\r?\n/u),h=g.filter(R=>/^\s*- \[[ xX]\] /u.test(R)).length,m=g.filter(R=>/^\s*- \[[xX]\] /u.test(R)).length,y=h-m,w=0,C=0;if(u.status==="ready"){let R=(await W(x(),f,{label:"Classic build plan"})).split(/\r?\n/u);w=R.filter(O=>/^\s*- \[[ xX]\] /u.test(O)).length,C=R.filter(O=>/^\s*- \[[xX]\] /u.test(O)).length}let k=w-C;e.stdout.push(` Tasks: ${m}/${h} done, ${y} pending`),w>0&&e.stdout.push(` Plan tasks: ${C}/${w} done, ${k} pending`),e.stdout.push("");let E=vx(t,q.relative(x(),n).replaceAll("\\","/"),i,r,s,o,a,c,l,u,y,k);e.stdout.push(E)}function dn(e){return!e||e==="null"}function vx(e,t,n,i,r,s,o,a,c,l,f,u){let d=l.status==="ready",p=n==="full"&&(dn(a)||dn(c));return s==="plan-ready"&&d&&(dn(i)||dn(r)||p)?n==="full"?"Recovery action: Plan-ready pause detected. Ask the user whether to continue, then choose isolation, build mode, TDD mode, and review mode without regenerating the plan.":"Recovery action: Plan-ready pause detected. Ask the user whether to continue, then choose isolation and build mode without regenerating the plan.":n==="full"&&!d?bx(e,t,l):s==="plan-ready"?r==="subagent-driven-development"&&(f>0||u>0)?o==="confirmed"?"Recovery action: Plan-ready pause is stale because build decisions are already selected. Clear build_pause to null, then inspect the first unchecked task (OpenSpec or plan additions) against recent git history/diff. If implemented, check it off; otherwise dispatch a subagent. Do not execute the pending task directly in the main window.":"Recovery action: Plan-ready pause is stale and selected subagent execution is not recorded. Run comet state set subagent_dispatch confirmed, then continue from the first unchecked task through subagent execution.":f>0||u>0?"Recovery action: Plan-ready pause is stale because build decisions are already selected. Clear build_pause to null, then continue from the first unchecked task.":"Recovery action: Plan-ready pause is stale and all tasks are done. Clear build_pause to null, then run guard to transition to verify.":dn(i)?"Recovery action: Isolation not selected. Use the current platform's user confirmation mechanism to ask user for branch/worktree choice.":dn(r)?"Recovery action: Build mode not selected. Use the current platform's user confirmation mechanism to ask user for execution method.":n==="full"&&dn(a)?"Recovery action: TDD mode not selected. Use the current platform's user confirmation mechanism to ask user for tdd or direct.":n==="full"&&dn(c)?"Recovery action: Review mode not selected. Use the current platform's user confirmation mechanism to ask user for off, standard, or thorough.":f>0?r==="subagent-driven-development"?o==="confirmed"?"Recovery action: Read tasks.md and the Superpowers plan (which may include additions beyond OpenSpec), then inspect the first unchecked task against recent git history/diff. If implemented, check it off; otherwise dispatch a subagent. Do not execute the pending task directly in the main window.":"Recovery action: Selected subagent execution is not recorded. Run comet state set subagent_dispatch confirmed, then continue from the first unchecked task through subagent execution.":"Recovery action: Read tasks.md and continue from first unchecked task.":u>0?r==="subagent-driven-development"?o==="confirmed"?"Recovery action: Read the Superpowers plan, then inspect the first unchecked Superpowers plan task against recent git history/diff. If implemented, check it off; otherwise dispatch a subagent. Do not execute the pending task directly in the main window.":"Recovery action: Selected subagent execution is not recorded. Run comet state set subagent_dispatch confirmed, then continue from the first unchecked task through subagent execution.":"Recovery action: Read the Superpowers plan and continue from the first unchecked plan task.":"Recovery action: All tasks done. Run guard to transition to verify."}function bx(e,t,n){let i=n.status==="missing",r=i?"classic-build-plan-missing":"classic-build-plan-broken",s=i?"plan is not recorded":"the recorded plan path does not resolve to a file",o=i?[]:[`RECORDED_PLAN: ${n.recordedPath}`],a=i?`comet state set ${e} plan `:`comet state set ${e} plan `,c=i?["2. Load the Superpowers writing-plans Skill.",`3. Read the Design Doc path from "comet state get ${e} design_doc" and read ${t}/tasks.md.`,"4. Create the implementation plan under docs/superpowers/plans/.","5. Record the plan path:",` ${a}`]:[`2. Restore the plan file at ${n.recordedPath}, or load the Superpowers writing-plans Skill and create a replacement under docs/superpowers/plans/.`,"3. When creating a replacement, record its path:",` ${a}`];return["COMET_RECOVERY: required",`ERROR_CODE: ${r}`,`CHANGE: ${e}`,"WORKFLOW: full","PHASE: build",`STATE: ${s}`,...o,"","ALLOWED_RECOVERY_WRITES:","- docs/superpowers/plans/.md","- Comet state updates performed by the comet CLI",`- ${t} artifacts allowed by the build phase`,"","RECOVERY:",`1. Resume /comet-build for ${e} and return to Step 1.`,...c,`${i?"6":"4"}. Verify recovery:`,` comet state check ${e} build --recover`,"","SUCCESS: plan is reported as DONE and recovery no longer returns classic-build-plan-missing or classic-build-plan-broken.","RETRY: resume build configuration or retry the blocked Write/Edit only after SUCCESS.","PROHIBITED: do not execute tasks.md or write project source before SUCCESS; tasks.md is not a substitute for the implementation plan.","If writing-plans is unavailable, stop and report the missing Skill instead of bypassing this recovery."].join(` +`)}async function Cx(e,t){let n=await _(t,"verify_result"),i=await _(t,"verify_failures"),r=await _(t,"verify_mode"),s=await _(t,"verification_report"),o=await _(t,"branch_status");e.stdout.push(" Verification:",await he("verify_result",n),` - verify_failures: ${i||"0"}`,await he("verify_mode",r),await he("verification_report",s,s),o==="handled"?" - branch_status: LEGACY (handled before archive; archive still owns final closure)":" - branch_status: DEFERRED (handled after the archive commit)","",n==="pass"?"Recovery action: Verification complete. Continue to archive; branch handling happens after archive changes are committed.":n==="fail"?"Recovery action: Verification failed and rolled back to build. Resume from /comet-build.":"Recovery action: Verification not yet started or in progress. Run scale assessment then verify.")}async function kx(e,t){let n=await _(t,"archive_confirmation");e.stdout.push(" Archive:",await he("verify_result",await _(t,"verify_result")),await he("archive_confirmation",n),await he("archived",await _(t,"archived")),"",n==="confirmed"?"Recovery action: Archive is confirmed. Run /comet-archive to complete archiving.":"Recovery action: Ask for final archive confirmation in /comet-archive before running the archive command.")}async function Sx(e,t){rt(t);let{file:n,directory:i,label:r}=await wt(t);await me(n)||S(`ERROR: .comet.yaml not found at ${r}/.comet.yaml`);let s=await _(t,"phase"),o=await _(t,"workflow");e.stdout.push(`=== Recovery Context: ${t} ===`,`Phase: ${s}`,`Workflow: ${o}`,"","State fields:"),s==="open"?await gx(e,i):s==="design"?await wx(e,t,i):s==="build"?await yx(e,t,i,o):s==="verify"?await Cx(e,t):s==="archive"?await kx(e,t):S(`ERROR: Unknown phase: ${s}`),e.stdout.push("","=== End Recovery Context ===")}async function Ex(e,t){rt(t);let{file:n,directory:i,label:r}=await wt(t);await me(n)||S(`ERROR: .comet.yaml not found at ${r}/.comet.yaml`);let s=q.join(i,"tasks.md"),o=await me(s)?(await W(x(),s,{label:"Classic scale task file"})).split(/\r?\n/u).filter(g=>/^- \[/u.test(g)).length:0,a=q.join(i,"specs"),c=0;if(await me(a))for(let g of await J_.readdir(a))await me(q.join(a,g,"spec.md"))&&(c+=1);let l=await _(t,"plan"),f="";l&&l!=="null"&&await me(l)&&(f=(await W(x(),l,{label:"Classic scale plan"})).match(/^base-ref:\s*(.+)$/mu)?.[1].trim()??""),f||(f=await _(t,"base_ref"));let u=Dg(["diff","--name-only",...f&&f!=="null"?[`${f}...HEAD`]:["HEAD"]]),d=u?u.split(/\r?\n/u).filter(Boolean).length:0,p=o>3||c>1||d>8?"full":"light";await Wg(new ca,t,"verify_mode",p),e.stderr.push(`=== Scale Assessment: ${t} ===`,` Tasks: ${o} (threshold: 3)`,` Delta specs: ${c} capabilities (threshold: 1)`,` Changed files: ${d} (threshold: 8)`,` → Result: ${p}`,it(`[SCALE] verify_mode=${p}`))}function Rx(e){let t,n,i;for(let r=0;r' to establish the first binding`);let r=To(Ot());r===null&&S("ERROR: cannot rebind while HEAD is detached; checkout a branch first");let s=await B(n);s.classic||S("ERROR: Classic state projection is missing"),await Ml(n,r);let o={...s.classic,boundBranch:r};await An(n,{change:t,event:"rebind",source:"comet-state",from:s.classic,to:o,effects:[{field:"boundBranch",from:i,to:r}]}),e.stderr.push(it(`[REBIND] bound_branch: ${i} → ${r}`))}async function Ix(e){let t=await Mo(x());if(t.status==="selected"){e.stdout.push(t.selection.change);return}t.status==="missing"&&S(`ERROR: no current change selected Use: comet-state.mjs select `),S(`ERROR: current change selection is stale: ${t.reason} -Use: comet-state.mjs select `)}async function Ax(e){await Zp(x()),e.stderr.push(nt("[CLEARED] current change selection"))}var Fg=async(e,t)=>dt(t,async()=>{let n=new ca;try{let[i,...r]=e;return await Px(i),i==="init"?(jt(r,2,"Usage: comet-state.mjs init "),await ox(n,r[0],r[1])):i==="get"?(jt(r,2,"Usage: comet-state.mjs get "),it(r[0]),n.stdout.push(await _(r[0],r[1]))):i==="set"?(jt(r,3,"Usage: comet-state.mjs set "),it(r[0]),await Dg(n,r[0],r[1],r[2])):i==="transition"?(jt(r,2,"Usage: comet-state.mjs transition "),await dx(n,r[0],r[1])):i==="check"?(jt(r,2,"Usage: comet-state.mjs check [--recover]"),r[2]==="--recover"?await Sx(n,r[0]):await hx(n,r[0],r[1])):i==="scale"?(jt(r,1,"Usage: comet-state.mjs scale "),await Ex(n,r[0])):i==="record-check"?(jt(r,2,"Usage: comet state record-check --command --exit-code [--cwd ]"),await _x(n,r[0],r[1],r.slice(2))):i==="task-checkoff"?(jt(r,2,"Usage: comet-state.mjs task-checkoff "),await px(n,r[0],r[1])):i==="rebind"?(aa(r,1,"Usage: comet-state.mjs rebind "),await $x(n,r[0])):i==="select"?(aa(r,1,"Usage: comet-state.mjs select "),await Ox(n,r[0])):i==="current"?(aa(r,0,"Usage: comet-state.mjs current"),await Ix(n)):i==="clear-selection"?(aa(r,0,"Usage: comet-state.mjs clear-selection"),await Ax(n)):i==="next"?(jt(r,1,"Usage: comet-state.mjs next "),await mx(n,r[0])):S(`Unknown subcommand: ${i??""}`),n.result()}catch(i){if(!(i instanceof Wr))throw i;if(i.message)for(let r of i.message.split(` -`))n.stderr.push(gu(r));return n.result(i.exitCode)}});var Bg=["state","validate","guard","handoff","archive","hook-guard","intent","resume-probe","openspec","root"],Tx={state:Fg,validate:Wo,guard:vh,handoff:Oh,archive:ih,"hook-guard":Bh,intent:Gh,"resume-probe":tg,openspec:Fm,root:Og};function jx(e){return Bg.includes(e)}function Lx(e){return e?{exitCode:64,stderr:`Unknown Classic command: ${e}`}:{exitCode:64,stderr:`Usage: comet-classic <${Bg.join("|")}> [args]`}}async function Mx(e,t,n,i){if(!e||!jx(e))return Lx(e);let r=i[e];if(!r)return{exitCode:70,stderr:`Classic command is not implemented: ${e}`};try{return await r(t,n)}catch(s){return{exitCode:70,stderr:s instanceof Error?s.message:String(s)}}}function qx(e,t){return{exitCode:t.exitCode,stdout:JSON.stringify({command:e??null,exitCode:t.exitCode,...t.stdout===void 0?{}:{stdout:t.stdout},...t.stderr===void 0?{}:{stderr:t.stderr}})+` +Use: comet-state.mjs select `)}async function Ax(e){await th(x()),e.stderr.push(it("[CLEARED] current change selection"))}var Bg=async(e,t)=>mt(t,async()=>{let n=new ca;try{let[i,...r]=e;return await Px(i),i==="init"?(jt(r,2,"Usage: comet-state.mjs init "),await ox(n,r[0],r[1])):i==="get"?(jt(r,2,"Usage: comet-state.mjs get "),rt(r[0]),n.stdout.push(await _(r[0],r[1]))):i==="set"?(jt(r,3,"Usage: comet-state.mjs set "),rt(r[0]),await Wg(n,r[0],r[1],r[2])):i==="transition"?(jt(r,2,"Usage: comet-state.mjs transition "),await dx(n,r[0],r[1])):i==="check"?(jt(r,2,"Usage: comet-state.mjs check [--recover]"),r[2]==="--recover"?await Sx(n,r[0]):await hx(n,r[0],r[1])):i==="scale"?(jt(r,1,"Usage: comet-state.mjs scale "),await Ex(n,r[0])):i==="record-check"?(jt(r,2,"Usage: comet state record-check --command --exit-code [--cwd ]"),await _x(n,r[0],r[1],r.slice(2))):i==="task-checkoff"?(jt(r,2,"Usage: comet-state.mjs task-checkoff "),await px(n,r[0],r[1])):i==="rebind"?(aa(r,1,"Usage: comet-state.mjs rebind "),await $x(n,r[0])):i==="select"?(aa(r,1,"Usage: comet-state.mjs select "),await Ox(n,r[0])):i==="current"?(aa(r,0,"Usage: comet-state.mjs current"),await Ix(n)):i==="clear-selection"?(aa(r,0,"Usage: comet-state.mjs clear-selection"),await Ax(n)):i==="next"?(jt(r,1,"Usage: comet-state.mjs next "),await mx(n,r[0])):S(`Unknown subcommand: ${i??""}`),n.result()}catch(i){if(!(i instanceof Wr))throw i;if(i.message)for(let r of i.message.split(` +`))n.stderr.push(gu(r));return n.result(i.exitCode)}});var Kg=["state","validate","guard","handoff","archive","hook-guard","intent","resume-probe","openspec","root"],Tx={state:Bg,validate:Wo,guard:Ch,handoff:Ih,archive:sh,"hook-guard":Kh,intent:Xh,"resume-probe":ig,openspec:Bm,root:Ig};function jx(e){return Kg.includes(e)}function Lx(e){return e?{exitCode:64,stderr:`Unknown Classic command: ${e}`}:{exitCode:64,stderr:`Usage: comet-classic <${Kg.join("|")}> [args]`}}async function Mx(e,t,n,i){if(!e||!jx(e))return Lx(e);let r=i[e];if(!r)return{exitCode:70,stderr:`Classic command is not implemented: ${e}`};try{return await r(t,n)}catch(s){return{exitCode:70,stderr:s instanceof Error?s.message:String(s)}}}function qx(e,t){return{exitCode:t.exitCode,stdout:JSON.stringify({command:e??null,exitCode:t.exitCode,...t.stdout===void 0?{}:{stdout:t.stdout},...t.stderr===void 0?{}:{stderr:t.stderr}})+` `}}async function Dx(e,t=Tx){let n=e[0]!=="openspec"&&e.includes("--json"),i=n?e.filter(o=>o!=="--json"):[...e],r=i.shift(),s=await Mx(r,i,{json:n,invocationCwd:process.cwd()},t);return n?qx(r,s):s}async function Fx(e=process.argv.slice(2)){let t=await Dx(e);return t.stdout&&process.stdout.write(t.stdout),t.stderr&&process.stderr.write(t.stderr+(t.stderr.endsWith(` `)?"":` -`)),t.exitCode}var Wg=process.argv[1];Wg&&import.meta.url===Nx(Wg).href&&Fx().then(e=>{process.exitCode=e});export{Bg as CLASSIC_COMMANDS,Fx as main,Dx as runClassicCli}; +`)),t.exitCode}var Hg=process.argv[1];Hg&&import.meta.url===Nx(Hg).href&&Fx().then(e=>{process.exitCode=e});export{Kg as CLASSIC_COMMANDS,Fx as main,Dx as runClassicCli}; diff --git a/assets/skills/comet/scripts/comet-state.mjs b/assets/skills/comet/scripts/comet-state.mjs index ac900e8a1..4ff55e2cd 100644 --- a/assets/skills/comet/scripts/comet-state.mjs +++ b/assets/skills/comet/scripts/comet-state.mjs @@ -1,77 +1,77 @@ #!/usr/bin/env node import { createRequire as __cometCreateRequire } from 'module'; const require = __cometCreateRequire(import.meta.url); -var Nf=Object.create;var Rr=Object.defineProperty;var Tf=Object.getOwnPropertyDescriptor;var jf=Object.getOwnPropertyNames;var If=Object.getPrototypeOf,$f=Object.prototype.hasOwnProperty;var Fn=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var U=(t,e,n)=>()=>{if(n)throw n[0];try{return t&&(e=t(t=0)),e}catch(i){throw n=[i],i}};var w=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(n){throw e=0,n}},qf=(t,e)=>{for(var n in e)Rr(t,n,{get:e[n],enumerable:!0})},Lf=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of jf(e))!$f.call(t,r)&&r!==n&&Rr(t,r,{get:()=>e[r],enumerable:!(i=Tf(e,r))||i.enumerable});return t};var ct=(t,e,n)=>(n=t!=null?Nf(If(t)):{},Lf(e||!t||!t.__esModule?Rr(n,"default",{value:t,enumerable:!0}):n,t));var P=w(F=>{"use strict";var _r=Symbol.for("yaml.alias"),na=Symbol.for("yaml.document"),Wn=Symbol.for("yaml.map"),ia=Symbol.for("yaml.pair"),xr=Symbol.for("yaml.scalar"),Bn=Symbol.for("yaml.seq"),we=Symbol.for("yaml.node.type"),Df=t=>!!t&&typeof t=="object"&&t[we]===_r,Mf=t=>!!t&&typeof t=="object"&&t[we]===na,Ff=t=>!!t&&typeof t=="object"&&t[we]===Wn,Wf=t=>!!t&&typeof t=="object"&&t[we]===ia,ra=t=>!!t&&typeof t=="object"&&t[we]===xr,Bf=t=>!!t&&typeof t=="object"&&t[we]===Bn;function sa(t){if(t&&typeof t=="object")switch(t[we]){case Wn:case Bn:return!0}return!1}function Kf(t){if(t&&typeof t=="object")switch(t[we]){case _r:case Wn:case xr:case Bn:return!0}return!1}var Uf=t=>(ra(t)||sa(t))&&!!t.anchor;F.ALIAS=_r;F.DOC=na;F.MAP=Wn;F.NODE_TYPE=we;F.PAIR=ia;F.SCALAR=xr;F.SEQ=Bn;F.hasAnchor=Uf;F.isAlias=Df;F.isCollection=sa;F.isDocument=Mf;F.isMap=Ff;F.isNode=Kf;F.isPair=Wf;F.isScalar=ra;F.isSeq=Bf});var Tt=w(Pr=>{"use strict";var M=P(),G=Symbol("break visit"),oa=Symbol("skip children"),de=Symbol("remove node");function Kn(t,e){let n=aa(e);M.isDocument(t)?lt(null,t.contents,n,Object.freeze([t]))===de&&(t.contents=null):lt(null,t,n,Object.freeze([]))}Kn.BREAK=G;Kn.SKIP=oa;Kn.REMOVE=de;function lt(t,e,n,i){let r=ca(t,e,n,i);if(M.isNode(r)||M.isPair(r))return la(t,i,r),lt(t,r,n,i);if(typeof r!="symbol"){if(M.isCollection(e)){i=Object.freeze(i.concat(e));for(let s=0;s{"use strict";var ua=P(),Yf=Tt(),Vf={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Jf=t=>t.replace(/[!,[\]{}]/g,e=>Vf[e]),jt=class t{constructor(e,n){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},t.defaultYaml,e),this.tags=Object.assign({},t.defaultTags,n)}clone(){let e=new t(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){let e=new t(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:t.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},t.defaultTags);break}return e}add(e,n){this.atNextDocument&&(this.yaml={explicit:t.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},t.defaultTags),this.atNextDocument=!1);let i=e.trim().split(/[ \t]+/),r=i.shift();switch(r){case"%TAG":{if(i.length!==2&&(n(0,"%TAG directive should contain exactly two parts"),i.length<2))return!1;let[s,o]=i;return this.tags[s]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,i.length!==1)return n(0,"%YAML directive should contain exactly one part"),!1;let[s]=i;if(s==="1.1"||s==="1.2")return this.yaml.version=s,!0;{let o=/^\d+\.\d+$/.test(s);return n(6,`Unsupported YAML version ${s}`,o),!1}}default:return n(0,`Unknown directive ${r}`,!0),!1}}tagName(e,n){if(e==="!")return"!";if(e[0]!=="!")return n(`Not a valid tag: ${e}`),null;if(e[1]==="<"){let o=e.slice(2,-1);return o==="!"||o==="!!"?(n(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&n("Verbatim tags must end with a >"),o)}let[,i,r]=e.match(/^(.*!)([^!]*)$/s);r||n(`The ${e} tag has no suffix`);let s=this.tags[i];if(s)try{return s+decodeURIComponent(r)}catch(o){return n(String(o)),null}return i==="!"?e:(n(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[n,i]of Object.entries(this.tags))if(e.startsWith(i))return n+Jf(e.substring(i.length));return e[0]==="!"?e:`!<${e}>`}toString(e){let n=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],i=Object.entries(this.tags),r;if(e&&i.length>0&&ua.isNode(e.contents)){let s={};Yf.visit(e.contents,(o,a)=>{ua.isNode(a)&&a.tag&&(s[a.tag]=!0)}),r=Object.keys(s)}else r=[];for(let[s,o]of i)s==="!!"&&o==="tag:yaml.org,2002:"||(!e||r.some(a=>a.startsWith(o)))&&n.push(`%TAG ${s} ${o}`);return n.join(` -`)}};jt.defaultYaml={explicit:!1,version:"1.2"};jt.defaultTags={"!!":"tag:yaml.org,2002:"};fa.Directives=jt});var Yn=w(It=>{"use strict";var da=P(),Hf=Tt();function Gf(t){if(/[\x00-\x19\s,[\]{}]/.test(t)){let n=`Anchor must not contain whitespace or control characters: ${JSON.stringify(t)}`;throw new Error(n)}return!0}function pa(t){let e=new Set;return Hf.visit(t,{Value(n,i){i.anchor&&e.add(i.anchor)}}),e}function ma(t,e){for(let n=1;;++n){let i=`${t}${n}`;if(!e.has(i))return i}}function zf(t,e){let n=[],i=new Map,r=null;return{onAnchor:s=>{n.push(s),r??(r=pa(t));let o=ma(e,r);return r.add(o),o},setAnchors:()=>{for(let s of n){let o=i.get(s);if(typeof o=="object"&&o.anchor&&(da.isScalar(o.node)||da.isCollection(o.node)))o.node.anchor=o.anchor;else{let a=new Error("Failed to resolve repeated object (this should not happen)");throw a.source=s,a}}},sourceObjects:i}}It.anchorIsValid=Gf;It.anchorNames=pa;It.createNodeAnchors=zf;It.findNewAnchor=ma});var Ar=w(ha=>{"use strict";function $t(t,e,n,i){if(i&&typeof i=="object")if(Array.isArray(i))for(let r=0,s=i.length;r{"use strict";var Xf=P();function ga(t,e,n){if(Array.isArray(t))return t.map((i,r)=>ga(i,String(r),n));if(t&&typeof t.toJSON=="function"){if(!n||!Xf.hasAnchor(t))return t.toJSON(e,n);let i={aliasCount:0,count:1,res:void 0};n.anchors.set(t,i),n.onCreate=s=>{i.res=s,delete n.onCreate};let r=t.toJSON(e,n);return n.onCreate&&n.onCreate(r),r}return typeof t=="bigint"&&!n?.keep?Number(t):t}wa.toJS=ga});var Vn=w(va=>{"use strict";var Qf=Ar(),ya=P(),Zf=xe(),Nr=class{constructor(e){Object.defineProperty(this,ya.NODE_TYPE,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:n,maxAliasCount:i,onAnchor:r,reviver:s}={}){if(!ya.isDocument(e))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:e,keep:!0,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},a=Zf.toJS(this,"",o);if(typeof r=="function")for(let{count:c,res:l}of o.anchors.values())r(l,c);return typeof s=="function"?Qf.applyReviver(s,{"":a},"",a):a}};va.NodeBase=Nr});var qt=w(ba=>{"use strict";var ed=Yn(),td=Tt(),ft=P(),nd=Vn(),id=xe(),Tr=class extends nd.NodeBase{constructor(e){super(ft.ALIAS),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,n){if(n?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let i;n?.aliasResolveCache?i=n.aliasResolveCache:(i=[],td.visit(e,{Node:(s,o)=>{(ft.isAlias(o)||ft.hasAnchor(o))&&i.push(o)}}),n&&(n.aliasResolveCache=i));let r;for(let s of i){if(s===this)break;s.anchor===this.source&&(r=s)}return r}toJSON(e,n){if(!n)return{source:this.source};let{anchors:i,doc:r,maxAliasCount:s}=n,o=this.resolve(r,n);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let a=i.get(o);if(a||(id.toJS(o,null,n),a=i.get(o)),a?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(s>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=Jn(r,o,i)),a.count*a.aliasCount>s)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return a.res}toString(e,n,i){let r=`*${this.source}`;if(e){if(ed.anchorIsValid(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let s=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(s)}if(e.implicitKey)return`${r} `}return r}};function Jn(t,e,n){if(ft.isAlias(e)){let i=e.resolve(t),r=n&&i&&n.get(i);return r?r.count*r.aliasCount:0}else if(ft.isCollection(e)){let i=0;for(let r of e.items){let s=Jn(t,r,n);s>i&&(i=s)}return i}else if(ft.isPair(e)){let i=Jn(t,e.key,n),r=Jn(t,e.value,n);return Math.max(i,r)}return 1}ba.Alias=Tr});var $=w(jr=>{"use strict";var rd=P(),sd=Vn(),od=xe(),ad=t=>!t||typeof t!="function"&&typeof t!="object",Pe=class extends sd.NodeBase{constructor(e){super(rd.SCALAR),this.value=e}toJSON(e,n){return n?.keep?this.value:od.toJS(this.value,e,n)}toString(){return String(this.value)}};Pe.BLOCK_FOLDED="BLOCK_FOLDED";Pe.BLOCK_LITERAL="BLOCK_LITERAL";Pe.PLAIN="PLAIN";Pe.QUOTE_DOUBLE="QUOTE_DOUBLE";Pe.QUOTE_SINGLE="QUOTE_SINGLE";jr.Scalar=Pe;jr.isScalarValue=ad});var Lt=w(Sa=>{"use strict";var cd=qt(),He=P(),ka=$(),ld="tag:yaml.org,2002:";function ud(t,e,n){if(e){let i=n.filter(s=>s.tag===e),r=i.find(s=>!s.format)??i[0];if(!r)throw new Error(`Tag ${e} not found`);return r}return n.find(i=>i.identify?.(t)&&!i.format)}function fd(t,e,n){if(He.isDocument(t)&&(t=t.contents),He.isNode(t))return t;if(He.isPair(t)){let u=n.schema[He.MAP].createNode?.(n.schema,null,n);return u.items.push(t),u}(t instanceof String||t instanceof Number||t instanceof Boolean||typeof BigInt<"u"&&t instanceof BigInt)&&(t=t.valueOf());let{aliasDuplicateObjects:i,onAnchor:r,onTagObj:s,schema:o,sourceObjects:a}=n,c;if(i&&t&&typeof t=="object"){if(c=a.get(t),c)return c.anchor??(c.anchor=r(t)),new cd.Alias(c.anchor);c={anchor:null,node:null},a.set(t,c)}e?.startsWith("!!")&&(e=ld+e.slice(2));let l=ud(t,e,o.tags);if(!l){if(t&&typeof t.toJSON=="function"&&(t=t.toJSON()),!t||typeof t!="object"){let u=new ka.Scalar(t);return c&&(c.node=u),u}l=t instanceof Map?o[He.MAP]:Symbol.iterator in Object(t)?o[He.SEQ]:o[He.MAP]}s&&(s(l),delete n.onTagObj);let f=l?.createNode?l.createNode(n.schema,t,n):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(n.schema,t,n):new ka.Scalar(t);return e?f.tag=e:l.default||(f.tag=l.tag),c&&(c.node=f),f}Sa.createNode=fd});var Gn=w(Hn=>{"use strict";var dd=Lt(),pe=P(),pd=Vn();function Ir(t,e,n){let i=n;for(let r=e.length-1;r>=0;--r){let s=e[r];if(typeof s=="number"&&Number.isInteger(s)&&s>=0){let o=[];o[s]=i,i=o}else i=new Map([[s,i]])}return dd.createNode(i,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:t,sourceObjects:new Map})}var Ca=t=>t==null||typeof t=="object"&&!!t[Symbol.iterator]().next().done,$r=class extends pd.NodeBase{constructor(e,n){super(e),Object.defineProperty(this,"schema",{value:n,configurable:!0,enumerable:!1,writable:!0})}clone(e){let n=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(n.schema=e),n.items=n.items.map(i=>pe.isNode(i)||pe.isPair(i)?i.clone(e):i),this.range&&(n.range=this.range.slice()),n}addIn(e,n){if(Ca(e))this.add(n);else{let[i,...r]=e,s=this.get(i,!0);if(pe.isCollection(s))s.addIn(r,n);else if(s===void 0&&this.schema)this.set(i,Ir(this.schema,r,n));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${r}`)}}deleteIn(e){let[n,...i]=e;if(i.length===0)return this.delete(n);let r=this.get(n,!0);if(pe.isCollection(r))return r.deleteIn(i);throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}getIn(e,n){let[i,...r]=e,s=this.get(i,!0);return r.length===0?!n&&pe.isScalar(s)?s.value:s:pe.isCollection(s)?s.getIn(r,n):void 0}hasAllNullValues(e){return this.items.every(n=>{if(!pe.isPair(n))return!1;let i=n.value;return i==null||e&&pe.isScalar(i)&&i.value==null&&!i.commentBefore&&!i.comment&&!i.tag})}hasIn(e){let[n,...i]=e;if(i.length===0)return this.has(n);let r=this.get(n,!0);return pe.isCollection(r)?r.hasIn(i):!1}setIn(e,n){let[i,...r]=e;if(r.length===0)this.set(i,n);else{let s=this.get(i,!0);if(pe.isCollection(s))s.setIn(r,n);else if(s===void 0&&this.schema)this.set(i,Ir(this.schema,r,n));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${r}`)}}};Hn.Collection=$r;Hn.collectionFromPath=Ir;Hn.isEmptyPath=Ca});var Dt=w(zn=>{"use strict";var md=t=>t.replace(/^(?!$)(?: $)?/gm,"#");function qr(t,e){return/^\n+$/.test(t)?t.substring(1):e?t.replace(/^(?! *$)/gm,e):t}var hd=(t,e,n)=>t.endsWith(` -`)?qr(n,e):n.includes(` +var Tf=Object.create;var _r=Object.defineProperty;var If=Object.getOwnPropertyDescriptor;var jf=Object.getOwnPropertyNames;var $f=Object.getPrototypeOf,qf=Object.prototype.hasOwnProperty;var Fn=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var U=(t,e,n)=>()=>{if(n)throw n[0];try{return t&&(e=t(t=0)),e}catch(i){throw n=[i],i}};var w=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(n){throw e=0,n}},Lf=(t,e)=>{for(var n in e)_r(t,n,{get:e[n],enumerable:!0})},Df=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of jf(e))!qf.call(t,r)&&r!==n&&_r(t,r,{get:()=>e[r],enumerable:!(i=If(e,r))||i.enumerable});return t};var ct=(t,e,n)=>(n=t!=null?Tf($f(t)):{},Df(e||!t||!t.__esModule?_r(n,"default",{value:t,enumerable:!0}):n,t));var P=w(F=>{"use strict";var xr=Symbol.for("yaml.alias"),na=Symbol.for("yaml.document"),Wn=Symbol.for("yaml.map"),ia=Symbol.for("yaml.pair"),Pr=Symbol.for("yaml.scalar"),Bn=Symbol.for("yaml.seq"),we=Symbol.for("yaml.node.type"),Mf=t=>!!t&&typeof t=="object"&&t[we]===xr,Ff=t=>!!t&&typeof t=="object"&&t[we]===na,Wf=t=>!!t&&typeof t=="object"&&t[we]===Wn,Bf=t=>!!t&&typeof t=="object"&&t[we]===ia,ra=t=>!!t&&typeof t=="object"&&t[we]===Pr,Kf=t=>!!t&&typeof t=="object"&&t[we]===Bn;function sa(t){if(t&&typeof t=="object")switch(t[we]){case Wn:case Bn:return!0}return!1}function Uf(t){if(t&&typeof t=="object")switch(t[we]){case xr:case Wn:case Pr:case Bn:return!0}return!1}var Yf=t=>(ra(t)||sa(t))&&!!t.anchor;F.ALIAS=xr;F.DOC=na;F.MAP=Wn;F.NODE_TYPE=we;F.PAIR=ia;F.SCALAR=Pr;F.SEQ=Bn;F.hasAnchor=Yf;F.isAlias=Mf;F.isCollection=sa;F.isDocument=Ff;F.isMap=Wf;F.isNode=Uf;F.isPair=Bf;F.isScalar=ra;F.isSeq=Kf});var Tt=w(Or=>{"use strict";var M=P(),G=Symbol("break visit"),oa=Symbol("skip children"),de=Symbol("remove node");function Kn(t,e){let n=aa(e);M.isDocument(t)?lt(null,t.contents,n,Object.freeze([t]))===de&&(t.contents=null):lt(null,t,n,Object.freeze([]))}Kn.BREAK=G;Kn.SKIP=oa;Kn.REMOVE=de;function lt(t,e,n,i){let r=ca(t,e,n,i);if(M.isNode(r)||M.isPair(r))return la(t,i,r),lt(t,r,n,i);if(typeof r!="symbol"){if(M.isCollection(e)){i=Object.freeze(i.concat(e));for(let s=0;s{"use strict";var ua=P(),Vf=Tt(),Jf={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Hf=t=>t.replace(/[!,[\]{}]/g,e=>Jf[e]),It=class t{constructor(e,n){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},t.defaultYaml,e),this.tags=Object.assign({},t.defaultTags,n)}clone(){let e=new t(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){let e=new t(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:t.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},t.defaultTags);break}return e}add(e,n){this.atNextDocument&&(this.yaml={explicit:t.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},t.defaultTags),this.atNextDocument=!1);let i=e.trim().split(/[ \t]+/),r=i.shift();switch(r){case"%TAG":{if(i.length!==2&&(n(0,"%TAG directive should contain exactly two parts"),i.length<2))return!1;let[s,o]=i;return this.tags[s]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,i.length!==1)return n(0,"%YAML directive should contain exactly one part"),!1;let[s]=i;if(s==="1.1"||s==="1.2")return this.yaml.version=s,!0;{let o=/^\d+\.\d+$/.test(s);return n(6,`Unsupported YAML version ${s}`,o),!1}}default:return n(0,`Unknown directive ${r}`,!0),!1}}tagName(e,n){if(e==="!")return"!";if(e[0]!=="!")return n(`Not a valid tag: ${e}`),null;if(e[1]==="<"){let o=e.slice(2,-1);return o==="!"||o==="!!"?(n(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&n("Verbatim tags must end with a >"),o)}let[,i,r]=e.match(/^(.*!)([^!]*)$/s);r||n(`The ${e} tag has no suffix`);let s=this.tags[i];if(s)try{return s+decodeURIComponent(r)}catch(o){return n(String(o)),null}return i==="!"?e:(n(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[n,i]of Object.entries(this.tags))if(e.startsWith(i))return n+Hf(e.substring(i.length));return e[0]==="!"?e:`!<${e}>`}toString(e){let n=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],i=Object.entries(this.tags),r;if(e&&i.length>0&&ua.isNode(e.contents)){let s={};Vf.visit(e.contents,(o,a)=>{ua.isNode(a)&&a.tag&&(s[a.tag]=!0)}),r=Object.keys(s)}else r=[];for(let[s,o]of i)s==="!!"&&o==="tag:yaml.org,2002:"||(!e||r.some(a=>a.startsWith(o)))&&n.push(`%TAG ${s} ${o}`);return n.join(` +`)}};It.defaultYaml={explicit:!1,version:"1.2"};It.defaultTags={"!!":"tag:yaml.org,2002:"};fa.Directives=It});var Yn=w(jt=>{"use strict";var da=P(),Gf=Tt();function zf(t){if(/[\x00-\x19\s,[\]{}]/.test(t)){let n=`Anchor must not contain whitespace or control characters: ${JSON.stringify(t)}`;throw new Error(n)}return!0}function pa(t){let e=new Set;return Gf.visit(t,{Value(n,i){i.anchor&&e.add(i.anchor)}}),e}function ma(t,e){for(let n=1;;++n){let i=`${t}${n}`;if(!e.has(i))return i}}function Xf(t,e){let n=[],i=new Map,r=null;return{onAnchor:s=>{n.push(s),r??(r=pa(t));let o=ma(e,r);return r.add(o),o},setAnchors:()=>{for(let s of n){let o=i.get(s);if(typeof o=="object"&&o.anchor&&(da.isScalar(o.node)||da.isCollection(o.node)))o.node.anchor=o.anchor;else{let a=new Error("Failed to resolve repeated object (this should not happen)");throw a.source=s,a}}},sourceObjects:i}}jt.anchorIsValid=zf;jt.anchorNames=pa;jt.createNodeAnchors=Xf;jt.findNewAnchor=ma});var Ar=w(ha=>{"use strict";function $t(t,e,n,i){if(i&&typeof i=="object")if(Array.isArray(i))for(let r=0,s=i.length;r{"use strict";var Qf=P();function ga(t,e,n){if(Array.isArray(t))return t.map((i,r)=>ga(i,String(r),n));if(t&&typeof t.toJSON=="function"){if(!n||!Qf.hasAnchor(t))return t.toJSON(e,n);let i={aliasCount:0,count:1,res:void 0};n.anchors.set(t,i),n.onCreate=s=>{i.res=s,delete n.onCreate};let r=t.toJSON(e,n);return n.onCreate&&n.onCreate(r),r}return typeof t=="bigint"&&!n?.keep?Number(t):t}wa.toJS=ga});var Vn=w(va=>{"use strict";var Zf=Ar(),ya=P(),ed=xe(),Tr=class{constructor(e){Object.defineProperty(this,ya.NODE_TYPE,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:n,maxAliasCount:i,onAnchor:r,reviver:s}={}){if(!ya.isDocument(e))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:e,keep:!0,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},a=ed.toJS(this,"",o);if(typeof r=="function")for(let{count:c,res:l}of o.anchors.values())r(l,c);return typeof s=="function"?Zf.applyReviver(s,{"":a},"",a):a}};va.NodeBase=Tr});var qt=w(ba=>{"use strict";var td=Yn(),nd=Tt(),ft=P(),id=Vn(),rd=xe(),Ir=class extends id.NodeBase{constructor(e){super(ft.ALIAS),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,n){if(n?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let i;n?.aliasResolveCache?i=n.aliasResolveCache:(i=[],nd.visit(e,{Node:(s,o)=>{(ft.isAlias(o)||ft.hasAnchor(o))&&i.push(o)}}),n&&(n.aliasResolveCache=i));let r;for(let s of i){if(s===this)break;s.anchor===this.source&&(r=s)}return r}toJSON(e,n){if(!n)return{source:this.source};let{anchors:i,doc:r,maxAliasCount:s}=n,o=this.resolve(r,n);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let a=i.get(o);if(a||(rd.toJS(o,null,n),a=i.get(o)),a?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(s>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=Jn(r,o,i)),a.count*a.aliasCount>s)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return a.res}toString(e,n,i){let r=`*${this.source}`;if(e){if(td.anchorIsValid(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let s=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(s)}if(e.implicitKey)return`${r} `}return r}};function Jn(t,e,n){if(ft.isAlias(e)){let i=e.resolve(t),r=n&&i&&n.get(i);return r?r.count*r.aliasCount:0}else if(ft.isCollection(e)){let i=0;for(let r of e.items){let s=Jn(t,r,n);s>i&&(i=s)}return i}else if(ft.isPair(e)){let i=Jn(t,e.key,n),r=Jn(t,e.value,n);return Math.max(i,r)}return 1}ba.Alias=Ir});var $=w(jr=>{"use strict";var sd=P(),od=Vn(),ad=xe(),cd=t=>!t||typeof t!="function"&&typeof t!="object",Pe=class extends od.NodeBase{constructor(e){super(sd.SCALAR),this.value=e}toJSON(e,n){return n?.keep?this.value:ad.toJS(this.value,e,n)}toString(){return String(this.value)}};Pe.BLOCK_FOLDED="BLOCK_FOLDED";Pe.BLOCK_LITERAL="BLOCK_LITERAL";Pe.PLAIN="PLAIN";Pe.QUOTE_DOUBLE="QUOTE_DOUBLE";Pe.QUOTE_SINGLE="QUOTE_SINGLE";jr.Scalar=Pe;jr.isScalarValue=cd});var Lt=w(Sa=>{"use strict";var ld=qt(),He=P(),ka=$(),ud="tag:yaml.org,2002:";function fd(t,e,n){if(e){let i=n.filter(s=>s.tag===e),r=i.find(s=>!s.format)??i[0];if(!r)throw new Error(`Tag ${e} not found`);return r}return n.find(i=>i.identify?.(t)&&!i.format)}function dd(t,e,n){if(He.isDocument(t)&&(t=t.contents),He.isNode(t))return t;if(He.isPair(t)){let u=n.schema[He.MAP].createNode?.(n.schema,null,n);return u.items.push(t),u}(t instanceof String||t instanceof Number||t instanceof Boolean||typeof BigInt<"u"&&t instanceof BigInt)&&(t=t.valueOf());let{aliasDuplicateObjects:i,onAnchor:r,onTagObj:s,schema:o,sourceObjects:a}=n,c;if(i&&t&&typeof t=="object"){if(c=a.get(t),c)return c.anchor??(c.anchor=r(t)),new ld.Alias(c.anchor);c={anchor:null,node:null},a.set(t,c)}e?.startsWith("!!")&&(e=ud+e.slice(2));let l=fd(t,e,o.tags);if(!l){if(t&&typeof t.toJSON=="function"&&(t=t.toJSON()),!t||typeof t!="object"){let u=new ka.Scalar(t);return c&&(c.node=u),u}l=t instanceof Map?o[He.MAP]:Symbol.iterator in Object(t)?o[He.SEQ]:o[He.MAP]}s&&(s(l),delete n.onTagObj);let f=l?.createNode?l.createNode(n.schema,t,n):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(n.schema,t,n):new ka.Scalar(t);return e?f.tag=e:l.default||(f.tag=l.tag),c&&(c.node=f),f}Sa.createNode=dd});var Gn=w(Hn=>{"use strict";var pd=Lt(),pe=P(),md=Vn();function $r(t,e,n){let i=n;for(let r=e.length-1;r>=0;--r){let s=e[r];if(typeof s=="number"&&Number.isInteger(s)&&s>=0){let o=[];o[s]=i,i=o}else i=new Map([[s,i]])}return pd.createNode(i,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:t,sourceObjects:new Map})}var Ca=t=>t==null||typeof t=="object"&&!!t[Symbol.iterator]().next().done,qr=class extends md.NodeBase{constructor(e,n){super(e),Object.defineProperty(this,"schema",{value:n,configurable:!0,enumerable:!1,writable:!0})}clone(e){let n=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(n.schema=e),n.items=n.items.map(i=>pe.isNode(i)||pe.isPair(i)?i.clone(e):i),this.range&&(n.range=this.range.slice()),n}addIn(e,n){if(Ca(e))this.add(n);else{let[i,...r]=e,s=this.get(i,!0);if(pe.isCollection(s))s.addIn(r,n);else if(s===void 0&&this.schema)this.set(i,$r(this.schema,r,n));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${r}`)}}deleteIn(e){let[n,...i]=e;if(i.length===0)return this.delete(n);let r=this.get(n,!0);if(pe.isCollection(r))return r.deleteIn(i);throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}getIn(e,n){let[i,...r]=e,s=this.get(i,!0);return r.length===0?!n&&pe.isScalar(s)?s.value:s:pe.isCollection(s)?s.getIn(r,n):void 0}hasAllNullValues(e){return this.items.every(n=>{if(!pe.isPair(n))return!1;let i=n.value;return i==null||e&&pe.isScalar(i)&&i.value==null&&!i.commentBefore&&!i.comment&&!i.tag})}hasIn(e){let[n,...i]=e;if(i.length===0)return this.has(n);let r=this.get(n,!0);return pe.isCollection(r)?r.hasIn(i):!1}setIn(e,n){let[i,...r]=e;if(r.length===0)this.set(i,n);else{let s=this.get(i,!0);if(pe.isCollection(s))s.setIn(r,n);else if(s===void 0&&this.schema)this.set(i,$r(this.schema,r,n));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${r}`)}}};Hn.Collection=qr;Hn.collectionFromPath=$r;Hn.isEmptyPath=Ca});var Dt=w(zn=>{"use strict";var hd=t=>t.replace(/^(?!$)(?: $)?/gm,"#");function Lr(t,e){return/^\n+$/.test(t)?t.substring(1):e?t.replace(/^(?! *$)/gm,e):t}var gd=(t,e,n)=>t.endsWith(` +`)?Lr(n,e):n.includes(` `)?` -`+qr(n,e):(t.endsWith(" ")?"":" ")+n;zn.indentComment=qr;zn.lineComment=hd;zn.stringifyComment=md});var Ra=w(Mt=>{"use strict";var gd="flow",Lr="block",Xn="quoted";function wd(t,e,n="flow",{indentAtStart:i,lineWidth:r=80,minContentWidth:s=20,onFold:o,onOverflow:a}={}){if(!r||r<0)return t;rr-Math.max(2,s)?l.push(0):u=r-i);let d,m,g=!1,p=-1,h=-1,v=-1;n===Lr&&(p=Ea(t,p,e.length),p!==-1&&(u=p+c));for(let S;S=t[p+=1];){if(n===Xn&&S==="\\"){switch(h=p,t[p+1]){case"x":p+=3;break;case"u":p+=5;break;case"U":p+=9;break;default:p+=1}v=p}if(S===` -`)n===Lr&&(p=Ea(t,p,e.length)),u=p+e.length+c,d=void 0;else{if(S===" "&&m&&m!==" "&&m!==` +`+Lr(n,e):(t.endsWith(" ")?"":" ")+n;zn.indentComment=Lr;zn.lineComment=gd;zn.stringifyComment=hd});var Ra=w(Mt=>{"use strict";var wd="flow",Dr="block",Xn="quoted";function yd(t,e,n="flow",{indentAtStart:i,lineWidth:r=80,minContentWidth:s=20,onFold:o,onOverflow:a}={}){if(!r||r<0)return t;rr-Math.max(2,s)?l.push(0):u=r-i);let d,m,g=!1,p=-1,h=-1,v=-1;n===Dr&&(p=Ea(t,p,e.length),p!==-1&&(u=p+c));for(let S;S=t[p+=1];){if(n===Xn&&S==="\\"){switch(h=p,t[p+1]){case"x":p+=3;break;case"u":p+=5;break;case"U":p+=9;break;default:p+=1}v=p}if(S===` +`)n===Dr&&(p=Ea(t,p,e.length)),u=p+e.length+c,d=void 0;else{if(S===" "&&m&&m!==" "&&m!==` `&&m!==" "){let R=t[p+1];R&&R!==" "&&R!==` `&&R!==" "&&(d=p)}if(p>=u)if(d)l.push(d),u=d+c,d=void 0;else if(n===Xn){for(;m===" "||m===" ";)m=S,S=t[p+=1],g=!0;let R=p>v+1?p-2:h-1;if(f[R])return t;l.push(R),f[R]=!0,u=R+c,d=void 0}else g=!0}m=S}if(g&&a&&a(),l.length===0)return t;o&&o();let y=t.slice(0,l[0]);for(let S=0;S{"use strict";var re=$(),Oe=Ra(),Zn=(t,e)=>({indentAtStart:e?t.indent.length:t.indentAtStart,lineWidth:t.options.lineWidth,minContentWidth:t.options.minContentWidth}),ei=t=>/^(%|---|\.\.\.)/m.test(t);function yd(t,e,n){if(!e||e<0)return!1;let i=e-n,r=t.length;if(r<=i)return!1;for(let s=0,o=0;s{"use strict";var re=$(),Oe=Ra(),Zn=(t,e)=>({indentAtStart:e?t.indent.length:t.indentAtStart,lineWidth:t.options.lineWidth,minContentWidth:t.options.minContentWidth}),ei=t=>/^(%|---|\.\.\.)/m.test(t);function vd(t,e,n){if(!e||e<0)return!1;let i=e-n,r=t.length;if(r<=i)return!1;for(let s=0,o=0;si)return!0;if(o=s+1,r-o<=i)return!1}return!0}function Ft(t,e){let n=JSON.stringify(t);if(e.options.doubleQuotedAsJSON)return n;let{implicitKey:i}=e,r=e.options.doubleQuotedMinMultiLineLength,s=e.indent||(ei(t)?" ":""),o="",a=0;for(let c=0,l=n[c];l;l=n[++c])if(l===" "&&n[c+1]==="\\"&&n[c+2]==="n"&&(o+=n.slice(a,c)+"\\ ",c+=1,a=c,l="\\"),l==="\\")switch(n[c+1]){case"u":{o+=n.slice(a,c);let f=n.substr(c+2,4);switch(f){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:f.substr(0,2)==="00"?o+="\\x"+f.substr(2):o+=n.substr(c,6)}c+=5,a=c+1}break;case"n":if(i||n[c+2]==='"'||n.length `;let u,d;for(d=n.length;d>0;--d){let _=n[d-1];if(_!==` `&&_!==" "&&_!==" ")break}let m=n.substring(d),g=m.indexOf(` `);g===-1?u="-":n===m||g!==m.length-1?(u="+",s&&s()):u="",m&&(n=n.slice(0,-m.length),m[m.length-1]===` -`&&(m=m.slice(0,-1)),m=m.replace(Mr,`$&${l}`));let p=!1,h,v=-1;for(h=0;h{E=!0});let k=Oe.foldFlowLines(`${y}${_}${m}`,l,Oe.FOLD_BLOCK,A);if(!E)return`>${R} +$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),E=!1,N=Zn(i,!0);o!=="folded"&&e!==re.Scalar.BLOCK_FOLDED&&(N.onOverflow=()=>{E=!0});let k=Oe.foldFlowLines(`${y}${_}${m}`,l,Oe.FOLD_BLOCK,N);if(!E)return`>${R} ${l}${k}`}return n=n.replace(/\n+/g,`$&${l}`),`|${R} -${l}${y}${n}${m}`}function vd(t,e,n,i){let{type:r,value:s}=t,{actualString:o,implicitKey:a,indent:c,indentStep:l,inFlow:f}=e;if(a&&s.includes(` +${l}${y}${n}${m}`}function bd(t,e,n,i){let{type:r,value:s}=t,{actualString:o,implicitKey:a,indent:c,indentStep:l,inFlow:f}=e;if(a&&s.includes(` `)||f&&/[[\]{},]/.test(s))return dt(s,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(s))return a||f||!s.includes(` `)?dt(s,e):Qn(t,e,n,i);if(!a&&!f&&r!==re.Scalar.PLAIN&&s.includes(` `))return Qn(t,e,n,i);if(ei(s)){if(c==="")return e.forceBlockIndent=!0,Qn(t,e,n,i);if(a&&c===l)return dt(s,e)}let u=s.replace(/\n+/g,`$& -${c}`);if(o){let d=p=>p.default&&p.tag!=="tag:yaml.org,2002:str"&&p.test?.test(u),{compat:m,tags:g}=e.doc.schema;if(g.some(d)||m?.some(d))return dt(s,e)}return a?u:Oe.foldFlowLines(u,c,Oe.FOLD_FLOW,Zn(e,!1))}function bd(t,e,n,i){let{implicitKey:r,inFlow:s}=e,o=typeof t.value=="string"?t:Object.assign({},t,{value:String(t.value)}),{type:a}=t;a!==re.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=re.Scalar.QUOTE_DOUBLE);let c=f=>{switch(f){case re.Scalar.BLOCK_FOLDED:case re.Scalar.BLOCK_LITERAL:return r||s?dt(o.value,e):Qn(o,e,n,i);case re.Scalar.QUOTE_DOUBLE:return Ft(o.value,e);case re.Scalar.QUOTE_SINGLE:return Dr(o.value,e);case re.Scalar.PLAIN:return vd(o,e,n,i);default:return null}},l=c(a);if(l===null){let{defaultKeyType:f,defaultStringType:u}=e.options,d=r&&f||u;if(l=c(d),l===null)throw new Error(`Unsupported default string type ${d}`)}return l}_a.stringifyString=bd});var Bt=w(Fr=>{"use strict";var kd=Yn(),Ae=P(),Sd=Dt(),Cd=Wt();function Ed(t,e){let n=Object.assign({blockQuote:!0,commentString:Sd.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},t.schema.toStringOptions,e),i;switch(n.collectionStyle){case"block":i=!1;break;case"flow":i=!0;break;default:i=null}return{anchors:new Set,doc:t,flowCollectionPadding:n.flowCollectionPadding?" ":"",indent:"",indentStep:typeof n.indent=="number"?" ".repeat(n.indent):" ",inFlow:i,options:n}}function Rd(t,e){if(e.tag){let r=t.filter(s=>s.tag===e.tag);if(r.length>0)return r.find(s=>s.format===e.format)??r[0]}let n,i;if(Ae.isScalar(e)){i=e.value;let r=t.filter(s=>s.identify?.(i));if(r.length>1){let s=r.filter(o=>o.test);s.length>0&&(r=s)}n=r.find(s=>s.format===e.format)??r.find(s=>!s.format)}else i=e,n=t.find(r=>r.nodeClass&&i instanceof r.nodeClass);if(!n){let r=i?.constructor?.name??(i===null?"null":typeof i);throw new Error(`Tag not resolved for ${r} value`)}return n}function _d(t,e,{anchors:n,doc:i}){if(!i.directives)return"";let r=[],s=(Ae.isScalar(t)||Ae.isCollection(t))&&t.anchor;s&&kd.anchorIsValid(s)&&(n.add(s),r.push(`&${s}`));let o=t.tag??(e.default?null:e.tag);return o&&r.push(i.directives.tagString(o)),r.join(" ")}function xd(t,e,n,i){if(Ae.isPair(t))return t.toString(e,n,i);if(Ae.isAlias(t)){if(e.doc.directives)return t.toString(e);if(e.resolvedAliases?.has(t))throw new TypeError("Cannot stringify circular structure without alias nodes");e.resolvedAliases?e.resolvedAliases.add(t):e.resolvedAliases=new Set([t]),t=t.resolve(e.doc)}let r,s=Ae.isNode(t)?t:e.doc.createNode(t,{onTagObj:c=>r=c});r??(r=Rd(e.doc.schema.tags,s));let o=_d(s,r,e);o.length>0&&(e.indentAtStart=(e.indentAtStart??0)+o.length+1);let a=typeof r.stringify=="function"?r.stringify(s,e,n,i):Ae.isScalar(s)?Cd.stringifyString(s,e,n,i):s.toString(e,n,i);return o?Ae.isScalar(s)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o} -${e.indent}${a}`:a}Fr.createStringifyContext=Ed;Fr.stringify=xd});var Aa=w(Oa=>{"use strict";var ye=P(),xa=$(),Pa=Bt(),Kt=Dt();function Pd({key:t,value:e},n,i,r){let{allNullValues:s,doc:o,indent:a,indentStep:c,options:{commentString:l,indentSeq:f,simpleKeys:u}}=n,d=ye.isNode(t)&&t.comment||null;if(u){if(d)throw new Error("With simple keys, key nodes cannot have comments");if(ye.isCollection(t)||!ye.isNode(t)&&typeof t=="object"){let A="With simple keys, collection cannot be used as a key value";throw new Error(A)}}let m=!u&&(!t||d&&e==null&&!n.inFlow||ye.isCollection(t)||(ye.isScalar(t)?t.type===xa.Scalar.BLOCK_FOLDED||t.type===xa.Scalar.BLOCK_LITERAL:typeof t=="object"));n=Object.assign({},n,{allNullValues:!1,implicitKey:!m&&(u||!s),indent:a+c});let g=!1,p=!1,h=Pa.stringify(t,n,()=>g=!0,()=>p=!0);if(!m&&!n.inFlow&&h.length>1024){if(u)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");m=!0}if(n.inFlow){if(s||e==null)return g&&i&&i(),h===""?"?":m?`? ${h}`:h}else if(s&&!u||e==null&&m)return h=`? ${h}`,d&&!g?h+=Kt.lineComment(h,n.indent,l(d)):p&&r&&r(),h;g&&(d=null),m?(d&&(h+=Kt.lineComment(h,n.indent,l(d))),h=`? ${h} +${c}`);if(o){let d=p=>p.default&&p.tag!=="tag:yaml.org,2002:str"&&p.test?.test(u),{compat:m,tags:g}=e.doc.schema;if(g.some(d)||m?.some(d))return dt(s,e)}return a?u:Oe.foldFlowLines(u,c,Oe.FOLD_FLOW,Zn(e,!1))}function kd(t,e,n,i){let{implicitKey:r,inFlow:s}=e,o=typeof t.value=="string"?t:Object.assign({},t,{value:String(t.value)}),{type:a}=t;a!==re.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=re.Scalar.QUOTE_DOUBLE);let c=f=>{switch(f){case re.Scalar.BLOCK_FOLDED:case re.Scalar.BLOCK_LITERAL:return r||s?dt(o.value,e):Qn(o,e,n,i);case re.Scalar.QUOTE_DOUBLE:return Ft(o.value,e);case re.Scalar.QUOTE_SINGLE:return Mr(o.value,e);case re.Scalar.PLAIN:return bd(o,e,n,i);default:return null}},l=c(a);if(l===null){let{defaultKeyType:f,defaultStringType:u}=e.options,d=r&&f||u;if(l=c(d),l===null)throw new Error(`Unsupported default string type ${d}`)}return l}_a.stringifyString=kd});var Bt=w(Wr=>{"use strict";var Sd=Yn(),Ne=P(),Cd=Dt(),Ed=Wt();function Rd(t,e){let n=Object.assign({blockQuote:!0,commentString:Cd.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},t.schema.toStringOptions,e),i;switch(n.collectionStyle){case"block":i=!1;break;case"flow":i=!0;break;default:i=null}return{anchors:new Set,doc:t,flowCollectionPadding:n.flowCollectionPadding?" ":"",indent:"",indentStep:typeof n.indent=="number"?" ".repeat(n.indent):" ",inFlow:i,options:n}}function _d(t,e){if(e.tag){let r=t.filter(s=>s.tag===e.tag);if(r.length>0)return r.find(s=>s.format===e.format)??r[0]}let n,i;if(Ne.isScalar(e)){i=e.value;let r=t.filter(s=>s.identify?.(i));if(r.length>1){let s=r.filter(o=>o.test);s.length>0&&(r=s)}n=r.find(s=>s.format===e.format)??r.find(s=>!s.format)}else i=e,n=t.find(r=>r.nodeClass&&i instanceof r.nodeClass);if(!n){let r=i?.constructor?.name??(i===null?"null":typeof i);throw new Error(`Tag not resolved for ${r} value`)}return n}function xd(t,e,{anchors:n,doc:i}){if(!i.directives)return"";let r=[],s=(Ne.isScalar(t)||Ne.isCollection(t))&&t.anchor;s&&Sd.anchorIsValid(s)&&(n.add(s),r.push(`&${s}`));let o=t.tag??(e.default?null:e.tag);return o&&r.push(i.directives.tagString(o)),r.join(" ")}function Pd(t,e,n,i){if(Ne.isPair(t))return t.toString(e,n,i);if(Ne.isAlias(t)){if(e.doc.directives)return t.toString(e);if(e.resolvedAliases?.has(t))throw new TypeError("Cannot stringify circular structure without alias nodes");e.resolvedAliases?e.resolvedAliases.add(t):e.resolvedAliases=new Set([t]),t=t.resolve(e.doc)}let r,s=Ne.isNode(t)?t:e.doc.createNode(t,{onTagObj:c=>r=c});r??(r=_d(e.doc.schema.tags,s));let o=xd(s,r,e);o.length>0&&(e.indentAtStart=(e.indentAtStart??0)+o.length+1);let a=typeof r.stringify=="function"?r.stringify(s,e,n,i):Ne.isScalar(s)?Ed.stringifyString(s,e,n,i):s.toString(e,n,i);return o?Ne.isScalar(s)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o} +${e.indent}${a}`:a}Wr.createStringifyContext=Rd;Wr.stringify=Pd});var Na=w(Oa=>{"use strict";var ye=P(),xa=$(),Pa=Bt(),Kt=Dt();function Od({key:t,value:e},n,i,r){let{allNullValues:s,doc:o,indent:a,indentStep:c,options:{commentString:l,indentSeq:f,simpleKeys:u}}=n,d=ye.isNode(t)&&t.comment||null;if(u){if(d)throw new Error("With simple keys, key nodes cannot have comments");if(ye.isCollection(t)||!ye.isNode(t)&&typeof t=="object"){let N="With simple keys, collection cannot be used as a key value";throw new Error(N)}}let m=!u&&(!t||d&&e==null&&!n.inFlow||ye.isCollection(t)||(ye.isScalar(t)?t.type===xa.Scalar.BLOCK_FOLDED||t.type===xa.Scalar.BLOCK_LITERAL:typeof t=="object"));n=Object.assign({},n,{allNullValues:!1,implicitKey:!m&&(u||!s),indent:a+c});let g=!1,p=!1,h=Pa.stringify(t,n,()=>g=!0,()=>p=!0);if(!m&&!n.inFlow&&h.length>1024){if(u)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");m=!0}if(n.inFlow){if(s||e==null)return g&&i&&i(),h===""?"?":m?`? ${h}`:h}else if(s&&!u||e==null&&m)return h=`? ${h}`,d&&!g?h+=Kt.lineComment(h,n.indent,l(d)):p&&r&&r(),h;g&&(d=null),m?(d&&(h+=Kt.lineComment(h,n.indent,l(d))),h=`? ${h} ${a}:`):(h=`${h}:`,d&&(h+=Kt.lineComment(h,n.indent,l(d))));let v,y,S;ye.isNode(e)?(v=!!e.spaceBefore,y=e.commentBefore,S=e.comment):(v=!1,y=null,S=null,e&&typeof e=="object"&&(e=o.createNode(e))),n.implicitKey=!1,!m&&!d&&ye.isScalar(e)&&(n.indentAtStart=h.length+1),p=!1,!f&&c.length>=2&&!n.inFlow&&!m&&ye.isSeq(e)&&!e.flow&&!e.tag&&!e.anchor&&(n.indent=n.indent.substring(2));let R=!1,_=Pa.stringify(e,n,()=>R=!0,()=>p=!0),E=" ";if(d||v||y){if(E=v?` -`:"",y){let A=l(y);E+=` -${Kt.indentComment(A,n.indent)}`}_===""&&!n.inFlow?E===` +`:"",y){let N=l(y);E+=` +${Kt.indentComment(N,n.indent)}`}_===""&&!n.inFlow?E===` `&&S&&(E=` `):E+=` -${n.indent}`}else if(!m&&ye.isCollection(e)){let A=_[0],k=_.indexOf(` -`),L=k!==-1,_e=n.inFlow??e.flow??e.items.length===0;if(L||!_e){let at=!1;if(L&&(A==="&"||A==="!")){let D=_.indexOf(" ");A==="&"&&D!==-1&&D{"use strict";var Na=Fn("process");function Od(t,...e){t==="debug"&&console.log(...e)}function Ad(t,e){(t==="debug"||t==="warn")&&(typeof Na.emitWarning=="function"?Na.emitWarning(e):console.warn(e))}Wr.debug=Od;Wr.warn=Ad});var si=w(ri=>{"use strict";var ii=P(),Ta=$(),ti="<<",ni={identify:t=>t===ti||typeof t=="symbol"&&t.description===ti,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new Ta.Scalar(Symbol(ti)),{addToJSMap:ja}),stringify:()=>ti},Nd=(t,e)=>(ni.identify(e)||ii.isScalar(e)&&(!e.type||e.type===Ta.Scalar.PLAIN)&&ni.identify(e.value))&&t?.doc.schema.tags.some(n=>n.tag===ni.tag&&n.default);function ja(t,e,n){let i=Ia(t,n);if(ii.isSeq(i))for(let r of i.items)Kr(t,e,r);else if(Array.isArray(i))for(let r of i)Kr(t,e,r);else Kr(t,e,i)}function Kr(t,e,n){let i=Ia(t,n);if(!ii.isMap(i))throw new Error("Merge sources must be maps or map aliases");let r=i.toJSON(null,t,Map);for(let[s,o]of r)e instanceof Map?e.has(s)||e.set(s,o):e instanceof Set?e.add(s):Object.prototype.hasOwnProperty.call(e,s)||Object.defineProperty(e,s,{value:o,writable:!0,enumerable:!0,configurable:!0});return e}function Ia(t,e){return t&&ii.isAlias(e)?e.resolve(t.doc,t):e}ri.addMergeToJSMap=ja;ri.isMergeKey=Nd;ri.merge=ni});var Yr=w(La=>{"use strict";var Td=Br(),$a=si(),jd=Bt(),qa=P(),Ur=xe();function Id(t,e,{key:n,value:i}){if(qa.isNode(n)&&n.addToJSMap)n.addToJSMap(t,e,i);else if($a.isMergeKey(t,n))$a.addMergeToJSMap(t,e,i);else{let r=Ur.toJS(n,"",t);if(e instanceof Map)e.set(r,Ur.toJS(i,r,t));else if(e instanceof Set)e.add(r);else{let s=$d(n,r,t),o=Ur.toJS(i,s,t);s in e?Object.defineProperty(e,s,{value:o,writable:!0,enumerable:!0,configurable:!0}):e[s]=o}}return e}function $d(t,e,n){if(e===null)return"";if(typeof e!="object")return String(e);if(qa.isNode(t)&&n?.doc){let i=jd.createStringifyContext(n.doc,{});i.anchors=new Set;for(let s of n.anchors.keys())i.anchors.add(s.anchor);i.inFlow=!0,i.inStringifyKey=!0;let r=t.toString(i);if(!n.mapKeyWarned){let s=JSON.stringify(r);s.length>40&&(s=s.substring(0,36)+'..."'),Td.warn(n.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${s}. Set mapAsMap: true to use object keys.`),n.mapKeyWarned=!0}return r}return JSON.stringify(e)}La.addPairToJSMap=Id});var Ne=w(Vr=>{"use strict";var Da=Lt(),qd=Aa(),Ld=Yr(),oi=P();function Dd(t,e,n){let i=Da.createNode(t,void 0,n),r=Da.createNode(e,void 0,n);return new ai(i,r)}var ai=class t{constructor(e,n=null){Object.defineProperty(this,oi.NODE_TYPE,{value:oi.PAIR}),this.key=e,this.value=n}clone(e){let{key:n,value:i}=this;return oi.isNode(n)&&(n=n.clone(e)),oi.isNode(i)&&(i=i.clone(e)),new t(n,i)}toJSON(e,n){let i=n?.mapAsMap?new Map:{};return Ld.addPairToJSMap(n,i,this)}toString(e,n,i){return e?.doc?qd.stringifyPair(this,e,n,i):JSON.stringify(this)}};Vr.Pair=ai;Vr.createPair=Dd});var Jr=w(Fa=>{"use strict";var Ge=P(),Ma=Bt(),ci=Dt();function Md(t,e,n){return(e.inFlow??t.flow?Wd:Fd)(t,e,n)}function Fd({comment:t,items:e},n,{blockItemPrefix:i,flowChars:r,itemIndent:s,onChompKeep:o,onComment:a}){let{indent:c,options:{commentString:l}}=n,f=Object.assign({},n,{indent:s,type:null}),u=!1,d=[];for(let g=0;gh=null,()=>u=!0);h&&(v+=ci.lineComment(v,s,l(h))),u&&h&&(u=!1),d.push(i+v)}let m;if(d.length===0)m=r.start+r.end;else{m=d[0];for(let g=1;g{"use strict";var Aa=Fn("process");function Nd(t,...e){t==="debug"&&console.log(...e)}function Ad(t,e){(t==="debug"||t==="warn")&&(typeof Aa.emitWarning=="function"?Aa.emitWarning(e):console.warn(e))}Br.debug=Nd;Br.warn=Ad});var si=w(ri=>{"use strict";var ii=P(),Ta=$(),ti="<<",ni={identify:t=>t===ti||typeof t=="symbol"&&t.description===ti,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new Ta.Scalar(Symbol(ti)),{addToJSMap:Ia}),stringify:()=>ti},Td=(t,e)=>(ni.identify(e)||ii.isScalar(e)&&(!e.type||e.type===Ta.Scalar.PLAIN)&&ni.identify(e.value))&&t?.doc.schema.tags.some(n=>n.tag===ni.tag&&n.default);function Ia(t,e,n){let i=ja(t,n);if(ii.isSeq(i))for(let r of i.items)Ur(t,e,r);else if(Array.isArray(i))for(let r of i)Ur(t,e,r);else Ur(t,e,i)}function Ur(t,e,n){let i=ja(t,n);if(!ii.isMap(i))throw new Error("Merge sources must be maps or map aliases");let r=i.toJSON(null,t,Map);for(let[s,o]of r)e instanceof Map?e.has(s)||e.set(s,o):e instanceof Set?e.add(s):Object.prototype.hasOwnProperty.call(e,s)||Object.defineProperty(e,s,{value:o,writable:!0,enumerable:!0,configurable:!0});return e}function ja(t,e){return t&&ii.isAlias(e)?e.resolve(t.doc,t):e}ri.addMergeToJSMap=Ia;ri.isMergeKey=Td;ri.merge=ni});var Vr=w(La=>{"use strict";var Id=Kr(),$a=si(),jd=Bt(),qa=P(),Yr=xe();function $d(t,e,{key:n,value:i}){if(qa.isNode(n)&&n.addToJSMap)n.addToJSMap(t,e,i);else if($a.isMergeKey(t,n))$a.addMergeToJSMap(t,e,i);else{let r=Yr.toJS(n,"",t);if(e instanceof Map)e.set(r,Yr.toJS(i,r,t));else if(e instanceof Set)e.add(r);else{let s=qd(n,r,t),o=Yr.toJS(i,s,t);s in e?Object.defineProperty(e,s,{value:o,writable:!0,enumerable:!0,configurable:!0}):e[s]=o}}return e}function qd(t,e,n){if(e===null)return"";if(typeof e!="object")return String(e);if(qa.isNode(t)&&n?.doc){let i=jd.createStringifyContext(n.doc,{});i.anchors=new Set;for(let s of n.anchors.keys())i.anchors.add(s.anchor);i.inFlow=!0,i.inStringifyKey=!0;let r=t.toString(i);if(!n.mapKeyWarned){let s=JSON.stringify(r);s.length>40&&(s=s.substring(0,36)+'..."'),Id.warn(n.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${s}. Set mapAsMap: true to use object keys.`),n.mapKeyWarned=!0}return r}return JSON.stringify(e)}La.addPairToJSMap=$d});var Ae=w(Jr=>{"use strict";var Da=Lt(),Ld=Na(),Dd=Vr(),oi=P();function Md(t,e,n){let i=Da.createNode(t,void 0,n),r=Da.createNode(e,void 0,n);return new ai(i,r)}var ai=class t{constructor(e,n=null){Object.defineProperty(this,oi.NODE_TYPE,{value:oi.PAIR}),this.key=e,this.value=n}clone(e){let{key:n,value:i}=this;return oi.isNode(n)&&(n=n.clone(e)),oi.isNode(i)&&(i=i.clone(e)),new t(n,i)}toJSON(e,n){let i=n?.mapAsMap?new Map:{};return Dd.addPairToJSMap(n,i,this)}toString(e,n,i){return e?.doc?Ld.stringifyPair(this,e,n,i):JSON.stringify(this)}};Jr.Pair=ai;Jr.createPair=Md});var Hr=w(Fa=>{"use strict";var Ge=P(),Ma=Bt(),ci=Dt();function Fd(t,e,n){return(e.inFlow??t.flow?Bd:Wd)(t,e,n)}function Wd({comment:t,items:e},n,{blockItemPrefix:i,flowChars:r,itemIndent:s,onChompKeep:o,onComment:a}){let{indent:c,options:{commentString:l}}=n,f=Object.assign({},n,{indent:s,type:null}),u=!1,d=[];for(let g=0;gh=null,()=>u=!0);h&&(v+=ci.lineComment(v,s,l(h))),u&&h&&(u=!1),d.push(i+v)}let m;if(d.length===0)m=r.start+r.end;else{m=d[0];for(let g=1;gh=null);l||(l=u.length>f||v.includes(` +`+ci.indentComment(l(t),c),a&&a()):u&&o&&o(),m}function Bd({items:t},e,{flowChars:n,itemIndent:i}){let{indent:r,indentStep:s,flowCollectionPadding:o,options:{commentString:a}}=e;i+=s;let c=Object.assign({},e,{indent:i,inFlow:!0,type:null}),l=!1,f=0,u=[];for(let g=0;gh=null);l||(l=u.length>f||v.includes(` `)),g0&&(l||(l=u.reduce((y,S)=>y+S.length+2,2)+(v.length+2)>e.options.lineWidth)),l&&(v+=",")),h&&(v+=ci.lineComment(v,i,a(h))),u.push(v),f=u.length}let{start:d,end:m}=n;if(u.length===0)return d+m;if(!l){let g=u.reduce((p,h)=>p+h.length+2,2);l=e.options.lineWidth>0&&g>e.options.lineWidth}if(l){let g=d;for(let p of u)g+=p?` ${s}${r}${p}`:` `;return`${g} -${r}${m}`}else return`${d}${o}${u.join(" ")}${o}${m}`}function li({indent:t,options:{commentString:e}},n,i,r){if(i&&r&&(i=i.replace(/^\n+/,"")),i){let s=ci.indentComment(e(i),t);n.push(s.trimStart())}}Fa.stringifyCollection=Md});var je=w(Gr=>{"use strict";var Bd=Jr(),Kd=Yr(),Ud=Gn(),Te=P(),ui=Ne(),Yd=$();function Ut(t,e){let n=Te.isScalar(e)?e.value:e;for(let i of t)if(Te.isPair(i)&&(i.key===e||i.key===n||Te.isScalar(i.key)&&i.key.value===n))return i}var Hr=class extends Ud.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(Te.MAP,e),this.items=[]}static from(e,n,i){let{keepUndefined:r,replacer:s}=i,o=new this(e),a=(c,l)=>{if(typeof s=="function")l=s.call(n,c,l);else if(Array.isArray(s)&&!s.includes(c))return;(l!==void 0||r)&&o.items.push(ui.createPair(c,l,i))};if(n instanceof Map)for(let[c,l]of n)a(c,l);else if(n&&typeof n=="object")for(let c of Object.keys(n))a(c,n[c]);return typeof e.sortMapEntries=="function"&&o.items.sort(e.sortMapEntries),o}add(e,n){let i;Te.isPair(e)?i=e:!e||typeof e!="object"||!("key"in e)?i=new ui.Pair(e,e?.value):i=new ui.Pair(e.key,e.value);let r=Ut(this.items,i.key),s=this.schema?.sortMapEntries;if(r){if(!n)throw new Error(`Key ${i.key} already set`);Te.isScalar(r.value)&&Yd.isScalarValue(i.value)?r.value.value=i.value:r.value=i.value}else if(s){let o=this.items.findIndex(a=>s(i,a)<0);o===-1?this.items.push(i):this.items.splice(o,0,i)}else this.items.push(i)}delete(e){let n=Ut(this.items,e);return n?this.items.splice(this.items.indexOf(n),1).length>0:!1}get(e,n){let r=Ut(this.items,e)?.value;return(!n&&Te.isScalar(r)?r.value:r)??void 0}has(e){return!!Ut(this.items,e)}set(e,n){this.add(new ui.Pair(e,n),!0)}toJSON(e,n,i){let r=i?new i:n?.mapAsMap?new Map:{};n?.onCreate&&n.onCreate(r);for(let s of this.items)Kd.addPairToJSMap(n,r,s);return r}toString(e,n,i){if(!e)return JSON.stringify(this);for(let r of this.items)if(!Te.isPair(r))throw new Error(`Map items must all be pairs; found ${JSON.stringify(r)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),Bd.stringifyCollection(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:i,onComment:n})}};Gr.YAMLMap=Hr;Gr.findPair=Ut});var pt=w(Ba=>{"use strict";var Vd=P(),Wa=je(),Jd={collection:"map",default:!0,nodeClass:Wa.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(t,e){return Vd.isMap(t)||e("Expected a mapping for this tag"),t},createNode:(t,e,n)=>Wa.YAMLMap.from(t,e,n)};Ba.map=Jd});var Ie=w(Ka=>{"use strict";var Hd=Lt(),Gd=Jr(),zd=Gn(),di=P(),Xd=$(),Qd=xe(),zr=class extends zd.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(di.SEQ,e),this.items=[]}add(e){this.items.push(e)}delete(e){let n=fi(e);return typeof n!="number"?!1:this.items.splice(n,1).length>0}get(e,n){let i=fi(e);if(typeof i!="number")return;let r=this.items[i];return!n&&di.isScalar(r)?r.value:r}has(e){let n=fi(e);return typeof n=="number"&&n=0?e:null}Ka.YAMLSeq=zr});var mt=w(Ya=>{"use strict";var Zd=P(),Ua=Ie(),ep={collection:"seq",default:!0,nodeClass:Ua.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(t,e){return Zd.isSeq(t)||e("Expected a sequence for this tag"),t},createNode:(t,e,n)=>Ua.YAMLSeq.from(t,e,n)};Ya.seq=ep});var Yt=w(Va=>{"use strict";var tp=Wt(),np={identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify(t,e,n,i){return e=Object.assign({actualString:!0},e),tp.stringifyString(t,e,n,i)}};Va.string=np});var pi=w(Ga=>{"use strict";var Ja=$(),Ha={identify:t=>t==null,createNode:()=>new Ja.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Ja.Scalar(null),stringify:({source:t},e)=>typeof t=="string"&&Ha.test.test(t)?t:e.options.nullStr};Ga.nullTag=Ha});var Xr=w(Xa=>{"use strict";var ip=$(),za={identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:t=>new ip.Scalar(t[0]==="t"||t[0]==="T"),stringify({source:t,value:e},n){if(t&&za.test.test(t)){let i=t[0]==="t"||t[0]==="T";if(e===i)return t}return e?n.options.trueStr:n.options.falseStr}};Xa.boolTag=za});var ht=w(Qa=>{"use strict";function rp({format:t,minFractionDigits:e,tag:n,value:i}){if(typeof i=="bigint")return String(i);let r=typeof i=="number"?i:Number(i);if(!isFinite(r))return isNaN(r)?".nan":r<0?"-.inf":".inf";let s=Object.is(i,-0)?"-0":JSON.stringify(i);if(!t&&e&&(!n||n==="tag:yaml.org,2002:float")&&/^-?\d/.test(s)&&!s.includes("e")){let o=s.indexOf(".");o<0&&(o=s.length,s+=".");let a=e-(s.length-o-1);for(;a-- >0;)s+="0"}return s}Qa.stringifyNumber=rp});var Zr=w(mi=>{"use strict";var sp=$(),Qr=ht(),op={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:t=>t.slice(-3).toLowerCase()==="nan"?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Qr.stringifyNumber},ap={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t),stringify(t){let e=Number(t.value);return isFinite(e)?e.toExponential():Qr.stringifyNumber(t)}},cp={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(t){let e=new sp.Scalar(parseFloat(t)),n=t.indexOf(".");return n!==-1&&t[t.length-1]==="0"&&(e.minFractionDigits=t.length-n-1),e},stringify:Qr.stringifyNumber};mi.float=cp;mi.floatExp=ap;mi.floatNaN=op});var ts=w(gi=>{"use strict";var Za=ht(),hi=t=>typeof t=="bigint"||Number.isInteger(t),es=(t,e,n,{intAsBigInt:i})=>i?BigInt(t):parseInt(t.substring(e),n);function ec(t,e,n){let{value:i}=t;return hi(i)&&i>=0?n+i.toString(e):Za.stringifyNumber(t)}var lp={identify:t=>hi(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(t,e,n)=>es(t,2,8,n),stringify:t=>ec(t,8,"0o")},up={identify:hi,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(t,e,n)=>es(t,0,10,n),stringify:Za.stringifyNumber},fp={identify:t=>hi(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(t,e,n)=>es(t,2,16,n),stringify:t=>ec(t,16,"0x")};gi.int=up;gi.intHex=fp;gi.intOct=lp});var nc=w(tc=>{"use strict";var dp=pt(),pp=pi(),mp=mt(),hp=Yt(),gp=Xr(),ns=Zr(),is=ts(),wp=[dp.map,mp.seq,hp.string,pp.nullTag,gp.boolTag,is.intOct,is.int,is.intHex,ns.floatNaN,ns.floatExp,ns.float];tc.schema=wp});var sc=w(rc=>{"use strict";var yp=$(),vp=pt(),bp=mt();function ic(t){return typeof t=="bigint"||Number.isInteger(t)}var wi=({value:t})=>JSON.stringify(t),kp=[{identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify:wi},{identify:t=>t==null,createNode:()=>new yp.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:wi},{identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:t=>t==="true",stringify:wi},{identify:ic,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(t,e,{intAsBigInt:n})=>n?BigInt(t):parseInt(t,10),stringify:({value:t})=>ic(t)?t.toString():JSON.stringify(t)},{identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:t=>parseFloat(t),stringify:wi}],Sp={default:!0,tag:"",test:/^/,resolve(t,e){return e(`Unresolved plain scalar ${JSON.stringify(t)}`),t}},Cp=[vp.map,bp.seq].concat(kp,Sp);rc.schema=Cp});var ss=w(oc=>{"use strict";var Vt=Fn("buffer"),rs=$(),Ep=Wt(),Rp={identify:t=>t instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(t,e){if(typeof Vt.Buffer=="function")return Vt.Buffer.from(t,"base64");if(typeof atob=="function"){let n=atob(t.replace(/[\n\r]/g,"")),i=new Uint8Array(n.length);for(let r=0;r{"use strict";var yi=P(),os=Ne(),_p=$(),xp=Ie();function ac(t,e){if(yi.isSeq(t))for(let n=0;n1&&e("Each pair must have its own sequence indicator");let r=i.items[0]||new os.Pair(new _p.Scalar(null));if(i.commentBefore&&(r.key.commentBefore=r.key.commentBefore?`${i.commentBefore} +${r}${m}`}else return`${d}${o}${u.join(" ")}${o}${m}`}function li({indent:t,options:{commentString:e}},n,i,r){if(i&&r&&(i=i.replace(/^\n+/,"")),i){let s=ci.indentComment(e(i),t);n.push(s.trimStart())}}Fa.stringifyCollection=Fd});var Ie=w(zr=>{"use strict";var Kd=Hr(),Ud=Vr(),Yd=Gn(),Te=P(),ui=Ae(),Vd=$();function Ut(t,e){let n=Te.isScalar(e)?e.value:e;for(let i of t)if(Te.isPair(i)&&(i.key===e||i.key===n||Te.isScalar(i.key)&&i.key.value===n))return i}var Gr=class extends Yd.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(Te.MAP,e),this.items=[]}static from(e,n,i){let{keepUndefined:r,replacer:s}=i,o=new this(e),a=(c,l)=>{if(typeof s=="function")l=s.call(n,c,l);else if(Array.isArray(s)&&!s.includes(c))return;(l!==void 0||r)&&o.items.push(ui.createPair(c,l,i))};if(n instanceof Map)for(let[c,l]of n)a(c,l);else if(n&&typeof n=="object")for(let c of Object.keys(n))a(c,n[c]);return typeof e.sortMapEntries=="function"&&o.items.sort(e.sortMapEntries),o}add(e,n){let i;Te.isPair(e)?i=e:!e||typeof e!="object"||!("key"in e)?i=new ui.Pair(e,e?.value):i=new ui.Pair(e.key,e.value);let r=Ut(this.items,i.key),s=this.schema?.sortMapEntries;if(r){if(!n)throw new Error(`Key ${i.key} already set`);Te.isScalar(r.value)&&Vd.isScalarValue(i.value)?r.value.value=i.value:r.value=i.value}else if(s){let o=this.items.findIndex(a=>s(i,a)<0);o===-1?this.items.push(i):this.items.splice(o,0,i)}else this.items.push(i)}delete(e){let n=Ut(this.items,e);return n?this.items.splice(this.items.indexOf(n),1).length>0:!1}get(e,n){let r=Ut(this.items,e)?.value;return(!n&&Te.isScalar(r)?r.value:r)??void 0}has(e){return!!Ut(this.items,e)}set(e,n){this.add(new ui.Pair(e,n),!0)}toJSON(e,n,i){let r=i?new i:n?.mapAsMap?new Map:{};n?.onCreate&&n.onCreate(r);for(let s of this.items)Ud.addPairToJSMap(n,r,s);return r}toString(e,n,i){if(!e)return JSON.stringify(this);for(let r of this.items)if(!Te.isPair(r))throw new Error(`Map items must all be pairs; found ${JSON.stringify(r)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),Kd.stringifyCollection(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:i,onComment:n})}};zr.YAMLMap=Gr;zr.findPair=Ut});var pt=w(Ba=>{"use strict";var Jd=P(),Wa=Ie(),Hd={collection:"map",default:!0,nodeClass:Wa.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(t,e){return Jd.isMap(t)||e("Expected a mapping for this tag"),t},createNode:(t,e,n)=>Wa.YAMLMap.from(t,e,n)};Ba.map=Hd});var je=w(Ka=>{"use strict";var Gd=Lt(),zd=Hr(),Xd=Gn(),di=P(),Qd=$(),Zd=xe(),Xr=class extends Xd.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(di.SEQ,e),this.items=[]}add(e){this.items.push(e)}delete(e){let n=fi(e);return typeof n!="number"?!1:this.items.splice(n,1).length>0}get(e,n){let i=fi(e);if(typeof i!="number")return;let r=this.items[i];return!n&&di.isScalar(r)?r.value:r}has(e){let n=fi(e);return typeof n=="number"&&n=0?e:null}Ka.YAMLSeq=Xr});var mt=w(Ya=>{"use strict";var ep=P(),Ua=je(),tp={collection:"seq",default:!0,nodeClass:Ua.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(t,e){return ep.isSeq(t)||e("Expected a sequence for this tag"),t},createNode:(t,e,n)=>Ua.YAMLSeq.from(t,e,n)};Ya.seq=tp});var Yt=w(Va=>{"use strict";var np=Wt(),ip={identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify(t,e,n,i){return e=Object.assign({actualString:!0},e),np.stringifyString(t,e,n,i)}};Va.string=ip});var pi=w(Ga=>{"use strict";var Ja=$(),Ha={identify:t=>t==null,createNode:()=>new Ja.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Ja.Scalar(null),stringify:({source:t},e)=>typeof t=="string"&&Ha.test.test(t)?t:e.options.nullStr};Ga.nullTag=Ha});var Qr=w(Xa=>{"use strict";var rp=$(),za={identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:t=>new rp.Scalar(t[0]==="t"||t[0]==="T"),stringify({source:t,value:e},n){if(t&&za.test.test(t)){let i=t[0]==="t"||t[0]==="T";if(e===i)return t}return e?n.options.trueStr:n.options.falseStr}};Xa.boolTag=za});var ht=w(Qa=>{"use strict";function sp({format:t,minFractionDigits:e,tag:n,value:i}){if(typeof i=="bigint")return String(i);let r=typeof i=="number"?i:Number(i);if(!isFinite(r))return isNaN(r)?".nan":r<0?"-.inf":".inf";let s=Object.is(i,-0)?"-0":JSON.stringify(i);if(!t&&e&&(!n||n==="tag:yaml.org,2002:float")&&/^-?\d/.test(s)&&!s.includes("e")){let o=s.indexOf(".");o<0&&(o=s.length,s+=".");let a=e-(s.length-o-1);for(;a-- >0;)s+="0"}return s}Qa.stringifyNumber=sp});var es=w(mi=>{"use strict";var op=$(),Zr=ht(),ap={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:t=>t.slice(-3).toLowerCase()==="nan"?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Zr.stringifyNumber},cp={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t),stringify(t){let e=Number(t.value);return isFinite(e)?e.toExponential():Zr.stringifyNumber(t)}},lp={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(t){let e=new op.Scalar(parseFloat(t)),n=t.indexOf(".");return n!==-1&&t[t.length-1]==="0"&&(e.minFractionDigits=t.length-n-1),e},stringify:Zr.stringifyNumber};mi.float=lp;mi.floatExp=cp;mi.floatNaN=ap});var ns=w(gi=>{"use strict";var Za=ht(),hi=t=>typeof t=="bigint"||Number.isInteger(t),ts=(t,e,n,{intAsBigInt:i})=>i?BigInt(t):parseInt(t.substring(e),n);function ec(t,e,n){let{value:i}=t;return hi(i)&&i>=0?n+i.toString(e):Za.stringifyNumber(t)}var up={identify:t=>hi(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(t,e,n)=>ts(t,2,8,n),stringify:t=>ec(t,8,"0o")},fp={identify:hi,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(t,e,n)=>ts(t,0,10,n),stringify:Za.stringifyNumber},dp={identify:t=>hi(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(t,e,n)=>ts(t,2,16,n),stringify:t=>ec(t,16,"0x")};gi.int=fp;gi.intHex=dp;gi.intOct=up});var nc=w(tc=>{"use strict";var pp=pt(),mp=pi(),hp=mt(),gp=Yt(),wp=Qr(),is=es(),rs=ns(),yp=[pp.map,hp.seq,gp.string,mp.nullTag,wp.boolTag,rs.intOct,rs.int,rs.intHex,is.floatNaN,is.floatExp,is.float];tc.schema=yp});var sc=w(rc=>{"use strict";var vp=$(),bp=pt(),kp=mt();function ic(t){return typeof t=="bigint"||Number.isInteger(t)}var wi=({value:t})=>JSON.stringify(t),Sp=[{identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify:wi},{identify:t=>t==null,createNode:()=>new vp.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:wi},{identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:t=>t==="true",stringify:wi},{identify:ic,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(t,e,{intAsBigInt:n})=>n?BigInt(t):parseInt(t,10),stringify:({value:t})=>ic(t)?t.toString():JSON.stringify(t)},{identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:t=>parseFloat(t),stringify:wi}],Cp={default:!0,tag:"",test:/^/,resolve(t,e){return e(`Unresolved plain scalar ${JSON.stringify(t)}`),t}},Ep=[bp.map,kp.seq].concat(Sp,Cp);rc.schema=Ep});var os=w(oc=>{"use strict";var Vt=Fn("buffer"),ss=$(),Rp=Wt(),_p={identify:t=>t instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(t,e){if(typeof Vt.Buffer=="function")return Vt.Buffer.from(t,"base64");if(typeof atob=="function"){let n=atob(t.replace(/[\n\r]/g,"")),i=new Uint8Array(n.length);for(let r=0;r{"use strict";var yi=P(),as=Ae(),xp=$(),Pp=je();function ac(t,e){if(yi.isSeq(t))for(let n=0;n1&&e("Each pair must have its own sequence indicator");let r=i.items[0]||new as.Pair(new xp.Scalar(null));if(i.commentBefore&&(r.key.commentBefore=r.key.commentBefore?`${i.commentBefore} ${r.key.commentBefore}`:i.commentBefore),i.comment){let s=r.value??r.key;s.comment=s.comment?`${i.comment} -${s.comment}`:i.comment}i=r}t.items[n]=yi.isPair(i)?i:new os.Pair(i)}}else e("Expected a sequence for this tag");return t}function cc(t,e,n){let{replacer:i}=n,r=new xp.YAMLSeq(t);r.tag="tag:yaml.org,2002:pairs";let s=0;if(e&&Symbol.iterator in Object(e))for(let o of e){typeof i=="function"&&(o=i.call(e,String(s++),o));let a,c;if(Array.isArray(o))if(o.length===2)a=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)a=l[0],c=o[a];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else a=o;r.items.push(os.createPair(a,c,n))}return r}var Pp={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:ac,createNode:cc};vi.createPairs=cc;vi.pairs=Pp;vi.resolvePairs=ac});var ls=w(cs=>{"use strict";var lc=P(),as=xe(),Jt=je(),Op=Ie(),uc=bi(),ze=class t extends Op.YAMLSeq{constructor(){super(),this.add=Jt.YAMLMap.prototype.add.bind(this),this.delete=Jt.YAMLMap.prototype.delete.bind(this),this.get=Jt.YAMLMap.prototype.get.bind(this),this.has=Jt.YAMLMap.prototype.has.bind(this),this.set=Jt.YAMLMap.prototype.set.bind(this),this.tag=t.tag}toJSON(e,n){if(!n)return super.toJSON(e);let i=new Map;n?.onCreate&&n.onCreate(i);for(let r of this.items){let s,o;if(lc.isPair(r)?(s=as.toJS(r.key,"",n),o=as.toJS(r.value,s,n)):s=as.toJS(r,"",n),i.has(s))throw new Error("Ordered maps must not include duplicate keys");i.set(s,o)}return i}static from(e,n,i){let r=uc.createPairs(e,n,i),s=new this;return s.items=r.items,s}};ze.tag="tag:yaml.org,2002:omap";var Ap={collection:"seq",identify:t=>t instanceof Map,nodeClass:ze,default:!1,tag:"tag:yaml.org,2002:omap",resolve(t,e){let n=uc.resolvePairs(t,e),i=[];for(let{key:r}of n.items)lc.isScalar(r)&&(i.includes(r.value)?e(`Ordered maps must not include duplicate keys: ${r.value}`):i.push(r.value));return Object.assign(new ze,n)},createNode:(t,e,n)=>ze.from(t,e,n)};cs.YAMLOMap=ze;cs.omap=Ap});var hc=w(us=>{"use strict";var fc=$();function dc({value:t,source:e},n){return e&&(t?pc:mc).test.test(e)?e:t?n.options.trueStr:n.options.falseStr}var pc={identify:t=>t===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new fc.Scalar(!0),stringify:dc},mc={identify:t=>t===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new fc.Scalar(!1),stringify:dc};us.falseTag=mc;us.trueTag=pc});var gc=w(ki=>{"use strict";var Np=$(),fs=ht(),Tp={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:t=>t.slice(-3).toLowerCase()==="nan"?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:fs.stringifyNumber},jp={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t.replace(/_/g,"")),stringify(t){let e=Number(t.value);return isFinite(e)?e.toExponential():fs.stringifyNumber(t)}},Ip={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(t){let e=new Np.Scalar(parseFloat(t.replace(/_/g,""))),n=t.indexOf(".");if(n!==-1){let i=t.substring(n+1).replace(/_/g,"");i[i.length-1]==="0"&&(e.minFractionDigits=i.length)}return e},stringify:fs.stringifyNumber};ki.float=Ip;ki.floatExp=jp;ki.floatNaN=Tp});var yc=w(Gt=>{"use strict";var wc=ht(),Ht=t=>typeof t=="bigint"||Number.isInteger(t);function Si(t,e,n,{intAsBigInt:i}){let r=t[0];if((r==="-"||r==="+")&&(e+=1),t=t.substring(e).replace(/_/g,""),i){switch(n){case 2:t=`0b${t}`;break;case 8:t=`0o${t}`;break;case 16:t=`0x${t}`;break}let o=BigInt(t);return r==="-"?BigInt(-1)*o:o}let s=parseInt(t,n);return r==="-"?-1*s:s}function ds(t,e,n){let{value:i}=t;if(Ht(i)){let r=i.toString(e);return i<0?"-"+n+r.substr(1):n+r}return wc.stringifyNumber(t)}var $p={identify:Ht,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(t,e,n)=>Si(t,2,2,n),stringify:t=>ds(t,2,"0b")},qp={identify:Ht,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(t,e,n)=>Si(t,1,8,n),stringify:t=>ds(t,8,"0")},Lp={identify:Ht,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(t,e,n)=>Si(t,0,10,n),stringify:wc.stringifyNumber},Dp={identify:Ht,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(t,e,n)=>Si(t,2,16,n),stringify:t=>ds(t,16,"0x")};Gt.int=Lp;Gt.intBin=$p;Gt.intHex=Dp;Gt.intOct=qp});var ms=w(ps=>{"use strict";var Ri=P(),Ci=Ne(),Ei=je(),Xe=class t extends Ei.YAMLMap{constructor(e){super(e),this.tag=t.tag}add(e){let n;Ri.isPair(e)?n=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?n=new Ci.Pair(e.key,null):n=new Ci.Pair(e,null),Ei.findPair(this.items,n.key)||this.items.push(n)}get(e,n){let i=Ei.findPair(this.items,e);return!n&&Ri.isPair(i)?Ri.isScalar(i.key)?i.key.value:i.key:i}set(e,n){if(typeof n!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof n}`);let i=Ei.findPair(this.items,e);i&&!n?this.items.splice(this.items.indexOf(i),1):!i&&n&&this.items.push(new Ci.Pair(e))}toJSON(e,n){return super.toJSON(e,n,Set)}toString(e,n,i){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),n,i);throw new Error("Set items must all have null values")}static from(e,n,i){let{replacer:r}=i,s=new this(e);if(n&&Symbol.iterator in Object(n))for(let o of n)typeof r=="function"&&(o=r.call(n,o,o)),s.items.push(Ci.createPair(o,null,i));return s}};Xe.tag="tag:yaml.org,2002:set";var Mp={collection:"map",identify:t=>t instanceof Set,nodeClass:Xe,default:!1,tag:"tag:yaml.org,2002:set",createNode:(t,e,n)=>Xe.from(t,e,n),resolve(t,e){if(Ri.isMap(t)){if(t.hasAllNullValues(!0))return Object.assign(new Xe,t);e("Set items must all have null values")}else e("Expected a mapping for this tag");return t}};ps.YAMLSet=Xe;ps.set=Mp});var gs=w(_i=>{"use strict";var Fp=ht();function hs(t,e){let n=t[0],i=n==="-"||n==="+"?t.substring(1):t,r=o=>e?BigInt(o):Number(o),s=i.replace(/_/g,"").split(":").reduce((o,a)=>o*r(60)+r(a),r(0));return n==="-"?r(-1)*s:s}function vc(t){let{value:e}=t,n=o=>o;if(typeof e=="bigint")n=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return Fp.stringifyNumber(t);let i="";e<0&&(i="-",e*=n(-1));let r=n(60),s=[e%r];return e<60?s.unshift(0):(e=(e-s[0])/r,s.unshift(e%r),e>=60&&(e=(e-s[0])/r,s.unshift(e))),i+s.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var Wp={identify:t=>typeof t=="bigint"||Number.isInteger(t),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(t,e,{intAsBigInt:n})=>hs(t,n),stringify:vc},Bp={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:t=>hs(t,!1),stringify:vc},bc={identify:t=>t instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(t){let e=t.match(bc.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,n,i,r,s,o,a]=e.map(Number),c=e[7]?Number((e[7]+"00").substr(1,3)):0,l=Date.UTC(n,i-1,r,s||0,o||0,a||0,c),f=e[8];if(f&&f!=="Z"){let u=hs(f,!1);Math.abs(u)<30&&(u*=60),l-=6e4*u}return new Date(l)},stringify:({value:t})=>t?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};_i.floatTime=Bp;_i.intTime=Wp;_i.timestamp=bc});var Cc=w(Sc=>{"use strict";var Kp=pt(),Up=pi(),Yp=mt(),Vp=Yt(),Jp=ss(),kc=hc(),ws=gc(),xi=yc(),Hp=si(),Gp=ls(),zp=bi(),Xp=ms(),ys=gs(),Qp=[Kp.map,Yp.seq,Vp.string,Up.nullTag,kc.trueTag,kc.falseTag,xi.intBin,xi.intOct,xi.int,xi.intHex,ws.floatNaN,ws.floatExp,ws.float,Jp.binary,Hp.merge,Gp.omap,zp.pairs,Xp.set,ys.intTime,ys.floatTime,ys.timestamp];Sc.schema=Qp});var jc=w(ks=>{"use strict";var xc=pt(),Zp=pi(),Pc=mt(),em=Yt(),tm=Xr(),vs=Zr(),bs=ts(),nm=nc(),im=sc(),Oc=ss(),zt=si(),Ac=ls(),Nc=bi(),Ec=Cc(),Tc=ms(),Pi=gs(),Rc=new Map([["core",nm.schema],["failsafe",[xc.map,Pc.seq,em.string]],["json",im.schema],["yaml11",Ec.schema],["yaml-1.1",Ec.schema]]),_c={binary:Oc.binary,bool:tm.boolTag,float:vs.float,floatExp:vs.floatExp,floatNaN:vs.floatNaN,floatTime:Pi.floatTime,int:bs.int,intHex:bs.intHex,intOct:bs.intOct,intTime:Pi.intTime,map:xc.map,merge:zt.merge,null:Zp.nullTag,omap:Ac.omap,pairs:Nc.pairs,seq:Pc.seq,set:Tc.set,timestamp:Pi.timestamp},rm={"tag:yaml.org,2002:binary":Oc.binary,"tag:yaml.org,2002:merge":zt.merge,"tag:yaml.org,2002:omap":Ac.omap,"tag:yaml.org,2002:pairs":Nc.pairs,"tag:yaml.org,2002:set":Tc.set,"tag:yaml.org,2002:timestamp":Pi.timestamp};function sm(t,e,n){let i=Rc.get(e);if(i&&!t)return n&&!i.includes(zt.merge)?i.concat(zt.merge):i.slice();let r=i;if(!r)if(Array.isArray(t))r=[];else{let s=Array.from(Rc.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${e}"; use one of ${s} or define customTags array`)}if(Array.isArray(t))for(let s of t)r=r.concat(s);else typeof t=="function"&&(r=t(r.slice()));return n&&(r=r.concat(zt.merge)),r.reduce((s,o)=>{let a=typeof o=="string"?_c[o]:o;if(!a){let c=JSON.stringify(o),l=Object.keys(_c).map(f=>JSON.stringify(f)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return s.includes(a)||s.push(a),s},[])}ks.coreKnownTags=rm;ks.getTags=sm});var Es=w(Ic=>{"use strict";var Ss=P(),om=pt(),am=mt(),cm=Yt(),Oi=jc(),lm=(t,e)=>t.keye.key?1:0,Cs=class t{constructor({compat:e,customTags:n,merge:i,resolveKnownTags:r,schema:s,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?Oi.getTags(e,"compat"):e?Oi.getTags(null,e):null,this.name=typeof s=="string"&&s||"core",this.knownTags=r?Oi.coreKnownTags:{},this.tags=Oi.getTags(n,this.name,i),this.toStringOptions=a??null,Object.defineProperty(this,Ss.MAP,{value:om.map}),Object.defineProperty(this,Ss.SCALAR,{value:cm.string}),Object.defineProperty(this,Ss.SEQ,{value:am.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?lm:null}clone(){let e=Object.create(t.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};Ic.Schema=Cs});var qc=w($c=>{"use strict";var um=P(),Rs=Bt(),Xt=Dt();function fm(t,e){let n=[],i=e.directives===!0;if(e.directives!==!1&&t.directives){let c=t.directives.toString(t);c?(n.push(c),i=!0):t.directives.docStart&&(i=!0)}i&&n.push("---");let r=Rs.createStringifyContext(t,e),{commentString:s}=r.options;if(t.commentBefore){n.length!==1&&n.unshift("");let c=s(t.commentBefore);n.unshift(Xt.indentComment(c,""))}let o=!1,a=null;if(t.contents){if(um.isNode(t.contents)){if(t.contents.spaceBefore&&i&&n.push(""),t.contents.commentBefore){let f=s(t.contents.commentBefore);n.push(Xt.indentComment(f,""))}r.forceBlockIndent=!!t.comment,a=t.contents.comment}let c=a?void 0:()=>o=!0,l=Rs.stringify(t.contents,r,()=>a=null,c);a&&(l+=Xt.lineComment(l,"",s(a))),(l[0]==="|"||l[0]===">")&&n[n.length-1]==="---"?n[n.length-1]=`--- ${l}`:n.push(l)}else n.push(Rs.stringify(t.contents,r));if(t.directives?.docEnd)if(t.comment){let c=s(t.comment);c.includes(` +${s.comment}`:i.comment}i=r}t.items[n]=yi.isPair(i)?i:new as.Pair(i)}}else e("Expected a sequence for this tag");return t}function cc(t,e,n){let{replacer:i}=n,r=new Pp.YAMLSeq(t);r.tag="tag:yaml.org,2002:pairs";let s=0;if(e&&Symbol.iterator in Object(e))for(let o of e){typeof i=="function"&&(o=i.call(e,String(s++),o));let a,c;if(Array.isArray(o))if(o.length===2)a=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)a=l[0],c=o[a];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else a=o;r.items.push(as.createPair(a,c,n))}return r}var Op={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:ac,createNode:cc};vi.createPairs=cc;vi.pairs=Op;vi.resolvePairs=ac});var us=w(ls=>{"use strict";var lc=P(),cs=xe(),Jt=Ie(),Np=je(),uc=bi(),ze=class t extends Np.YAMLSeq{constructor(){super(),this.add=Jt.YAMLMap.prototype.add.bind(this),this.delete=Jt.YAMLMap.prototype.delete.bind(this),this.get=Jt.YAMLMap.prototype.get.bind(this),this.has=Jt.YAMLMap.prototype.has.bind(this),this.set=Jt.YAMLMap.prototype.set.bind(this),this.tag=t.tag}toJSON(e,n){if(!n)return super.toJSON(e);let i=new Map;n?.onCreate&&n.onCreate(i);for(let r of this.items){let s,o;if(lc.isPair(r)?(s=cs.toJS(r.key,"",n),o=cs.toJS(r.value,s,n)):s=cs.toJS(r,"",n),i.has(s))throw new Error("Ordered maps must not include duplicate keys");i.set(s,o)}return i}static from(e,n,i){let r=uc.createPairs(e,n,i),s=new this;return s.items=r.items,s}};ze.tag="tag:yaml.org,2002:omap";var Ap={collection:"seq",identify:t=>t instanceof Map,nodeClass:ze,default:!1,tag:"tag:yaml.org,2002:omap",resolve(t,e){let n=uc.resolvePairs(t,e),i=[];for(let{key:r}of n.items)lc.isScalar(r)&&(i.includes(r.value)?e(`Ordered maps must not include duplicate keys: ${r.value}`):i.push(r.value));return Object.assign(new ze,n)},createNode:(t,e,n)=>ze.from(t,e,n)};ls.YAMLOMap=ze;ls.omap=Ap});var hc=w(fs=>{"use strict";var fc=$();function dc({value:t,source:e},n){return e&&(t?pc:mc).test.test(e)?e:t?n.options.trueStr:n.options.falseStr}var pc={identify:t=>t===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new fc.Scalar(!0),stringify:dc},mc={identify:t=>t===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new fc.Scalar(!1),stringify:dc};fs.falseTag=mc;fs.trueTag=pc});var gc=w(ki=>{"use strict";var Tp=$(),ds=ht(),Ip={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:t=>t.slice(-3).toLowerCase()==="nan"?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:ds.stringifyNumber},jp={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t.replace(/_/g,"")),stringify(t){let e=Number(t.value);return isFinite(e)?e.toExponential():ds.stringifyNumber(t)}},$p={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(t){let e=new Tp.Scalar(parseFloat(t.replace(/_/g,""))),n=t.indexOf(".");if(n!==-1){let i=t.substring(n+1).replace(/_/g,"");i[i.length-1]==="0"&&(e.minFractionDigits=i.length)}return e},stringify:ds.stringifyNumber};ki.float=$p;ki.floatExp=jp;ki.floatNaN=Ip});var yc=w(Gt=>{"use strict";var wc=ht(),Ht=t=>typeof t=="bigint"||Number.isInteger(t);function Si(t,e,n,{intAsBigInt:i}){let r=t[0];if((r==="-"||r==="+")&&(e+=1),t=t.substring(e).replace(/_/g,""),i){switch(n){case 2:t=`0b${t}`;break;case 8:t=`0o${t}`;break;case 16:t=`0x${t}`;break}let o=BigInt(t);return r==="-"?BigInt(-1)*o:o}let s=parseInt(t,n);return r==="-"?-1*s:s}function ps(t,e,n){let{value:i}=t;if(Ht(i)){let r=i.toString(e);return i<0?"-"+n+r.substr(1):n+r}return wc.stringifyNumber(t)}var qp={identify:Ht,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(t,e,n)=>Si(t,2,2,n),stringify:t=>ps(t,2,"0b")},Lp={identify:Ht,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(t,e,n)=>Si(t,1,8,n),stringify:t=>ps(t,8,"0")},Dp={identify:Ht,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(t,e,n)=>Si(t,0,10,n),stringify:wc.stringifyNumber},Mp={identify:Ht,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(t,e,n)=>Si(t,2,16,n),stringify:t=>ps(t,16,"0x")};Gt.int=Dp;Gt.intBin=qp;Gt.intHex=Mp;Gt.intOct=Lp});var hs=w(ms=>{"use strict";var Ri=P(),Ci=Ae(),Ei=Ie(),Xe=class t extends Ei.YAMLMap{constructor(e){super(e),this.tag=t.tag}add(e){let n;Ri.isPair(e)?n=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?n=new Ci.Pair(e.key,null):n=new Ci.Pair(e,null),Ei.findPair(this.items,n.key)||this.items.push(n)}get(e,n){let i=Ei.findPair(this.items,e);return!n&&Ri.isPair(i)?Ri.isScalar(i.key)?i.key.value:i.key:i}set(e,n){if(typeof n!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof n}`);let i=Ei.findPair(this.items,e);i&&!n?this.items.splice(this.items.indexOf(i),1):!i&&n&&this.items.push(new Ci.Pair(e))}toJSON(e,n){return super.toJSON(e,n,Set)}toString(e,n,i){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),n,i);throw new Error("Set items must all have null values")}static from(e,n,i){let{replacer:r}=i,s=new this(e);if(n&&Symbol.iterator in Object(n))for(let o of n)typeof r=="function"&&(o=r.call(n,o,o)),s.items.push(Ci.createPair(o,null,i));return s}};Xe.tag="tag:yaml.org,2002:set";var Fp={collection:"map",identify:t=>t instanceof Set,nodeClass:Xe,default:!1,tag:"tag:yaml.org,2002:set",createNode:(t,e,n)=>Xe.from(t,e,n),resolve(t,e){if(Ri.isMap(t)){if(t.hasAllNullValues(!0))return Object.assign(new Xe,t);e("Set items must all have null values")}else e("Expected a mapping for this tag");return t}};ms.YAMLSet=Xe;ms.set=Fp});var ws=w(_i=>{"use strict";var Wp=ht();function gs(t,e){let n=t[0],i=n==="-"||n==="+"?t.substring(1):t,r=o=>e?BigInt(o):Number(o),s=i.replace(/_/g,"").split(":").reduce((o,a)=>o*r(60)+r(a),r(0));return n==="-"?r(-1)*s:s}function vc(t){let{value:e}=t,n=o=>o;if(typeof e=="bigint")n=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return Wp.stringifyNumber(t);let i="";e<0&&(i="-",e*=n(-1));let r=n(60),s=[e%r];return e<60?s.unshift(0):(e=(e-s[0])/r,s.unshift(e%r),e>=60&&(e=(e-s[0])/r,s.unshift(e))),i+s.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var Bp={identify:t=>typeof t=="bigint"||Number.isInteger(t),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(t,e,{intAsBigInt:n})=>gs(t,n),stringify:vc},Kp={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:t=>gs(t,!1),stringify:vc},bc={identify:t=>t instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(t){let e=t.match(bc.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,n,i,r,s,o,a]=e.map(Number),c=e[7]?Number((e[7]+"00").substr(1,3)):0,l=Date.UTC(n,i-1,r,s||0,o||0,a||0,c),f=e[8];if(f&&f!=="Z"){let u=gs(f,!1);Math.abs(u)<30&&(u*=60),l-=6e4*u}return new Date(l)},stringify:({value:t})=>t?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};_i.floatTime=Kp;_i.intTime=Bp;_i.timestamp=bc});var Cc=w(Sc=>{"use strict";var Up=pt(),Yp=pi(),Vp=mt(),Jp=Yt(),Hp=os(),kc=hc(),ys=gc(),xi=yc(),Gp=si(),zp=us(),Xp=bi(),Qp=hs(),vs=ws(),Zp=[Up.map,Vp.seq,Jp.string,Yp.nullTag,kc.trueTag,kc.falseTag,xi.intBin,xi.intOct,xi.int,xi.intHex,ys.floatNaN,ys.floatExp,ys.float,Hp.binary,Gp.merge,zp.omap,Xp.pairs,Qp.set,vs.intTime,vs.floatTime,vs.timestamp];Sc.schema=Zp});var Ic=w(Ss=>{"use strict";var xc=pt(),em=pi(),Pc=mt(),tm=Yt(),nm=Qr(),bs=es(),ks=ns(),im=nc(),rm=sc(),Oc=os(),zt=si(),Nc=us(),Ac=bi(),Ec=Cc(),Tc=hs(),Pi=ws(),Rc=new Map([["core",im.schema],["failsafe",[xc.map,Pc.seq,tm.string]],["json",rm.schema],["yaml11",Ec.schema],["yaml-1.1",Ec.schema]]),_c={binary:Oc.binary,bool:nm.boolTag,float:bs.float,floatExp:bs.floatExp,floatNaN:bs.floatNaN,floatTime:Pi.floatTime,int:ks.int,intHex:ks.intHex,intOct:ks.intOct,intTime:Pi.intTime,map:xc.map,merge:zt.merge,null:em.nullTag,omap:Nc.omap,pairs:Ac.pairs,seq:Pc.seq,set:Tc.set,timestamp:Pi.timestamp},sm={"tag:yaml.org,2002:binary":Oc.binary,"tag:yaml.org,2002:merge":zt.merge,"tag:yaml.org,2002:omap":Nc.omap,"tag:yaml.org,2002:pairs":Ac.pairs,"tag:yaml.org,2002:set":Tc.set,"tag:yaml.org,2002:timestamp":Pi.timestamp};function om(t,e,n){let i=Rc.get(e);if(i&&!t)return n&&!i.includes(zt.merge)?i.concat(zt.merge):i.slice();let r=i;if(!r)if(Array.isArray(t))r=[];else{let s=Array.from(Rc.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${e}"; use one of ${s} or define customTags array`)}if(Array.isArray(t))for(let s of t)r=r.concat(s);else typeof t=="function"&&(r=t(r.slice()));return n&&(r=r.concat(zt.merge)),r.reduce((s,o)=>{let a=typeof o=="string"?_c[o]:o;if(!a){let c=JSON.stringify(o),l=Object.keys(_c).map(f=>JSON.stringify(f)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return s.includes(a)||s.push(a),s},[])}Ss.coreKnownTags=sm;Ss.getTags=om});var Rs=w(jc=>{"use strict";var Cs=P(),am=pt(),cm=mt(),lm=Yt(),Oi=Ic(),um=(t,e)=>t.keye.key?1:0,Es=class t{constructor({compat:e,customTags:n,merge:i,resolveKnownTags:r,schema:s,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?Oi.getTags(e,"compat"):e?Oi.getTags(null,e):null,this.name=typeof s=="string"&&s||"core",this.knownTags=r?Oi.coreKnownTags:{},this.tags=Oi.getTags(n,this.name,i),this.toStringOptions=a??null,Object.defineProperty(this,Cs.MAP,{value:am.map}),Object.defineProperty(this,Cs.SCALAR,{value:lm.string}),Object.defineProperty(this,Cs.SEQ,{value:cm.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?um:null}clone(){let e=Object.create(t.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};jc.Schema=Es});var qc=w($c=>{"use strict";var fm=P(),_s=Bt(),Xt=Dt();function dm(t,e){let n=[],i=e.directives===!0;if(e.directives!==!1&&t.directives){let c=t.directives.toString(t);c?(n.push(c),i=!0):t.directives.docStart&&(i=!0)}i&&n.push("---");let r=_s.createStringifyContext(t,e),{commentString:s}=r.options;if(t.commentBefore){n.length!==1&&n.unshift("");let c=s(t.commentBefore);n.unshift(Xt.indentComment(c,""))}let o=!1,a=null;if(t.contents){if(fm.isNode(t.contents)){if(t.contents.spaceBefore&&i&&n.push(""),t.contents.commentBefore){let f=s(t.contents.commentBefore);n.push(Xt.indentComment(f,""))}r.forceBlockIndent=!!t.comment,a=t.contents.comment}let c=a?void 0:()=>o=!0,l=_s.stringify(t.contents,r,()=>a=null,c);a&&(l+=Xt.lineComment(l,"",s(a))),(l[0]==="|"||l[0]===">")&&n[n.length-1]==="---"?n[n.length-1]=`--- ${l}`:n.push(l)}else n.push(_s.stringify(t.contents,r));if(t.directives?.docEnd)if(t.comment){let c=s(t.comment);c.includes(` `)?(n.push("..."),n.push(Xt.indentComment(c,""))):n.push(`... ${c}`)}else n.push("...");else{let c=t.comment;c&&o&&(c=c.replace(/^\n+/,"")),c&&((!o||a)&&n[n.length-1]!==""&&n.push(""),n.push(Xt.indentComment(s(c),"")))}return n.join(` `)+` -`}$c.stringifyDocument=fm});var Qt=w(Lc=>{"use strict";var dm=qt(),gt=Gn(),ee=P(),pm=Ne(),mm=xe(),hm=Es(),gm=qc(),_s=Yn(),wm=Ar(),ym=Lt(),xs=Or(),Ps=class t{constructor(e,n,i){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,ee.NODE_TYPE,{value:ee.DOC});let r=null;typeof n=="function"||Array.isArray(n)?r=n:i===void 0&&n&&(i=n,n=void 0);let s=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},i);this.options=s;let{version:o}=s;i?._directives?(this.directives=i._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new xs.Directives({version:o}),this.setSchema(o,i),this.contents=e===void 0?null:this.createNode(e,r,i)}clone(){let e=Object.create(t.prototype,{[ee.NODE_TYPE]:{value:ee.DOC}});return e.commentBefore=this.commentBefore,e.comment=this.comment,e.errors=this.errors.slice(),e.warnings=this.warnings.slice(),e.options=Object.assign({},this.options),this.directives&&(e.directives=this.directives.clone()),e.schema=this.schema.clone(),e.contents=ee.isNode(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){wt(this.contents)&&this.contents.add(e)}addIn(e,n){wt(this.contents)&&this.contents.addIn(e,n)}createAlias(e,n){if(!e.anchor){let i=_s.anchorNames(this);e.anchor=!n||i.has(n)?_s.findNewAnchor(n||"a",i):n}return new dm.Alias(e.anchor)}createNode(e,n,i){let r;if(typeof n=="function")e=n.call({"":e},"",e),r=n;else if(Array.isArray(n)){let h=y=>typeof y=="number"||y instanceof String||y instanceof Number,v=n.filter(h).map(String);v.length>0&&(n=n.concat(v)),r=n}else i===void 0&&n&&(i=n,n=void 0);let{aliasDuplicateObjects:s,anchorPrefix:o,flow:a,keepUndefined:c,onTagObj:l,tag:f}=i??{},{onAnchor:u,setAnchors:d,sourceObjects:m}=_s.createNodeAnchors(this,o||"a"),g={aliasDuplicateObjects:s??!0,keepUndefined:c??!1,onAnchor:u,onTagObj:l,replacer:r,schema:this.schema,sourceObjects:m},p=ym.createNode(e,f,g);return a&&ee.isCollection(p)&&(p.flow=!0),d(),p}createPair(e,n,i={}){let r=this.createNode(e,null,i),s=this.createNode(n,null,i);return new pm.Pair(r,s)}delete(e){return wt(this.contents)?this.contents.delete(e):!1}deleteIn(e){return gt.isEmptyPath(e)?this.contents==null?!1:(this.contents=null,!0):wt(this.contents)?this.contents.deleteIn(e):!1}get(e,n){return ee.isCollection(this.contents)?this.contents.get(e,n):void 0}getIn(e,n){return gt.isEmptyPath(e)?!n&&ee.isScalar(this.contents)?this.contents.value:this.contents:ee.isCollection(this.contents)?this.contents.getIn(e,n):void 0}has(e){return ee.isCollection(this.contents)?this.contents.has(e):!1}hasIn(e){return gt.isEmptyPath(e)?this.contents!==void 0:ee.isCollection(this.contents)?this.contents.hasIn(e):!1}set(e,n){this.contents==null?this.contents=gt.collectionFromPath(this.schema,[e],n):wt(this.contents)&&this.contents.set(e,n)}setIn(e,n){gt.isEmptyPath(e)?this.contents=n:this.contents==null?this.contents=gt.collectionFromPath(this.schema,Array.from(e),n):wt(this.contents)&&this.contents.setIn(e,n)}setSchema(e,n={}){typeof e=="number"&&(e=String(e));let i;switch(e){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new xs.Directives({version:"1.1"}),i={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=e:this.directives=new xs.Directives({version:e}),i={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,i=null;break;default:{let r=JSON.stringify(e);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${r}`)}}if(n.schema instanceof Object)this.schema=n.schema;else if(i)this.schema=new hm.Schema(Object.assign(i,n));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:e,jsonArg:n,mapAsMap:i,maxAliasCount:r,onAnchor:s,reviver:o}={}){let a={anchors:new Map,doc:this,keep:!e,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},c=mm.toJS(this.contents,n??"",a);if(typeof s=="function")for(let{count:l,res:f}of a.anchors.values())s(f,l);return typeof o=="function"?wm.applyReviver(o,{"":c},"",c):c}toJSON(e,n){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:n})}toString(e={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let n=JSON.stringify(e.indent);throw new Error(`"indent" option must be a positive integer, not ${n}`)}return gm.stringifyDocument(this,e)}};function wt(t){if(ee.isCollection(t))return!0;throw new Error("Expected a YAML collection as document contents")}Lc.Document=Ps});var tn=w(en=>{"use strict";var Zt=class extends Error{constructor(e,n,i,r){super(),this.name=e,this.code=i,this.message=r,this.pos=n}},Os=class extends Zt{constructor(e,n,i){super("YAMLParseError",e,n,i)}},As=class extends Zt{constructor(e,n,i){super("YAMLWarning",e,n,i)}},vm=(t,e)=>n=>{if(n.pos[0]===-1)return;n.linePos=n.pos.map(a=>e.linePos(a));let{line:i,col:r}=n.linePos[0];n.message+=` at line ${i}, column ${r}`;let s=r-1,o=t.substring(e.lineStarts[i-1],e.lineStarts[i]).replace(/[\n\r]+$/,"");if(s>=60&&o.length>80){let a=Math.min(s-39,o.length-79);o="…"+o.substring(a),s-=a-1}if(o.length>80&&(o=o.substring(0,79)+"…"),i>1&&/^ *$/.test(o.substring(0,s))){let a=t.substring(e.lineStarts[i-2],e.lineStarts[i-1]);a.length>80&&(a=a.substring(0,79)+`… +`}$c.stringifyDocument=dm});var Qt=w(Lc=>{"use strict";var pm=qt(),gt=Gn(),te=P(),mm=Ae(),hm=xe(),gm=Rs(),wm=qc(),xs=Yn(),ym=Ar(),vm=Lt(),Ps=Nr(),Os=class t{constructor(e,n,i){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,te.NODE_TYPE,{value:te.DOC});let r=null;typeof n=="function"||Array.isArray(n)?r=n:i===void 0&&n&&(i=n,n=void 0);let s=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},i);this.options=s;let{version:o}=s;i?._directives?(this.directives=i._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new Ps.Directives({version:o}),this.setSchema(o,i),this.contents=e===void 0?null:this.createNode(e,r,i)}clone(){let e=Object.create(t.prototype,{[te.NODE_TYPE]:{value:te.DOC}});return e.commentBefore=this.commentBefore,e.comment=this.comment,e.errors=this.errors.slice(),e.warnings=this.warnings.slice(),e.options=Object.assign({},this.options),this.directives&&(e.directives=this.directives.clone()),e.schema=this.schema.clone(),e.contents=te.isNode(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){wt(this.contents)&&this.contents.add(e)}addIn(e,n){wt(this.contents)&&this.contents.addIn(e,n)}createAlias(e,n){if(!e.anchor){let i=xs.anchorNames(this);e.anchor=!n||i.has(n)?xs.findNewAnchor(n||"a",i):n}return new pm.Alias(e.anchor)}createNode(e,n,i){let r;if(typeof n=="function")e=n.call({"":e},"",e),r=n;else if(Array.isArray(n)){let h=y=>typeof y=="number"||y instanceof String||y instanceof Number,v=n.filter(h).map(String);v.length>0&&(n=n.concat(v)),r=n}else i===void 0&&n&&(i=n,n=void 0);let{aliasDuplicateObjects:s,anchorPrefix:o,flow:a,keepUndefined:c,onTagObj:l,tag:f}=i??{},{onAnchor:u,setAnchors:d,sourceObjects:m}=xs.createNodeAnchors(this,o||"a"),g={aliasDuplicateObjects:s??!0,keepUndefined:c??!1,onAnchor:u,onTagObj:l,replacer:r,schema:this.schema,sourceObjects:m},p=vm.createNode(e,f,g);return a&&te.isCollection(p)&&(p.flow=!0),d(),p}createPair(e,n,i={}){let r=this.createNode(e,null,i),s=this.createNode(n,null,i);return new mm.Pair(r,s)}delete(e){return wt(this.contents)?this.contents.delete(e):!1}deleteIn(e){return gt.isEmptyPath(e)?this.contents==null?!1:(this.contents=null,!0):wt(this.contents)?this.contents.deleteIn(e):!1}get(e,n){return te.isCollection(this.contents)?this.contents.get(e,n):void 0}getIn(e,n){return gt.isEmptyPath(e)?!n&&te.isScalar(this.contents)?this.contents.value:this.contents:te.isCollection(this.contents)?this.contents.getIn(e,n):void 0}has(e){return te.isCollection(this.contents)?this.contents.has(e):!1}hasIn(e){return gt.isEmptyPath(e)?this.contents!==void 0:te.isCollection(this.contents)?this.contents.hasIn(e):!1}set(e,n){this.contents==null?this.contents=gt.collectionFromPath(this.schema,[e],n):wt(this.contents)&&this.contents.set(e,n)}setIn(e,n){gt.isEmptyPath(e)?this.contents=n:this.contents==null?this.contents=gt.collectionFromPath(this.schema,Array.from(e),n):wt(this.contents)&&this.contents.setIn(e,n)}setSchema(e,n={}){typeof e=="number"&&(e=String(e));let i;switch(e){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new Ps.Directives({version:"1.1"}),i={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=e:this.directives=new Ps.Directives({version:e}),i={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,i=null;break;default:{let r=JSON.stringify(e);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${r}`)}}if(n.schema instanceof Object)this.schema=n.schema;else if(i)this.schema=new gm.Schema(Object.assign(i,n));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:e,jsonArg:n,mapAsMap:i,maxAliasCount:r,onAnchor:s,reviver:o}={}){let a={anchors:new Map,doc:this,keep:!e,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},c=hm.toJS(this.contents,n??"",a);if(typeof s=="function")for(let{count:l,res:f}of a.anchors.values())s(f,l);return typeof o=="function"?ym.applyReviver(o,{"":c},"",c):c}toJSON(e,n){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:n})}toString(e={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let n=JSON.stringify(e.indent);throw new Error(`"indent" option must be a positive integer, not ${n}`)}return wm.stringifyDocument(this,e)}};function wt(t){if(te.isCollection(t))return!0;throw new Error("Expected a YAML collection as document contents")}Lc.Document=Os});var tn=w(en=>{"use strict";var Zt=class extends Error{constructor(e,n,i,r){super(),this.name=e,this.code=i,this.message=r,this.pos=n}},Ns=class extends Zt{constructor(e,n,i){super("YAMLParseError",e,n,i)}},As=class extends Zt{constructor(e,n,i){super("YAMLWarning",e,n,i)}},bm=(t,e)=>n=>{if(n.pos[0]===-1)return;n.linePos=n.pos.map(a=>e.linePos(a));let{line:i,col:r}=n.linePos[0];n.message+=` at line ${i}, column ${r}`;let s=r-1,o=t.substring(e.lineStarts[i-1],e.lineStarts[i]).replace(/[\n\r]+$/,"");if(s>=60&&o.length>80){let a=Math.min(s-39,o.length-79);o="…"+o.substring(a),s-=a-1}if(o.length>80&&(o=o.substring(0,79)+"…"),i>1&&/^ *$/.test(o.substring(0,s))){let a=t.substring(e.lineStarts[i-2],e.lineStarts[i-1]);a.length>80&&(a=a.substring(0,79)+`… `),o=a+o}if(/[^ ]/.test(o)){let a=1,c=n.linePos[1];c?.line===i&&c.col>r&&(a=Math.max(1,Math.min(c.col-r,80-s)));let l=" ".repeat(s)+"^".repeat(a);n.message+=`: ${o} ${l} -`}};en.YAMLError=Zt;en.YAMLParseError=Os;en.YAMLWarning=As;en.prettifyError=vm});var nn=w(Dc=>{"use strict";function bm(t,{flow:e,indicator:n,next:i,offset:r,onError:s,parentIndent:o,startOnNewline:a}){let c=!1,l=a,f=a,u="",d="",m=!1,g=!1,p=null,h=null,v=null,y=null,S=null,R=null,_=null;for(let k of t)switch(g&&(k.type!=="space"&&k.type!=="newline"&&k.type!=="comma"&&s(k.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),g=!1),p&&(l&&k.type!=="comment"&&k.type!=="newline"&&s(p,"TAB_AS_INDENT","Tabs are not allowed as indentation"),p=null),k.type){case"space":!e&&(n!=="doc-start"||i?.type!=="flow-collection")&&k.source.includes(" ")&&(p=k),f=!0;break;case"comment":{f||s(k,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let L=k.source.substring(1)||" ";u?u+=d+L:u=L,d="",l=!1;break}case"newline":l?u?u+=k.source:(!R||n!=="seq-item-ind")&&(c=!0):d+=k.source,l=!0,m=!0,(h||v)&&(y=k),f=!0;break;case"anchor":h&&s(k,"MULTIPLE_ANCHORS","A node can have at most one anchor"),k.source.endsWith(":")&&s(k.offset+k.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),h=k,_??(_=k.offset),l=!1,f=!1,g=!0;break;case"tag":{v&&s(k,"MULTIPLE_TAGS","A node can have at most one tag"),v=k,_??(_=k.offset),l=!1,f=!1,g=!0;break}case n:(h||v)&&s(k,"BAD_PROP_ORDER",`Anchors and tags must be after the ${k.source} indicator`),R&&s(k,"UNEXPECTED_TOKEN",`Unexpected ${k.source} in ${e??"collection"}`),R=k,l=n==="seq-item-ind"||n==="explicit-key-ind",f=!1;break;case"comma":if(e){S&&s(k,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),S=k,l=!1,f=!1;break}default:s(k,"UNEXPECTED_TOKEN",`Unexpected ${k.type} token`),l=!1,f=!1}let E=t[t.length-1],A=E?E.offset+E.source.length:r;return g&&i&&i.type!=="space"&&i.type!=="newline"&&i.type!=="comma"&&(i.type!=="scalar"||i.source!=="")&&s(i.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),p&&(l&&p.indent<=o||i?.type==="block-map"||i?.type==="block-seq")&&s(p,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:S,found:R,spaceBefore:c,comment:u,hasNewline:m,anchor:h,tag:v,newlineAfterProp:y,end:A,start:_??A}}Dc.resolveProps=bm});var Ai=w(Mc=>{"use strict";function Ns(t){if(!t)return null;switch(t.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(t.source.includes(` -`))return!0;if(t.end){for(let e of t.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(let e of t.items){for(let n of e.start)if(n.type==="newline")return!0;if(e.sep){for(let n of e.sep)if(n.type==="newline")return!0}if(Ns(e.key)||Ns(e.value))return!0}return!1;default:return!0}}Mc.containsNewline=Ns});var Ts=w(Fc=>{"use strict";var km=Ai();function Sm(t,e,n){if(e?.type==="flow-collection"){let i=e.end[0];i.indent===t&&(i.source==="]"||i.source==="}")&&km.containsNewline(e)&&n(i,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Fc.flowIndentCheck=Sm});var js=w(Bc=>{"use strict";var Wc=P();function Cm(t,e,n){let{uniqueKeys:i}=t.options;if(i===!1)return!1;let r=typeof i=="function"?i:(s,o)=>s===o||Wc.isScalar(s)&&Wc.isScalar(o)&&s.value===o.value;return e.some(s=>r(s.key,n))}Bc.mapIncludes=Cm});var Hc=w(Jc=>{"use strict";var Kc=Ne(),Em=je(),Uc=nn(),Rm=Ai(),Yc=Ts(),_m=js(),Vc="All mapping items must start at the same column";function xm({composeNode:t,composeEmptyNode:e},n,i,r,s){let o=s?.nodeClass??Em.YAMLMap,a=new o(n.schema);n.atRoot&&(n.atRoot=!1);let c=i.offset,l=null;for(let f of i.items){let{start:u,key:d,sep:m,value:g}=f,p=Uc.resolveProps(u,{indicator:"explicit-key-ind",next:d??m?.[0],offset:c,onError:r,parentIndent:i.indent,startOnNewline:!0}),h=!p.found;if(h){if(d&&(d.type==="block-seq"?r(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in d&&d.indent!==i.indent&&r(c,"BAD_INDENT",Vc)),!p.anchor&&!p.tag&&!m){l=p.end,p.comment&&(a.comment?a.comment+=` -`+p.comment:a.comment=p.comment);continue}(p.newlineAfterProp||Rm.containsNewline(d))&&r(d??u[u.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else p.found?.indent!==i.indent&&r(c,"BAD_INDENT",Vc);n.atKey=!0;let v=p.end,y=d?t(n,d,p,r):e(n,v,u,null,p,r);n.schema.compat&&Yc.flowIndentCheck(i.indent,d,r),n.atKey=!1,_m.mapIncludes(n,a.items,y)&&r(v,"DUPLICATE_KEY","Map keys must be unique");let S=Uc.resolveProps(m??[],{indicator:"map-value-ind",next:g,offset:y.range[2],onError:r,parentIndent:i.indent,startOnNewline:!d||d.type==="block-scalar"});if(c=S.end,S.found){h&&(g?.type==="block-map"&&!S.hasNewline&&r(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),n.options.strict&&p.start{"use strict";var Pm=Ie(),Om=nn(),Am=Ts();function Nm({composeNode:t,composeEmptyNode:e},n,i,r,s){let o=s?.nodeClass??Pm.YAMLSeq,a=new o(n.schema);n.atRoot&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let c=i.offset,l=null;for(let{start:f,value:u}of i.items){let d=Om.resolveProps(f,{indicator:"seq-item-ind",next:u,offset:c,onError:r,parentIndent:i.indent,startOnNewline:!0});if(!d.found)if(d.anchor||d.tag||u)u?.type==="block-seq"?r(d.end,"BAD_INDENT","All sequence items must start at the same column"):r(c,"MISSING_CHAR","Sequence item without - indicator");else{l=d.end,d.comment&&(a.comment=d.comment);continue}let m=u?t(n,u,d,r):e(n,d.end,f,null,d,r);n.schema.compat&&Am.flowIndentCheck(i.indent,u,r),c=m.range[2],a.items.push(m)}return a.range=[i.offset,c,l??c],a}Gc.resolveBlockSeq=Nm});var yt=w(Xc=>{"use strict";function Tm(t,e,n,i){let r="";if(t){let s=!1,o="";for(let a of t){let{source:c,type:l}=a;switch(l){case"space":s=!0;break;case"comment":{n&&!s&&i(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let f=c.substring(1)||" ";r?r+=o+f:r=f,o="";break}case"newline":r&&(o+=c),s=!0;break;default:i(a,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}e+=c.length}}return{comment:r,offset:e}}Xc.resolveEnd=Tm});var tl=w(el=>{"use strict";var jm=P(),Im=Ne(),Qc=je(),$m=Ie(),qm=yt(),Zc=nn(),Lm=Ai(),Dm=js(),Is="Block collections are not allowed within flow collections",$s=t=>t&&(t.type==="block-map"||t.type==="block-seq");function Mm({composeNode:t,composeEmptyNode:e},n,i,r,s){let o=i.start.source==="{",a=o?"flow map":"flow sequence",c=s?.nodeClass??(o?Qc.YAMLMap:$m.YAMLSeq),l=new c(n.schema);l.flow=!0;let f=n.atRoot;f&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let u=i.offset+i.start.source.length;for(let h=0;h0){let h=qm.resolveEnd(g,p,n.options.strict,r);h.comment&&(l.comment?l.comment+=` -`+h.comment:l.comment=h.comment),l.range=[i.offset,p,h.offset]}else l.range=[i.offset,p,p];return l}el.resolveFlowCollection=Mm});var il=w(nl=>{"use strict";var Fm=P(),Wm=$(),Bm=je(),Km=Ie(),Um=Hc(),Ym=zc(),Vm=tl();function qs(t,e,n,i,r,s){let o=n.type==="block-map"?Um.resolveBlockMap(t,e,n,i,s):n.type==="block-seq"?Ym.resolveBlockSeq(t,e,n,i,s):Vm.resolveFlowCollection(t,e,n,i,s),a=o.constructor;return r==="!"||r===a.tagName?(o.tag=a.tagName,o):(r&&(o.tag=r),o)}function Jm(t,e,n,i,r){let s=i.tag,o=s?e.directives.tagName(s.source,d=>r(s,"TAG_RESOLVE_FAILED",d)):null;if(n.type==="block-seq"){let{anchor:d,newlineAfterProp:m}=i,g=d&&s?d.offset>s.offset?d:s:d??s;g&&(!m||m.offsetd.tag===o&&d.collection===a);if(!c){let d=e.schema.knownTags[o];if(d?.collection===a)e.schema.tags.push(Object.assign({},d,{default:!1})),c=d;else return d?r(s,"BAD_COLLECTION_TYPE",`${d.tag} used for ${a} collection, but expects ${d.collection??"scalar"}`,!0):r(s,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),qs(t,e,n,r,o)}let l=qs(t,e,n,r,o,c),f=c.resolve?.(l,d=>r(s,"TAG_RESOLVE_FAILED",d),e.options)??l,u=Fm.isNode(f)?f:new Wm.Scalar(f);return u.range=l.range,u.tag=o,c?.format&&(u.format=c.format),u}nl.composeCollection=Jm});var Ds=w(rl=>{"use strict";var Ls=$();function Hm(t,e,n){let i=e.offset,r=Gm(e,t.options.strict,n);if(!r)return{value:"",type:null,comment:"",range:[i,i,i]};let s=r.mode===">"?Ls.Scalar.BLOCK_FOLDED:Ls.Scalar.BLOCK_LITERAL,o=e.source?zm(e.source):[],a=o.length;for(let p=o.length-1;p>=0;--p){let h=o[p][1];if(h===""||h==="\r")a=p;else break}if(a===0){let p=r.chomp==="+"&&o.length>0?` +`}};en.YAMLError=Zt;en.YAMLParseError=Ns;en.YAMLWarning=As;en.prettifyError=bm});var nn=w(Dc=>{"use strict";function km(t,{flow:e,indicator:n,next:i,offset:r,onError:s,parentIndent:o,startOnNewline:a}){let c=!1,l=a,f=a,u="",d="",m=!1,g=!1,p=null,h=null,v=null,y=null,S=null,R=null,_=null;for(let k of t)switch(g&&(k.type!=="space"&&k.type!=="newline"&&k.type!=="comma"&&s(k.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),g=!1),p&&(l&&k.type!=="comment"&&k.type!=="newline"&&s(p,"TAB_AS_INDENT","Tabs are not allowed as indentation"),p=null),k.type){case"space":!e&&(n!=="doc-start"||i?.type!=="flow-collection")&&k.source.includes(" ")&&(p=k),f=!0;break;case"comment":{f||s(k,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let L=k.source.substring(1)||" ";u?u+=d+L:u=L,d="",l=!1;break}case"newline":l?u?u+=k.source:(!R||n!=="seq-item-ind")&&(c=!0):d+=k.source,l=!0,m=!0,(h||v)&&(y=k),f=!0;break;case"anchor":h&&s(k,"MULTIPLE_ANCHORS","A node can have at most one anchor"),k.source.endsWith(":")&&s(k.offset+k.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),h=k,_??(_=k.offset),l=!1,f=!1,g=!0;break;case"tag":{v&&s(k,"MULTIPLE_TAGS","A node can have at most one tag"),v=k,_??(_=k.offset),l=!1,f=!1,g=!0;break}case n:(h||v)&&s(k,"BAD_PROP_ORDER",`Anchors and tags must be after the ${k.source} indicator`),R&&s(k,"UNEXPECTED_TOKEN",`Unexpected ${k.source} in ${e??"collection"}`),R=k,l=n==="seq-item-ind"||n==="explicit-key-ind",f=!1;break;case"comma":if(e){S&&s(k,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),S=k,l=!1,f=!1;break}default:s(k,"UNEXPECTED_TOKEN",`Unexpected ${k.type} token`),l=!1,f=!1}let E=t[t.length-1],N=E?E.offset+E.source.length:r;return g&&i&&i.type!=="space"&&i.type!=="newline"&&i.type!=="comma"&&(i.type!=="scalar"||i.source!=="")&&s(i.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),p&&(l&&p.indent<=o||i?.type==="block-map"||i?.type==="block-seq")&&s(p,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:S,found:R,spaceBefore:c,comment:u,hasNewline:m,anchor:h,tag:v,newlineAfterProp:y,end:N,start:_??N}}Dc.resolveProps=km});var Ni=w(Mc=>{"use strict";function Ts(t){if(!t)return null;switch(t.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(t.source.includes(` +`))return!0;if(t.end){for(let e of t.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(let e of t.items){for(let n of e.start)if(n.type==="newline")return!0;if(e.sep){for(let n of e.sep)if(n.type==="newline")return!0}if(Ts(e.key)||Ts(e.value))return!0}return!1;default:return!0}}Mc.containsNewline=Ts});var Is=w(Fc=>{"use strict";var Sm=Ni();function Cm(t,e,n){if(e?.type==="flow-collection"){let i=e.end[0];i.indent===t&&(i.source==="]"||i.source==="}")&&Sm.containsNewline(e)&&n(i,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Fc.flowIndentCheck=Cm});var js=w(Bc=>{"use strict";var Wc=P();function Em(t,e,n){let{uniqueKeys:i}=t.options;if(i===!1)return!1;let r=typeof i=="function"?i:(s,o)=>s===o||Wc.isScalar(s)&&Wc.isScalar(o)&&s.value===o.value;return e.some(s=>r(s.key,n))}Bc.mapIncludes=Em});var Hc=w(Jc=>{"use strict";var Kc=Ae(),Rm=Ie(),Uc=nn(),_m=Ni(),Yc=Is(),xm=js(),Vc="All mapping items must start at the same column";function Pm({composeNode:t,composeEmptyNode:e},n,i,r,s){let o=s?.nodeClass??Rm.YAMLMap,a=new o(n.schema);n.atRoot&&(n.atRoot=!1);let c=i.offset,l=null;for(let f of i.items){let{start:u,key:d,sep:m,value:g}=f,p=Uc.resolveProps(u,{indicator:"explicit-key-ind",next:d??m?.[0],offset:c,onError:r,parentIndent:i.indent,startOnNewline:!0}),h=!p.found;if(h){if(d&&(d.type==="block-seq"?r(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in d&&d.indent!==i.indent&&r(c,"BAD_INDENT",Vc)),!p.anchor&&!p.tag&&!m){l=p.end,p.comment&&(a.comment?a.comment+=` +`+p.comment:a.comment=p.comment);continue}(p.newlineAfterProp||_m.containsNewline(d))&&r(d??u[u.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else p.found?.indent!==i.indent&&r(c,"BAD_INDENT",Vc);n.atKey=!0;let v=p.end,y=d?t(n,d,p,r):e(n,v,u,null,p,r);n.schema.compat&&Yc.flowIndentCheck(i.indent,d,r),n.atKey=!1,xm.mapIncludes(n,a.items,y)&&r(v,"DUPLICATE_KEY","Map keys must be unique");let S=Uc.resolveProps(m??[],{indicator:"map-value-ind",next:g,offset:y.range[2],onError:r,parentIndent:i.indent,startOnNewline:!d||d.type==="block-scalar"});if(c=S.end,S.found){h&&(g?.type==="block-map"&&!S.hasNewline&&r(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),n.options.strict&&p.start{"use strict";var Om=je(),Nm=nn(),Am=Is();function Tm({composeNode:t,composeEmptyNode:e},n,i,r,s){let o=s?.nodeClass??Om.YAMLSeq,a=new o(n.schema);n.atRoot&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let c=i.offset,l=null;for(let{start:f,value:u}of i.items){let d=Nm.resolveProps(f,{indicator:"seq-item-ind",next:u,offset:c,onError:r,parentIndent:i.indent,startOnNewline:!0});if(!d.found)if(d.anchor||d.tag||u)u?.type==="block-seq"?r(d.end,"BAD_INDENT","All sequence items must start at the same column"):r(c,"MISSING_CHAR","Sequence item without - indicator");else{l=d.end,d.comment&&(a.comment=d.comment);continue}let m=u?t(n,u,d,r):e(n,d.end,f,null,d,r);n.schema.compat&&Am.flowIndentCheck(i.indent,u,r),c=m.range[2],a.items.push(m)}return a.range=[i.offset,c,l??c],a}Gc.resolveBlockSeq=Tm});var yt=w(Xc=>{"use strict";function Im(t,e,n,i){let r="";if(t){let s=!1,o="";for(let a of t){let{source:c,type:l}=a;switch(l){case"space":s=!0;break;case"comment":{n&&!s&&i(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let f=c.substring(1)||" ";r?r+=o+f:r=f,o="";break}case"newline":r&&(o+=c),s=!0;break;default:i(a,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}e+=c.length}}return{comment:r,offset:e}}Xc.resolveEnd=Im});var tl=w(el=>{"use strict";var jm=P(),$m=Ae(),Qc=Ie(),qm=je(),Lm=yt(),Zc=nn(),Dm=Ni(),Mm=js(),$s="Block collections are not allowed within flow collections",qs=t=>t&&(t.type==="block-map"||t.type==="block-seq");function Fm({composeNode:t,composeEmptyNode:e},n,i,r,s){let o=i.start.source==="{",a=o?"flow map":"flow sequence",c=s?.nodeClass??(o?Qc.YAMLMap:qm.YAMLSeq),l=new c(n.schema);l.flow=!0;let f=n.atRoot;f&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let u=i.offset+i.start.source.length;for(let h=0;h0){let h=Lm.resolveEnd(g,p,n.options.strict,r);h.comment&&(l.comment?l.comment+=` +`+h.comment:l.comment=h.comment),l.range=[i.offset,p,h.offset]}else l.range=[i.offset,p,p];return l}el.resolveFlowCollection=Fm});var il=w(nl=>{"use strict";var Wm=P(),Bm=$(),Km=Ie(),Um=je(),Ym=Hc(),Vm=zc(),Jm=tl();function Ls(t,e,n,i,r,s){let o=n.type==="block-map"?Ym.resolveBlockMap(t,e,n,i,s):n.type==="block-seq"?Vm.resolveBlockSeq(t,e,n,i,s):Jm.resolveFlowCollection(t,e,n,i,s),a=o.constructor;return r==="!"||r===a.tagName?(o.tag=a.tagName,o):(r&&(o.tag=r),o)}function Hm(t,e,n,i,r){let s=i.tag,o=s?e.directives.tagName(s.source,d=>r(s,"TAG_RESOLVE_FAILED",d)):null;if(n.type==="block-seq"){let{anchor:d,newlineAfterProp:m}=i,g=d&&s?d.offset>s.offset?d:s:d??s;g&&(!m||m.offsetd.tag===o&&d.collection===a);if(!c){let d=e.schema.knownTags[o];if(d?.collection===a)e.schema.tags.push(Object.assign({},d,{default:!1})),c=d;else return d?r(s,"BAD_COLLECTION_TYPE",`${d.tag} used for ${a} collection, but expects ${d.collection??"scalar"}`,!0):r(s,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),Ls(t,e,n,r,o)}let l=Ls(t,e,n,r,o,c),f=c.resolve?.(l,d=>r(s,"TAG_RESOLVE_FAILED",d),e.options)??l,u=Wm.isNode(f)?f:new Bm.Scalar(f);return u.range=l.range,u.tag=o,c?.format&&(u.format=c.format),u}nl.composeCollection=Hm});var Ms=w(rl=>{"use strict";var Ds=$();function Gm(t,e,n){let i=e.offset,r=zm(e,t.options.strict,n);if(!r)return{value:"",type:null,comment:"",range:[i,i,i]};let s=r.mode===">"?Ds.Scalar.BLOCK_FOLDED:Ds.Scalar.BLOCK_LITERAL,o=e.source?Xm(e.source):[],a=o.length;for(let p=o.length-1;p>=0;--p){let h=o[p][1];if(h===""||h==="\r")a=p;else break}if(a===0){let p=r.chomp==="+"&&o.length>0?` `.repeat(Math.max(1,o.length-1)):"",h=i+r.length;return e.source&&(h+=e.source.length),{value:p,type:s,comment:r.comment,range:[i,h,h]}}let c=e.indent+r.indent,l=e.offset+r.length,f=0;for(let p=0;pc&&(c=h.length);else{h.length=a;--p)o[p][0].length>c&&(a=p+1);let u="",d="",m=!1;for(let p=0;pc||v[0]===" "?(d===" "?d=` `:!m&&d===` `&&(d=` @@ -84,46 +84,46 @@ ${l} `+o[p][0].slice(c);u[u.length-1]!==` `&&(u+=` `);break;default:u+=` -`}let g=i+r.length+e.source.length;return{value:u,type:s,comment:r.comment,range:[i,g,g]}}function Gm({offset:t,props:e},n,i){if(e[0].type!=="block-scalar-header")return i(e[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:r}=e[0],s=r[0],o=0,a="",c=-1;for(let d=1;d{"use strict";var Ms=$(),Xm=yt();function Qm(t,e,n){let{offset:i,type:r,source:s,end:o}=t,a,c,l=(d,m,g)=>n(i+d,m,g);switch(r){case"scalar":a=Ms.Scalar.PLAIN,c=Zm(s,l);break;case"single-quoted-scalar":a=Ms.Scalar.QUOTE_SINGLE,c=eh(s,l);break;case"double-quoted-scalar":a=Ms.Scalar.QUOTE_DOUBLE,c=th(s,l);break;default:return n(t,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${r}`),{value:"",type:null,comment:"",range:[i,i+s.length,i+s.length]}}let f=i+s.length,u=Xm.resolveEnd(o,f,e,n);return{value:c,type:a,comment:u.comment,range:[i,f,u.offset]}}function Zm(t,e){let n="";switch(t[0]){case" ":n="a tab character";break;case",":n="flow indicator character ,";break;case"%":n="directive indicator character %";break;case"|":case">":{n=`block scalar indicator ${t[0]}`;break}case"@":case"`":{n=`reserved character ${t[0]}`;break}}return n&&e(0,"BAD_SCALAR_START",`Plain value cannot start with ${n}`),sl(t)}function eh(t,e){return(t[t.length-1]!=="'"||t.length===1)&&e(t.length,"MISSING_CHAR","Missing closing 'quote"),sl(t.slice(1,-1)).replace(/''/g,"'")}function sl(t){let e,n;try{e=new RegExp(`(.*?)(?{"use strict";var Fs=$(),Qm=yt();function Zm(t,e,n){let{offset:i,type:r,source:s,end:o}=t,a,c,l=(d,m,g)=>n(i+d,m,g);switch(r){case"scalar":a=Fs.Scalar.PLAIN,c=eh(s,l);break;case"single-quoted-scalar":a=Fs.Scalar.QUOTE_SINGLE,c=th(s,l);break;case"double-quoted-scalar":a=Fs.Scalar.QUOTE_DOUBLE,c=nh(s,l);break;default:return n(t,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${r}`),{value:"",type:null,comment:"",range:[i,i+s.length,i+s.length]}}let f=i+s.length,u=Qm.resolveEnd(o,f,e,n);return{value:c,type:a,comment:u.comment,range:[i,f,u.offset]}}function eh(t,e){let n="";switch(t[0]){case" ":n="a tab character";break;case",":n="flow indicator character ,";break;case"%":n="directive indicator character %";break;case"|":case">":{n=`block scalar indicator ${t[0]}`;break}case"@":case"`":{n=`reserved character ${t[0]}`;break}}return n&&e(0,"BAD_SCALAR_START",`Plain value cannot start with ${n}`),sl(t)}function th(t,e){return(t[t.length-1]!=="'"||t.length===1)&&e(t.length,"MISSING_CHAR","Missing closing 'quote"),sl(t.slice(1,-1)).replace(/''/g,"'")}function sl(t){let e,n;try{e=new RegExp(`(.*?)(?s?t.slice(s,i+1):r)}else n+=r}return(t[t.length-1]!=='"'||t.length===1)&&e(t.length,"MISSING_CHAR",'Missing closing "quote'),n}function nh(t,e){let n="",i=t[e+1];for(;(i===" "||i===" "||i===` +`)&&(n+=i>s?t.slice(s,i+1):r)}else n+=r}return(t[t.length-1]!=='"'||t.length===1)&&e(t.length,"MISSING_CHAR",'Missing closing "quote'),n}function ih(t,e){let n="",i=t[e+1];for(;(i===" "||i===" "||i===` `||i==="\r")&&!(i==="\r"&&t[e+2]!==` `);)i===` `&&(n+=` -`),e+=1,i=t[e+1];return n||(n=" "),{fold:n,offset:e}}var ih={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:` -`,r:"\r",t:" ",v:"\v",N:"…",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function rh(t,e,n,i){let r=t.substr(e,n),o=r.length===n&&/^[0-9a-fA-F]+$/.test(r)?parseInt(r,16):NaN;try{return String.fromCodePoint(o)}catch{let a=t.substr(e-2,n+2);return i(e-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),a}}ol.resolveFlowScalar=Qm});var ll=w(cl=>{"use strict";var Qe=P(),al=$(),sh=Ds(),oh=Fs();function ah(t,e,n,i){let{value:r,type:s,comment:o,range:a}=e.type==="block-scalar"?sh.resolveBlockScalar(t,e,i):oh.resolveFlowScalar(e,t.options.strict,i),c=n?t.directives.tagName(n.source,u=>i(n,"TAG_RESOLVE_FAILED",u)):null,l;t.options.stringKeys&&t.atKey?l=t.schema[Qe.SCALAR]:c?l=ch(t.schema,r,c,n,i):e.type==="scalar"?l=lh(t,r,e,i):l=t.schema[Qe.SCALAR];let f;try{let u=l.resolve(r,d=>i(n??e,"TAG_RESOLVE_FAILED",d),t.options);f=Qe.isScalar(u)?u:new al.Scalar(u)}catch(u){let d=u instanceof Error?u.message:String(u);i(n??e,"TAG_RESOLVE_FAILED",d),f=new al.Scalar(r)}return f.range=a,f.source=r,s&&(f.type=s),c&&(f.tag=c),l.format&&(f.format=l.format),o&&(f.comment=o),f}function ch(t,e,n,i,r){if(n==="!")return t[Qe.SCALAR];let s=[];for(let a of t.tags)if(!a.collection&&a.tag===n)if(a.default&&a.test)s.push(a);else return a;for(let a of s)if(a.test?.test(e))return a;let o=t.knownTags[n];return o&&!o.collection?(t.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(r(i,"TAG_RESOLVE_FAILED",`Unresolved tag: ${n}`,n!=="tag:yaml.org,2002:str"),t[Qe.SCALAR])}function lh({atKey:t,directives:e,schema:n},i,r,s){let o=n.tags.find(a=>(a.default===!0||t&&a.default==="key")&&a.test?.test(i))||n[Qe.SCALAR];if(n.compat){let a=n.compat.find(c=>c.default&&c.test?.test(i))??n[Qe.SCALAR];if(o.tag!==a.tag){let c=e.tagString(o.tag),l=e.tagString(a.tag),f=`Value may be parsed as either ${c} or ${l}`;s(r,"TAG_RESOLVE_FAILED",f,!0)}}return o}cl.composeScalar=ah});var fl=w(ul=>{"use strict";function uh(t,e,n){if(e){n??(n=e.length);for(let i=n-1;i>=0;--i){let r=e[i];switch(r.type){case"space":case"comment":case"newline":t-=r.source.length;continue}for(r=e[++i];r?.type==="space";)t+=r.source.length,r=e[++i];break}}return t}ul.emptyScalarPosition=uh});var ml=w(Bs=>{"use strict";var fh=qt(),dh=P(),ph=il(),dl=ll(),mh=yt(),hh=fl(),gh={composeNode:pl,composeEmptyNode:Ws};function pl(t,e,n,i){let r=t.atKey,{spaceBefore:s,comment:o,anchor:a,tag:c}=n,l,f=!0;switch(e.type){case"alias":l=wh(t,e,i),(a||c)&&i(e,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=dl.composeScalar(t,e,c,i),a&&(l.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=ph.composeCollection(gh,t,e,n,i),a&&(l.anchor=a.source.substring(1))}catch(u){let d=u instanceof Error?u.message:String(u);i(e,"RESOURCE_EXHAUSTION",d)}break;default:{let u=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;i(e,"UNEXPECTED_TOKEN",u),f=!1}}return l??(l=Ws(t,e.offset,void 0,null,n,i)),a&&l.anchor===""&&i(a,"BAD_ALIAS","Anchor cannot be an empty string"),r&&t.options.stringKeys&&(!dh.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&i(c??e,"NON_STRING_KEY","With stringKeys, all keys must be strings"),s&&(l.spaceBefore=!0),o&&(e.type==="scalar"&&e.source===""?l.comment=o:l.commentBefore=o),t.options.keepSourceTokens&&f&&(l.srcToken=e),l}function Ws(t,e,n,i,{spaceBefore:r,comment:s,anchor:o,tag:a,end:c},l){let f={type:"scalar",offset:hh.emptyScalarPosition(e,n,i),indent:-1,source:""},u=dl.composeScalar(t,f,a,l);return o&&(u.anchor=o.source.substring(1),u.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),r&&(u.spaceBefore=!0),s&&(u.comment=s,u.range[2]=c),u}function wh({options:t},{offset:e,source:n,end:i},r){let s=new fh.Alias(n.substring(1));s.source===""&&r(e,"BAD_ALIAS","Alias cannot be an empty string"),s.source.endsWith(":")&&r(e+n.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=e+n.length,a=mh.resolveEnd(i,o,t.strict,r);return s.range=[e,o,a.offset],a.comment&&(s.comment=a.comment),s}Bs.composeEmptyNode=Ws;Bs.composeNode=pl});var wl=w(gl=>{"use strict";var yh=Qt(),hl=ml(),vh=yt(),bh=nn();function kh(t,e,{offset:n,start:i,value:r,end:s},o){let a=Object.assign({_directives:e},t),c=new yh.Document(void 0,a),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},f=bh.resolveProps(i,{indicator:"doc-start",next:r??s?.[0],offset:n,onError:o,parentIndent:0,startOnNewline:!0});f.found&&(c.directives.docStart=!0,r&&(r.type==="block-map"||r.type==="block-seq")&&!f.hasNewline&&o(f.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=r?hl.composeNode(l,r,f,o):hl.composeEmptyNode(l,f.end,i,null,f,o);let u=c.contents.range[2],d=vh.resolveEnd(s,u,!1,o);return d.comment&&(c.comment=d.comment),c.range=[n,u,d.offset],c}gl.composeDoc=kh});var Us=w(bl=>{"use strict";var Sh=Fn("process"),Ch=Or(),Eh=Qt(),rn=tn(),yl=P(),Rh=wl(),_h=yt();function sn(t){if(typeof t=="number")return[t,t+1];if(Array.isArray(t))return t.length===2?t:[t[0],t[1]];let{offset:e,source:n}=t;return[e,e+(typeof n=="string"?n.length:1)]}function vl(t){let e="",n=!1,i=!1;for(let r=0;r{"use strict";var Qe=P(),al=$(),oh=Ms(),ah=Ws();function ch(t,e,n,i){let{value:r,type:s,comment:o,range:a}=e.type==="block-scalar"?oh.resolveBlockScalar(t,e,i):ah.resolveFlowScalar(e,t.options.strict,i),c=n?t.directives.tagName(n.source,u=>i(n,"TAG_RESOLVE_FAILED",u)):null,l;t.options.stringKeys&&t.atKey?l=t.schema[Qe.SCALAR]:c?l=lh(t.schema,r,c,n,i):e.type==="scalar"?l=uh(t,r,e,i):l=t.schema[Qe.SCALAR];let f;try{let u=l.resolve(r,d=>i(n??e,"TAG_RESOLVE_FAILED",d),t.options);f=Qe.isScalar(u)?u:new al.Scalar(u)}catch(u){let d=u instanceof Error?u.message:String(u);i(n??e,"TAG_RESOLVE_FAILED",d),f=new al.Scalar(r)}return f.range=a,f.source=r,s&&(f.type=s),c&&(f.tag=c),l.format&&(f.format=l.format),o&&(f.comment=o),f}function lh(t,e,n,i,r){if(n==="!")return t[Qe.SCALAR];let s=[];for(let a of t.tags)if(!a.collection&&a.tag===n)if(a.default&&a.test)s.push(a);else return a;for(let a of s)if(a.test?.test(e))return a;let o=t.knownTags[n];return o&&!o.collection?(t.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(r(i,"TAG_RESOLVE_FAILED",`Unresolved tag: ${n}`,n!=="tag:yaml.org,2002:str"),t[Qe.SCALAR])}function uh({atKey:t,directives:e,schema:n},i,r,s){let o=n.tags.find(a=>(a.default===!0||t&&a.default==="key")&&a.test?.test(i))||n[Qe.SCALAR];if(n.compat){let a=n.compat.find(c=>c.default&&c.test?.test(i))??n[Qe.SCALAR];if(o.tag!==a.tag){let c=e.tagString(o.tag),l=e.tagString(a.tag),f=`Value may be parsed as either ${c} or ${l}`;s(r,"TAG_RESOLVE_FAILED",f,!0)}}return o}cl.composeScalar=ch});var fl=w(ul=>{"use strict";function fh(t,e,n){if(e){n??(n=e.length);for(let i=n-1;i>=0;--i){let r=e[i];switch(r.type){case"space":case"comment":case"newline":t-=r.source.length;continue}for(r=e[++i];r?.type==="space";)t+=r.source.length,r=e[++i];break}}return t}ul.emptyScalarPosition=fh});var ml=w(Ks=>{"use strict";var dh=qt(),ph=P(),mh=il(),dl=ll(),hh=yt(),gh=fl(),wh={composeNode:pl,composeEmptyNode:Bs};function pl(t,e,n,i){let r=t.atKey,{spaceBefore:s,comment:o,anchor:a,tag:c}=n,l,f=!0;switch(e.type){case"alias":l=yh(t,e,i),(a||c)&&i(e,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=dl.composeScalar(t,e,c,i),a&&(l.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=mh.composeCollection(wh,t,e,n,i),a&&(l.anchor=a.source.substring(1))}catch(u){let d=u instanceof Error?u.message:String(u);i(e,"RESOURCE_EXHAUSTION",d)}break;default:{let u=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;i(e,"UNEXPECTED_TOKEN",u),f=!1}}return l??(l=Bs(t,e.offset,void 0,null,n,i)),a&&l.anchor===""&&i(a,"BAD_ALIAS","Anchor cannot be an empty string"),r&&t.options.stringKeys&&(!ph.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&i(c??e,"NON_STRING_KEY","With stringKeys, all keys must be strings"),s&&(l.spaceBefore=!0),o&&(e.type==="scalar"&&e.source===""?l.comment=o:l.commentBefore=o),t.options.keepSourceTokens&&f&&(l.srcToken=e),l}function Bs(t,e,n,i,{spaceBefore:r,comment:s,anchor:o,tag:a,end:c},l){let f={type:"scalar",offset:gh.emptyScalarPosition(e,n,i),indent:-1,source:""},u=dl.composeScalar(t,f,a,l);return o&&(u.anchor=o.source.substring(1),u.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),r&&(u.spaceBefore=!0),s&&(u.comment=s,u.range[2]=c),u}function yh({options:t},{offset:e,source:n,end:i},r){let s=new dh.Alias(n.substring(1));s.source===""&&r(e,"BAD_ALIAS","Alias cannot be an empty string"),s.source.endsWith(":")&&r(e+n.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=e+n.length,a=hh.resolveEnd(i,o,t.strict,r);return s.range=[e,o,a.offset],a.comment&&(s.comment=a.comment),s}Ks.composeEmptyNode=Bs;Ks.composeNode=pl});var wl=w(gl=>{"use strict";var vh=Qt(),hl=ml(),bh=yt(),kh=nn();function Sh(t,e,{offset:n,start:i,value:r,end:s},o){let a=Object.assign({_directives:e},t),c=new vh.Document(void 0,a),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},f=kh.resolveProps(i,{indicator:"doc-start",next:r??s?.[0],offset:n,onError:o,parentIndent:0,startOnNewline:!0});f.found&&(c.directives.docStart=!0,r&&(r.type==="block-map"||r.type==="block-seq")&&!f.hasNewline&&o(f.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=r?hl.composeNode(l,r,f,o):hl.composeEmptyNode(l,f.end,i,null,f,o);let u=c.contents.range[2],d=bh.resolveEnd(s,u,!1,o);return d.comment&&(c.comment=d.comment),c.range=[n,u,d.offset],c}gl.composeDoc=Sh});var Ys=w(bl=>{"use strict";var Ch=Fn("process"),Eh=Nr(),Rh=Qt(),rn=tn(),yl=P(),_h=wl(),xh=yt();function sn(t){if(typeof t=="number")return[t,t+1];if(Array.isArray(t))return t.length===2?t:[t[0],t[1]];let{offset:e,source:n}=t;return[e,e+(typeof n=="string"?n.length:1)]}function vl(t){let e="",n=!1,i=!1;for(let r=0;r{let o=sn(n);s?this.warnings.push(new rn.YAMLWarning(o,i,r)):this.errors.push(new rn.YAMLParseError(o,i,r))},this.directives=new Ch.Directives({version:e.version||"1.2"}),this.options=e}decorate(e,n){let{comment:i,afterEmptyLine:r}=vl(this.prelude);if(i){let s=e.contents;if(n)e.comment=e.comment?`${e.comment} +`)+(s.substring(1)||" "),n=!0,i=!1;break;case"%":t[r+1]?.[0]!=="#"&&(r+=1),n=!1;break;default:n||(i=!0),n=!1}}return{comment:e,afterEmptyLine:i}}var Us=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(n,i,r,s)=>{let o=sn(n);s?this.warnings.push(new rn.YAMLWarning(o,i,r)):this.errors.push(new rn.YAMLParseError(o,i,r))},this.directives=new Eh.Directives({version:e.version||"1.2"}),this.options=e}decorate(e,n){let{comment:i,afterEmptyLine:r}=vl(this.prelude);if(i){let s=e.contents;if(n)e.comment=e.comment?`${e.comment} ${i}`:i;else if(r||e.directives.docStart||!s)e.commentBefore=i;else if(yl.isCollection(s)&&!s.flow&&s.items.length>0){let o=s.items[0];yl.isPair(o)&&(o=o.key);let a=o.commentBefore;o.commentBefore=a?`${i} ${a}`:i}else{let o=s.commentBefore;s.commentBefore=o?`${i} -${o}`:i}}if(n){for(let s=0;s{let s=sn(e);s[0]+=n,this.onError(s,"BAD_DIRECTIVE",i,r)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let n=Rh.composeDoc(this.options,this.directives,e,this.onError);this.atDirectives&&!n.directives.docStart&&this.onError(e,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(n,!1),this.doc&&(yield this.doc),this.doc=n,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(e.source);break;case"error":{let n=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,i=new rn.YAMLParseError(sn(e),"UNEXPECTED_TOKEN",n);this.atDirectives||!this.doc?this.errors.push(i):this.doc.errors.push(i);break}case"doc-end":{if(!this.doc){let i="Unexpected doc-end without preceding document";this.errors.push(new rn.YAMLParseError(sn(e),"UNEXPECTED_TOKEN",i));break}this.doc.directives.docEnd=!0;let n=_h.resolveEnd(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),n.comment){let i=this.doc.comment;this.doc.comment=i?`${i} -${n.comment}`:n.comment}this.doc.range[2]=n.offset;break}default:this.errors.push(new rn.YAMLParseError(sn(e),"UNEXPECTED_TOKEN",`Unsupported token ${e.type}`))}}*end(e=!1,n=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let i=Object.assign({_directives:this.directives},this.options),r=new Eh.Document(void 0,i);this.atDirectives&&this.onError(n,"MISSING_CHAR","Missing directives-end indicator line"),r.range=[0,n,n],this.decorate(r,!1),yield r}}};bl.Composer=Ks});var Cl=w(Ni=>{"use strict";var xh=Ds(),Ph=Fs(),Oh=tn(),kl=Wt();function Ah(t,e=!0,n){if(t){let i=(r,s,o)=>{let a=typeof r=="number"?r:Array.isArray(r)?r[0]:r.offset;if(n)n(a,s,o);else throw new Oh.YAMLParseError([a,a+1],s,o)};switch(t.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return Ph.resolveFlowScalar(t,e,i);case"block-scalar":return xh.resolveBlockScalar({options:{strict:e}},t,i)}}return null}function Nh(t,e){let{implicitKey:n=!1,indent:i,inFlow:r=!1,offset:s=-1,type:o="PLAIN"}=e,a=kl.stringifyString({type:o,value:t},{implicitKey:n,indent:i>0?" ".repeat(i):"",inFlow:r,options:{blockQuote:!0,lineWidth:-1}}),c=e.end??[{type:"newline",offset:-1,indent:i,source:` +${o}`:i}}if(n){for(let s=0;s{let s=sn(e);s[0]+=n,this.onError(s,"BAD_DIRECTIVE",i,r)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let n=_h.composeDoc(this.options,this.directives,e,this.onError);this.atDirectives&&!n.directives.docStart&&this.onError(e,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(n,!1),this.doc&&(yield this.doc),this.doc=n,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(e.source);break;case"error":{let n=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,i=new rn.YAMLParseError(sn(e),"UNEXPECTED_TOKEN",n);this.atDirectives||!this.doc?this.errors.push(i):this.doc.errors.push(i);break}case"doc-end":{if(!this.doc){let i="Unexpected doc-end without preceding document";this.errors.push(new rn.YAMLParseError(sn(e),"UNEXPECTED_TOKEN",i));break}this.doc.directives.docEnd=!0;let n=xh.resolveEnd(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),n.comment){let i=this.doc.comment;this.doc.comment=i?`${i} +${n.comment}`:n.comment}this.doc.range[2]=n.offset;break}default:this.errors.push(new rn.YAMLParseError(sn(e),"UNEXPECTED_TOKEN",`Unsupported token ${e.type}`))}}*end(e=!1,n=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let i=Object.assign({_directives:this.directives},this.options),r=new Rh.Document(void 0,i);this.atDirectives&&this.onError(n,"MISSING_CHAR","Missing directives-end indicator line"),r.range=[0,n,n],this.decorate(r,!1),yield r}}};bl.Composer=Us});var Cl=w(Ai=>{"use strict";var Ph=Ms(),Oh=Ws(),Nh=tn(),kl=Wt();function Ah(t,e=!0,n){if(t){let i=(r,s,o)=>{let a=typeof r=="number"?r:Array.isArray(r)?r[0]:r.offset;if(n)n(a,s,o);else throw new Nh.YAMLParseError([a,a+1],s,o)};switch(t.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return Oh.resolveFlowScalar(t,e,i);case"block-scalar":return Ph.resolveBlockScalar({options:{strict:e}},t,i)}}return null}function Th(t,e){let{implicitKey:n=!1,indent:i,inFlow:r=!1,offset:s=-1,type:o="PLAIN"}=e,a=kl.stringifyString({type:o,value:t},{implicitKey:n,indent:i>0?" ".repeat(i):"",inFlow:r,options:{blockQuote:!0,lineWidth:-1}}),c=e.end??[{type:"newline",offset:-1,indent:i,source:` `}];switch(a[0]){case"|":case">":{let l=a.indexOf(` `),f=a.substring(0,l),u=a.substring(l+1)+` `,d=[{type:"block-scalar-header",offset:s,indent:i,source:f}];return Sl(d,c)||d.push({type:"newline",offset:-1,indent:i,source:` -`}),{type:"block-scalar",offset:s,indent:i,props:d,source:u}}case'"':return{type:"double-quoted-scalar",offset:s,indent:i,source:a,end:c};case"'":return{type:"single-quoted-scalar",offset:s,indent:i,source:a,end:c};default:return{type:"scalar",offset:s,indent:i,source:a,end:c}}}function Th(t,e,n={}){let{afterKey:i=!1,implicitKey:r=!1,inFlow:s=!1,type:o}=n,a="indent"in t?t.indent:null;if(i&&typeof a=="number"&&(a+=2),!o)switch(t.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let l=t.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let c=kl.stringifyString({type:o,value:e},{implicitKey:r||a===null,indent:a!==null&&a>0?" ".repeat(a):"",inFlow:s,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":jh(t,c);break;case'"':Ys(t,c,"double-quoted-scalar");break;case"'":Ys(t,c,"single-quoted-scalar");break;default:Ys(t,c,"scalar")}}function jh(t,e){let n=e.indexOf(` +`}),{type:"block-scalar",offset:s,indent:i,props:d,source:u}}case'"':return{type:"double-quoted-scalar",offset:s,indent:i,source:a,end:c};case"'":return{type:"single-quoted-scalar",offset:s,indent:i,source:a,end:c};default:return{type:"scalar",offset:s,indent:i,source:a,end:c}}}function Ih(t,e,n={}){let{afterKey:i=!1,implicitKey:r=!1,inFlow:s=!1,type:o}=n,a="indent"in t?t.indent:null;if(i&&typeof a=="number"&&(a+=2),!o)switch(t.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let l=t.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let c=kl.stringifyString({type:o,value:e},{implicitKey:r||a===null,indent:a!==null&&a>0?" ".repeat(a):"",inFlow:s,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":jh(t,c);break;case'"':Vs(t,c,"double-quoted-scalar");break;case"'":Vs(t,c,"single-quoted-scalar");break;default:Vs(t,c,"scalar")}}function jh(t,e){let n=e.indexOf(` `),i=e.substring(0,n),r=e.substring(n+1)+` `;if(t.type==="block-scalar"){let s=t.props[0];if(s.type!=="block-scalar-header")throw new Error("Invalid block scalar header");s.source=i,t.source=r}else{let{offset:s}=t,o="indent"in t?t.indent:-1,a=[{type:"block-scalar-header",offset:s,indent:o,source:i}];Sl(a,"end"in t?t.end:void 0)||a.push({type:"newline",offset:-1,indent:o,source:` -`});for(let c of Object.keys(t))c!=="type"&&c!=="offset"&&delete t[c];Object.assign(t,{type:"block-scalar",indent:o,props:a,source:r})}}function Sl(t,e){if(e)for(let n of e)switch(n.type){case"space":case"comment":t.push(n);break;case"newline":return t.push(n),!0}return!1}function Ys(t,e,n){switch(t.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":t.type=n,t.source=e;break;case"block-scalar":{let i=t.props.slice(1),r=e.length;t.props[0].type==="block-scalar-header"&&(r-=t.props[0].source.length);for(let s of i)s.offset+=r;delete t.props,Object.assign(t,{type:n,source:e,end:i});break}case"block-map":case"block-seq":{let r={type:"newline",offset:t.offset+e.length,indent:t.indent,source:` -`};delete t.items,Object.assign(t,{type:n,source:e,end:[r]});break}default:{let i="indent"in t?t.indent:-1,r="end"in t&&Array.isArray(t.end)?t.end.filter(s=>s.type==="space"||s.type==="comment"||s.type==="newline"):[];for(let s of Object.keys(t))s!=="type"&&s!=="offset"&&delete t[s];Object.assign(t,{type:n,indent:i,source:e,end:r})}}}Ni.createScalarToken=Nh;Ni.resolveAsScalar=Ah;Ni.setScalarValue=Th});var Rl=w(El=>{"use strict";var Ih=t=>"type"in t?ji(t):Ti(t);function ji(t){switch(t.type){case"block-scalar":{let e="";for(let n of t.props)e+=ji(n);return e+t.source}case"block-map":case"block-seq":{let e="";for(let n of t.items)e+=Ti(n);return e}case"flow-collection":{let e=t.start.source;for(let n of t.items)e+=Ti(n);for(let n of t.end)e+=n.source;return e}case"document":{let e=Ti(t);if(t.end)for(let n of t.end)e+=n.source;return e}default:{let e=t.source;if("end"in t&&t.end)for(let n of t.end)e+=n.source;return e}}}function Ti({start:t,key:e,sep:n,value:i}){let r="";for(let s of t)r+=s.source;if(e&&(r+=ji(e)),n)for(let s of n)r+=s.source;return i&&(r+=ji(i)),r}El.stringify=Ih});var Ol=w(Pl=>{"use strict";var Vs=Symbol("break visit"),$h=Symbol("skip children"),_l=Symbol("remove item");function Ze(t,e){"type"in t&&t.type==="document"&&(t={start:t.start,value:t.value}),xl(Object.freeze([]),t,e)}Ze.BREAK=Vs;Ze.SKIP=$h;Ze.REMOVE=_l;Ze.itemAtPath=(t,e)=>{let n=t;for(let[i,r]of e){let s=n?.[i];if(s&&"items"in s)n=s.items[r];else return}return n};Ze.parentCollection=(t,e)=>{let n=Ze.itemAtPath(t,e.slice(0,-1)),i=e[e.length-1][0],r=n?.[i];if(r&&"items"in r)return r;throw new Error("Parent collection not found")};function xl(t,e,n){let i=n(e,t);if(typeof i=="symbol")return i;for(let r of["key","value"]){let s=e[r];if(s&&"items"in s){for(let o=0;o{"use strict";var Js=Cl(),qh=Rl(),Lh=Ol(),Hs="\uFEFF",Gs="",zs="",Xs="",Dh=t=>!!t&&"items"in t,Mh=t=>!!t&&(t.type==="scalar"||t.type==="single-quoted-scalar"||t.type==="double-quoted-scalar"||t.type==="block-scalar");function Fh(t){switch(t){case Hs:return"";case Gs:return"";case zs:return"";case Xs:return"";default:return JSON.stringify(t)}}function Wh(t){switch(t){case Hs:return"byte-order-mark";case Gs:return"doc-mode";case zs:return"flow-error-end";case Xs:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case` +`});for(let c of Object.keys(t))c!=="type"&&c!=="offset"&&delete t[c];Object.assign(t,{type:"block-scalar",indent:o,props:a,source:r})}}function Sl(t,e){if(e)for(let n of e)switch(n.type){case"space":case"comment":t.push(n);break;case"newline":return t.push(n),!0}return!1}function Vs(t,e,n){switch(t.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":t.type=n,t.source=e;break;case"block-scalar":{let i=t.props.slice(1),r=e.length;t.props[0].type==="block-scalar-header"&&(r-=t.props[0].source.length);for(let s of i)s.offset+=r;delete t.props,Object.assign(t,{type:n,source:e,end:i});break}case"block-map":case"block-seq":{let r={type:"newline",offset:t.offset+e.length,indent:t.indent,source:` +`};delete t.items,Object.assign(t,{type:n,source:e,end:[r]});break}default:{let i="indent"in t?t.indent:-1,r="end"in t&&Array.isArray(t.end)?t.end.filter(s=>s.type==="space"||s.type==="comment"||s.type==="newline"):[];for(let s of Object.keys(t))s!=="type"&&s!=="offset"&&delete t[s];Object.assign(t,{type:n,indent:i,source:e,end:r})}}}Ai.createScalarToken=Th;Ai.resolveAsScalar=Ah;Ai.setScalarValue=Ih});var Rl=w(El=>{"use strict";var $h=t=>"type"in t?Ii(t):Ti(t);function Ii(t){switch(t.type){case"block-scalar":{let e="";for(let n of t.props)e+=Ii(n);return e+t.source}case"block-map":case"block-seq":{let e="";for(let n of t.items)e+=Ti(n);return e}case"flow-collection":{let e=t.start.source;for(let n of t.items)e+=Ti(n);for(let n of t.end)e+=n.source;return e}case"document":{let e=Ti(t);if(t.end)for(let n of t.end)e+=n.source;return e}default:{let e=t.source;if("end"in t&&t.end)for(let n of t.end)e+=n.source;return e}}}function Ti({start:t,key:e,sep:n,value:i}){let r="";for(let s of t)r+=s.source;if(e&&(r+=Ii(e)),n)for(let s of n)r+=s.source;return i&&(r+=Ii(i)),r}El.stringify=$h});var Ol=w(Pl=>{"use strict";var Js=Symbol("break visit"),qh=Symbol("skip children"),_l=Symbol("remove item");function Ze(t,e){"type"in t&&t.type==="document"&&(t={start:t.start,value:t.value}),xl(Object.freeze([]),t,e)}Ze.BREAK=Js;Ze.SKIP=qh;Ze.REMOVE=_l;Ze.itemAtPath=(t,e)=>{let n=t;for(let[i,r]of e){let s=n?.[i];if(s&&"items"in s)n=s.items[r];else return}return n};Ze.parentCollection=(t,e)=>{let n=Ze.itemAtPath(t,e.slice(0,-1)),i=e[e.length-1][0],r=n?.[i];if(r&&"items"in r)return r;throw new Error("Parent collection not found")};function xl(t,e,n){let i=n(e,t);if(typeof i=="symbol")return i;for(let r of["key","value"]){let s=e[r];if(s&&"items"in s){for(let o=0;o{"use strict";var Hs=Cl(),Lh=Rl(),Dh=Ol(),Gs="\uFEFF",zs="",Xs="",Qs="",Mh=t=>!!t&&"items"in t,Fh=t=>!!t&&(t.type==="scalar"||t.type==="single-quoted-scalar"||t.type==="double-quoted-scalar"||t.type==="block-scalar");function Wh(t){switch(t){case Gs:return"";case zs:return"";case Xs:return"";case Qs:return"";default:return JSON.stringify(t)}}function Bh(t){switch(t){case Gs:return"byte-order-mark";case zs:return"doc-mode";case Xs:return"flow-error-end";case Qs:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case` `:case`\r -`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(t[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}z.createScalarToken=Js.createScalarToken;z.resolveAsScalar=Js.resolveAsScalar;z.setScalarValue=Js.setScalarValue;z.stringify=qh.stringify;z.visit=Lh.visit;z.BOM=Hs;z.DOCUMENT=Gs;z.FLOW_END=zs;z.SCALAR=Xs;z.isCollection=Dh;z.isScalar=Mh;z.prettyToken=Fh;z.tokenType=Wh});var eo=w(Nl=>{"use strict";var on=Ii();function se(t){switch(t){case void 0:case" ":case` -`:case"\r":case" ":return!0;default:return!1}}var Al=new Set("0123456789ABCDEFabcdef"),Bh=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),$i=new Set(",[]{}"),Kh=new Set(` ,[]{} -\r `),Qs=t=>!t||Kh.has(t),Zs=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,n=!1){if(e){if(typeof e!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!n;let i=this.next??"stream";for(;i&&(n||this.hasChars(1));)i=yield*this.parseNext(i)}atLineEnd(){let e=this.pos,n=this.buffer[e];for(;n===" "||n===" ";)n=this.buffer[++e];return!n||n==="#"||n===` +`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(t[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}z.createScalarToken=Hs.createScalarToken;z.resolveAsScalar=Hs.resolveAsScalar;z.setScalarValue=Hs.setScalarValue;z.stringify=Lh.stringify;z.visit=Dh.visit;z.BOM=Gs;z.DOCUMENT=zs;z.FLOW_END=Xs;z.SCALAR=Qs;z.isCollection=Mh;z.isScalar=Fh;z.prettyToken=Wh;z.tokenType=Bh});var to=w(Al=>{"use strict";var on=ji();function se(t){switch(t){case void 0:case" ":case` +`:case"\r":case" ":return!0;default:return!1}}var Nl=new Set("0123456789ABCDEFabcdef"),Kh=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),$i=new Set(",[]{}"),Uh=new Set(` ,[]{} +\r `),Zs=t=>!t||Uh.has(t),eo=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,n=!1){if(e){if(typeof e!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!n;let i=this.next??"stream";for(;i&&(n||this.hasChars(1));)i=yield*this.parseNext(i)}atLineEnd(){let e=this.pos,n=this.buffer[e];for(;n===" "||n===" ";)n=this.buffer[++e];return!n||n==="#"||n===` `?!0:n==="\r"?this.buffer[e+1]===` `:!1}charAt(e){return this.buffer[this.pos+e]}continueScalar(e){let n=this.buffer[e];if(this.indentNext>0){let i=0;for(;n===" ";)n=this.buffer[++i+e];if(n==="\r"){let r=this.buffer[i+e+1];if(r===` `||!r&&!this.atEnd)return e+i+1}return n===` `||i>=this.indentNext||!n&&!this.atEnd?e+i:-1}if(n==="-"||n==="."){let i=this.buffer.substr(e,3);if((i==="---"||i==="...")&&se(this.buffer[e+3]))return-1}return e}getLine(){let e=this.lineEndPos;return(typeof e!="number"||e!==-1&&ethis.indentValue&&!se(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[e,n]=this.peek(2);if(!n&&!this.atEnd)return this.setNext("block-start");if((e==="-"||e==="?"||e===":")&&se(n)){let i=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=i,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let e=this.getLine();if(e===null)return this.setNext("doc");let n=yield*this.pushIndicators();switch(e[n]){case"#":yield*this.pushCount(e.length-n);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(Qs),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return n+=yield*this.parseBlockScalarHeader(),n+=yield*this.pushSpaces(!0),yield*this.pushCount(e.length-n),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,n,i=-1;do e=yield*this.pushNewline(),e>0?(n=yield*this.pushSpaces(!1),this.indentValue=i=n):n=0,n+=yield*this.pushSpaces(!0);while(e+n>0);let r=this.getLine();if(r===null)return this.setNext("flow");if((i!==-1&&ithis.indentValue&&!se(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[e,n]=this.peek(2);if(!n&&!this.atEnd)return this.setNext("block-start");if((e==="-"||e==="?"||e===":")&&se(n)){let i=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=i,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let e=this.getLine();if(e===null)return this.setNext("doc");let n=yield*this.pushIndicators();switch(e[n]){case"#":yield*this.pushCount(e.length-n);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(Zs),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return n+=yield*this.parseBlockScalarHeader(),n+=yield*this.pushSpaces(!0),yield*this.pushCount(e.length-n),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,n,i=-1;do e=yield*this.pushNewline(),e>0?(n=yield*this.pushSpaces(!1),this.indentValue=i=n):n=0,n+=yield*this.pushSpaces(!0);while(e+n>0);let r=this.getLine();if(r===null)return this.setNext("flow");if((i!==-1&&i"0"&&n<="9")this.blockScalarIndent=Number(n)-1;else if(n!=="-")break}return yield*this.pushUntil(n=>se(n)||n==="#")}*parseBlockScalar(){let e=this.pos-1,n=0,i;e:for(let s=this.pos;i=this.buffer[s];++s)switch(i){case" ":n+=1;break;case` `:e=s,n=0;break;case"\r":{let o=this.buffer[s+1];if(!o&&!this.atEnd)return this.setNext("block-scalar");if(o===` @@ -133,34 +133,34 @@ ${n.comment}`:n.comment}this.doc.range[2]=n.offset;break}default:this.errors.pus `&&s>=this.pos&&s+1+n>a)e=s;else break}while(!0);return yield on.SCALAR,yield*this.pushToIndex(e+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let e=this.flowLevel>0,n=this.pos-1,i=this.pos-1,r;for(;r=this.buffer[++i];)if(r===":"){let s=this.buffer[i+1];if(se(s)||e&&$i.has(s))break;n=i}else if(se(r)){let s=this.buffer[i+1];if(r==="\r"&&(s===` `?(i+=1,r=` `,s=this.buffer[i+1]):n=i),s==="#"||e&&$i.has(s))break;if(r===` -`){let o=this.continueScalar(i+1);if(o===-1)break;i=Math.max(i,o-2)}}else{if(e&&$i.has(r))break;n=i}return!r&&!this.atEnd?this.setNext("plain-scalar"):(yield on.SCALAR,yield*this.pushToIndex(n+1,!0),e?"flow":"doc")}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,n){let i=this.buffer.slice(this.pos,e);return i?(yield i,this.pos+=i.length,i.length):(n&&(yield""),0)}*pushIndicators(){let e=0;e:for(;;){switch(this.charAt(0)){case"!":e+=yield*this.pushTag(),e+=yield*this.pushSpaces(!0);continue e;case"&":e+=yield*this.pushUntil(Qs),e+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let n=this.flowLevel>0,i=this.charAt(1);if(se(i)||n&&$i.has(i)){n?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,e+=yield*this.pushCount(1),e+=yield*this.pushSpaces(!0);continue e}}}break e}return e}*pushTag(){if(this.charAt(1)==="<"){let e=this.pos+2,n=this.buffer[e];for(;!se(n)&&n!==">";)n=this.buffer[++e];return yield*this.pushToIndex(n===">"?e+1:e,!1)}else{let e=this.pos+1,n=this.buffer[e];for(;n;)if(Bh.has(n))n=this.buffer[++e];else if(n==="%"&&Al.has(this.buffer[e+1])&&Al.has(this.buffer[e+2]))n=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];return e===` +`){let o=this.continueScalar(i+1);if(o===-1)break;i=Math.max(i,o-2)}}else{if(e&&$i.has(r))break;n=i}return!r&&!this.atEnd?this.setNext("plain-scalar"):(yield on.SCALAR,yield*this.pushToIndex(n+1,!0),e?"flow":"doc")}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,n){let i=this.buffer.slice(this.pos,e);return i?(yield i,this.pos+=i.length,i.length):(n&&(yield""),0)}*pushIndicators(){let e=0;e:for(;;){switch(this.charAt(0)){case"!":e+=yield*this.pushTag(),e+=yield*this.pushSpaces(!0);continue e;case"&":e+=yield*this.pushUntil(Zs),e+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let n=this.flowLevel>0,i=this.charAt(1);if(se(i)||n&&$i.has(i)){n?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,e+=yield*this.pushCount(1),e+=yield*this.pushSpaces(!0);continue e}}}break e}return e}*pushTag(){if(this.charAt(1)==="<"){let e=this.pos+2,n=this.buffer[e];for(;!se(n)&&n!==">";)n=this.buffer[++e];return yield*this.pushToIndex(n===">"?e+1:e,!1)}else{let e=this.pos+1,n=this.buffer[e];for(;n;)if(Kh.has(n))n=this.buffer[++e];else if(n==="%"&&Nl.has(this.buffer[e+1])&&Nl.has(this.buffer[e+2]))n=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];return e===` `?yield*this.pushCount(1):e==="\r"&&this.charAt(1)===` -`?yield*this.pushCount(2):0}*pushSpaces(e){let n=this.pos-1,i;do i=this.buffer[++n];while(i===" "||e&&i===" ");let r=n-this.pos;return r>0&&(yield this.buffer.substr(this.pos,r),this.pos=n),r}*pushUntil(e){let n=this.pos,i=this.buffer[n];for(;!e(i);)i=this.buffer[++n];return yield*this.pushToIndex(n,!1)}};Nl.Lexer=Zs});var no=w(Tl=>{"use strict";var to=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let n=0,i=this.lineStarts.length;for(;n>1;this.lineStarts[s]{"use strict";var Uh=Fn("process"),jl=Ii(),Yh=eo();function $e(t,e){for(let n=0;n=0;)switch(t[e].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;t[++e]?.type==="space";);return t.splice(e,t.length)}function Li(t,e){if(e.length<1e5)Array.prototype.push.apply(t,e);else for(let n=0;n0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let e=this.peek(1);if(this.type==="doc-end"&&e?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!e)return yield*this.stream();switch(e.type){case"document":return yield*this.document(e);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(e);case"block-scalar":return yield*this.blockScalar(e);case"block-map":return yield*this.blockMap(e);case"block-seq":return yield*this.blockSequence(e);case"flow-collection":return yield*this.flowCollection(e);case"doc-end":return yield*this.documentEnd(e)}yield*this.pop()}peek(e){return this.stack[this.stack.length-e]}*pop(e){let n=e??this.stack.pop();if(!n)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield n;else{let i=this.peek(1);switch(n.type==="block-scalar"?n.indent="indent"in i?i.indent:0:n.type==="flow-collection"&&i.type==="document"&&(n.indent=0),n.type==="flow-collection"&&$l(n),i.type){case"document":i.value=n;break;case"block-scalar":i.props.push(n);break;case"block-map":{let r=i.items[i.items.length-1];if(r.value){i.items.push({start:[],key:n,sep:[]}),this.onKeyLine=!0;return}else if(r.sep)r.value=n;else{Object.assign(r,{key:n,sep:[]}),this.onKeyLine=!r.explicitKey;return}break}case"block-seq":{let r=i.items[i.items.length-1];r.value?i.items.push({start:[],value:n}):r.value=n;break}case"flow-collection":{let r=i.items[i.items.length-1];!r||r.value?i.items.push({start:[],key:n,sep:[]}):r.sep?r.value=n:Object.assign(r,{key:n,sep:[]});return}default:yield*this.pop(),yield*this.pop(n)}if((i.type==="document"||i.type==="block-map"||i.type==="block-seq")&&(n.type==="block-map"||n.type==="block-seq")){let r=n.items[n.items.length-1];r&&!r.sep&&!r.value&&r.start.length>0&&Il(r.start)===-1&&(n.indent===0||r.start.every(s=>s.type!=="comment"||s.indent0&&(yield this.buffer.substr(this.pos,r),this.pos=n),r}*pushUntil(e){let n=this.pos,i=this.buffer[n];for(;!e(i);)i=this.buffer[++n];return yield*this.pushToIndex(n,!1)}};Al.Lexer=eo});var io=w(Tl=>{"use strict";var no=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let n=0,i=this.lineStarts.length;for(;n>1;this.lineStarts[s]{"use strict";var Yh=Fn("process"),Il=ji(),Vh=to();function $e(t,e){for(let n=0;n=0;)switch(t[e].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;t[++e]?.type==="space";);return t.splice(e,t.length)}function Li(t,e){if(e.length<1e5)Array.prototype.push.apply(t,e);else for(let n=0;n0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let e=this.peek(1);if(this.type==="doc-end"&&e?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!e)return yield*this.stream();switch(e.type){case"document":return yield*this.document(e);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(e);case"block-scalar":return yield*this.blockScalar(e);case"block-map":return yield*this.blockMap(e);case"block-seq":return yield*this.blockSequence(e);case"flow-collection":return yield*this.flowCollection(e);case"doc-end":return yield*this.documentEnd(e)}yield*this.pop()}peek(e){return this.stack[this.stack.length-e]}*pop(e){let n=e??this.stack.pop();if(!n)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield n;else{let i=this.peek(1);switch(n.type==="block-scalar"?n.indent="indent"in i?i.indent:0:n.type==="flow-collection"&&i.type==="document"&&(n.indent=0),n.type==="flow-collection"&&$l(n),i.type){case"document":i.value=n;break;case"block-scalar":i.props.push(n);break;case"block-map":{let r=i.items[i.items.length-1];if(r.value){i.items.push({start:[],key:n,sep:[]}),this.onKeyLine=!0;return}else if(r.sep)r.value=n;else{Object.assign(r,{key:n,sep:[]}),this.onKeyLine=!r.explicitKey;return}break}case"block-seq":{let r=i.items[i.items.length-1];r.value?i.items.push({start:[],value:n}):r.value=n;break}case"flow-collection":{let r=i.items[i.items.length-1];!r||r.value?i.items.push({start:[],key:n,sep:[]}):r.sep?r.value=n:Object.assign(r,{key:n,sep:[]});return}default:yield*this.pop(),yield*this.pop(n)}if((i.type==="document"||i.type==="block-map"||i.type==="block-seq")&&(n.type==="block-map"||n.type==="block-seq")){let r=n.items[n.items.length-1];r&&!r.sep&&!r.value&&r.start.length>0&&jl(r.start)===-1&&(n.indent===0||r.start.every(s=>s.type!=="comment"||s.indent=e.indent){let i=!this.onKeyLine&&this.indent===e.indent,r=i&&(n.sep||n.explicitKey)&&this.type!=="seq-item-ind",s=[];if(r&&n.sep&&!n.value){let o=[];for(let a=0;ae.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(s=n.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":r||n.value?(s.push(this.sourceToken),e.items.push({start:s}),this.onKeyLine=!0):n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"explicit-key-ind":!n.sep&&!n.explicitKey?(n.start.push(this.sourceToken),n.explicitKey=!0):r||n.value?(s.push(this.sourceToken),e.items.push({start:s,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(n.explicitKey)if(n.sep)if(n.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if($e(n.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:s,key:null,sep:[this.sourceToken]}]});else if(ql(n.key)&&!$e(n.sep,"newline")){let o=vt(n.start),a=n.key,c=n.sep;c.push(this.sourceToken),delete n.key,delete n.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:a,sep:c}]})}else s.length>0?n.sep=n.sep.concat(s,this.sourceToken):n.sep.push(this.sourceToken);else if($e(n.start,"newline"))Object.assign(n,{key:null,sep:[this.sourceToken]});else{let o=vt(n.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else n.sep?n.value||r?e.items.push({start:s,key:null,sep:[this.sourceToken]}):$e(n.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):n.sep.push(this.sourceToken):Object.assign(n,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);r||n.value?(e.items.push({start:s,key:o,sep:[]}),this.onKeyLine=!0):n.sep?this.stack.push(o):(Object.assign(n,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(e);if(o){if(o.type==="block-seq"){if(!n.explicitKey&&n.sep&&!$e(n.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else i&&e.items.push({start:s});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let n=e.items[e.items.length-1];switch(this.type){case"newline":if(n.value){let i="end"in n.value?n.value.end:void 0;(Array.isArray(i)?i[i.length-1]:void 0)?.type==="comment"?i?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else n.start.push(this.sourceToken);return;case"space":case"comment":if(n.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(n.start,e.indent)){let r=e.items[e.items.length-2]?.value?.end;if(Array.isArray(r)){Li(r,n.start),r.push(this.sourceToken),e.items.pop();return}}n.start.push(this.sourceToken)}return;case"anchor":case"tag":if(n.value||this.indent<=e.indent)break;n.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;n.value||$e(n.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):n.start.push(this.sourceToken);return}if(this.indent>e.indent){let i=this.startBlockValue(e);if(i){this.stack.push(i);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let n=e.items[e.items.length-1];if(this.type==="flow-error-end"){let i;do yield*this.pop(),i=this.peek(1);while(i?.type==="flow-collection")}else if(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!n||n.sep?e.items.push({start:[this.sourceToken]}):n.start.push(this.sourceToken);return;case"map-value-ind":!n||n.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):n.sep?n.sep.push(this.sourceToken):Object.assign(n,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!n||n.value?e.items.push({start:[this.sourceToken]}):n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let r=this.flowScalar(this.type);!n||n.value?e.items.push({start:[],key:r,sep:[]}):n.sep?this.stack.push(r):Object.assign(n,{key:r,sep:[]});return}case"flow-map-end":case"flow-seq-end":e.end.push(this.sourceToken);return}let i=this.startBlockValue(e);i?this.stack.push(i):(yield*this.pop(),yield*this.step())}else{let i=this.peek(2);if(i.type==="block-map"&&(this.type==="map-value-ind"&&i.indent===e.indent||this.type==="newline"&&!i.items[i.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&i.type!=="flow-collection"){let r=qi(i),s=vt(r);$l(e);let o=e.end.splice(1,e.end.length);o.push(this.sourceToken);let a={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:s,key:e,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let n=this.source.indexOf(` `)+1;for(;n!==0;)this.onNewLine(this.offset+n),n=this.source.indexOf(` -`,n)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let n=qi(e),i=vt(n);return i.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let n=qi(e),i=vt(n);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,n){return this.type!=="comment"||this.indent<=n?!1:e.every(i=>i.type==="newline"||i.type==="space")}*documentEnd(e){this.type!=="doc-mode"&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};Ll.Parser=io});var Bl=w(cn=>{"use strict";var Dl=Us(),Vh=Qt(),an=tn(),Jh=Br(),Hh=P(),Gh=no(),Ml=ro();function Fl(t){let e=t.prettyErrors!==!1;return{lineCounter:t.lineCounter||e&&new Gh.LineCounter||null,prettyErrors:e}}function zh(t,e={}){let{lineCounter:n,prettyErrors:i}=Fl(e),r=new Ml.Parser(n?.addNewLine),s=new Dl.Composer(e),o=Array.from(s.compose(r.parse(t)));if(i&&n)for(let a of o)a.errors.forEach(an.prettifyError(t,n)),a.warnings.forEach(an.prettifyError(t,n));return o.length>0?o:Object.assign([],{empty:!0},s.streamInfo())}function Wl(t,e={}){let{lineCounter:n,prettyErrors:i}=Fl(e),r=new Ml.Parser(n?.addNewLine),s=new Dl.Composer(e),o=null;for(let a of s.compose(r.parse(t),!0,t.length))if(!o)o=a;else if(o.options.logLevel!=="silent"){o.errors.push(new an.YAMLParseError(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return i&&n&&(o.errors.forEach(an.prettifyError(t,n)),o.warnings.forEach(an.prettifyError(t,n))),o}function Xh(t,e,n){let i;typeof e=="function"?i=e:n===void 0&&e&&typeof e=="object"&&(n=e);let r=Wl(t,n);if(!r)return null;if(r.warnings.forEach(s=>Jh.warn(r.options.logLevel,s)),r.errors.length>0){if(r.options.logLevel!=="silent")throw r.errors[0];r.errors=[]}return r.toJS(Object.assign({reviver:i},n))}function Qh(t,e,n){let i=null;if(typeof e=="function"||Array.isArray(e)?i=e:n===void 0&&e&&(n=e),typeof n=="string"&&(n=n.length),typeof n=="number"){let r=Math.round(n);n=r<1?void 0:r>8?{indent:8}:{indent:r}}if(t===void 0){let{keepUndefined:r}=n??e??{};if(!r)return}return Hh.isDocument(t)&&!i?t.toString(n):new Vh.Document(t,i,n).toString(n)}cn.parse=Xh;cn.parseAllDocuments=zh;cn.parseDocument=Wl;cn.stringify=Qh});var et=w(N=>{"use strict";var Zh=Us(),eg=Qt(),tg=Es(),so=tn(),ng=qt(),qe=P(),ig=Ne(),rg=$(),sg=je(),og=Ie(),ag=Ii(),cg=eo(),lg=no(),ug=ro(),Di=Bl(),Kl=Tt();N.Composer=Zh.Composer;N.Document=eg.Document;N.Schema=tg.Schema;N.YAMLError=so.YAMLError;N.YAMLParseError=so.YAMLParseError;N.YAMLWarning=so.YAMLWarning;N.Alias=ng.Alias;N.isAlias=qe.isAlias;N.isCollection=qe.isCollection;N.isDocument=qe.isDocument;N.isMap=qe.isMap;N.isNode=qe.isNode;N.isPair=qe.isPair;N.isScalar=qe.isScalar;N.isSeq=qe.isSeq;N.Pair=ig.Pair;N.Scalar=rg.Scalar;N.YAMLMap=sg.YAMLMap;N.YAMLSeq=og.YAMLSeq;N.CST=ag;N.Lexer=cg.Lexer;N.LineCounter=lg.LineCounter;N.Parser=ug.Parser;N.parse=Di.parse;N.parseAllDocuments=Di.parseAllDocuments;N.parseDocument=Di.parseDocument;N.stringify=Di.stringify;N.visit=Kl.visit;N.visitAsync=Kl.visitAsync});function Le(t){return t!==0&&t!==0n&&t!=="0"}function Mi(t,e){return Le(t.dev)&&Le(e.dev)&&Le(t.ino)&&Le(e.ino)}function ve(t,e){let n=Le(t.dev)&&Le(e.dev);if(n&&t.dev!==e.dev)return!1;let i=Le(t.ino)&&Le(e.ino);return i&&t.ino!==e.ino?!1:n&&i?!0:t.birthtime===e.birthtime}var Fi=U(()=>{"use strict"});import{constants as Wi,promises as tt}from"fs";function oo(t){return"birthtimeNs"in t&&typeof t.birthtimeNs=="bigint"?t.birthtimeNs:t.birthtimeMs}function Ul(t){return"ctimeNs"in t&&typeof t.ctimeNs=="bigint"?t.ctimeNs:t.ctimeMs}function ln(t){return{dev:t.dev,ino:t.ino,birthtime:oo(t)}}function Bi(t,e){let n=ln(t),i=ln(e);return Mi(n,i)?ve(n,i):ve(n,i)&&oo(t)===oo(e)&&Ul(t)===Ul(e)&&t.size===e.size}async function Ki(t,e,n={}){if(!Number.isSafeInteger(e)||e<1)throw new Error("race-safe read byte limit must be a positive integer");let i=n.label??"file",r=n.bigint===!0,s=await tt.lstat(t,{bigint:r});if(!s.isFile()||s.isSymbolicLink())throw new De("not-regular-file",`${i} must be a regular file`);if(BigInt(s.size)>BigInt(e))throw new De("too-large",`${i} exceeds ${e} bytes`);let o=await tt.realpath(t);await n.verify?.("pre-open",{realPath:o,identity:ln(s)});let a=process.platform==="win32"?Wi.O_RDONLY:Wi.O_RDONLY|Wi.O_NOFOLLOW|Wi.O_NONBLOCK,c;try{c=await tt.open(t,a)}catch(l){throw l.code==="ELOOP"?new De("not-regular-file",`${i} must be a regular file`,{cause:l}):l}try{let[l,f,u]=await Promise.all([c.stat({bigint:r}),tt.lstat(t,{bigint:r}),tt.realpath(t)]);if(!l.isFile()||!f.isFile()||f.isSymbolicLink()||u!==o||!Bi(s,l)||!Bi(s,f))throw new De("changed",`${i} changed while opening`);await n.verify?.("post-open",{realPath:u,identity:ln(l)}),await n.hooks?.afterOpen?.();let d=[],m=0,g=Buffer.allocUnsafe(Math.min(64*1024,e+1));for(;;){let y=e+1-m,{bytesRead:S}=await c.read(g,0,Math.min(g.length,y),null);if(S===0)break;if(m+=S,m>e)throw new De("too-large",`${i} exceeds ${e} bytes`);d.push(Buffer.from(g.subarray(0,S)))}await n.hooks?.beforeFinalCheck?.();let[p,h,v]=await Promise.all([c.stat({bigint:r}),tt.lstat(t,{bigint:r}),tt.realpath(t)]);if(!h.isFile()||h.isSymbolicLink()||v!==o||!Bi(s,p)||!Bi(s,h))throw new De("changed",`${i} changed while reading`);return await n.verify?.("post-read",{realPath:v,identity:ln(p)}),{bytes:Buffer.concat(d,m),stat:p,realPath:v}}finally{await c.close()}}var De,ao=U(()=>{"use strict";Fi();De=class extends Error{reason;constructor(e,n,i){super(n,i),this.name="RaceSafeReadError",this.reason=e}}});import Ji from"path";function kg(t,e){if(typeof t!="string")throw new Error(`${e} must be a string`);let n=t.trim();if(n.length===0||Ji.posix.isAbsolute(n)||Ji.win32.isAbsolute(n)||/^(?:~|[\\/])/u.test(n))throw new Error(`${e} must be a project-relative path`);if(n===".")return[];let i=n.replaceAll("\\","/").split("/");if(i.some(r=>r===".."))throw new Error(`${e} must stay inside the project root`);if(i.some(r=>r===""||r==="."))throw new Error(`${e} must not contain empty or dot path segments`);return i}function hn(t){let e=kg(t,"native.artifact_root");return e.length===0?".":e.join("/")}function su(t,e="docs"){let n=t??e;if(n!=="legacy"&&n!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return n}function Me(t,e,n=!1){if(typeof t!="string")throw new Error(`${e} must be a string`);let i=t.trim().replaceAll("\\","/");if(i.length===0||Ji.posix.isAbsolute(i)||Ji.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${e} must be relative to its declared path base`);let r=i.split("/");if(r.some(s=>s===".."))throw new Error(`${e} must stay inside its declared path base`);if(r.some(s=>s===""||s==="."))throw new Error(`${e} must not contain empty or dot path segments`);if(!n&&/[*?]/u.test(i))throw new Error(`${e} cannot contain wildcards`);return r.join("/")}function gn(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function ou(t,e,n){let i=t??e;if(i!=="en"&&i!=="zh-CN")throw new Error(`${n} must be en or zh-CN`);return i}function au(t,e){if(typeof t!="string"||t.length===0||t.includes("\\")||t.includes("\0")||t.startsWith("/")||t.split("/").includes(".."))throw new Error(`${e} contains an unsafe pattern`);if(t.length>yo)throw new Error(`${e} exceeds ${yo} characters`);let n=0;for(let i=0;ivo)throw new Error(`${e} contains more than ${vo} wildcard tokens`);return t}function iu(t,e,n){if(t===void 0)return[...n];if(!Array.isArray(t))throw new Error(`${e} contains an unsafe pattern`);return[...new Set(t.map(i=>au(i,e)))].sort((i,r)=>i.localeCompare(r,"en"))}function wo(t,e,n){let i=t??e;if(!Number.isSafeInteger(i)||i<1)throw new Error(`${n} must be a positive integer`);return i}function Sg(t){if(t===void 0)return{...te,include:[...te.include],exclude:[...te.exclude]};let e=gn(t,"native.snapshot");return{include:iu(e.include,"native.snapshot.include",te.include),exclude:iu(e.exclude,"native.snapshot.exclude",te.exclude),max_files:wo(e.max_files,te.max_files,"native.snapshot.max_files"),max_total_bytes:wo(e.max_total_bytes,te.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:wo(e.max_duration_ms,te.max_duration_ms,"native.snapshot.max_duration_ms")}}function Cg(t){if(t===void 0)return;let e=gn(t,"native.pending_root_move"),n=e.id,i=e.from_artifact_root,r=e.to_artifact_root,s=e.stage;if(typeof n!="string"||!/^[a-f0-9-]{8,}$/u.test(n))throw new Error("native.pending_root_move.id is invalid");if(typeof i!="string"||typeof r!="string")throw new Error("native.pending_root_move roots must be strings");if(s!=="copying"&&s!=="ready"&&s!=="switched")throw new Error("native.pending_root_move.stage is invalid");let o;if(e.cleanup!==void 0){let a=gn(e.cleanup,"native.pending_root_move.cleanup"),c=a.kind,l=a.state,f=a.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof f!="string"||!/^[a-f0-9]{64}$/u.test(f))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:f}}return{id:n,fromArtifactRoot:hn(i),toArtifactRoot:hn(r),stage:s,...o?{cleanup:o}:{}}}function Eg(t,e={}){let n=gn(t,"native"),i=n.artifact_root??(e.allowMissingArtifactRoot?"docs":void 0);if(typeof i!="string")throw new Error("native.artifact_root must be a string");let r=n.clarification_mode??"sequential";if(r!=="sequential"&&r!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let s=n.archive_confirmation??"automatic";if(s!=="automatic"&&s!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=n.max_verify_failures??ru;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let a=Cg(n.pending_root_move);return{artifact_root:hn(i),language:ou(n.language,"en","native.language"),clarification_mode:r,archive_confirmation:s,max_verify_failures:o,snapshot:Sg(n.snapshot),...a?{pending_root_move:a}:{}}}function Rg(t){let e=gn(t,"classic"),n=e.context_compression??"off";if(n!=="off"&&n!=="beta")throw new Error("classic.context_compression must be off or beta");let i=e.review_mode??"standard";if(i!=="off"&&i!=="standard"&&i!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let r=e.auto_transition??!0;if(typeof r!="boolean")throw new Error("classic.auto_transition must be true or false");return{artifact_layout:su(e.artifact_layout),language:ou(e.language,"zh-CN","classic.language"),context_compression:n,review_mode:i,auto_transition:r}}function _g(t){let e=t??!0;if(typeof e!="boolean")throw new Error("ambient_resume must be true or false");return e}function xg(t,e,n,i,r){let s=t.schema!==void 0;if(!(s||t.default_workflow!==void 0||t.workflows!==void 0||!r.allowPartialProject&&t.native!==void 0)||r.allowPartialProject&&!s)return null;if(t.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(t.default_workflow!=="native"&&t.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let a=t.workflows??[t.default_workflow];if(!Array.isArray(a)||a.length===0||a.some(l=>l!=="native"&&l!=="classic"))throw new Error("workflows must contain native and/or classic");let c=[...new Set(a)];if(!c.includes(t.default_workflow))throw new Error("workflows must include default_workflow");if(c.includes("native")&&!e)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:t.default_workflow,workflows:c,ambient_resume:i,...e?{native:e}:{},...n?{classic:n}:{}}}function Fe(t,e={}){let n=(0,bo.parseDocument)(t,{uniqueKeys:!0});if(n.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${n.errors[0].message}`);let i=n.toJS();if(i==null)return{value:{},config:null,ambient_resume:!0};if(typeof i!="object"||Array.isArray(i))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let r=i,s=_g(r.ambient_resume),o=r.native===void 0?void 0:Eg(r.native,{allowMissingArtifactRoot:e.allowMissingNativeFields}),a=r.classic===void 0?void 0:Rg(r.classic),c=xg(r,o,a,s,{allowPartialProject:e.allowPartialProject??!1});return{value:r,config:c,ambient_resume:s,...o?{native:o}:{},...a?{classic:a}:{}}}function ko(t="docs",e="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,native:{artifact_root:hn(t),language:e,clarification_mode:"sequential",archive_confirmation:"automatic",max_verify_failures:ru,snapshot:{...te,include:[...te.include],exclude:[...te.exclude]}}}}var bo,bt,yo,vo,ru,bg,te,be=U(()=>{"use strict";bo=ct(et(),1),bt=64*1024,yo=1024,vo=64,ru=5,bg=[".agents/skills/**",".amazonq/skills/**",".augment/skills/**",".bob/skills/**",".claude/skills/**",".cline/skills/**",".codebuddy/skills/**",".continue/skills/**",".cospec/skills/**",".crush/skills/**",".cursor/skills/**",".factory/skills/**",".forge/skills/**",".gemini/skills/**",".github/skills/**",".iflow/skills/**",".junie/skills/**",".kilocode/skills/**",".kimi-code/skills/**",".kiro/skills/**",".lingma/skills/**",".mimocode/skills/**",".opencode/skills/**",".pi/skills/**",".qoder/skills/**",".qwen/skills/**",".roo/skills/**",".trae-cn/skills/**",".trae/skills/**",".windsurf/skills/**",".zcode/skills/**"],te={include:["**/*"],exclude:[...bg],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4}});import{promises as We}from"fs";import oe from"path";function cu(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}function Hi(t,e){let n=oe.relative(t,e);return n===""||!oe.isAbsolute(n)&&n!==".."&&!n.startsWith(`..${oe.sep}`)}async function So(t,e){let n=oe.resolve(t),i=await We.lstat(n);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${e} project root must be a real directory`);return We.realpath(n)}async function Co(t,e,n,i){let r=t;for(let s=0;s{if(!Hi(s,a.realPath))throw new Error(`${i.label} resolves outside the project root`);await Co(r.projectRoot,s,r.relative.split("/"),{label:i.label,expected:"file"})}})}var ae=U(()=>{"use strict";ao();be()});import{createHash as Pg}from"crypto";function Og(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function kt(t,e={}){return(await zi(t,e)).document}async function Ag(t){try{return(await W(t,wn,bt,{label:wn})).bytes}catch(e){if(Og(e))return null;throw e}}function Ng(t){return t?{exists:!0,sha256:Pg("sha256").update(t).digest("hex")}:{exists:!1,sha256:null}}async function zi(t,e={}){let n=await Ag(t);return{document:n?Fe(n.toString("utf8"),e):null,identity:Ng(n)}}var wn,St=U(()=>{"use strict";be();ae();wn=".comet/config.yaml"});import{randomUUID as Tg}from"crypto";import{constants as jg,promises as q}from"fs";import B from"path";async function Ro(t,e){try{return await q.link(t,e),{linked:!0}}catch(n){let i=n.code;if(i!=="ENOTSUP"&&i!=="EOPNOTSUPP")throw n}return await q.copyFile(t,e,jg.COPYFILE_EXCL),{linked:!1}}function Ct(t,e){let n=B.relative(t,e);return n===""||!B.isAbsolute(n)&&n!==".."&&!n.startsWith(`..${B.sep}`)}function Qi(t){return{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs}}function Ig(t,e){return ve(t,Qi(e))}function Xi(t,e){let n=Qi(t),i=Qi(e);return Mi(n,i)?ve(n,i):ve(n,i)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.size===e.size}async function Zi(t){let e=await q.lstat(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Contained atomic write parent must be a real directory: ${t}`);return{path:t,realPath:await q.realpath(t),...Qi(e)}}async function Be(t){for(let e of t){let n=await q.lstat(e.path);if(!n.isDirectory()||n.isSymbolicLink()||!Ig(e,n)||await q.realpath(e.path)!==e.realPath)throw new Error(`Contained atomic write parent changed before commit: ${e.path}`)}}async function $g(t,e){let n=B.resolve(t),i=B.resolve(e);if(!Ct(n,i))throw new Error(`Contained atomic write parent is outside its managed root: ${e}`);let r=[await Zi(n)],s=B.relative(n,i).split(B.sep).filter(Boolean),o=n;for(let a of s){await Be(r),o=B.join(o,a);try{await q.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await Zi(o);if(!Ct(r[0].realPath,c.realPath))throw new Error(`Contained atomic write parent resolves outside its managed root: ${o}`);r.push(c)}return await Be(r),r}async function qg(t,e){let n=B.resolve(t),i=B.resolve(e);if(!Ct(n,i))throw new Error(`Contained file parent is outside its managed root: ${e}`);let r=[await Zi(n)],s=B.relative(n,i).split(B.sep).filter(Boolean),o=n;for(let a of s){o=B.join(o,a);try{let c=await Zi(o);if(!Ct(r[0].realPath,c.realPath))throw new Error(`Contained file parent resolves outside its managed root: ${o}`);r.push(c)}catch(c){if(c.code==="ENOENT")return null;throw c}}return await Be(r),r}async function lu(t){let e;try{e=await q.open(t,"r"),await e.sync()}catch(n){let i=n.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(i??""))throw n}finally{await e?.close()}}async function Lg(t,e,n){let i=B.dirname(t),r=await $g(n.containedRoot,i),s=B.join(i,`.${B.basename(t)}.${Tg()}.tmp`),o,a;try{await n.beforeTemporaryOpen?.(),o=await q.open(s,"wx"),a=await o.stat();let[c,l]=await Promise.all([q.lstat(s),q.realpath(s)]);if(await Be(r),!c.isFile()||c.isSymbolicLink()||!Xi(a,c)||!Ct(r[0].realPath,l))throw new Error("Contained atomic write temporary file opened outside its managed parent");if(typeof e=="string"?await o.writeFile(e,"utf8"):await o.writeFile(e),await o.sync(),!Xi(a,await o.stat()))throw new Error("Contained atomic write temporary file changed while writing");await o.close(),o=void 0,await n.beforeCommit?.(),await Be(r);let f=await q.lstat(s);if(!f.isFile()||f.isSymbolicLink()||!Xi(f,a))throw new Error("Contained atomic write temporary file changed before commit");n.exclusive?(await Ro(s,t),await q.unlink(s)):await q.rename(s,t),await lu(i)}catch(c){await o?.close();try{await Be(r),await q.rm(s,{force:!0})}catch{}throw c}}async function ce(t,e,n){await Lg(t,e,n)}async function _o(t,e){let n=B.dirname(t),i=await qg(e.containedRoot,n);if(!i)return!1;let r,s;try{r=await q.lstat(t),s=await q.realpath(t)}catch(c){if(c.code==="ENOENT")return!1;throw c}if(!r.isFile()||r.isSymbolicLink()||!Ct(i[0].realPath,s))throw new Error("Contained file removal target must be a regular file inside its managed root");await e.beforeRemove?.(),await Be(i);let[o,a]=await Promise.all([q.lstat(t),q.realpath(t)]);if(!o.isFile()||o.isSymbolicLink()||!Xi(r,o)||a!==s)throw new Error("Contained file removal target changed before removal");return await q.unlink(t),await Be(i),await lu(n),!0}var nt=U(()=>{"use strict";Fi()});var _k,xo=U(()=>{"use strict";nt();St();ae();_k=16*1024});var Oo=U(()=>{"use strict";nt();be();St();ae();xo()});var nr=U(()=>{"use strict"});var Su=U(()=>{"use strict"});var To=U(()=>{"use strict";nr()});var Cu=U(()=>{"use strict";nr();To()});function rw(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}function sw(t){let e=(0,Eu.parseDocument)(t,{uniqueKeys:!0});if(e.errors.length>0)throw new Error(`Invalid global Comet config: ${e.errors[0].message}`);let n=e.toJS();if(n==null)return{};if(typeof n!="object"||Array.isArray(n))throw new Error("Invalid global Comet config: root must be a mapping");return n}function _u(t){if(t.native?.pending_root_move)throw new Error("Global Comet config cannot contain native.pending_root_move");let e=t.native?(({pending_root_move:n,...i})=>i)(t.native):void 0;return{...t,schema:"comet.global.v1",...e?{native:e}:{}}}function ow(t){let e=Fe(JSON.stringify({...t,schema:"comet.project.v1"})).config;if(!e)throw new Error("Invalid global Comet config: workflow template is incomplete");return _u(e)}function aw(t){let e=Fe(t,{allowPartialProject:!0,allowMissingNativeFields:!0});if(!e.native&&!e.classic)return null;let n=e.native?"native":"classic",i=e.native?.language??e.classic?.language??"en",r=ko(e.native?.artifact_root??"docs",i);return{schema:"comet.global.v1",default_workflow:n,workflows:[n],ambient_resume:e.ambient_resume,...e.native?{native:{...r.native,...e.native}}:{},...e.classic?{classic:e.classic}:{}}}function xu(t){let e=sw(t);if(Object.keys(e).length===0)return null;if(e.schema===void 0)return aw(t);if(e.schema!=="comet.global.v1")throw new Error("Unsupported Comet global schema");return ow(e)}async function jo(t){try{let e=await W(t,Ru,bt,{label:"global Comet config"});return xu(e.bytes.toString("utf8"))}catch(e){if(rw(e))return null;throw e}}var Eu,Ru,Io=U(()=>{"use strict";Eu=ct(et(),1);nt();be();ae();Ru=".comet/config.yaml"});var Pu=U(()=>{"use strict";nr();nt();Su();Cu();be();Io();ae();St();Oo();xo();To()});import{TextDecoder as cw}from"util";function Ou(t){return{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs}}function lw(t,e){try{return new cw("utf-8",{fatal:!0}).decode(t.bytes)}catch(n){throw new Error(`${e} is not valid UTF-8`,{cause:n})}}async function $o(t,e,n,i,r={}){try{let s=await W(t,e,n,{label:i,hooks:r.hooks});return{result:s,text:lw(s,i)}}catch(s){let o=s.code;if(o==="ENOENT"||o==="ENOTDIR")return null;throw s}}async function Cn(t,e,n,i,r={}){return(await $o(t,e,n,i,r))?.text??null}async function ir(t,e,n,i,r,s={}){if(Buffer.byteLength(n,"utf8")>i)throw new Error(`${r} exceeds ${i} bytes`);let o=await $o(t,e,i,r),a=await I(t,e,{label:r,expected:"file"});await ce(a.target,n,{containedRoot:a.projectRoot,beforeCommit:async()=>{await s.beforeCommit?.();let c=await $o(t,e,i,r);if(!(!o&&!c)){if(!o||!c)throw new Error(`${r} changed before commit`);if(o.result.realPath!==c.result.realPath||!ve(Ou(o.result.stat),Ou(c.result.stat))||o.text!==c.text)throw new Error(`${r} changed before commit`)}}})}async function rr(t,e,n,i,r,s={}){let o=await Cn(t,e,i,r);await ir(t,e,`${o??""}${n}`,i,r,s)}async function qo(t,e,n,i={}){let r=await I(t,e,{label:n,expected:"file"});return r.exists?_o(r.target,{containedRoot:r.projectRoot,beforeRemove:i.beforeRemove}):!1}var sr=U(()=>{"use strict";Pu();Fi()});var Tu={};qf(Tu,{RUN_STATE_FILE:()=>ar,applyRunStateToDocument:()=>Lo,readRunState:()=>_n,removeRunState:()=>Do,runStateFromDocument:()=>or,writeRunState:()=>cr});import uw from"path";function Rn(t,e){let n=t[e];if(typeof n!="string"||n.length===0)throw new Error(`Invalid Run state: ${e} must be a non-empty string`);return n}function En(t,e){let n=Rn(t,e);if(uw.isAbsolute(n)||/^(?:[A-Za-z]:|[\\/]|~)/u.test(n)||n.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Run state: ${e} must stay inside the change directory`);return n}function fw(t){let e=t.run_retries??"{}",n;try{n=typeof e=="string"?JSON.parse(e):e}catch(i){throw new Error("Invalid Run state: run_retries must be a JSON object",{cause:i})}if(!n||typeof n!="object"||Array.isArray(n))throw new Error("Invalid Run state: run_retries must be a JSON object");for(let i of Object.values(n))if(!Number.isInteger(i)||Number(i)<0)throw new Error("Invalid Run state: retry counts must be non-negative integers");return n}function or(t){if(!t.run_id)return null;let e=Rn(t,"run_id"),n=Rn(t,"skill"),i=Rn(t,"skill_version"),r=Rn(t,"skill_hash"),s=En(t,"pending_ref"),o=En(t,"trajectory_ref"),a=En(t,"context_ref"),c=En(t,"artifacts_ref"),l=En(t,"checkpoint_ref"),f=Number(t.iteration);if(!Number.isInteger(f)||f<0)throw new Error("Invalid Run state: iteration must be a non-negative integer");if(t.orchestration!=="deterministic"&&t.orchestration!=="adaptive")throw new Error("Invalid Run state: orchestration must be deterministic or adaptive");if(t.run_status!=="running"&&t.run_status!=="waiting"&&t.run_status!=="completed"&&t.run_status!=="failed")throw new Error("Invalid Run state: run_status is invalid");return{runId:e,skill:n,skillVersion:i,skillHash:r,orchestration:t.orchestration,currentStep:Au(t,"current_step"),iteration:f,pending:Au(t,"pending"),pendingRef:s,trajectoryRef:o,contextRef:a,artifactsRef:c,checkpointRef:l,status:t.run_status,retries:fw(t)}}function Lo(t,e){e?t.run_id=e.runId:delete t.run_id}function dw(t){return{runId:t.runId,skill:t.skill,skillVersion:t.skillVersion,skillHash:t.skillHash,orchestration:t.orchestration,currentStep:t.currentStep,iteration:t.iteration,pending:t.pending,pendingRef:t.pendingRef,trajectoryRef:t.trajectoryRef,contextRef:t.contextRef,artifactsRef:t.artifactsRef,checkpointRef:t.checkpointRef,status:t.status,retries:t.retries}}function pw(t){let e={run_id:t.runId,skill:t.skill,skill_version:t.skillVersion,skill_hash:t.skillHash,orchestration:t.orchestration,current_step:t.currentStep,iteration:t.iteration,pending:t.pending,pending_ref:t.pendingRef,trajectory_ref:t.trajectoryRef,context_ref:t.contextRef,artifacts_ref:t.artifactsRef,checkpoint_ref:t.checkpointRef,run_status:t.status,run_retries:JSON.stringify(t.retries)};return or(e)}async function _n(t,e={}){let n=await Cn(t,ar,Nu,"Run state",e);if(n===null)return null;let i=JSON.parse(n);return pw(i)}async function cr(t,e,n={}){await ir(t,ar,JSON.stringify(dw(e),null,2),Nu,"Run state",n)}async function Do(t,e={}){await qo(t,ar,"Run state",e)}var Au,ar,Nu,xn=U(()=>{"use strict";sr();Au=(t,e)=>{let n=t[e];return n==null?null:String(n)};ar=".comet/run-state.json",Nu=256*1024});var Mn=ct(et(),1);import{spawnSync as Iy}from"child_process";import{promises as $y}from"fs";import O from"path";ao();import{randomUUID as fg}from"crypto";import{promises as un}from"fs";import Vl from"path";var co="comet.selection.v2",dg=16*1024;function Ui(t){return Vl.join(t,".comet","current-change.json")}function pg(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function Yl(t){return t===null||typeof t=="string"}function Jl(t){let e;try{e=JSON.parse(t)}catch(n){throw new Error(`current change selection contains invalid JSON: ${n instanceof Error?n.message:String(n)}`,{cause:n})}if(!pg(e))throw new Error("current change selection must be a JSON object");if(e.version===1){if(typeof e.change!="string")throw new Error("legacy current change selection change must be a string");if(e.branch!==void 0&&!Yl(e.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:co,workflow:"classic",change:e.change,branch:e.branch??null},legacy:!0}}if(e.schema!==co)throw new Error(`current change selection schema must be ${co}`);if(e.workflow!=="native"&&e.workflow!=="classic")throw new Error("current change selection workflow must be native or classic");if(typeof e.change!="string")throw new Error("current change selection change must be a string");if(!Yl(e.branch))throw new Error("current change selection branch must be a string or null");if(e.workflow==="native"&&e.branch!==null)throw new Error("Native current change selection branch must be null");return{selection:e,legacy:!1}}async function lo(t){let e;try{let i=Ui(t),{bytes:r}=await Ki(i,dg,{label:"current change selection"});e=r.toString("utf8")}catch(i){if(i.code==="ENOENT")return{status:"missing"};throw new Error(`cannot read current change selection: ${i instanceof Error?i.message:String(i)}`,{cause:i})}return{status:"selected",...Jl(e)}}async function Hl(t,e){let n=Jl(JSON.stringify(e));if(n.legacy)throw new Error("cannot write a legacy current change selection");let i=Ui(t),r=`${i}.${fg()}.tmp`;await un.mkdir(Vl.dirname(i),{recursive:!0});try{await un.writeFile(r,`${JSON.stringify(n.selection,null,2)} -`,"utf8"),await un.rename(r,i)}catch(s){throw await un.rm(r,{force:!0}),s}}async function Gl(t){await un.rm(Ui(t),{force:!0})}var zl=null;function Xl(t,e){let n=t;for(let i of e)n+="\0"+(typeof i=="string"?i:JSON.stringify(i));return n}function Ql(t,e){return(...n)=>{let i=zl;if(i===null)return e(...n);let r=Xl(`async:${t}`,n),s=i.entries.get(r);if(s)return s.value;let o=e(...n).catch(a=>{throw i.entries.delete(r),a});return i.entries.set(r,{value:o}),o}}function uo(t,e){return(...n)=>{let i=zl;if(i===null)return e(...n);let r=Xl(`sync:${t}`,n),s=i.entries.get(r);if(s)return s.value;let o=e(...n);return i.entries.set(r,{value:o}),o}}var fo=ct(et(),1);import{execFileSync as Zl}from"child_process";import{randomUUID as mg}from"crypto";import{promises as fn}from"fs";import eu from"path";function Yi(t){try{let e=Zl("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();return e&&e!=="HEAD"?e:null}catch{return null}}var hg=uo("liveGitBranch",t=>Yi(t));function po(t){try{return Zl("git",["rev-parse","--is-inside-work-tree"],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()==="true"}catch{return!1}}var gg=uo("isGitWorkTree",t=>po(t)),wg=["current","branch","worktree"];function Vi(t){return wg.includes(t)}function mo(t){return Vi(t.isolation)?t.boundBranch===null&&t.currentBranch===null&&t.gitWorkTree===!1?{status:"not-applicable"}:t.boundBranch===null?t.currentBranch===null?{status:"unbound-detached"}:{status:"needs-heal",branch:t.currentBranch}:t.currentBranch===t.boundBranch?{status:"ok"}:{status:"drift",boundBranch:t.boundBranch,currentBranch:t.currentBranch}:{status:"not-applicable"}}async function dn(t,e){let n=eu.join(t,".comet.yaml"),i=(0,fo.parseDocument)(await fn.readFile(n,"utf8"),{uniqueKeys:!1});if(i.errors.length>0)throw new Error(`Invalid .comet.yaml: ${i.errors[0].message}`);let r=i.toJS()??{},s=typeof r.isolation=="string"?r.isolation:null,o=typeof r.bound_branch=="string"&&r.bound_branch!==""?r.bound_branch:null,a=Vi(s),c=hg(e.cwd),l=a&&o===null&&c===null?gg(e.cwd):!0,f=mo({isolation:s,boundBranch:o,currentBranch:c,gitWorkTree:l});return f.status==="needs-heal"&&e.heal?(await ho(t,f.branch),{status:"healed",branch:f.branch,bindingRequired:a,currentBranch:c}):{...f,bindingRequired:a,currentBranch:c}}async function ho(t,e){let n=eu.join(t,".comet.yaml"),i=(0,fo.parseDocument)(await fn.readFile(n,"utf8"),{uniqueKeys:!1});i.set("bound_branch",e);let r=`${n}.${mg()}.tmp`;try{await fn.writeFile(r,i.toString(),"utf8"),await fn.rename(r,n)}catch(s){throw await fn.rm(r,{force:!0}),s}}function tu(t){return t??"detached HEAD"}function nu(t,e,n){return`change '${t}' is bound to branch '${e}', but current branch is '${tu(n)}'. -Next: ask the user to confirm — switch back to '${e}', or run \`comet state rebind ${t}\` after explicit confirmation.`}function go(t,e,n){return`change '${t}' is bound to branch '${e}', but current branch is '${tu(n)}'`}function pn(t){return`change '${t}' uses a branch-bound workspace mode but has no bound branch and HEAD is detached; checkout a branch first before continuing.`}import{promises as Gg}from"fs";import Et from"path";import{promises as Bg}from"fs";import j from"path";import{promises as yg}from"fs";async function mn(t){try{return await yg.access(t),!0}catch(e){if(vg(e))return!1;throw e}}function vg(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}be();St();Oo();ae();var yn=class extends Error{code="classic-layout-unavailable";constructor(e="Classic artifact layout is unavailable from .comet/config.yaml"){super(e),this.name="ClassicLayoutUnavailableError"}},Ao=class extends Error{constructor(n,i,r){let s=X(r,n),o=X(r,i);super(`Classic layout conflict: both ${s}/ and ${o}/ exist; run comet doctor and resolve the conflict before writing`);this.configuredRoot=n;this.alternateRoot=i;this.name="ClassicLayoutConflictError"}configuredRoot;alternateRoot;code="classic-layout-conflict"},du=".comet/config.yaml";function Kg(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function pu(t){await I(t,du,{label:du,expected:"file"})}function mu(t,e){let n=j.resolve(t),i=e==="docs"?j.join(n,"docs"):n,r=j.join(i,"openspec"),s=j.join(n,"docs","superpowers");return{projectRoot:n,artifactLayout:e,openSpecBase:i,openSpecRoot:r,changesDir:j.join(r,"changes"),archiveDir:j.join(r,"changes","archive"),specsDir:j.join(r,"specs"),superpowersRoot:s,superpowersSpecsDir:j.join(s,"specs"),superpowersPlansDir:j.join(s,"plans"),superpowersReportsDir:j.join(s,"reports")}}async function Ug(t){await pu(t);let e=await kt(t,{allowPartialProject:!0,allowMissingNativeFields:!0});if(!e?.config)throw new yn;if(!(e.config.workflows??[e.config.default_workflow]).includes("classic"))throw new yn("Classic artifact layout is unavailable because Classic is not enabled");return e.classic?.artifact_layout??"legacy"}async function Yg(t,e){return mu(t,e??await Ug(t))}async function Vg(t,e){let n=await Yg(t,e),i=n.artifactLayout==="legacy"?"docs":"legacy",r=mu(t,i).openSpecRoot,[s,o]=await Promise.all([I(n.projectRoot,X(n.projectRoot,n.openSpecRoot),{label:"Configured Classic OpenSpec root",expected:"directory"}),I(n.projectRoot,X(n.projectRoot,r),{label:"Alternate Classic OpenSpec root",expected:"directory"})]),a=s.exists,c=o.exists;return{paths:n,configuredRootExists:a,alternateRoot:r,alternateRootExists:c,dualRoots:a&&c}}async function Jg(t,e){let n=[t.openSpecRoot,t.changesDir,t.archiveDir,t.specsDir,e,t.superpowersRoot,t.superpowersSpecsDir,t.superpowersPlansDir,t.superpowersReportsDir];for(let i of n){let r=X(t.projectRoot,i);await I(t.projectRoot,r,{label:`Classic managed physical path ${r}`,expected:"directory"})}}async function ne(t,e,n={}){let i=await Vg(t,e);if(await Jg(i.paths,i.alternateRoot),i.dualRoots&&!n.allowAlternateRoot)throw new Ao(i.paths.openSpecRoot,i.alternateRoot,i.paths.projectRoot);if(!i.configuredRootExists){let r=X(i.paths.projectRoot,i.paths.openSpecRoot),s=X(i.paths.projectRoot,i.alternateRoot);throw new yn(`Configured Classic OpenSpec root is missing: ${r} (alternate ${s} is ${i.alternateRootExists?"present":"missing"})`)}return i.paths}async function er(t,e,n={}){let i=j.join(j.resolve(t),".comet","classic-root-move.json");if(await mn(i))throw new Error("Classic root move transaction is incomplete; inspect it with comet doctor and recover it explicitly before writing");let r=await ne(t,e,n);if(!await mn(r.openSpecRoot))throw new Error(`Configured Classic OpenSpec root is missing: ${X(r.projectRoot,r.openSpecRoot)}`);return r}async function vn(t){let e=j.resolve(t),n=null;try{(await Bg.lstat(e)).isDirectory()||(e=j.dirname(e))}catch(i){if(!Kg(i))throw i}for(;;){j.basename(e)==="openspec"&&(n=j.dirname(e));let i=j.join(e,".comet","config.yaml"),r=!1;if(await mn(i))try{await pu(e);let o=(await kt(e))?.value;r=!!o&&typeof o=="object"&&!Array.isArray(o)&&(o.schema==="comet.project.v1"||o.default_workflow!==void 0||o.native!==void 0)}catch{}if(r||await mn(j.join(e,".git")))return e;let s=j.dirname(e);if(s===e)return n??j.resolve(t);e=s}}function X(t,e){return j.relative(j.resolve(t),e).replaceAll("\\","/")}nt();be();ae();import bn from"path";var Hg=2*1024*1024;function tr(t,e,n){let i=bn.resolve(t),r=bn.isAbsolute(e)?bn.resolve(e):bn.resolve(i,e),s=bn.relative(i,r).replaceAll("\\","/");return{root:i,relative:Me(s,n),target:r}}async function Ke(t,e,n){let i=tr(t,e,n.label);return I(i.root,i.relative,n)}async function kn(t,e,n){return(await Ke(t,e,{label:n.label,expected:n.expected??"any"})).exists}async function hu(t,e,n,i){return await kn(t,e,{label:n,expected:"file"})?(await gu(t,e,{label:n,hooks:i})).byteLength>0:!1}async function Ue(t,e,n){return(await gu(t,e,n)).toString("utf8")}async function gu(t,e,n){let i=tr(t,e,n.label);return(await W(i.root,i.relative,n.maxBytes??Hg,{label:n.label,hooks:n.hooks})).bytes}async function wu(t,e,n){let i=tr(t,e,n);return Eo(i.root,i.relative,{label:n})}async function yu(t,e,n,i){let r=tr(t,e,i.label);await I(r.root,r.relative,{label:i.label,expected:"file"}),await ce(r.target,n,{containedRoot:r.root,beforeTemporaryOpen:i.beforeTemporaryOpen,beforeCommit:i.beforeCommit,exclusive:i.exclusive})}function No(t){return t?/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t)?t.includes("..")?"Change name cannot contain '..' (path traversal not allowed)":null:`Invalid change name: '${t}' -Valid format: lowercase kebab-case (a-z, 0-9, single hyphens)`:"Change name cannot be empty"}function it(t){let e=No(t);if(e)throw new Error(e)}function zg(t,e){return{label:X(t,e),directory:e}}async function Sn(t,e,n){let i=zg(t,e);if(!(await Ke(t,e,{label:n,expected:"directory"})).exists)return{change:i,exists:!1,stateExists:!1};let s=await Ke(t,Et.join(e,".comet.yaml"),{label:`${n} state`,expected:"file"});return{change:i,exists:!0,stateExists:s.exists}}function Xg(t,e){let n=e.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&");return new RegExp(`^\\d{4}-\\d{2}-\\d{2}-${n}$`,"u").test(t)}async function Qg(t,e,n,i={}){if(!i.skipExactCompatibility){let o=await Sn(t,Et.join(e,n),`Classic archived change ${n}`);if(o.exists)return o.change}if(!(await Ke(t,e,{label:"Classic archive directory",expected:"directory"})).exists)return null;let s=[];for(let o of await Gg.readdir(e,{withFileTypes:!0})){if(!Xg(o.name,n))continue;let a=await Sn(t,Et.join(e,o.name),`Classic archived change ${o.name}`);a.exists&&a.stateExists&&s.push(a.change)}return s.sort((o,a)=>a.directory.localeCompare(o.directory))[0]??null}async function vu(t,e=process.cwd()){it(t);let n=await ne(e),i=await Sn(n.projectRoot,Et.join(n.changesDir,t),`Classic active change ${t}`);return{...i.change,exists:i.exists,stateExists:i.stateExists}}async function bu(t,e=process.cwd()){it(t);let n=await er(e),i=Et.join(n.changesDir,t),r=await Sn(n.projectRoot,i,`Classic active change ${t}`);return r.exists||await wu(n.projectRoot,i,`Classic active change ${t}`),r.change}async function ku(t,e=process.cwd()){it(t);let n=await ne(e),i=await Sn(n.projectRoot,Et.join(n.changesDir,t),`Classic active change ${t}`);if(i.exists)return i.change;let r=await Qg(n.projectRoot,n.archiveDir,t);return r||i.change}var fr=ct(et(),1);nt();ae();import ur from"path";xn();var ju=["full","hotfix","tweak"],Pn=1,mw=["open","design","build","verify","archive"],hw=["en","zh-CN"],gw=["off","beta"],ww=["subagent-driven-development","executing-plans","direct"],yw=["plan-ready"],vw=["confirmed"],bw=["tdd","direct"],kw=["off","standard","thorough"],Sw=["current","branch","worktree"],Cw=["light","full"],Ew=["pending","pass","fail"],Rw=["pending","handled"],_w=["pending","confirmed"],_t=["workflow","language","phase","context_compression","build_mode","build_pause","subagent_dispatch","tdd_mode","review_mode","isolation","bound_branch","verify_mode","auto_transition","base_ref","design_doc","plan","verify_result","verify_failures","verification_report","branch_status","created_at","verified_at","archive_confirmation","archived","direct_override","handoff_context","handoff_hash","classic_profile","classic_migration"],Fo=["run_id"],xw=new Set([..._t,...Fo]),Pw=["workflow","phase","design_doc","plan","build_mode","isolation","verify_mode","verify_result","verified_at","archived"];function Iu(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function Rt(t,e){let n=t[e];if(n==null||n==="")return null;if(typeof n!="string")throw new Error(`Invalid Classic state: ${e} must be a string or null`);return n}function V(t,e,n,i=!0){let r=t[e];if(r==null||r===""){if(i)return null;throw new Error(`Invalid Classic state: ${e} is required`)}if(typeof r!="string"||!n.includes(r))throw new Error(`Invalid Classic state: ${e} must be one of ${n.join(", ")}${i?" or null":""}`);return r}function Mo(t,e,n=!0){let i=t[e];if(i==null||i===""){if(n)return null;throw new Error(`Invalid Classic state: ${e} is required`)}if(typeof i!="boolean")throw new Error(`Invalid Classic state: ${e} must be true or false`);return i}function Ow(t,e,n=0){let i=t[e];if(i==null||i==="")return n;if(typeof i!="number"||!Number.isInteger(i)||i<0)throw new Error(`Invalid Classic state: ${e} must be a non-negative integer`);return i}function lr(t,e){let n=Rt(t,e);if(n===null)return null;if(/^(?:[A-Za-z]:|[\\/]|~)/u.test(n)||n.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Classic state: ${e} must be a relative repository path`);return n}function Aw(t,e){let n=Rt(t,e);if(n!==null&&!/^[a-f0-9]{64}$/u.test(n))throw new Error(`Invalid Classic state: ${e} must be a sha256 hex digest`);return n}function Nw(t){let e=t.classic_migration;if(e==null||e==="")return null;if(e!==Pn)throw new Error(`Invalid Classic state: classic_migration must be ${Pn}`);return e}function Tw(t){if(!_t.some(n=>Iu(t,n)))return null;for(let n of Pw)if(!Iu(t,n))return null;return{workflow:V(t,"workflow",ju,!1),language:V(t,"language",hw),phase:V(t,"phase",mw,!1),contextCompression:V(t,"context_compression",gw),buildMode:V(t,"build_mode",ww),buildPause:V(t,"build_pause",yw),subagentDispatch:V(t,"subagent_dispatch",vw),tddMode:V(t,"tdd_mode",bw),reviewMode:V(t,"review_mode",kw),isolation:V(t,"isolation",Sw),boundBranch:Rt(t,"bound_branch"),verifyMode:V(t,"verify_mode",Cw),autoTransition:Mo(t,"auto_transition"),baseRef:Rt(t,"base_ref"),designDoc:lr(t,"design_doc"),plan:lr(t,"plan"),verifyResult:V(t,"verify_result",Ew,!1),verifyFailures:Ow(t,"verify_failures"),verificationReport:lr(t,"verification_report"),branchStatus:V(t,"branch_status",Rw),createdAt:Rt(t,"created_at"),verifiedAt:Rt(t,"verified_at"),archiveConfirmation:V(t,"archive_confirmation",_w),archived:Mo(t,"archived",!1),directOverride:Mo(t,"direct_override"),handoffContext:lr(t,"handoff_context"),handoffHash:Aw(t,"handoff_hash"),classicProfile:V(t,"classic_profile",ju),classicMigration:Nw(t)}}function On(t,e){let n=e??null;if(n===null&&e===void 0&&t.run_id&&t.skill)try{n=or(t)}catch(i){let r=i instanceof Error?i.message:String(i);throw new Error(r.replace(/^Invalid Run state:/u,"Invalid Classic state:"),{cause:i})}return{classic:Tw(t),run:n,unknownKeys:Object.keys(t).filter(i=>!xw.has(i))}}function $u(t){return{workflow:t.workflow,language:t.language,phase:t.phase,context_compression:t.contextCompression,build_mode:t.buildMode,build_pause:t.buildPause,subagent_dispatch:t.subagentDispatch,tdd_mode:t.tddMode,review_mode:t.reviewMode,isolation:t.isolation,bound_branch:t.boundBranch,verify_mode:t.verifyMode,auto_transition:t.autoTransition,base_ref:t.baseRef,design_doc:t.designDoc,plan:t.plan,verify_result:t.verifyResult,verify_failures:t.verifyFailures,verification_report:t.verificationReport,branch_status:t.branchStatus,created_at:t.createdAt,verified_at:t.verifiedAt,archive_confirmation:t.archiveConfirmation,archived:t.archived,direct_override:t.directOverride,handoff_context:t.handoffContext,handoff_hash:t.handoffHash,classic_profile:t.classicProfile,classic_migration:t.classicMigration}}xn();var jw=2*1024*1024;function An(t){let e=t.toJS();if(e===null)return{};if(typeof e!="object"||Array.isArray(e))throw new Error("Invalid Classic state document: root must be a mapping");return e}function qu(t,e,n){t.get(e)!==n&&t.set(e,n)}function Iw(t,e){if(e.classic)for(let[n,i]of Object.entries($u(e.classic)))qu(t,n,i);else for(let n of _t)t.delete(n);Lo(t.toJS(),e.run),e.run?qu(t,"run_id",e.run.runId):t.delete("run_id")}function $w(t){let e=["skill","skill_version","skill_hash","orchestration","current_step","iteration","pending","pending_ref","trajectory_ref","context_ref","artifacts_ref","checkpoint_ref","run_status","run_retries"];for(let n of e)t.delete(n)}function qw(t){let e=!1;for(let n of["build_command","verify_command"])t.has(n)&&(t.delete(n),e=!0);return e}async function Lu(t){let e;try{e=(await W(ur.dirname(t),ur.basename(t),jw,{label:"Classic state document"})).bytes.toString("utf8")}catch(i){if(i.code!=="ENOENT")throw i;return new fr.Document({})}let n=(0,fr.parseDocument)(e);if(n.errors.length>0)throw new Error(`Invalid Classic state document: ${n.errors[0].message}`);return An(n),n}async function me(t,e={}){let n=e.migrate!==!1,i=ur.join(t,".comet.yaml"),r=await Lu(i),s=An(r),o=qw(r);o&&(s=An(r));let a=await _n(t);if(!a&&s.run_id&&s.skill){let{runStateFromDocument:c}=await Promise.resolve().then(()=>(xn(),Tu));a=c(s),a&&n&&(await cr(t,a),$w(r),o=!0)}return o&&n&&await ce(i,r.toString(),{containedRoot:t}),On(An(r),a)}async function xt(t,e,n={}){let i=ur.join(t,".comet.yaml"),r=await Lu(i);Iw(r,{...e,unknownKeys:e.unknownKeys??[]}),On(An(r),e.run??null),await ce(i,r.toString(),{containedRoot:t,beforeCommit:n.beforeCommit}),e.run?await cr(t,e.run):await Do(t)}var Lw=Ql("readCometCurrentSelection",t=>lo(t));async function Du(t,e){it(e);let n=await vu(e,t);if(!n.stateExists)throw new Error(`Cannot select current change '${e}': active change state not found`);let i=await me(n.directory,{migrate:!1});if(!i.classic)throw new Error(`Cannot select current change '${e}': Classic state is incomplete`);if(i.classic.archived)throw new Error(`Cannot select current change '${e}': change is archived`);return n.directory}async function Mu(t,e){let n=await Du(t,e),i=await dn(n,{heal:!0,cwd:t});if(i.status==="drift")throw new Error(go(e,i.boundBranch,i.currentBranch));if(i.status==="unbound-detached")throw new Error(pn(e));let r={schema:"comet.selection.v2",workflow:"classic",change:e,branch:i.currentBranch};return await Hl(t,r),r}async function Fu(t){let e;try{e=await Lw(t)}catch(s){return{status:"stale",reason:s instanceof Error?s.message:String(s)}}if(e.status==="missing")return{status:"missing"};if(e.selection.workflow!=="classic")return{status:"stale",reason:`current change '${e.selection.change}' belongs to Native, not Classic`};let n=e.selection,i;try{i=await Du(t,n.change)}catch(s){return{status:"stale",reason:s instanceof Error?s.message:String(s)}}let r=await dn(i,{heal:!1,cwd:t});return r.status==="drift"?{status:"stale",reason:go(n.change,r.boundBranch,r.currentBranch)}:r.status==="unbound-detached"?{status:"stale",reason:pn(n.change)}:r.status==="ok"?{status:"selected",selection:n}:n.branch!==null&&r.currentBranch!==n.branch?{status:"stale",reason:`current change '${n.change}' was selected on branch '${n.branch}', current branch is '${r.currentBranch??"detached HEAD"}'`}:{status:"selected",selection:n}}async function Wu(t){let e;try{e=await lo(t)}catch{return}e.status==="selected"&&e.selection.workflow==="classic"&&await Gl(t)}import{promises as Mw}from"fs";import ke from"path";ae();be();import Nn from"path";function Dw(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function Bu(t,e,n,i){let r=Me(n,"Classic handoff artifact pointer");if((await I(t,r,{label:"Classic handoff artifact",expected:"file"})).exists)return null;let o=await ne(t),a=`${X(t,o.changesDir)}/`,l=(o.artifactLayout==="docs"?[a,"openspec/changes/"]:[a]).find(y=>r.startsWith(y));if(!l)return null;let f=r.slice(l.length).split("/");if(f.length<4||f[1]!==".comet"||f.slice(2).some(y=>y.length===0))return null;let u=f[0];it(u);let d=f.slice(2),m=Nn.resolve(e);if(Nn.dirname(m)!==Nn.resolve(o.archiveDir))return null;let g=Nn.basename(m),p=/^\d{4}-\d{2}-\d{2}-(.+)$/u.exec(g);if(g!==u&&p?.[1]!==u)return null;await I(t,X(t,m),{label:"Classic archived change directory",expected:"directory"});let h=Nn.join(m,".comet",...d),v=X(t,h);try{return await W(t,v,i,{label:"Historical Classic archived handoff artifact"}),v}catch(y){if(Dw(y))return null;throw y}}ae();var Ku=2*1024*1024;function Tn(t,e){return ke.relative(t,e).split(ke.sep).join("/")}async function jn(t,e,n){if(!n)return{code:e,satisfied:!1};let i=n.replaceAll("\\","/");try{let r=await Gi(t,i,{label:`${e} artifact`});return{code:e,satisfied:r,source:i,...r?{resolvedSource:i}:{}}}catch(r){return{code:e,satisfied:!1,source:i,detail:`unsafe artifact pointer outside the project or through a special path: ${r instanceof Error?r.message:String(r)}`}}}async function Fw(t,e,n){try{await ne(t)}catch(r){return{code:"design.handoff",satisfied:!1,...n?{source:n.replaceAll("\\","/")}:{},detail:`Classic layout is unsafe or unavailable for handoff evidence: ${r instanceof Error?r.message:String(r)}`}}let i=await jn(t,"design.handoff",n);if(!n||i.satisfied||i.detail)return i;try{let r=await Bu(t,e,n,Ku);return r?{...i,satisfied:!0,resolvedSource:r,detail:`resolved historical legacy pointer from archived change: ${r}`}:i}catch(r){return{...i,satisfied:!1,detail:`unsafe archived handoff fallback: ${r instanceof Error?r.message:String(r)}`}}}async function dr(t,e,n){return jn(t,e,Tn(t,n))}async function Ww(t,e){let n=ke.join(e,"specs"),i;try{let o=Tn(t,n);if(!(await I(t,o,{label:"OpenSpec delta-spec directory",expected:"directory"})).exists)return{code:"openspec.delta-spec",satisfied:!1};i=await Mw.readdir(n)}catch(o){return o.code==="ENOENT"?{code:"openspec.delta-spec",satisfied:!1}:{code:"openspec.delta-spec",satisfied:!1,detail:`unsafe delta-spec path: ${o instanceof Error?o.message:String(o)}`}}let r=i.map(o=>ke.join(n,o,"spec.md")),s=(await Promise.all(r.map(async o=>{try{return await Gi(t,Tn(t,o),{label:"OpenSpec delta spec"})?o:null}catch{return null}}))).filter(o=>o!==null);return{code:"openspec.delta-spec",satisfied:s.length>0,source:s[0]?Tn(t,s[0]):void 0,detail:`${s.length} delta spec${s.length===1?"":"s"}`}}async function Bw(t,e){let n,i=Tn(t,e);try{n=(await W(t,i,Ku,{label:"Classic tasks artifact"})).bytes.toString("utf8")}catch(o){return o.code==="ENOENT"?{code:"build.tasks-complete",satisfied:!1}:{code:"build.tasks-complete",satisfied:!1,source:i,detail:`unsafe tasks artifact: ${o instanceof Error?o.message:String(o)}`}}let r=[...n.matchAll(/^\s*[-*]\s+\[([ xX])\]\s+/gmu)],s=r.filter(o=>o[1].toLowerCase()==="x").length;return{code:"build.tasks-complete",satisfied:r.length>0&&s===r.length,source:i,detail:`${s} of ${r.length} tasks complete`}}function In(t,e){return t.some(n=>n.code===e&&n.satisfied)}async function Pt(t,e){let n=await vn(t),i=e.classic,r=ke.join(t,"proposal.md"),s=ke.join(t,"design.md"),o=ke.join(t,"tasks.md"),a=e.run?ke.resolve(t,e.run.checkpointRef):ke.join(t,".comet","checkpoint.json"),c=await Promise.all([dr(n,"openspec.proposal",r),dr(n,"openspec.design",s),dr(n,"openspec.tasks",o),Ww(n,t),jn(n,"design.document",i?.designDoc??null),jn(n,"build.plan",i?.plan??null),Bw(n,o),jn(n,"verification.report",i?.verificationReport??null),Fw(n,t,i?.handoffContext??null),dr(n,"run.checkpoint",a)]),l=c.find(f=>f.code==="design.handoff");return l&&!i?.handoffHash&&(l.satisfied=!1,l.detail="handoff hash is missing"),c.push({code:"archive.confirmed",satisfied:i?.archiveConfirmation==="confirmed"}),c}import{AsyncLocalStorage as Kw}from"async_hooks";import{promises as Uu}from"fs";import $n from"path";var pr=new Kw;function Uw(t,e){let n=$n.relative(t,e);return n===""||!$n.isAbsolute(n)&&n!==".."&&!n.startsWith(`..${$n.sep}`)}async function Yw(t){let e=$n.resolve(t.invocationCwd??process.cwd()),n=$n.resolve(t.projectRoot??await vn(e)),[i,r]=await Promise.all([Uu.realpath(e),Uu.realpath(n)]);if(!Uw(r,i))throw new Error(`Classic command invocation cwd is outside the discovered project: ${e}`);return{invocationCwd:e,projectRoot:n}}async function Yu(t,e){let n=pr.getStore();if(n)return e(n);let i=await Yw(t);return pr.run(i,()=>e(i))}function T(){let t=pr.getStore();if(!t)throw new Error("Classic command project context is unavailable");return t.projectRoot}function qn(){let t=pr.getStore();if(!t)throw new Error("Classic command invocation context is unavailable");return t.invocationCwd}function Vw(t){return t.classicProfile??t.workflow}function Jw(t){return!t.buildMode||!t.tddMode||!t.isolation||!t.verifyMode?!1:t.buildMode==="subagent-driven-development"?t.subagentDispatch==="confirmed":t.buildMode==="direct"?t.directOverride===!0:!0}function Hw(t){return t.buildMode==="direct"&&t.tddMode==="direct"&&t.isolation!==null&&t.verifyMode==="light"}function Gw(t,e,n){if(e.verifyResult==="fail")return t==="full"?"full.build.fix":`${t}.build.execute`;if(t==="full"){if(!In(n,"build.plan"))return"full.build.plan";if(e.buildPause==="plan-ready")return"full.build.plan-ready";if(!Jw(e))return"full.build.configure"}else if(!Hw(e))throw new Error(`${t} build configuration is incomplete`);return In(n,"build.tasks-complete")?`${t}.build.complete`:`${t}.build.execute`}function zw(t,e,n){return e.verifyResult!=="pass"||!In(n,"verification.report")?`${t}.verify.run`:`${t}.verify.branch`}function Xw(t,e){if(e.verifyResult!=="pass")throw new Error("archive requires verify_result=pass");return e.archiveConfirmation==="confirmed"?`${t}.archive.execute`:`${t}.archive.confirm`}function Ot(t,e){let n=Vw(t);if(t.archived&&t.phase!=="archive")throw new Error("archived=true requires phase=archive");if(t.archived)return"completed";if(n!=="full"&&t.phase==="design")throw new Error(`${n} workflow cannot enter design`);switch(t.phase){case"open":return`${n}.open`;case"design":return In(e,"design.handoff")?"full.design.document":"full.design.handoff";case"build":return Gw(n,t,e);case"verify":return zw(n,t,e);case"archive":return Xw(n,t)}}import{promises as ff}from"fs";import Z from"path";import{fileURLToPath as df}from"url";sr();import mr from"path";var Vu={trajectory:8*1024*1024,artifacts:1024*1024,context:1024*1024,pendingAction:256*1024,checkpoint:256*1024};function Ju(t,e){if(mr.isAbsolute(e))throw new Error("Run path must stay inside the change directory");let n=mr.resolve(t),i=mr.resolve(n,e);if(i!==n&&!i.startsWith(n+mr.sep))throw new Error("Run path must stay inside the change directory")}async function rt(t,e,n,i={}){Ju(t,e),await rr(t,e,`${JSON.stringify(n)} -`,Vu.trajectory,"Run trajectory",i)}async function At(t,e,n={}){Ju(t,e);let i=await Cn(t,e,Vu.trajectory,"Run trajectory",n);return i===null?[]:i.split(/\r?\n/).map((r,s)=>({line:r,number:s+1})).filter(({line:r})=>r.length>0).map(({line:r,number:s})=>{try{return JSON.parse(r)}catch(o){throw new Error(`Invalid Trajectory event at line ${s}`,{cause:o})}})}import{createHash as cf,randomUUID as YC}from"crypto";import{promises as Nt}from"fs";import he from"path";var zu=ct(et(),1);import{promises as Wo}from"fs";import ie from"path";var Qw=["invoke_skill","call_tool","handoff","ask_user","checkpoint"],Zw=["deterministic","adaptive"],ey=["function","mcp","script","agent"],ty=["none","read","write","external"],ny=["progress","step","completion"],iy=["artifact_exists","state_equals"];function st(t,e,n){return new Error(`${t}: ${e} ${n}`)}function Q(t,e,n="document"){if(t===null||typeof t!="object"||Array.isArray(t))throw st(e,n,"must be an object")}function Ye(t,e,n){if(!Array.isArray(t))throw st(e,n,"must be an array")}function J(t,e,n){if(typeof t!="string")throw st(e,n,"must be a string")}function le(t,e,n,i){e in t&&J(t[e],n,`${i}.${e}`)}function Xu(t,e,n,i){if(e in t&&typeof t[e]!="boolean")throw st(n,`${i}.${e}`,"must be a boolean")}function Ve(t,e,n,i){if(typeof t!="string"||!e.includes(t))throw st(n,i,`must be one of ${e.join(", ")}`)}function hr(t,e,n){Ye(t,e,n),t.forEach((i,r)=>{J(i,e,`${n}[${r}]`)})}function Hu(t,e,n){Q(t,e,n),J(t.name,e,`${n}.name`),J(t.description,e,`${n}.description`),Xu(t,"required",e,n)}function ry(t,e,n){Q(t,e,n),J(t.id,e,`${n}.id`),le(t,"source",e,n),le(t,"version",e,n)}function sy(t,e,n){Q(t,e,n),J(t.id,e,`${n}.id`),J(t.role,e,`${n}.role`),le(t,"instructions",e,n)}function oy(t,e,n){Q(t,e,n),J(t.id,e,`${n}.id`),Ve(t.kind,ey,e,`${n}.kind`),J(t.source,e,`${n}.source`),Ve(t.sideEffect,ty,e,`${n}.sideEffect`),Xu(t,"requiresConfirmation",e,n)}function ay(t,e,n){Q(t,e,n),Ve(t.type,Qw,e,`${n}.type`),le(t,"ref",e,n),le(t,"prompt",e,n),le(t,"question",e,n),"options"in t&&hr(t.options,e,`${n}.options`)}function cy(t,e,n){Q(t,e,n),J(t.id,e,`${n}.id`),ay(t.action,e,`${n}.action`),le(t,"next",e,n),"completionEvals"in t&&hr(t.completionEvals,e,`${n}.completionEvals`)}function ly(t,e){let n="goal";Q(t,e,n),J(t.statement,e,`${n}.statement`),Ye(t.inputs,e,`${n}.inputs`),t.inputs.forEach((i,r)=>{Hu(i,e,`${n}.inputs[${r}]`)}),Ye(t.outputs,e,`${n}.outputs`),t.outputs.forEach((i,r)=>{Hu(i,e,`${n}.outputs[${r}]`)}),hr(t.success,e,`${n}.success`)}function uy(t,e){let n="orchestration";Q(t,e,n),Ve(t.mode,Zw,e,`${n}.mode`),le(t,"entry",e,n),"steps"in t&&(Ye(t.steps,e,`${n}.steps`),t.steps.forEach((i,r)=>{cy(i,e,`${n}.steps[${r}]`)}))}function Qu(t,e){return Q(t,e),Ve(t.apiVersion,["comet/v1alpha1"],e,"apiVersion"),Ve(t.kind,["Skill"],e,"kind"),Q(t.metadata,e,"metadata"),J(t.metadata.name,e,"metadata.name"),J(t.metadata.version,e,"metadata.version"),J(t.metadata.description,e,"metadata.description"),ly(t.goal,e),uy(t.orchestration,e),Ye(t.skills,e,"skills"),t.skills.forEach((n,i)=>{ry(n,e,`skills[${i}]`)}),Ye(t.agents,e,"agents"),t.agents.forEach((n,i)=>{sy(n,e,`agents[${i}]`)}),Ye(t.tools,e,"tools"),t.tools.forEach((n,i)=>{oy(n,e,`tools[${i}]`)}),t}function Zu(t,e){Q(t,e);for(let n of["allowedSkills","allowedAgents","allowedTools","confirmationRequiredFor"])n in t&&hr(t[n],e,n);for(let n of["maxIterations","maxRetriesPerAction"])if(n in t&&(typeof t[n]!="number"||!Number.isFinite(t[n])))throw st(e,n,"must be a finite number");return t}function fy(t,e){return Q(t,e),"runtime"in t&&ef(t.runtime,e,"runtime"),t}function ef(t,e,n){return Ye(t,e,n),t.forEach((i,r)=>{let s=`${n}[${r}]`;Q(i,e,s),J(i.id,e,`${s}.id`),Ve(i.scope,ny,e,`${s}.scope`),Ve(i.type,iy,e,`${s}.type`),le(i,"artifact",e,s),le(i,"field",e,s),le(i,"equals",e,s)}),t}async function Bo(t){let e=await Wo.readFile(t,"utf8");try{return(0,zu.parse)(e)}catch(n){let i=n instanceof Error?n.message:String(n);throw st(t,"document",i)}}async function dy(t){try{return await Bo(t)}catch(e){if(e.code==="ENOENT")return null;throw e}}async function Gu(t){try{return await Wo.access(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function py(t){let e=ie.join(t,"checks.yaml"),n=ie.join(t,"evals.yaml"),[i,r]=await Promise.all([Gu(e),Gu(n)]);if(r)throw new Error(`${n}: evals.yaml is no longer supported; use checks.yaml`);return i?{document:fy(await Bo(e),e)}:{document:null}}async function tf(t){let e=ie.resolve(t.root),n=ie.resolve(t.controlRoot);t.requireSkillMarkdown&&await Wo.access(ie.join(e,"SKILL.md"));let i=ie.join(n,"skill.yaml"),r=ie.join(n,"guardrails.yaml"),s=Qu(await Bo(i),i),o=await dy(r),a=o===null?null:Zu(o,r),c=await py(n),l={allowedSkills:s.skills.map(f=>f.id),allowedAgents:s.agents.map(f=>f.id),allowedTools:s.tools.map(f=>f.id),maxIterations:50,maxRetriesPerAction:3,confirmationRequiredFor:s.tools.filter(f=>f.requiresConfirmation).map(f=>f.id)};return{root:e,packageKind:t.packageKind==="runtime"?"runtime":void 0,definition:s,guardrails:{...l,...a},evals:c.document?.runtime??[]}}async function nf(t){let e=ie.resolve(t);return tf({root:e,controlRoot:ie.join(e,"comet"),packageKind:"skill",requireSkillMarkdown:!0})}async function rf(t){let e=ie.resolve(t);return tf({root:e,controlRoot:e,packageKind:"runtime",requireSkillMarkdown:!1})}function sf(t,e,n=ie.join(e,"package.json")){Q(t,n);let i=t.packageKind==="runtime"?"runtime":void 0,r=Qu(t.definition,n),s=Zu(t.guardrails,n),o=ef(t.evals,n,"evals"),a={allowedSkills:r.skills.map(c=>c.id),allowedAgents:r.agents.map(c=>c.id),allowedTools:r.tools.map(c=>c.id),maxIterations:50,maxRetriesPerAction:3,confirmationRequiredFor:r.tools.filter(c=>c.requiresConfirmation).map(c=>c.id)};return{root:ie.resolve(e),packageKind:i,definition:r,guardrails:{...a,...s},evals:o}}import of from"path";function my(t,e,n,i){t.type==="invoke_skill"&&!e.definition.skills.some(r=>r.id===t.ref)&&n.push(`step ${i} references undeclared skill: ${t.ref??"(missing)"}`),t.type==="call_tool"&&!e.definition.tools.some(r=>r.id===t.ref)&&n.push(`step ${i} references undeclared tool: ${t.ref??"(missing)"}`),t.type==="handoff"&&!e.definition.agents.some(r=>r.id===t.ref)&&n.push(`step ${i} references undeclared agent: ${t.ref??"(missing)"}`),t.type==="ask_user"&&!t.question&&n.push(`step ${i} ask_user action requires question`)}function af(t){let e=[],{definition:n,guardrails:i,evals:r}=t;n.apiVersion!=="comet/v1alpha1"&&e.push("unsupported apiVersion"),n.kind!=="Skill"&&e.push("kind must be Skill"),n.metadata.name||e.push("metadata.name is required"),n.goal.statement||e.push("goal.statement is required"),i.maxIterations<1&&e.push("maxIterations must be at least 1"),i.maxRetriesPerAction<0&&e.push("maxRetriesPerAction must not be negative");let s=n.orchestration.steps??[];if(n.orchestration.mode==="adaptive")(n.orchestration.entry||s.length>0)&&e.push("adaptive orchestration must not define entry or steps");else{let o=new Set;for(let a of s)o.has(a.id)&&e.push(`duplicate step id: ${a.id}`),o.add(a.id),my(a.action,t,e,a.id);(!n.orchestration.entry||!o.has(n.orchestration.entry))&&e.push(`orchestration.entry references unknown step: ${n.orchestration.entry??"(missing)"}`);for(let a of s){a.next&&!o.has(a.next)&&e.push(`step ${a.id} has unknown next step: ${a.next}`);for(let c of a.completionEvals??[])r.some(l=>l.id===c)||e.push(`step ${a.id} references unknown eval: ${c}`)}}for(let o of n.tools){if(o.kind!=="script")continue;let a=of.posix.normalize(o.source.replaceAll("\\","/"));(of.isAbsolute(o.source)||a===".."||a.startsWith("../"))&&e.push(`script tool ${o.id} must reference a relative path inside the Skill package`)}for(let o of i.allowedSkills)n.skills.some(a=>a.id===o)||e.push(`guardrails allow undeclared skill: ${o}`);for(let o of i.allowedAgents)n.agents.some(a=>a.id===o)||e.push(`guardrails allow undeclared agent: ${o}`);for(let o of i.allowedTools)n.tools.some(a=>a.id===o)||e.push(`guardrails allow undeclared tool: ${o}`);return e}function gr(t){return Array.isArray(t)?t.map(gr):t&&typeof t=="object"?Object.fromEntries(Object.entries(t).sort(([e],[n])=>e.localeCompare(n)).map(([e,n])=>[e,gr(n)])):t}function hy(t){return gr({...t.packageKind==="runtime"?{packageKind:"runtime"}:{},definition:t.definition,guardrails:t.guardrails,evals:t.evals})}function gy(t){return he.posix.normalize(t.replaceAll("\\","/"))}function Ko(t,e,n){let i=he.relative(t,e);if(!(i===""||!he.isAbsolute(i)&&!i.startsWith(`..${he.sep}`)))throw new Error(`${n} resolves outside the Skill package`)}async function lf(t,e,n){let i=gy(e);if(he.posix.isAbsolute(i)||i===".."||i.startsWith("../"))throw new Error(`${n} resolves outside the Skill package`);let r=he.resolve(t,...i.split("/"));Ko(t,r,n);let s;try{s=await Nt.realpath(r)}catch(o){throw o.code==="ENOENT"?new Error(`${n} does not exist: ${e}`,{cause:o}):o}if(Ko(t,s,n),!(await Nt.stat(s)).isFile())throw new Error(`${n} is not a file: ${e}`);return{path:i,content:await Nt.readFile(s)}}async function wy(t){let e=await Nt.realpath(t.root),n=t.packageKind==="runtime"?[]:[await lf(e,"SKILL.md","SKILL.md")];for(let i of t.definition.tools)i.kind==="script"&&n.push(await lf(e,i.source,`Script tool ${i.id}`));return n.sort((i,r)=>i.path.localeCompare(r.path))}function yy(t,e){let n=e.map(i=>({path:i.path,sha256:cf("sha256").update(i.content).digest("hex")}));return cf("sha256").update(JSON.stringify(gr({package:t,files:n}))).digest("hex")}async function vy(t){let e=hy(t),n=await wy(t);return{document:e,files:n,hash:yy(e,n)}}async function uf(t){return(await vy(t)).hash}async function Uo(t,e){if(!/^[a-f0-9]{64}$/u.test(e))throw new Error(`Invalid Skill snapshot hash: ${e}`);let n=he.resolve(t,".comet","skill-snapshots"),i=he.join(n,e);Ko(n,i,"Skill snapshot");try{let r=(await Nt.readFile(he.join(i,"sha256"),"utf8")).trim();if(r!==e)throw new Error(`stored hash is ${r||"(empty)"}`);let s=he.join(i,"package.json"),o=JSON.parse(await Nt.readFile(s,"utf8")),a=sf(o,i,s),c=af(a);if(c.length>0)throw new Error(c.map(f=>` - ${f}`).join(` -`));let l=await uf(a);if(l!==e)throw new Error(`calculated hash is ${l}`);return a}catch(r){throw new Error(`Skill snapshot is invalid or missing: ${e}`,{cause:r})}}async function by(t){try{return(await ff.stat(t)).isDirectory()}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function wr(t){try{return(await ff.stat(t)).isFile()}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function ky(t){return await by(t)?await wr(Z.join(t,"skill.yaml"))?!0:await wr(Z.join(t,"SKILL.md"))&&await wr(Z.join(t,"comet","skill.yaml")):!1}function Sy(t){return{root:t,packageKind:"runtime",definition:{apiVersion:"comet/v1alpha1",kind:"Skill",metadata:{name:"comet-classic",version:"1",description:"Internal compatibility orchestration for classic Comet full, hotfix, and tweak workflows"},goal:{statement:"Advance or restore a classic Comet Run without changing the user command surface",inputs:[{name:"classic-state",description:"Validated ClassicState consistent with the Run projection",required:!0},{name:"evidence",description:"Structured evidence produced by the Classic Evidence collector",required:!0}],outputs:[{name:"run-state",description:"Atomically synchronized Classic and Run state",required:!0}],success:["Legacy fields and Run fields remain consistent","Every step invokes only a declared public Comet Skill","The completed state passes its completion eval"]},orchestration:{mode:"deterministic",entry:"full.open",steps:[{id:"full.open",action:{type:"invoke_skill",ref:"comet-open"},next:"full.design.handoff"},{id:"full.design.handoff",action:{type:"invoke_skill",ref:"comet-design"},next:"full.design.document"},{id:"full.design.document",action:{type:"invoke_skill",ref:"comet-design"},next:"full.build.plan"},{id:"full.build.plan",action:{type:"invoke_skill",ref:"comet-build"},next:"full.build.plan-ready"},{id:"full.build.plan-ready",action:{type:"invoke_skill",ref:"comet-build"},next:"full.build.configure"},{id:"full.build.configure",action:{type:"invoke_skill",ref:"comet-build"},next:"full.build.execute"},{id:"full.build.execute",action:{type:"invoke_skill",ref:"comet-build"},next:"full.build.complete"},{id:"full.build.complete",action:{type:"invoke_skill",ref:"comet-build"},next:"full.verify.run"},{id:"full.build.fix",action:{type:"invoke_skill",ref:"comet-build"},next:"full.build.execute"},{id:"full.verify.run",action:{type:"invoke_skill",ref:"comet-verify"},next:"full.verify.branch"},{id:"full.verify.branch",action:{type:"invoke_skill",ref:"comet-verify"},next:"full.archive.confirm"},{id:"full.archive.confirm",action:{type:"invoke_skill",ref:"comet-archive"},next:"full.archive.execute"},{id:"full.archive.execute",action:{type:"invoke_skill",ref:"comet-archive"},next:"completed"},{id:"hotfix.open",action:{type:"invoke_skill",ref:"comet-hotfix"},next:"hotfix.build.execute"},{id:"hotfix.build.execute",action:{type:"invoke_skill",ref:"comet-build"},next:"hotfix.build.complete"},{id:"hotfix.build.complete",action:{type:"invoke_skill",ref:"comet-build"},next:"hotfix.verify.run"},{id:"hotfix.verify.run",action:{type:"invoke_skill",ref:"comet-verify"},next:"hotfix.verify.branch"},{id:"hotfix.verify.branch",action:{type:"invoke_skill",ref:"comet-verify"},next:"hotfix.archive.confirm"},{id:"hotfix.archive.confirm",action:{type:"invoke_skill",ref:"comet-archive"},next:"hotfix.archive.execute"},{id:"hotfix.archive.execute",action:{type:"invoke_skill",ref:"comet-archive"},next:"completed"},{id:"tweak.open",action:{type:"invoke_skill",ref:"comet-tweak"},next:"tweak.build.execute"},{id:"tweak.build.execute",action:{type:"invoke_skill",ref:"comet-build"},next:"tweak.build.complete"},{id:"tweak.build.complete",action:{type:"invoke_skill",ref:"comet-build"},next:"tweak.verify.run"},{id:"tweak.verify.run",action:{type:"invoke_skill",ref:"comet-verify"},next:"tweak.verify.branch"},{id:"tweak.verify.branch",action:{type:"invoke_skill",ref:"comet-verify"},next:"tweak.archive.confirm"},{id:"tweak.archive.confirm",action:{type:"invoke_skill",ref:"comet-archive"},next:"tweak.archive.execute"},{id:"tweak.archive.execute",action:{type:"invoke_skill",ref:"comet-archive"},next:"completed"},{id:"completed",action:{type:"checkpoint"},completionEvals:["classic-completed"]}]},skills:[{id:"comet-open"},{id:"comet-design"},{id:"comet-build"},{id:"comet-verify"},{id:"comet-archive"},{id:"comet-hotfix"},{id:"comet-tweak"}],agents:[],tools:[]},guardrails:{allowedSkills:["comet-open","comet-design","comet-build","comet-verify","comet-archive","comet-hotfix","comet-tweak"],allowedAgents:[],allowedTools:[],maxIterations:500,maxRetriesPerAction:3,confirmationRequiredFor:[]},evals:[{id:"classic-completed",scope:"completion",type:"state_equals",field:"status",equals:"completed"}]}}async function Cy(){let t=Z.dirname(df(import.meta.url)),e=[process.env.COMET_RUNTIME_CLASSIC_ROOT,Z.resolve(t,"..","runtime","classic"),Z.resolve(t,"..","..","comet","runtime","classic"),Z.resolve(t,"..","..","assets","skills","comet","runtime","classic"),Z.resolve("assets","skills","comet","runtime","classic"),process.env.COMET_CLASSIC_SKILL_ROOT,Z.resolve(t,"..","..","comet-classic"),Z.resolve(t,"..","..","assets","skills","comet-classic"),Z.resolve("assets","skills","comet-classic")].filter(n=>!!n);for(let n of e)if(await ky(n))return n;return null}async function Ey(t){return await wr(Z.join(t,"skill.yaml"))?rf(t):nf(t)}async function pf(t,e){let n=e??await me(t,{migrate:!1}),i=Array.from(new Set(n.unknownKeys)).sort();if(i.length>0)throw new Error(`Invalid Classic state: unknown field(s): ${i.join(", ")}`);if(!n.classic||!n.run)throw new Error("Classic runtime validation requires synchronized Classic and Run projections");if(n.classic.classicMigration!==Pn)throw new Error("Classic Run exists without a supported classic_migration marker");let r=await Cy(),s=r?await Ey(r):Sy(Z.dirname(df(import.meta.url)));if(n.run.skill!==s.definition.metadata.name)throw new Error(`Classic Run skill mismatch: expected ${s.definition.metadata.name}, got ${n.run.skill}`);let o=await Uo(t,n.run.skillHash);if(o.definition.metadata.name!==n.run.skill)throw new Error(`Classic Run snapshot skill mismatch: expected ${n.run.skill}, got ${o.definition.metadata.name}`);let a=await Pt(t,n),c=Ot(n.classic,a);if(n.run.currentStep!==c)throw new Error(`Classic Run step mismatch: expected ${c}, got ${n.run.currentStep}`);return{classic:n.classic,run:n.run,evidence:a,migrated:!1,snapshotDir:Z.join(t,".comet","skill-snapshots",n.run.skillHash)}}async function mf(t,e,n,i){let r=await me(t);if(!r.classic||!r.run)throw new Error("Classic transition requires synchronized Classic and Run projections");let s=await Pt(t,{classic:e,run:n,unknownKeys:r.unknownKeys}),o=Ot(e,s),a={...n,currentStep:o,iteration:n.iteration+1,status:o==="completed"?"completed":"running"};await xt(t,{classic:e,run:a,unknownKeys:r.unknownKeys});let c=await At(t,a.trajectoryRef);return await rt(t,a.trajectoryRef,{sequence:c.length+1,timestamp:new Date().toISOString(),type:"state_transitioned",runId:a.runId,data:{kind:"classic",fromStep:n.currentStep,toStep:o,...i}}),a}sr();import Ry from"path";var _y=Ry.join(".comet","state-events.jsonl"),xy=8*1024*1024;async function Yo(t,e){let n={schemaVersion:1,timestamp:new Date().toISOString(),...e};return await rr(t,_y,`${JSON.stringify(n)} -`,xy,"Classic state event log"),n}var hf=["open-complete","design-complete","build-complete","verify-pass","verify-fail","archive-confirm","archive-reopen","archived","preset-escalate"],Py={"open-complete":{event:"open-complete",from:"open",guardRefs:["open-artifacts-present"]},"design-complete":{event:"design-complete",from:"design",guardRefs:["design-evidence-present"]},"build-complete":{event:"build-complete",from:"build",guardRefs:["build-decisions-selected"]},"verify-pass":{event:"verify-pass",from:"verify",guardRefs:["verification-report-present"]},"verify-fail":{event:"verify-fail",from:"verify",guardRefs:["verification-failed"]},"archive-confirm":{event:"archive-confirm",from:"archive",guardRefs:["archive-final-confirmation"]},"archive-reopen":{event:"archive-reopen",from:"archive",guardRefs:["archive-not-finalized"]},archived:{event:"archived",from:"archive",guardRefs:["verify-result-pass","archive-confirmed"]},"preset-escalate":{event:"preset-escalate",from:"build",guardRefs:["preset-workflow"]}};function Oy(t){return t.toISOString().slice(0,10)}function x(t,e,n,i){let r=t[n];t[n]=i,r!==i&&e.push({field:n,from:r,to:i})}function gf(t,e,n={}){let i=Py[e];if(t.phase!==i.from)throw new Error(`Cannot apply ${e}: phase is '${t.phase}', expected '${i.from}'`);let r={...t},s=[],o=n.now??new Date;if(e==="open-complete")x(r,s,"phase",r.workflow==="full"?"design":"build");else if(e==="design-complete")x(r,s,"phase","build");else if(e==="build-complete"){let a=r.verifyResult==="fail";x(r,s,"phase","verify"),x(r,s,"verifyResult","pending"),x(r,s,"branchStatus","pending"),a||x(r,s,"verificationReport",null)}else if(e==="verify-pass")x(r,s,"verifyResult","pass"),x(r,s,"verifyFailures",0),x(r,s,"phase","archive"),x(r,s,"verifiedAt",Oy(o)),x(r,s,"archiveConfirmation","pending"),x(r,s,"branchStatus","pending");else if(e==="verify-fail")x(r,s,"verifyResult","fail"),x(r,s,"verifyFailures",r.verifyFailures+1),x(r,s,"phase","build"),x(r,s,"branchStatus","pending");else if(e==="preset-escalate"){if(r.workflow!=="hotfix"&&r.workflow!=="tweak")throw new Error(`Cannot apply ${e}: workflow must be hotfix or tweak, got '${r.workflow}'`);x(r,s,"workflow","full"),x(r,s,"classicProfile","full"),x(r,s,"phase","design"),x(r,s,"designDoc",null),x(r,s,"buildPause",null),x(r,s,"buildMode",null),x(r,s,"subagentDispatch",null),x(r,s,"tddMode",null),x(r,s,"reviewMode",null),x(r,s,"isolation",null),x(r,s,"boundBranch",null),x(r,s,"verifyMode",null),x(r,s,"directOverride",null)}else if(e==="archive-confirm"){if(r.verifyResult!=="pass")throw new Error(`Cannot apply ${e}: verifyResult must be pass`);if(r.archived)throw new Error(`Cannot apply ${e}: already archived`);x(r,s,"archiveConfirmation","confirmed")}else if(e==="archive-reopen"){if(r.archived)throw new Error(`Cannot apply ${e}: already archived`);x(r,s,"verifyResult","pending"),x(r,s,"verifyFailures",0),x(r,s,"phase","verify"),x(r,s,"verifiedAt",null),x(r,s,"archiveConfirmation",null),x(r,s,"branchStatus","pending")}else{if(r.verifyResult!=="pass")throw new Error(`Cannot apply ${e}: verifyResult must be pass`);if(r.archiveConfirmation!=="confirmed")throw new Error(`Cannot apply ${e}: archiveConfirmation must be confirmed`);x(r,s,"archived",!0)}return{classic:r,effects:s,definition:i}}xn();import yr from"path";function Ay(t){if(t!=="build"&&t!=="verify")throw new Error(`Invalid command check scope: '${String(t)}'`)}function Ny(t,e="."){if(e.trim().length===0)throw new Error("Command check cwd cannot be blank");let n=yr.resolve(t),i=yr.resolve(n,e);if(i!==n&&!i.startsWith(n+yr.sep))throw new Error(`Command check cwd must resolve within the project root: '${e}'`);return yr.relative(n,i).replaceAll("\\","/")||"."}async function wf(t,e,n,i){if(Ay(i.scope),typeof i.command!="string"||i.command.trim().length===0)throw new Error("Command check command cannot be blank");if(!Number.isInteger(i.exitCode))throw new Error("Command check exitCode must be an integer");let s={sequence:(await At(e,n.trajectoryRef)).reduce((o,a)=>Math.max(o,a.sequence),0)+1,timestamp:new Date().toISOString(),runId:n.runId,scope:i.scope,command:i.command,exitCode:i.exitCode,cwd:Ny(t,i.cwd)};return await rt(e,n.trajectoryRef,{sequence:s.sequence,timestamp:s.timestamp,type:"command_check_recorded",runId:s.runId,data:{scope:s.scope,command:s.command,exitCode:s.exitCode,cwd:s.cwd}}),s}Io();St();import Ty from"os";import vr from"path";function jy(t={}){let e=t.cwd??process.cwd(),n=t.homeDir??Ty.homedir(),i=[{file:vr.resolve(e,".comet","config.yaml"),source:".comet/config.yaml",scope:"project"},{file:vr.resolve(n,".comet","config.yaml"),source:"~/.comet/config.yaml",scope:"global"}];return i.filter((r,s)=>i.findIndex(o=>o.file===r.file)===s)}async function Vo(t,e={}){for(let n of jy(e)){let i=vr.dirname(vr.dirname(n.file)),r=n.scope==="global"?(await jo(i))?.classic:(await kt(i,{allowPartialProject:!0}))?.value.classic;if(!r||typeof r!="object"||Array.isArray(r))continue;let s=r[t];if(s!=null)return{value:String(s),source:n.source}}return null}import ot from"node:path";async function yf(t,e){if(!e||e==="null")return{status:"missing",recordedPath:null};let n=await ne(t),i=ot.resolve(t,e),r=ot.relative(n.superpowersPlansDir,i);return ot.isAbsolute(e)||!r||r.startsWith(`..${ot.sep}`)||ot.isAbsolute(r)||r.includes(ot.sep)||ot.extname(r).toLowerCase()!==".md"?{status:"broken",recordedPath:e}:await kn(t,e,{label:`Classic build plan ${e}`,expected:"file"})?{status:"ready",recordedPath:e}:{status:"broken",recordedPath:e}}var qy="\x1B[32m",Ly="\x1B[31m",Dy="\x1B[33m",Xo="\x1B[0m",Ln=["full","hotfix","tweak"],Qo=["open","design","build","verify","archive"],bf=["en","zh-CN"],My=hf,Ho=new Set([...Fo,"archive_confirmation","verify_failures","classic_profile","classic_migration","bound_branch"]),Fy=new Set(_t.filter(t=>!Ho.has(t))),Wy={workflow:Ln,phase:Qo,context_compression:["off","beta"],build_mode:["subagent-driven-development","executing-plans","direct"],build_pause:["null","plan-ready"],subagent_dispatch:["null","confirmed"],tdd_mode:["tdd","direct"],review_mode:["off","standard","thorough"],isolation:["current","branch","worktree"],verify_mode:["light","full"],auto_transition:["true","false"],verify_result:["pending","pass","fail"],branch_status:["pending","handled"],archive_confirmation:["pending","confirmed"],archived:["true","false"],direct_override:["true","false"],classic_profile:Ln,classic_migration:["1"]},By=new Set(["design_doc","plan","verification_report","handoff_context"]),Ky={archived:"archived",branchStatus:"branch_status",classicProfile:"classic_profile",designDoc:"design_doc",language:"language",phase:"phase",verificationReport:"verification_report",verifiedAt:"verified_at",archiveConfirmation:"archive_confirmation",verifyResult:"verify_result",verifyFailures:"verify_failures",workflow:"workflow"},Dn=class extends Error{constructor(n,i=1){super(n);this.exitCode=i}exitCode},kr=class{stdout=[];stderr=[];result(e=0){return{exitCode:e,...this.stdout.length>0?{stdout:this.stdout.join(` +`,n)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let n=qi(e),i=vt(n);return i.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let n=qi(e),i=vt(n);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,n){return this.type!=="comment"||this.indent<=n?!1:e.every(i=>i.type==="newline"||i.type==="space")}*documentEnd(e){this.type!=="doc-mode"&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};Ll.Parser=ro});var Bl=w(cn=>{"use strict";var Dl=Ys(),Jh=Qt(),an=tn(),Hh=Kr(),Gh=P(),zh=io(),Ml=so();function Fl(t){let e=t.prettyErrors!==!1;return{lineCounter:t.lineCounter||e&&new zh.LineCounter||null,prettyErrors:e}}function Xh(t,e={}){let{lineCounter:n,prettyErrors:i}=Fl(e),r=new Ml.Parser(n?.addNewLine),s=new Dl.Composer(e),o=Array.from(s.compose(r.parse(t)));if(i&&n)for(let a of o)a.errors.forEach(an.prettifyError(t,n)),a.warnings.forEach(an.prettifyError(t,n));return o.length>0?o:Object.assign([],{empty:!0},s.streamInfo())}function Wl(t,e={}){let{lineCounter:n,prettyErrors:i}=Fl(e),r=new Ml.Parser(n?.addNewLine),s=new Dl.Composer(e),o=null;for(let a of s.compose(r.parse(t),!0,t.length))if(!o)o=a;else if(o.options.logLevel!=="silent"){o.errors.push(new an.YAMLParseError(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return i&&n&&(o.errors.forEach(an.prettifyError(t,n)),o.warnings.forEach(an.prettifyError(t,n))),o}function Qh(t,e,n){let i;typeof e=="function"?i=e:n===void 0&&e&&typeof e=="object"&&(n=e);let r=Wl(t,n);if(!r)return null;if(r.warnings.forEach(s=>Hh.warn(r.options.logLevel,s)),r.errors.length>0){if(r.options.logLevel!=="silent")throw r.errors[0];r.errors=[]}return r.toJS(Object.assign({reviver:i},n))}function Zh(t,e,n){let i=null;if(typeof e=="function"||Array.isArray(e)?i=e:n===void 0&&e&&(n=e),typeof n=="string"&&(n=n.length),typeof n=="number"){let r=Math.round(n);n=r<1?void 0:r>8?{indent:8}:{indent:r}}if(t===void 0){let{keepUndefined:r}=n??e??{};if(!r)return}return Gh.isDocument(t)&&!i?t.toString(n):new Jh.Document(t,i,n).toString(n)}cn.parse=Qh;cn.parseAllDocuments=Xh;cn.parseDocument=Wl;cn.stringify=Zh});var et=w(A=>{"use strict";var eg=Ys(),tg=Qt(),ng=Rs(),oo=tn(),ig=qt(),qe=P(),rg=Ae(),sg=$(),og=Ie(),ag=je(),cg=ji(),lg=to(),ug=io(),fg=so(),Di=Bl(),Kl=Tt();A.Composer=eg.Composer;A.Document=tg.Document;A.Schema=ng.Schema;A.YAMLError=oo.YAMLError;A.YAMLParseError=oo.YAMLParseError;A.YAMLWarning=oo.YAMLWarning;A.Alias=ig.Alias;A.isAlias=qe.isAlias;A.isCollection=qe.isCollection;A.isDocument=qe.isDocument;A.isMap=qe.isMap;A.isNode=qe.isNode;A.isPair=qe.isPair;A.isScalar=qe.isScalar;A.isSeq=qe.isSeq;A.Pair=rg.Pair;A.Scalar=sg.Scalar;A.YAMLMap=og.YAMLMap;A.YAMLSeq=ag.YAMLSeq;A.CST=cg;A.Lexer=lg.Lexer;A.LineCounter=ug.LineCounter;A.Parser=fg.Parser;A.parse=Di.parse;A.parseAllDocuments=Di.parseAllDocuments;A.parseDocument=Di.parseDocument;A.stringify=Di.stringify;A.visit=Kl.visit;A.visitAsync=Kl.visitAsync});function Le(t){return t!==0&&t!==0n&&t!=="0"}function Mi(t,e){return Le(t.dev)&&Le(e.dev)&&Le(t.ino)&&Le(e.ino)}function ve(t,e){let n=Le(t.dev)&&Le(e.dev);if(n&&t.dev!==e.dev)return!1;let i=Le(t.ino)&&Le(e.ino);return i&&t.ino!==e.ino?!1:n&&i?!0:t.birthtime===e.birthtime}var Fi=U(()=>{"use strict"});import{constants as Wi,promises as tt}from"fs";function ao(t){return"birthtimeNs"in t&&typeof t.birthtimeNs=="bigint"?t.birthtimeNs:t.birthtimeMs}function Ul(t){return"ctimeNs"in t&&typeof t.ctimeNs=="bigint"?t.ctimeNs:t.ctimeMs}function ln(t){return{dev:t.dev,ino:t.ino,birthtime:ao(t)}}function Bi(t,e){let n=ln(t),i=ln(e);return Mi(n,i)?ve(n,i):ve(n,i)&&ao(t)===ao(e)&&Ul(t)===Ul(e)&&t.size===e.size}async function Ki(t,e,n={}){if(!Number.isSafeInteger(e)||e<1)throw new Error("race-safe read byte limit must be a positive integer");let i=n.label??"file",r=n.bigint===!0,s=await tt.lstat(t,{bigint:r});if(!s.isFile()||s.isSymbolicLink())throw new De("not-regular-file",`${i} must be a regular file`);if(BigInt(s.size)>BigInt(e))throw new De("too-large",`${i} exceeds ${e} bytes`);let o=await tt.realpath(t);await n.verify?.("pre-open",{realPath:o,identity:ln(s)});let a=process.platform==="win32"?Wi.O_RDONLY:Wi.O_RDONLY|Wi.O_NOFOLLOW|Wi.O_NONBLOCK,c;try{c=await tt.open(t,a)}catch(l){throw l.code==="ELOOP"?new De("not-regular-file",`${i} must be a regular file`,{cause:l}):l}try{let[l,f,u]=await Promise.all([c.stat({bigint:r}),tt.lstat(t,{bigint:r}),tt.realpath(t)]);if(!l.isFile()||!f.isFile()||f.isSymbolicLink()||u!==o||!Bi(s,l)||!Bi(s,f))throw new De("changed",`${i} changed while opening`);await n.verify?.("post-open",{realPath:u,identity:ln(l)}),await n.hooks?.afterOpen?.();let d=[],m=0,g=Buffer.allocUnsafe(Math.min(64*1024,e+1));for(;;){let y=e+1-m,{bytesRead:S}=await c.read(g,0,Math.min(g.length,y),null);if(S===0)break;if(m+=S,m>e)throw new De("too-large",`${i} exceeds ${e} bytes`);d.push(Buffer.from(g.subarray(0,S)))}await n.hooks?.beforeFinalCheck?.();let[p,h,v]=await Promise.all([c.stat({bigint:r}),tt.lstat(t,{bigint:r}),tt.realpath(t)]);if(!h.isFile()||h.isSymbolicLink()||v!==o||!Bi(s,p)||!Bi(s,h))throw new De("changed",`${i} changed while reading`);return await n.verify?.("post-read",{realPath:v,identity:ln(p)}),{bytes:Buffer.concat(d,m),stat:p,realPath:v}}finally{await c.close()}}var De,co=U(()=>{"use strict";Fi();De=class extends Error{reason;constructor(e,n,i){super(n,i),this.name="RaceSafeReadError",this.reason=e}}});import Ji from"path";function Sg(t,e){if(typeof t!="string")throw new Error(`${e} must be a string`);let n=t.trim();if(n.length===0||Ji.posix.isAbsolute(n)||Ji.win32.isAbsolute(n)||/^(?:~|[\\/])/u.test(n))throw new Error(`${e} must be a project-relative path`);if(n===".")return[];let i=n.replaceAll("\\","/").split("/");if(i.some(r=>r===".."))throw new Error(`${e} must stay inside the project root`);if(i.some(r=>r===""||r==="."))throw new Error(`${e} must not contain empty or dot path segments`);return i}function hn(t){let e=Sg(t,"native.artifact_root");return e.length===0?".":e.join("/")}function su(t,e="docs"){let n=t??e;if(n!=="legacy"&&n!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return n}function Me(t,e,n=!1){if(typeof t!="string")throw new Error(`${e} must be a string`);let i=t.trim().replaceAll("\\","/");if(i.length===0||Ji.posix.isAbsolute(i)||Ji.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${e} must be relative to its declared path base`);let r=i.split("/");if(r.some(s=>s===".."))throw new Error(`${e} must stay inside its declared path base`);if(r.some(s=>s===""||s==="."))throw new Error(`${e} must not contain empty or dot path segments`);if(!n&&/[*?]/u.test(i))throw new Error(`${e} cannot contain wildcards`);return r.join("/")}function gn(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function ou(t,e,n){let i=t??e;if(i!=="en"&&i!=="zh-CN")throw new Error(`${n} must be en or zh-CN`);return i}function au(t,e){if(typeof t!="string"||t.length===0||t.includes("\\")||t.includes("\0")||t.startsWith("/")||t.split("/").includes(".."))throw new Error(`${e} contains an unsafe pattern`);if(t.length>vo)throw new Error(`${e} exceeds ${vo} characters`);let n=0;for(let i=0;ibo)throw new Error(`${e} contains more than ${bo} wildcard tokens`);return t}function iu(t,e,n){if(t===void 0)return[...n];if(!Array.isArray(t))throw new Error(`${e} contains an unsafe pattern`);return[...new Set(t.map(i=>au(i,e)))].sort((i,r)=>i.localeCompare(r,"en"))}function yo(t,e,n){let i=t??e;if(!Number.isSafeInteger(i)||i<1)throw new Error(`${n} must be a positive integer`);return i}function Cg(t){if(t===void 0)return{...ne,include:[...ne.include],exclude:[...ne.exclude]};let e=gn(t,"native.snapshot");return{include:iu(e.include,"native.snapshot.include",ne.include),exclude:iu(e.exclude,"native.snapshot.exclude",ne.exclude),max_files:yo(e.max_files,ne.max_files,"native.snapshot.max_files"),max_total_bytes:yo(e.max_total_bytes,ne.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:yo(e.max_duration_ms,ne.max_duration_ms,"native.snapshot.max_duration_ms")}}function Eg(t){if(t===void 0)return;let e=gn(t,"native.pending_root_move"),n=e.id,i=e.from_artifact_root,r=e.to_artifact_root,s=e.stage;if(typeof n!="string"||!/^[a-f0-9-]{8,}$/u.test(n))throw new Error("native.pending_root_move.id is invalid");if(typeof i!="string"||typeof r!="string")throw new Error("native.pending_root_move roots must be strings");if(s!=="copying"&&s!=="ready"&&s!=="switched")throw new Error("native.pending_root_move.stage is invalid");let o;if(e.cleanup!==void 0){let a=gn(e.cleanup,"native.pending_root_move.cleanup"),c=a.kind,l=a.state,f=a.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof f!="string"||!/^[a-f0-9]{64}$/u.test(f))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:f}}return{id:n,fromArtifactRoot:hn(i),toArtifactRoot:hn(r),stage:s,...o?{cleanup:o}:{}}}function Rg(t,e={}){let n=gn(t,"native"),i=n.artifact_root??(e.allowMissingArtifactRoot?"docs":void 0);if(typeof i!="string")throw new Error("native.artifact_root must be a string");let r=n.clarification_mode??"sequential";if(r!=="sequential"&&r!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let s=n.archive_confirmation??"automatic";if(s!=="automatic"&&s!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=n.max_verify_failures??ru;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let a=Eg(n.pending_root_move);return{artifact_root:hn(i),language:ou(n.language,"en","native.language"),clarification_mode:r,archive_confirmation:s,max_verify_failures:o,snapshot:Cg(n.snapshot),...a?{pending_root_move:a}:{}}}function _g(t){let e=gn(t,"classic"),n=e.context_compression??"off";if(n!=="off"&&n!=="beta")throw new Error("classic.context_compression must be off or beta");let i=e.review_mode??"standard";if(i!=="off"&&i!=="standard"&&i!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let r=e.auto_transition??!0;if(typeof r!="boolean")throw new Error("classic.auto_transition must be true or false");return{artifact_layout:su(e.artifact_layout),language:ou(e.language,"zh-CN","classic.language"),context_compression:n,review_mode:i,auto_transition:r}}function xg(t){let e=t??!0;if(typeof e!="boolean")throw new Error("ambient_resume must be true or false");return e}function Pg(t,e,n,i,r){let s=t.schema!==void 0;if(!(s||t.default_workflow!==void 0||t.workflows!==void 0||!r.allowPartialProject&&t.native!==void 0)||r.allowPartialProject&&!s)return null;if(t.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(t.default_workflow!=="native"&&t.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let a=t.workflows??[t.default_workflow];if(!Array.isArray(a)||a.length===0||a.some(l=>l!=="native"&&l!=="classic"))throw new Error("workflows must contain native and/or classic");let c=[...new Set(a)];if(!c.includes(t.default_workflow))throw new Error("workflows must include default_workflow");if(c.includes("native")&&!e)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:t.default_workflow,workflows:c,ambient_resume:i,...e?{native:e}:{},...n?{classic:n}:{}}}function Fe(t,e={}){let n=(0,ko.parseDocument)(t,{uniqueKeys:!0});if(n.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${n.errors[0].message}`);let i=n.toJS();if(i==null)return{value:{},config:null,ambient_resume:!0};if(typeof i!="object"||Array.isArray(i))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let r=i,s=xg(r.ambient_resume),o=r.native===void 0?void 0:Rg(r.native,{allowMissingArtifactRoot:e.allowMissingNativeFields}),a=r.classic===void 0?void 0:_g(r.classic),c=Pg(r,o,a,s,{allowPartialProject:e.allowPartialProject??!1});return{value:r,config:c,ambient_resume:s,...o?{native:o}:{},...a?{classic:a}:{}}}function So(t="docs",e="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,native:{artifact_root:hn(t),language:e,clarification_mode:"sequential",archive_confirmation:"automatic",max_verify_failures:ru,snapshot:{...ne,include:[...ne.include],exclude:[...ne.exclude]}}}}var ko,bt,vo,bo,ru,kg,ne,be=U(()=>{"use strict";ko=ct(et(),1),bt=64*1024,vo=1024,bo=64,ru=5,kg=[".agents/skills/**",".amazonq/skills/**",".augment/skills/**",".bob/skills/**",".claude/skills/**",".cline/skills/**",".codebuddy/skills/**",".continue/skills/**",".cospec/skills/**",".crush/skills/**",".cursor/skills/**",".factory/skills/**",".forge/skills/**",".gemini/skills/**",".github/skills/**",".iflow/skills/**",".junie/skills/**",".kilocode/skills/**",".kimi-code/skills/**",".kiro/skills/**",".lingma/skills/**",".mimocode/skills/**",".opencode/skills/**",".pi/skills/**",".qoder/skills/**",".qwen/skills/**",".roo/skills/**",".trae-cn/skills/**",".trae/skills/**",".windsurf/skills/**",".zcode/skills/**"],ne={include:["**/*"],exclude:[...kg],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4}});import{promises as We}from"fs";import oe from"path";function cu(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}function Hi(t,e){let n=oe.relative(t,e);return n===""||!oe.isAbsolute(n)&&n!==".."&&!n.startsWith(`..${oe.sep}`)}async function Co(t,e){let n=oe.resolve(t),i=await We.lstat(n);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${e} project root must be a real directory`);return We.realpath(n)}async function Eo(t,e,n,i){let r=t;for(let s=0;s{if(!Hi(s,a.realPath))throw new Error(`${i.label} resolves outside the project root`);await Eo(r.projectRoot,s,r.relative.split("/"),{label:i.label,expected:"file"})}})}var ae=U(()=>{"use strict";co();be()});import{createHash as Og}from"crypto";function Ng(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function kt(t,e={}){return(await zi(t,e)).document}async function Ag(t){try{return(await W(t,wn,bt,{label:wn})).bytes}catch(e){if(Ng(e))return null;throw e}}function Tg(t){return t?{exists:!0,sha256:Og("sha256").update(t).digest("hex")}:{exists:!1,sha256:null}}async function zi(t,e={}){let n=await Ag(t);return{document:n?Fe(n.toString("utf8"),e):null,identity:Tg(n)}}var wn,St=U(()=>{"use strict";be();ae();wn=".comet/config.yaml"});import{randomUUID as Ig}from"crypto";import{constants as jg,promises as q}from"fs";import B from"path";async function _o(t,e){try{return await q.link(t,e),{linked:!0}}catch(n){let i=n.code;if(i!=="ENOTSUP"&&i!=="EOPNOTSUPP")throw n}return await q.copyFile(t,e,jg.COPYFILE_EXCL),{linked:!1}}function Ct(t,e){let n=B.relative(t,e);return n===""||!B.isAbsolute(n)&&n!==".."&&!n.startsWith(`..${B.sep}`)}function Qi(t){return{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs}}function $g(t,e){return ve(t,Qi(e))}function Xi(t,e){let n=Qi(t),i=Qi(e);return Mi(n,i)?ve(n,i):ve(n,i)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.size===e.size}async function Zi(t){let e=await q.lstat(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Contained atomic write parent must be a real directory: ${t}`);return{path:t,realPath:await q.realpath(t),...Qi(e)}}async function Be(t){for(let e of t){let n=await q.lstat(e.path);if(!n.isDirectory()||n.isSymbolicLink()||!$g(e,n)||await q.realpath(e.path)!==e.realPath)throw new Error(`Contained atomic write parent changed before commit: ${e.path}`)}}async function qg(t,e){let n=B.resolve(t),i=B.resolve(e);if(!Ct(n,i))throw new Error(`Contained atomic write parent is outside its managed root: ${e}`);let r=[await Zi(n)],s=B.relative(n,i).split(B.sep).filter(Boolean),o=n;for(let a of s){await Be(r),o=B.join(o,a);try{await q.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await Zi(o);if(!Ct(r[0].realPath,c.realPath))throw new Error(`Contained atomic write parent resolves outside its managed root: ${o}`);r.push(c)}return await Be(r),r}async function Lg(t,e){let n=B.resolve(t),i=B.resolve(e);if(!Ct(n,i))throw new Error(`Contained file parent is outside its managed root: ${e}`);let r=[await Zi(n)],s=B.relative(n,i).split(B.sep).filter(Boolean),o=n;for(let a of s){o=B.join(o,a);try{let c=await Zi(o);if(!Ct(r[0].realPath,c.realPath))throw new Error(`Contained file parent resolves outside its managed root: ${o}`);r.push(c)}catch(c){if(c.code==="ENOENT")return null;throw c}}return await Be(r),r}async function lu(t){let e;try{e=await q.open(t,"r"),await e.sync()}catch(n){let i=n.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(i??""))throw n}finally{await e?.close()}}async function Dg(t,e,n){let i=B.dirname(t),r=await qg(n.containedRoot,i),s=B.join(i,`.${B.basename(t)}.${Ig()}.tmp`),o,a;try{await n.beforeTemporaryOpen?.(),o=await q.open(s,"wx"),a=await o.stat();let[c,l]=await Promise.all([q.lstat(s),q.realpath(s)]);if(await Be(r),!c.isFile()||c.isSymbolicLink()||!Xi(a,c)||!Ct(r[0].realPath,l))throw new Error("Contained atomic write temporary file opened outside its managed parent");if(typeof e=="string"?await o.writeFile(e,"utf8"):await o.writeFile(e),await o.sync(),!Xi(a,await o.stat()))throw new Error("Contained atomic write temporary file changed while writing");await o.close(),o=void 0,await n.beforeCommit?.(),await Be(r);let f=await q.lstat(s);if(!f.isFile()||f.isSymbolicLink()||!Xi(f,a))throw new Error("Contained atomic write temporary file changed before commit");n.exclusive?(await _o(s,t),await q.unlink(s)):await q.rename(s,t),await lu(i)}catch(c){await o?.close();try{await Be(r),await q.rm(s,{force:!0})}catch{}throw c}}async function ce(t,e,n){await Dg(t,e,n)}async function xo(t,e){let n=B.dirname(t),i=await Lg(e.containedRoot,n);if(!i)return!1;let r,s;try{r=await q.lstat(t),s=await q.realpath(t)}catch(c){if(c.code==="ENOENT")return!1;throw c}if(!r.isFile()||r.isSymbolicLink()||!Ct(i[0].realPath,s))throw new Error("Contained file removal target must be a regular file inside its managed root");await e.beforeRemove?.(),await Be(i);let[o,a]=await Promise.all([q.lstat(t),q.realpath(t)]);if(!o.isFile()||o.isSymbolicLink()||!Xi(r,o)||a!==s)throw new Error("Contained file removal target changed before removal");return await q.unlink(t),await Be(i),await lu(n),!0}var nt=U(()=>{"use strict";Fi()});var _k,Po=U(()=>{"use strict";nt();St();ae();_k=16*1024});var No=U(()=>{"use strict";nt();be();St();ae();Po()});var ir=U(()=>{"use strict"});var Cu=U(()=>{"use strict"});var To=U(()=>{"use strict";ir()});var Eu=U(()=>{"use strict";ir();To()});function rw(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}function sw(t){let e=(0,Ru.parseDocument)(t,{uniqueKeys:!0});if(e.errors.length>0)throw new Error(`Invalid global Comet config: ${e.errors[0].message}`);let n=e.toJS();if(n==null)return{};if(typeof n!="object"||Array.isArray(n))throw new Error("Invalid global Comet config: root must be a mapping");return n}function xu(t){if(t.native?.pending_root_move)throw new Error("Global Comet config cannot contain native.pending_root_move");let e=t.native?(({pending_root_move:n,...i})=>i)(t.native):void 0;return{...t,schema:"comet.global.v1",...e?{native:e}:{}}}function ow(t){let e=Fe(JSON.stringify({...t,schema:"comet.project.v1"})).config;if(!e)throw new Error("Invalid global Comet config: workflow template is incomplete");return xu(e)}function aw(t){let e=Fe(t,{allowPartialProject:!0,allowMissingNativeFields:!0});if(!e.native&&!e.classic)return null;let n=e.native?"native":"classic",i=e.native?.language??e.classic?.language??"en",r=So(e.native?.artifact_root??"docs",i);return{schema:"comet.global.v1",default_workflow:n,workflows:[n],ambient_resume:e.ambient_resume,...e.native?{native:{...r.native,...e.native}}:{},...e.classic?{classic:e.classic}:{}}}function Pu(t){let e=sw(t);if(Object.keys(e).length===0)return null;if(e.schema===void 0)return aw(t);if(e.schema!=="comet.global.v1")throw new Error("Unsupported Comet global schema");return ow(e)}async function Io(t){try{let e=await W(t,_u,bt,{label:"global Comet config"});return Pu(e.bytes.toString("utf8"))}catch(e){if(rw(e))return null;throw e}}var Ru,_u,jo=U(()=>{"use strict";Ru=ct(et(),1);nt();be();ae();_u=".comet/config.yaml"});var Ou=U(()=>{"use strict";ir();nt();Cu();Eu();be();jo();ae();St();No();Po();To()});import{TextDecoder as cw}from"util";function Nu(t){return{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs}}function lw(t,e){try{return new cw("utf-8",{fatal:!0}).decode(t.bytes)}catch(n){throw new Error(`${e} is not valid UTF-8`,{cause:n})}}async function $o(t,e,n,i,r={}){try{let s=await W(t,e,n,{label:i,hooks:r.hooks});return{result:s,text:lw(s,i)}}catch(s){let o=s.code;if(o==="ENOENT"||o==="ENOTDIR")return null;throw s}}async function Cn(t,e,n,i,r={}){return(await $o(t,e,n,i,r))?.text??null}async function rr(t,e,n,i,r,s={}){if(Buffer.byteLength(n,"utf8")>i)throw new Error(`${r} exceeds ${i} bytes`);let o=await $o(t,e,i,r),a=await j(t,e,{label:r,expected:"file"});await ce(a.target,n,{containedRoot:a.projectRoot,beforeCommit:async()=>{await s.beforeCommit?.();let c=await $o(t,e,i,r);if(!(!o&&!c)){if(!o||!c)throw new Error(`${r} changed before commit`);if(o.result.realPath!==c.result.realPath||!ve(Nu(o.result.stat),Nu(c.result.stat))||o.text!==c.text)throw new Error(`${r} changed before commit`)}}})}async function sr(t,e,n,i,r,s={}){let o=await Cn(t,e,i,r);await rr(t,e,`${o??""}${n}`,i,r,s)}async function qo(t,e,n,i={}){let r=await j(t,e,{label:n,expected:"file"});return r.exists?xo(r.target,{containedRoot:r.projectRoot,beforeRemove:i.beforeRemove}):!1}var or=U(()=>{"use strict";Ou();Fi()});var Iu={};Lf(Iu,{RUN_STATE_FILE:()=>cr,applyRunStateToDocument:()=>Lo,readRunState:()=>_n,removeRunState:()=>Do,runStateFromDocument:()=>ar,writeRunState:()=>lr});import uw from"path";function Rn(t,e){let n=t[e];if(typeof n!="string"||n.length===0)throw new Error(`Invalid Run state: ${e} must be a non-empty string`);return n}function En(t,e){let n=Rn(t,e);if(uw.isAbsolute(n)||/^(?:[A-Za-z]:|[\\/]|~)/u.test(n)||n.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Run state: ${e} must stay inside the change directory`);return n}function fw(t){let e=t.run_retries??"{}",n;try{n=typeof e=="string"?JSON.parse(e):e}catch(i){throw new Error("Invalid Run state: run_retries must be a JSON object",{cause:i})}if(!n||typeof n!="object"||Array.isArray(n))throw new Error("Invalid Run state: run_retries must be a JSON object");for(let i of Object.values(n))if(!Number.isInteger(i)||Number(i)<0)throw new Error("Invalid Run state: retry counts must be non-negative integers");return n}function ar(t){if(!t.run_id)return null;let e=Rn(t,"run_id"),n=Rn(t,"skill"),i=Rn(t,"skill_version"),r=Rn(t,"skill_hash"),s=En(t,"pending_ref"),o=En(t,"trajectory_ref"),a=En(t,"context_ref"),c=En(t,"artifacts_ref"),l=En(t,"checkpoint_ref"),f=Number(t.iteration);if(!Number.isInteger(f)||f<0)throw new Error("Invalid Run state: iteration must be a non-negative integer");if(t.orchestration!=="deterministic"&&t.orchestration!=="adaptive")throw new Error("Invalid Run state: orchestration must be deterministic or adaptive");if(t.run_status!=="running"&&t.run_status!=="waiting"&&t.run_status!=="completed"&&t.run_status!=="failed")throw new Error("Invalid Run state: run_status is invalid");return{runId:e,skill:n,skillVersion:i,skillHash:r,orchestration:t.orchestration,currentStep:Au(t,"current_step"),iteration:f,pending:Au(t,"pending"),pendingRef:s,trajectoryRef:o,contextRef:a,artifactsRef:c,checkpointRef:l,status:t.run_status,retries:fw(t)}}function Lo(t,e){e?t.run_id=e.runId:delete t.run_id}function dw(t){return{runId:t.runId,skill:t.skill,skillVersion:t.skillVersion,skillHash:t.skillHash,orchestration:t.orchestration,currentStep:t.currentStep,iteration:t.iteration,pending:t.pending,pendingRef:t.pendingRef,trajectoryRef:t.trajectoryRef,contextRef:t.contextRef,artifactsRef:t.artifactsRef,checkpointRef:t.checkpointRef,status:t.status,retries:t.retries}}function pw(t){let e={run_id:t.runId,skill:t.skill,skill_version:t.skillVersion,skill_hash:t.skillHash,orchestration:t.orchestration,current_step:t.currentStep,iteration:t.iteration,pending:t.pending,pending_ref:t.pendingRef,trajectory_ref:t.trajectoryRef,context_ref:t.contextRef,artifacts_ref:t.artifactsRef,checkpoint_ref:t.checkpointRef,run_status:t.status,run_retries:JSON.stringify(t.retries)};return ar(e)}async function _n(t,e={}){let n=await Cn(t,cr,Tu,"Run state",e);if(n===null)return null;let i=JSON.parse(n);return pw(i)}async function lr(t,e,n={}){await rr(t,cr,JSON.stringify(dw(e),null,2),Tu,"Run state",n)}async function Do(t,e={}){await qo(t,cr,"Run state",e)}var Au,cr,Tu,xn=U(()=>{"use strict";or();Au=(t,e)=>{let n=t[e];return n==null?null:String(n)};cr=".comet/run-state.json",Tu=256*1024});var Mn=ct(et(),1);import{spawnSync as jy}from"child_process";import{promises as $y}from"fs";import O from"path";co();import{randomUUID as dg}from"crypto";import{promises as un}from"fs";import Vl from"path";var lo="comet.selection.v2",pg=16*1024;function Ui(t){return Vl.join(t,".comet","current-change.json")}function mg(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function Yl(t){return t===null||typeof t=="string"}function Jl(t){let e;try{e=JSON.parse(t)}catch(n){throw new Error(`current change selection contains invalid JSON: ${n instanceof Error?n.message:String(n)}`,{cause:n})}if(!mg(e))throw new Error("current change selection must be a JSON object");if(e.version===1){if(typeof e.change!="string")throw new Error("legacy current change selection change must be a string");if(e.branch!==void 0&&!Yl(e.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:lo,workflow:"classic",change:e.change,branch:e.branch??null},legacy:!0}}if(e.schema!==lo)throw new Error(`current change selection schema must be ${lo}`);if(e.workflow!=="native"&&e.workflow!=="classic")throw new Error("current change selection workflow must be native or classic");if(typeof e.change!="string")throw new Error("current change selection change must be a string");if(!Yl(e.branch))throw new Error("current change selection branch must be a string or null");if(e.workflow==="native"&&e.branch!==null)throw new Error("Native current change selection branch must be null");return{selection:e,legacy:!1}}async function uo(t){let e;try{let i=Ui(t),{bytes:r}=await Ki(i,pg,{label:"current change selection"});e=r.toString("utf8")}catch(i){if(i.code==="ENOENT")return{status:"missing"};throw new Error(`cannot read current change selection: ${i instanceof Error?i.message:String(i)}`,{cause:i})}return{status:"selected",...Jl(e)}}async function Hl(t,e){let n=Jl(JSON.stringify(e));if(n.legacy)throw new Error("cannot write a legacy current change selection");let i=Ui(t),r=`${i}.${dg()}.tmp`;await un.mkdir(Vl.dirname(i),{recursive:!0});try{await un.writeFile(r,`${JSON.stringify(n.selection,null,2)} +`,"utf8"),await un.rename(r,i)}catch(s){throw await un.rm(r,{force:!0}),s}}async function Gl(t){await un.rm(Ui(t),{force:!0})}var zl=null;function Xl(t,e){let n=t;for(let i of e)n+="\0"+(typeof i=="string"?i:JSON.stringify(i));return n}function Ql(t,e){return(...n)=>{let i=zl;if(i===null)return e(...n);let r=Xl(`async:${t}`,n),s=i.entries.get(r);if(s)return s.value;let o=e(...n).catch(a=>{throw i.entries.delete(r),a});return i.entries.set(r,{value:o}),o}}function fo(t,e){return(...n)=>{let i=zl;if(i===null)return e(...n);let r=Xl(`sync:${t}`,n),s=i.entries.get(r);if(s)return s.value;let o=e(...n);return i.entries.set(r,{value:o}),o}}var po=ct(et(),1);import{execFileSync as Zl}from"child_process";import{randomUUID as hg}from"crypto";import{promises as fn}from"fs";import eu from"path";function Yi(t){try{let e=Zl("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();return e&&e!=="HEAD"?e:null}catch{return null}}var gg=fo("liveGitBranch",t=>Yi(t));function mo(t){try{return Zl("git",["rev-parse","--is-inside-work-tree"],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()==="true"}catch{return!1}}var wg=fo("isGitWorkTree",t=>mo(t)),yg=["current","branch","worktree"];function Vi(t){return yg.includes(t)}function ho(t){return Vi(t.isolation)?t.boundBranch===null&&t.currentBranch===null&&t.gitWorkTree===!1?{status:"not-applicable"}:t.boundBranch===null?t.currentBranch===null?{status:"unbound-detached"}:{status:"needs-heal",branch:t.currentBranch}:t.currentBranch===t.boundBranch?{status:"ok"}:{status:"drift",boundBranch:t.boundBranch,currentBranch:t.currentBranch}:{status:"not-applicable"}}async function dn(t,e){let n=eu.join(t,".comet.yaml"),i=(0,po.parseDocument)(await fn.readFile(n,"utf8"),{uniqueKeys:!1});if(i.errors.length>0)throw new Error(`Invalid .comet.yaml: ${i.errors[0].message}`);let r=i.toJS()??{},s=typeof r.isolation=="string"?r.isolation:null,o=typeof r.bound_branch=="string"&&r.bound_branch!==""?r.bound_branch:null,a=Vi(s),c=gg(e.cwd),l=a&&o===null&&c===null?wg(e.cwd):!0,f=ho({isolation:s,boundBranch:o,currentBranch:c,gitWorkTree:l});return f.status==="needs-heal"&&e.heal?(await go(t,f.branch),{status:"healed",branch:f.branch,bindingRequired:a,currentBranch:c}):{...f,bindingRequired:a,currentBranch:c}}async function go(t,e){let n=eu.join(t,".comet.yaml"),i=(0,po.parseDocument)(await fn.readFile(n,"utf8"),{uniqueKeys:!1});i.set("bound_branch",e);let r=`${n}.${hg()}.tmp`;try{await fn.writeFile(r,i.toString(),"utf8"),await fn.rename(r,n)}catch(s){throw await fn.rm(r,{force:!0}),s}}function tu(t){return t??"detached HEAD"}function nu(t,e,n){return`change '${t}' is bound to branch '${e}', but current branch is '${tu(n)}'. +Next: ask the user to confirm — switch back to '${e}', or run \`comet state rebind ${t}\` after explicit confirmation.`}function wo(t,e,n){return`change '${t}' is bound to branch '${e}', but current branch is '${tu(n)}'`}function pn(t){return`change '${t}' uses a branch-bound workspace mode but has no bound branch and HEAD is detached; checkout a branch first before continuing.`}import{promises as Gg}from"fs";import Et from"path";import{promises as pu}from"fs";import I from"path";import{promises as vg}from"fs";async function mn(t){try{return await vg.access(t),!0}catch(e){if(bg(e))return!1;throw e}}function bg(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}be();St();No();ae();var yn=class extends Error{code="classic-layout-unavailable";constructor(e="Classic artifact layout is unavailable from .comet/config.yaml"){super(e),this.name="ClassicLayoutUnavailableError"}},du=".comet/config.yaml";function mu(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function hu(t){await j(t,du,{label:du,expected:"file"})}function er(t,e){let n=I.resolve(t),i=e==="docs"?I.join(n,"docs"):n,r=I.join(i,"openspec"),s=I.join(n,"docs","superpowers");return{projectRoot:n,artifactLayout:e,openSpecBase:i,openSpecRoot:r,changesDir:I.join(r,"changes"),archiveDir:I.join(r,"changes","archive"),specsDir:I.join(r,"specs"),superpowersRoot:s,superpowersSpecsDir:I.join(s,"specs"),superpowersPlansDir:I.join(s,"plans"),superpowersReportsDir:I.join(s,"reports")}}async function Kg(t){await hu(t);let e=await kt(t,{allowPartialProject:!0,allowMissingNativeFields:!0});if(!e?.config)throw new yn;if(!(e.config.workflows??[e.config.default_workflow]).includes("classic"))throw new yn("Classic artifact layout is unavailable because Classic is not enabled");return e.classic?.artifact_layout??"legacy"}async function Ug(t,e){return er(t,e??await Kg(t))}async function Yg(t){try{return await pu.lstat(t),!0}catch(e){if(mu(e))return!1;throw e}}async function Vg(t,e){let n=await Ug(t,e),i=n.artifactLayout==="legacy"?"docs":"legacy",r=er(t,i).openSpecRoot,[s,o]=await Promise.all([j(n.projectRoot,Z(n.projectRoot,n.openSpecRoot),{label:"Configured Classic OpenSpec root",expected:"directory"}),Yg(r)]),a=s.exists;return{paths:n,configuredRootExists:a,alternateRoot:r,alternateRootExists:o,dualRoots:a&&o}}async function Jg(t){let e=[t.openSpecRoot,t.changesDir,t.archiveDir,t.specsDir,t.superpowersRoot,t.superpowersSpecsDir,t.superpowersPlansDir,t.superpowersReportsDir];for(let n of e){let i=Z(t.projectRoot,n);await j(t.projectRoot,i,{label:`Classic managed physical path ${i}`,expected:"directory"})}}async function ee(t,e){let n=await Vg(t,e);if(await Jg(n.paths),!n.configuredRootExists){let i=Z(n.paths.projectRoot,n.paths.openSpecRoot),r=Z(n.paths.projectRoot,n.alternateRoot);throw new yn(`Configured Classic OpenSpec root is missing: ${i} (alternate ${r} is ${n.alternateRootExists?"present":"missing"})`)}return n.paths}async function tr(t,e){let n=I.join(I.resolve(t),".comet","classic-root-move.json");if(await mn(n))throw new Error("Classic root move transaction is incomplete; inspect it with comet doctor and recover it explicitly before writing");let i=await ee(t,e);if(!await mn(i.openSpecRoot))throw new Error(`Configured Classic OpenSpec root is missing: ${Z(i.projectRoot,i.openSpecRoot)}`);return i}async function vn(t){let e=I.resolve(t),n=null;try{(await pu.lstat(e)).isDirectory()||(e=I.dirname(e))}catch(i){if(!mu(i))throw i}for(;;){I.basename(e)==="openspec"&&(n=I.dirname(e));let i=I.join(e,".comet","config.yaml"),r=!1;if(await mn(i))try{await hu(e);let o=(await kt(e))?.value;r=!!o&&typeof o=="object"&&!Array.isArray(o)&&(o.schema==="comet.project.v1"||o.default_workflow!==void 0||o.native!==void 0)}catch{}if(r||await mn(I.join(e,".git")))return e;let s=I.dirname(e);if(s===e)return n??I.resolve(t);e=s}}function Z(t,e){return I.relative(I.resolve(t),e).replaceAll("\\","/")}nt();be();ae();import bn from"path";var Hg=2*1024*1024;function nr(t,e,n){let i=bn.resolve(t),r=bn.isAbsolute(e)?bn.resolve(e):bn.resolve(i,e),s=bn.relative(i,r).replaceAll("\\","/");return{root:i,relative:Me(s,n),target:r}}async function Ke(t,e,n){let i=nr(t,e,n.label);return j(i.root,i.relative,n)}async function kn(t,e,n){return(await Ke(t,e,{label:n.label,expected:n.expected??"any"})).exists}async function gu(t,e,n,i){return await kn(t,e,{label:n,expected:"file"})?(await wu(t,e,{label:n,hooks:i})).byteLength>0:!1}async function Ue(t,e,n){return(await wu(t,e,n)).toString("utf8")}async function wu(t,e,n){let i=nr(t,e,n.label);return(await W(i.root,i.relative,n.maxBytes??Hg,{label:n.label,hooks:n.hooks})).bytes}async function yu(t,e,n){let i=nr(t,e,n);return Ro(i.root,i.relative,{label:n})}async function vu(t,e,n,i){let r=nr(t,e,i.label);await j(r.root,r.relative,{label:i.label,expected:"file"}),await ce(r.target,n,{containedRoot:r.root,beforeTemporaryOpen:i.beforeTemporaryOpen,beforeCommit:i.beforeCommit,exclusive:i.exclusive})}function Ao(t){return t?/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t)?t.includes("..")?"Change name cannot contain '..' (path traversal not allowed)":null:`Invalid change name: '${t}' +Valid format: lowercase kebab-case (a-z, 0-9, single hyphens)`:"Change name cannot be empty"}function it(t){let e=Ao(t);if(e)throw new Error(e)}function zg(t,e){return{label:Z(t,e),directory:e}}async function Sn(t,e,n){let i=zg(t,e);if(!(await Ke(t,e,{label:n,expected:"directory"})).exists)return{change:i,exists:!1,stateExists:!1};let s=await Ke(t,Et.join(e,".comet.yaml"),{label:`${n} state`,expected:"file"});return{change:i,exists:!0,stateExists:s.exists}}function Xg(t,e){let n=e.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&");return new RegExp(`^\\d{4}-\\d{2}-\\d{2}-${n}$`,"u").test(t)}async function Qg(t,e,n,i={}){if(!i.skipExactCompatibility){let o=await Sn(t,Et.join(e,n),`Classic archived change ${n}`);if(o.exists)return o.change}if(!(await Ke(t,e,{label:"Classic archive directory",expected:"directory"})).exists)return null;let s=[];for(let o of await Gg.readdir(e,{withFileTypes:!0})){if(!Xg(o.name,n))continue;let a=await Sn(t,Et.join(e,o.name),`Classic archived change ${o.name}`);a.exists&&a.stateExists&&s.push(a.change)}return s.sort((o,a)=>a.directory.localeCompare(o.directory))[0]??null}async function bu(t,e=process.cwd()){it(t);let n=await ee(e),i=await Sn(n.projectRoot,Et.join(n.changesDir,t),`Classic active change ${t}`);return{...i.change,exists:i.exists,stateExists:i.stateExists}}async function ku(t,e=process.cwd()){it(t);let n=await tr(e),i=Et.join(n.changesDir,t),r=await Sn(n.projectRoot,i,`Classic active change ${t}`);return r.exists||await yu(n.projectRoot,i,`Classic active change ${t}`),r.change}async function Su(t,e=process.cwd()){it(t);let n=await ee(e),i=await Sn(n.projectRoot,Et.join(n.changesDir,t),`Classic active change ${t}`);if(i.exists)return i.change;let r=await Qg(n.projectRoot,n.archiveDir,t);return r||i.change}var dr=ct(et(),1);nt();ae();import fr from"path";xn();var ju=["full","hotfix","tweak"],Pn=1,mw=["open","design","build","verify","archive"],hw=["en","zh-CN"],gw=["off","beta"],ww=["subagent-driven-development","executing-plans","direct"],yw=["plan-ready"],vw=["confirmed"],bw=["tdd","direct"],kw=["off","standard","thorough"],Sw=["current","branch","worktree"],Cw=["light","full"],Ew=["pending","pass","fail"],Rw=["pending","handled"],_w=["pending","confirmed"],_t=["workflow","language","phase","context_compression","build_mode","build_pause","subagent_dispatch","tdd_mode","review_mode","isolation","bound_branch","verify_mode","auto_transition","base_ref","design_doc","plan","verify_result","verify_failures","verification_report","branch_status","created_at","verified_at","archive_confirmation","archived","direct_override","handoff_context","handoff_hash","classic_profile","classic_migration"],Fo=["run_id"],xw=new Set([..._t,...Fo]),Pw=["workflow","phase","design_doc","plan","build_mode","isolation","verify_mode","verify_result","verified_at","archived"];function $u(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function Rt(t,e){let n=t[e];if(n==null||n==="")return null;if(typeof n!="string")throw new Error(`Invalid Classic state: ${e} must be a string or null`);return n}function V(t,e,n,i=!0){let r=t[e];if(r==null||r===""){if(i)return null;throw new Error(`Invalid Classic state: ${e} is required`)}if(typeof r!="string"||!n.includes(r))throw new Error(`Invalid Classic state: ${e} must be one of ${n.join(", ")}${i?" or null":""}`);return r}function Mo(t,e,n=!0){let i=t[e];if(i==null||i===""){if(n)return null;throw new Error(`Invalid Classic state: ${e} is required`)}if(typeof i!="boolean")throw new Error(`Invalid Classic state: ${e} must be true or false`);return i}function Ow(t,e,n=0){let i=t[e];if(i==null||i==="")return n;if(typeof i!="number"||!Number.isInteger(i)||i<0)throw new Error(`Invalid Classic state: ${e} must be a non-negative integer`);return i}function ur(t,e){let n=Rt(t,e);if(n===null)return null;if(/^(?:[A-Za-z]:|[\\/]|~)/u.test(n)||n.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Classic state: ${e} must be a relative repository path`);return n}function Nw(t,e){let n=Rt(t,e);if(n!==null&&!/^[a-f0-9]{64}$/u.test(n))throw new Error(`Invalid Classic state: ${e} must be a sha256 hex digest`);return n}function Aw(t){let e=t.classic_migration;if(e==null||e==="")return null;if(e!==Pn)throw new Error(`Invalid Classic state: classic_migration must be ${Pn}`);return e}function Tw(t){if(!_t.some(n=>$u(t,n)))return null;for(let n of Pw)if(!$u(t,n))return null;return{workflow:V(t,"workflow",ju,!1),language:V(t,"language",hw),phase:V(t,"phase",mw,!1),contextCompression:V(t,"context_compression",gw),buildMode:V(t,"build_mode",ww),buildPause:V(t,"build_pause",yw),subagentDispatch:V(t,"subagent_dispatch",vw),tddMode:V(t,"tdd_mode",bw),reviewMode:V(t,"review_mode",kw),isolation:V(t,"isolation",Sw),boundBranch:Rt(t,"bound_branch"),verifyMode:V(t,"verify_mode",Cw),autoTransition:Mo(t,"auto_transition"),baseRef:Rt(t,"base_ref"),designDoc:ur(t,"design_doc"),plan:ur(t,"plan"),verifyResult:V(t,"verify_result",Ew,!1),verifyFailures:Ow(t,"verify_failures"),verificationReport:ur(t,"verification_report"),branchStatus:V(t,"branch_status",Rw),createdAt:Rt(t,"created_at"),verifiedAt:Rt(t,"verified_at"),archiveConfirmation:V(t,"archive_confirmation",_w),archived:Mo(t,"archived",!1),directOverride:Mo(t,"direct_override"),handoffContext:ur(t,"handoff_context"),handoffHash:Nw(t,"handoff_hash"),classicProfile:V(t,"classic_profile",ju),classicMigration:Aw(t)}}function On(t,e){let n=e??null;if(n===null&&e===void 0&&t.run_id&&t.skill)try{n=ar(t)}catch(i){let r=i instanceof Error?i.message:String(i);throw new Error(r.replace(/^Invalid Run state:/u,"Invalid Classic state:"),{cause:i})}return{classic:Tw(t),run:n,unknownKeys:Object.keys(t).filter(i=>!xw.has(i))}}function qu(t){return{workflow:t.workflow,language:t.language,phase:t.phase,context_compression:t.contextCompression,build_mode:t.buildMode,build_pause:t.buildPause,subagent_dispatch:t.subagentDispatch,tdd_mode:t.tddMode,review_mode:t.reviewMode,isolation:t.isolation,bound_branch:t.boundBranch,verify_mode:t.verifyMode,auto_transition:t.autoTransition,base_ref:t.baseRef,design_doc:t.designDoc,plan:t.plan,verify_result:t.verifyResult,verify_failures:t.verifyFailures,verification_report:t.verificationReport,branch_status:t.branchStatus,created_at:t.createdAt,verified_at:t.verifiedAt,archive_confirmation:t.archiveConfirmation,archived:t.archived,direct_override:t.directOverride,handoff_context:t.handoffContext,handoff_hash:t.handoffHash,classic_profile:t.classicProfile,classic_migration:t.classicMigration}}xn();var Iw=2*1024*1024;function Nn(t){let e=t.toJS();if(e===null)return{};if(typeof e!="object"||Array.isArray(e))throw new Error("Invalid Classic state document: root must be a mapping");return e}function Lu(t,e,n){t.get(e)!==n&&t.set(e,n)}function jw(t,e){if(e.classic)for(let[n,i]of Object.entries(qu(e.classic)))Lu(t,n,i);else for(let n of _t)t.delete(n);Lo(t.toJS(),e.run),e.run?Lu(t,"run_id",e.run.runId):t.delete("run_id")}function $w(t){let e=["skill","skill_version","skill_hash","orchestration","current_step","iteration","pending","pending_ref","trajectory_ref","context_ref","artifacts_ref","checkpoint_ref","run_status","run_retries"];for(let n of e)t.delete(n)}function qw(t){let e=!1;for(let n of["build_command","verify_command"])t.has(n)&&(t.delete(n),e=!0);return e}async function Du(t){let e;try{e=(await W(fr.dirname(t),fr.basename(t),Iw,{label:"Classic state document"})).bytes.toString("utf8")}catch(i){if(i.code!=="ENOENT")throw i;return new dr.Document({})}let n=(0,dr.parseDocument)(e);if(n.errors.length>0)throw new Error(`Invalid Classic state document: ${n.errors[0].message}`);return Nn(n),n}async function me(t,e={}){let n=e.migrate!==!1,i=fr.join(t,".comet.yaml"),r=await Du(i),s=Nn(r),o=qw(r);o&&(s=Nn(r));let a=await _n(t);if(!a&&s.run_id&&s.skill){let{runStateFromDocument:c}=await Promise.resolve().then(()=>(xn(),Iu));a=c(s),a&&n&&(await lr(t,a),$w(r),o=!0)}return o&&n&&await ce(i,r.toString(),{containedRoot:t}),On(Nn(r),a)}async function xt(t,e,n={}){let i=fr.join(t,".comet.yaml"),r=await Du(i);jw(r,{...e,unknownKeys:e.unknownKeys??[]}),On(Nn(r),e.run??null),await ce(i,r.toString(),{containedRoot:t,beforeCommit:n.beforeCommit}),e.run?await lr(t,e.run):await Do(t)}var Lw=Ql("readCometCurrentSelection",t=>uo(t));async function Mu(t,e){it(e);let n=await bu(e,t);if(!n.stateExists)throw new Error(`Cannot select current change '${e}': active change state not found`);let i=await me(n.directory,{migrate:!1});if(!i.classic)throw new Error(`Cannot select current change '${e}': Classic state is incomplete`);if(i.classic.archived)throw new Error(`Cannot select current change '${e}': change is archived`);return n.directory}async function Fu(t,e){let n=await Mu(t,e),i=await dn(n,{heal:!0,cwd:t});if(i.status==="drift")throw new Error(wo(e,i.boundBranch,i.currentBranch));if(i.status==="unbound-detached")throw new Error(pn(e));let r={schema:"comet.selection.v2",workflow:"classic",change:e,branch:i.currentBranch};return await Hl(t,r),r}async function Wu(t){let e;try{e=await Lw(t)}catch(s){return{status:"stale",reason:s instanceof Error?s.message:String(s)}}if(e.status==="missing")return{status:"missing"};if(e.selection.workflow!=="classic")return{status:"stale",reason:`current change '${e.selection.change}' belongs to Native, not Classic`};let n=e.selection,i;try{i=await Mu(t,n.change)}catch(s){return{status:"stale",reason:s instanceof Error?s.message:String(s)}}let r=await dn(i,{heal:!1,cwd:t});return r.status==="drift"?{status:"stale",reason:wo(n.change,r.boundBranch,r.currentBranch)}:r.status==="unbound-detached"?{status:"stale",reason:pn(n.change)}:r.status==="ok"?{status:"selected",selection:n}:n.branch!==null&&r.currentBranch!==n.branch?{status:"stale",reason:`current change '${n.change}' was selected on branch '${n.branch}', current branch is '${r.currentBranch??"detached HEAD"}'`}:{status:"selected",selection:n}}async function Bu(t){let e;try{e=await uo(t)}catch{return}e.status==="selected"&&e.selection.workflow==="classic"&&await Gl(t)}import{promises as Mw}from"fs";import ke from"path";ae();be();import An from"path";function Dw(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function Ku(t,e,n,i){let r=Me(n,"Classic handoff artifact pointer");if((await j(t,r,{label:"Classic handoff artifact",expected:"file"})).exists)return null;let o=await ee(t),a=`${Z(t,o.changesDir)}/`,l=(o.artifactLayout==="docs"?[a,"openspec/changes/"]:[a]).find(y=>r.startsWith(y));if(!l)return null;let f=r.slice(l.length).split("/");if(f.length<4||f[1]!==".comet"||f.slice(2).some(y=>y.length===0))return null;let u=f[0];it(u);let d=f.slice(2),m=An.resolve(e);if(An.dirname(m)!==An.resolve(o.archiveDir))return null;let g=An.basename(m),p=/^\d{4}-\d{2}-\d{2}-(.+)$/u.exec(g);if(g!==u&&p?.[1]!==u)return null;await j(t,Z(t,m),{label:"Classic archived change directory",expected:"directory"});let h=An.join(m,".comet",...d),v=Z(t,h);try{return await W(t,v,i,{label:"Historical Classic archived handoff artifact"}),v}catch(y){if(Dw(y))return null;throw y}}ae();var Uu=2*1024*1024;function Tn(t,e){return ke.relative(t,e).split(ke.sep).join("/")}async function In(t,e,n,i,r){if(!n)return{code:e,satisfied:!1};let s=n.replaceAll("\\","/");if(r)return{code:e,satisfied:!1,source:s,detail:`Classic layout is unsafe or unavailable: ${r instanceof Error?r.message:String(r)}`};try{if(i){let a=i.artifactLayout==="legacy"?"docs":"legacy",c=Z(t,er(t,a).openSpecRoot);if((s===c||s.startsWith(`${c}/`))&&(await j(t,s,{label:`${e} artifact`,expected:"file"})).exists)return{code:e,satisfied:!1,source:s,detail:"standalone OpenSpec root is not a Comet artifact root"}}let o=await Gi(t,s,{label:`${e} artifact`});return{code:e,satisfied:o,source:s,...o?{resolvedSource:s}:{}}}catch(o){return{code:e,satisfied:!1,source:s,detail:`unsafe artifact pointer outside the project or through a special path: ${o instanceof Error?o.message:String(o)}`}}}async function Fw(t,e,n,i){try{i??=await ee(t)}catch(s){return{code:"design.handoff",satisfied:!1,...n?{source:n.replaceAll("\\","/")}:{},detail:`Classic layout is unsafe or unavailable for handoff evidence: ${s instanceof Error?s.message:String(s)}`}}let r=await In(t,"design.handoff",n,i);if(!n||r.satisfied||r.detail)return r;try{let s=await Ku(t,e,n,Uu);return s?{...r,satisfied:!0,resolvedSource:s,detail:`resolved historical legacy pointer from archived change: ${s}`}:r}catch(s){return{...r,satisfied:!1,detail:`unsafe archived handoff fallback: ${s instanceof Error?s.message:String(s)}`}}}async function pr(t,e,n){return In(t,e,Tn(t,n))}async function Ww(t,e){let n=ke.join(e,"specs"),i;try{let o=Tn(t,n);if(!(await j(t,o,{label:"OpenSpec delta-spec directory",expected:"directory"})).exists)return{code:"openspec.delta-spec",satisfied:!1};i=await Mw.readdir(n)}catch(o){return o.code==="ENOENT"?{code:"openspec.delta-spec",satisfied:!1}:{code:"openspec.delta-spec",satisfied:!1,detail:`unsafe delta-spec path: ${o instanceof Error?o.message:String(o)}`}}let r=i.map(o=>ke.join(n,o,"spec.md")),s=(await Promise.all(r.map(async o=>{try{return await Gi(t,Tn(t,o),{label:"OpenSpec delta spec"})?o:null}catch{return null}}))).filter(o=>o!==null);return{code:"openspec.delta-spec",satisfied:s.length>0,source:s[0]?Tn(t,s[0]):void 0,detail:`${s.length} delta spec${s.length===1?"":"s"}`}}async function Bw(t,e){let n,i=Tn(t,e);try{n=(await W(t,i,Uu,{label:"Classic tasks artifact"})).bytes.toString("utf8")}catch(o){return o.code==="ENOENT"?{code:"build.tasks-complete",satisfied:!1}:{code:"build.tasks-complete",satisfied:!1,source:i,detail:`unsafe tasks artifact: ${o instanceof Error?o.message:String(o)}`}}let r=[...n.matchAll(/^\s*[-*]\s+\[([ xX])\]\s+/gmu)],s=r.filter(o=>o[1].toLowerCase()==="x").length;return{code:"build.tasks-complete",satisfied:r.length>0&&s===r.length,source:i,detail:`${s} of ${r.length} tasks complete`}}function jn(t,e){return t.some(n=>n.code===e&&n.satisfied)}async function Pt(t,e){let n=await vn(t),i=e.classic,r=ke.join(t,"proposal.md"),s=ke.join(t,"design.md"),o=ke.join(t,"tasks.md"),a=e.run?ke.resolve(t,e.run.checkpointRef):ke.join(t,".comet","checkpoint.json"),c,l;try{c=await ee(n)}catch(d){l=d}let f=await Promise.all([pr(n,"openspec.proposal",r),pr(n,"openspec.design",s),pr(n,"openspec.tasks",o),Ww(n,t),In(n,"design.document",i?.designDoc??null,c,l),In(n,"build.plan",i?.plan??null,c,l),Bw(n,o),In(n,"verification.report",i?.verificationReport??null,c,l),Fw(n,t,i?.handoffContext??null,c),pr(n,"run.checkpoint",a)]),u=f.find(d=>d.code==="design.handoff");return u&&!i?.handoffHash&&(u.satisfied=!1,u.detail="handoff hash is missing"),f.push({code:"archive.confirmed",satisfied:i?.archiveConfirmation==="confirmed"}),f}import{AsyncLocalStorage as Kw}from"async_hooks";import{promises as Yu}from"fs";import $n from"path";var mr=new Kw;function Uw(t,e){let n=$n.relative(t,e);return n===""||!$n.isAbsolute(n)&&n!==".."&&!n.startsWith(`..${$n.sep}`)}async function Yw(t){let e=$n.resolve(t.invocationCwd??process.cwd()),n=$n.resolve(t.projectRoot??await vn(e)),[i,r]=await Promise.all([Yu.realpath(e),Yu.realpath(n)]);if(!Uw(r,i))throw new Error(`Classic command invocation cwd is outside the discovered project: ${e}`);return{invocationCwd:e,projectRoot:n}}async function Vu(t,e){let n=mr.getStore();if(n)return e(n);let i=await Yw(t);return mr.run(i,()=>e(i))}function T(){let t=mr.getStore();if(!t)throw new Error("Classic command project context is unavailable");return t.projectRoot}function qn(){let t=mr.getStore();if(!t)throw new Error("Classic command invocation context is unavailable");return t.invocationCwd}function Vw(t){return t.classicProfile??t.workflow}function Jw(t){return!t.buildMode||!t.tddMode||!t.isolation||!t.verifyMode?!1:t.buildMode==="subagent-driven-development"?t.subagentDispatch==="confirmed":t.buildMode==="direct"?t.directOverride===!0:!0}function Hw(t){return t.buildMode==="direct"&&t.tddMode==="direct"&&t.isolation!==null&&t.verifyMode==="light"}function Gw(t,e,n){if(e.verifyResult==="fail")return t==="full"?"full.build.fix":`${t}.build.execute`;if(t==="full"){if(!jn(n,"build.plan"))return"full.build.plan";if(e.buildPause==="plan-ready")return"full.build.plan-ready";if(!Jw(e))return"full.build.configure"}else if(!Hw(e))throw new Error(`${t} build configuration is incomplete`);return jn(n,"build.tasks-complete")?`${t}.build.complete`:`${t}.build.execute`}function zw(t,e,n){return e.verifyResult!=="pass"||!jn(n,"verification.report")?`${t}.verify.run`:`${t}.verify.branch`}function Xw(t,e){if(e.verifyResult!=="pass")throw new Error("archive requires verify_result=pass");return e.archiveConfirmation==="confirmed"?`${t}.archive.execute`:`${t}.archive.confirm`}function Ot(t,e){let n=Vw(t);if(t.archived&&t.phase!=="archive")throw new Error("archived=true requires phase=archive");if(t.archived)return"completed";if(n!=="full"&&t.phase==="design")throw new Error(`${n} workflow cannot enter design`);switch(t.phase){case"open":return`${n}.open`;case"design":return jn(e,"design.handoff")?"full.design.document":"full.design.handoff";case"build":return Gw(n,t,e);case"verify":return zw(n,t,e);case"archive":return Xw(n,t)}}import{promises as df}from"fs";import Q from"path";import{fileURLToPath as pf}from"url";or();import hr from"path";var Ju={trajectory:8*1024*1024,artifacts:1024*1024,context:1024*1024,pendingAction:256*1024,checkpoint:256*1024};function Hu(t,e){if(hr.isAbsolute(e))throw new Error("Run path must stay inside the change directory");let n=hr.resolve(t),i=hr.resolve(n,e);if(i!==n&&!i.startsWith(n+hr.sep))throw new Error("Run path must stay inside the change directory")}async function rt(t,e,n,i={}){Hu(t,e),await sr(t,e,`${JSON.stringify(n)} +`,Ju.trajectory,"Run trajectory",i)}async function Nt(t,e,n={}){Hu(t,e);let i=await Cn(t,e,Ju.trajectory,"Run trajectory",n);return i===null?[]:i.split(/\r?\n/).map((r,s)=>({line:r,number:s+1})).filter(({line:r})=>r.length>0).map(({line:r,number:s})=>{try{return JSON.parse(r)}catch(o){throw new Error(`Invalid Trajectory event at line ${s}`,{cause:o})}})}import{createHash as lf,randomUUID as YC}from"crypto";import{promises as At}from"fs";import he from"path";var Xu=ct(et(),1);import{promises as Wo}from"fs";import ie from"path";var Qw=["invoke_skill","call_tool","handoff","ask_user","checkpoint"],Zw=["deterministic","adaptive"],ey=["function","mcp","script","agent"],ty=["none","read","write","external"],ny=["progress","step","completion"],iy=["artifact_exists","state_equals"];function st(t,e,n){return new Error(`${t}: ${e} ${n}`)}function X(t,e,n="document"){if(t===null||typeof t!="object"||Array.isArray(t))throw st(e,n,"must be an object")}function Ye(t,e,n){if(!Array.isArray(t))throw st(e,n,"must be an array")}function J(t,e,n){if(typeof t!="string")throw st(e,n,"must be a string")}function le(t,e,n,i){e in t&&J(t[e],n,`${i}.${e}`)}function Qu(t,e,n,i){if(e in t&&typeof t[e]!="boolean")throw st(n,`${i}.${e}`,"must be a boolean")}function Ve(t,e,n,i){if(typeof t!="string"||!e.includes(t))throw st(n,i,`must be one of ${e.join(", ")}`)}function gr(t,e,n){Ye(t,e,n),t.forEach((i,r)=>{J(i,e,`${n}[${r}]`)})}function Gu(t,e,n){X(t,e,n),J(t.name,e,`${n}.name`),J(t.description,e,`${n}.description`),Qu(t,"required",e,n)}function ry(t,e,n){X(t,e,n),J(t.id,e,`${n}.id`),le(t,"source",e,n),le(t,"version",e,n)}function sy(t,e,n){X(t,e,n),J(t.id,e,`${n}.id`),J(t.role,e,`${n}.role`),le(t,"instructions",e,n)}function oy(t,e,n){X(t,e,n),J(t.id,e,`${n}.id`),Ve(t.kind,ey,e,`${n}.kind`),J(t.source,e,`${n}.source`),Ve(t.sideEffect,ty,e,`${n}.sideEffect`),Qu(t,"requiresConfirmation",e,n)}function ay(t,e,n){X(t,e,n),Ve(t.type,Qw,e,`${n}.type`),le(t,"ref",e,n),le(t,"prompt",e,n),le(t,"question",e,n),"options"in t&&gr(t.options,e,`${n}.options`)}function cy(t,e,n){X(t,e,n),J(t.id,e,`${n}.id`),ay(t.action,e,`${n}.action`),le(t,"next",e,n),"completionEvals"in t&&gr(t.completionEvals,e,`${n}.completionEvals`)}function ly(t,e){let n="goal";X(t,e,n),J(t.statement,e,`${n}.statement`),Ye(t.inputs,e,`${n}.inputs`),t.inputs.forEach((i,r)=>{Gu(i,e,`${n}.inputs[${r}]`)}),Ye(t.outputs,e,`${n}.outputs`),t.outputs.forEach((i,r)=>{Gu(i,e,`${n}.outputs[${r}]`)}),gr(t.success,e,`${n}.success`)}function uy(t,e){let n="orchestration";X(t,e,n),Ve(t.mode,Zw,e,`${n}.mode`),le(t,"entry",e,n),"steps"in t&&(Ye(t.steps,e,`${n}.steps`),t.steps.forEach((i,r)=>{cy(i,e,`${n}.steps[${r}]`)}))}function Zu(t,e){return X(t,e),Ve(t.apiVersion,["comet/v1alpha1"],e,"apiVersion"),Ve(t.kind,["Skill"],e,"kind"),X(t.metadata,e,"metadata"),J(t.metadata.name,e,"metadata.name"),J(t.metadata.version,e,"metadata.version"),J(t.metadata.description,e,"metadata.description"),ly(t.goal,e),uy(t.orchestration,e),Ye(t.skills,e,"skills"),t.skills.forEach((n,i)=>{ry(n,e,`skills[${i}]`)}),Ye(t.agents,e,"agents"),t.agents.forEach((n,i)=>{sy(n,e,`agents[${i}]`)}),Ye(t.tools,e,"tools"),t.tools.forEach((n,i)=>{oy(n,e,`tools[${i}]`)}),t}function ef(t,e){X(t,e);for(let n of["allowedSkills","allowedAgents","allowedTools","confirmationRequiredFor"])n in t&&gr(t[n],e,n);for(let n of["maxIterations","maxRetriesPerAction"])if(n in t&&(typeof t[n]!="number"||!Number.isFinite(t[n])))throw st(e,n,"must be a finite number");return t}function fy(t,e){return X(t,e),"runtime"in t&&tf(t.runtime,e,"runtime"),t}function tf(t,e,n){return Ye(t,e,n),t.forEach((i,r)=>{let s=`${n}[${r}]`;X(i,e,s),J(i.id,e,`${s}.id`),Ve(i.scope,ny,e,`${s}.scope`),Ve(i.type,iy,e,`${s}.type`),le(i,"artifact",e,s),le(i,"field",e,s),le(i,"equals",e,s)}),t}async function Bo(t){let e=await Wo.readFile(t,"utf8");try{return(0,Xu.parse)(e)}catch(n){let i=n instanceof Error?n.message:String(n);throw st(t,"document",i)}}async function dy(t){try{return await Bo(t)}catch(e){if(e.code==="ENOENT")return null;throw e}}async function zu(t){try{return await Wo.access(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function py(t){let e=ie.join(t,"checks.yaml"),n=ie.join(t,"evals.yaml"),[i,r]=await Promise.all([zu(e),zu(n)]);if(r)throw new Error(`${n}: evals.yaml is no longer supported; use checks.yaml`);return i?{document:fy(await Bo(e),e)}:{document:null}}async function nf(t){let e=ie.resolve(t.root),n=ie.resolve(t.controlRoot);t.requireSkillMarkdown&&await Wo.access(ie.join(e,"SKILL.md"));let i=ie.join(n,"skill.yaml"),r=ie.join(n,"guardrails.yaml"),s=Zu(await Bo(i),i),o=await dy(r),a=o===null?null:ef(o,r),c=await py(n),l={allowedSkills:s.skills.map(f=>f.id),allowedAgents:s.agents.map(f=>f.id),allowedTools:s.tools.map(f=>f.id),maxIterations:50,maxRetriesPerAction:3,confirmationRequiredFor:s.tools.filter(f=>f.requiresConfirmation).map(f=>f.id)};return{root:e,packageKind:t.packageKind==="runtime"?"runtime":void 0,definition:s,guardrails:{...l,...a},evals:c.document?.runtime??[]}}async function rf(t){let e=ie.resolve(t);return nf({root:e,controlRoot:ie.join(e,"comet"),packageKind:"skill",requireSkillMarkdown:!0})}async function sf(t){let e=ie.resolve(t);return nf({root:e,controlRoot:e,packageKind:"runtime",requireSkillMarkdown:!1})}function of(t,e,n=ie.join(e,"package.json")){X(t,n);let i=t.packageKind==="runtime"?"runtime":void 0,r=Zu(t.definition,n),s=ef(t.guardrails,n),o=tf(t.evals,n,"evals"),a={allowedSkills:r.skills.map(c=>c.id),allowedAgents:r.agents.map(c=>c.id),allowedTools:r.tools.map(c=>c.id),maxIterations:50,maxRetriesPerAction:3,confirmationRequiredFor:r.tools.filter(c=>c.requiresConfirmation).map(c=>c.id)};return{root:ie.resolve(e),packageKind:i,definition:r,guardrails:{...a,...s},evals:o}}import af from"path";function my(t,e,n,i){t.type==="invoke_skill"&&!e.definition.skills.some(r=>r.id===t.ref)&&n.push(`step ${i} references undeclared skill: ${t.ref??"(missing)"}`),t.type==="call_tool"&&!e.definition.tools.some(r=>r.id===t.ref)&&n.push(`step ${i} references undeclared tool: ${t.ref??"(missing)"}`),t.type==="handoff"&&!e.definition.agents.some(r=>r.id===t.ref)&&n.push(`step ${i} references undeclared agent: ${t.ref??"(missing)"}`),t.type==="ask_user"&&!t.question&&n.push(`step ${i} ask_user action requires question`)}function cf(t){let e=[],{definition:n,guardrails:i,evals:r}=t;n.apiVersion!=="comet/v1alpha1"&&e.push("unsupported apiVersion"),n.kind!=="Skill"&&e.push("kind must be Skill"),n.metadata.name||e.push("metadata.name is required"),n.goal.statement||e.push("goal.statement is required"),i.maxIterations<1&&e.push("maxIterations must be at least 1"),i.maxRetriesPerAction<0&&e.push("maxRetriesPerAction must not be negative");let s=n.orchestration.steps??[];if(n.orchestration.mode==="adaptive")(n.orchestration.entry||s.length>0)&&e.push("adaptive orchestration must not define entry or steps");else{let o=new Set;for(let a of s)o.has(a.id)&&e.push(`duplicate step id: ${a.id}`),o.add(a.id),my(a.action,t,e,a.id);(!n.orchestration.entry||!o.has(n.orchestration.entry))&&e.push(`orchestration.entry references unknown step: ${n.orchestration.entry??"(missing)"}`);for(let a of s){a.next&&!o.has(a.next)&&e.push(`step ${a.id} has unknown next step: ${a.next}`);for(let c of a.completionEvals??[])r.some(l=>l.id===c)||e.push(`step ${a.id} references unknown eval: ${c}`)}}for(let o of n.tools){if(o.kind!=="script")continue;let a=af.posix.normalize(o.source.replaceAll("\\","/"));(af.isAbsolute(o.source)||a===".."||a.startsWith("../"))&&e.push(`script tool ${o.id} must reference a relative path inside the Skill package`)}for(let o of i.allowedSkills)n.skills.some(a=>a.id===o)||e.push(`guardrails allow undeclared skill: ${o}`);for(let o of i.allowedAgents)n.agents.some(a=>a.id===o)||e.push(`guardrails allow undeclared agent: ${o}`);for(let o of i.allowedTools)n.tools.some(a=>a.id===o)||e.push(`guardrails allow undeclared tool: ${o}`);return e}function wr(t){return Array.isArray(t)?t.map(wr):t&&typeof t=="object"?Object.fromEntries(Object.entries(t).sort(([e],[n])=>e.localeCompare(n)).map(([e,n])=>[e,wr(n)])):t}function hy(t){return wr({...t.packageKind==="runtime"?{packageKind:"runtime"}:{},definition:t.definition,guardrails:t.guardrails,evals:t.evals})}function gy(t){return he.posix.normalize(t.replaceAll("\\","/"))}function Ko(t,e,n){let i=he.relative(t,e);if(!(i===""||!he.isAbsolute(i)&&!i.startsWith(`..${he.sep}`)))throw new Error(`${n} resolves outside the Skill package`)}async function uf(t,e,n){let i=gy(e);if(he.posix.isAbsolute(i)||i===".."||i.startsWith("../"))throw new Error(`${n} resolves outside the Skill package`);let r=he.resolve(t,...i.split("/"));Ko(t,r,n);let s;try{s=await At.realpath(r)}catch(o){throw o.code==="ENOENT"?new Error(`${n} does not exist: ${e}`,{cause:o}):o}if(Ko(t,s,n),!(await At.stat(s)).isFile())throw new Error(`${n} is not a file: ${e}`);return{path:i,content:await At.readFile(s)}}async function wy(t){let e=await At.realpath(t.root),n=t.packageKind==="runtime"?[]:[await uf(e,"SKILL.md","SKILL.md")];for(let i of t.definition.tools)i.kind==="script"&&n.push(await uf(e,i.source,`Script tool ${i.id}`));return n.sort((i,r)=>i.path.localeCompare(r.path))}function yy(t,e){let n=e.map(i=>({path:i.path,sha256:lf("sha256").update(i.content).digest("hex")}));return lf("sha256").update(JSON.stringify(wr({package:t,files:n}))).digest("hex")}async function vy(t){let e=hy(t),n=await wy(t);return{document:e,files:n,hash:yy(e,n)}}async function ff(t){return(await vy(t)).hash}async function Uo(t,e){if(!/^[a-f0-9]{64}$/u.test(e))throw new Error(`Invalid Skill snapshot hash: ${e}`);let n=he.resolve(t,".comet","skill-snapshots"),i=he.join(n,e);Ko(n,i,"Skill snapshot");try{let r=(await At.readFile(he.join(i,"sha256"),"utf8")).trim();if(r!==e)throw new Error(`stored hash is ${r||"(empty)"}`);let s=he.join(i,"package.json"),o=JSON.parse(await At.readFile(s,"utf8")),a=of(o,i,s),c=cf(a);if(c.length>0)throw new Error(c.map(f=>` - ${f}`).join(` +`));let l=await ff(a);if(l!==e)throw new Error(`calculated hash is ${l}`);return a}catch(r){throw new Error(`Skill snapshot is invalid or missing: ${e}`,{cause:r})}}async function by(t){try{return(await df.stat(t)).isDirectory()}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function yr(t){try{return(await df.stat(t)).isFile()}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function ky(t){return await by(t)?await yr(Q.join(t,"skill.yaml"))?!0:await yr(Q.join(t,"SKILL.md"))&&await yr(Q.join(t,"comet","skill.yaml")):!1}function Sy(t){return{root:t,packageKind:"runtime",definition:{apiVersion:"comet/v1alpha1",kind:"Skill",metadata:{name:"comet-classic",version:"1",description:"Internal compatibility orchestration for classic Comet full, hotfix, and tweak workflows"},goal:{statement:"Advance or restore a classic Comet Run without changing the user command surface",inputs:[{name:"classic-state",description:"Validated ClassicState consistent with the Run projection",required:!0},{name:"evidence",description:"Structured evidence produced by the Classic Evidence collector",required:!0}],outputs:[{name:"run-state",description:"Atomically synchronized Classic and Run state",required:!0}],success:["Legacy fields and Run fields remain consistent","Every step invokes only a declared public Comet Skill","The completed state passes its completion eval"]},orchestration:{mode:"deterministic",entry:"full.open",steps:[{id:"full.open",action:{type:"invoke_skill",ref:"comet-open"},next:"full.design.handoff"},{id:"full.design.handoff",action:{type:"invoke_skill",ref:"comet-design"},next:"full.design.document"},{id:"full.design.document",action:{type:"invoke_skill",ref:"comet-design"},next:"full.build.plan"},{id:"full.build.plan",action:{type:"invoke_skill",ref:"comet-build"},next:"full.build.plan-ready"},{id:"full.build.plan-ready",action:{type:"invoke_skill",ref:"comet-build"},next:"full.build.configure"},{id:"full.build.configure",action:{type:"invoke_skill",ref:"comet-build"},next:"full.build.execute"},{id:"full.build.execute",action:{type:"invoke_skill",ref:"comet-build"},next:"full.build.complete"},{id:"full.build.complete",action:{type:"invoke_skill",ref:"comet-build"},next:"full.verify.run"},{id:"full.build.fix",action:{type:"invoke_skill",ref:"comet-build"},next:"full.build.execute"},{id:"full.verify.run",action:{type:"invoke_skill",ref:"comet-verify"},next:"full.verify.branch"},{id:"full.verify.branch",action:{type:"invoke_skill",ref:"comet-verify"},next:"full.archive.confirm"},{id:"full.archive.confirm",action:{type:"invoke_skill",ref:"comet-archive"},next:"full.archive.execute"},{id:"full.archive.execute",action:{type:"invoke_skill",ref:"comet-archive"},next:"completed"},{id:"hotfix.open",action:{type:"invoke_skill",ref:"comet-hotfix"},next:"hotfix.build.execute"},{id:"hotfix.build.execute",action:{type:"invoke_skill",ref:"comet-build"},next:"hotfix.build.complete"},{id:"hotfix.build.complete",action:{type:"invoke_skill",ref:"comet-build"},next:"hotfix.verify.run"},{id:"hotfix.verify.run",action:{type:"invoke_skill",ref:"comet-verify"},next:"hotfix.verify.branch"},{id:"hotfix.verify.branch",action:{type:"invoke_skill",ref:"comet-verify"},next:"hotfix.archive.confirm"},{id:"hotfix.archive.confirm",action:{type:"invoke_skill",ref:"comet-archive"},next:"hotfix.archive.execute"},{id:"hotfix.archive.execute",action:{type:"invoke_skill",ref:"comet-archive"},next:"completed"},{id:"tweak.open",action:{type:"invoke_skill",ref:"comet-tweak"},next:"tweak.build.execute"},{id:"tweak.build.execute",action:{type:"invoke_skill",ref:"comet-build"},next:"tweak.build.complete"},{id:"tweak.build.complete",action:{type:"invoke_skill",ref:"comet-build"},next:"tweak.verify.run"},{id:"tweak.verify.run",action:{type:"invoke_skill",ref:"comet-verify"},next:"tweak.verify.branch"},{id:"tweak.verify.branch",action:{type:"invoke_skill",ref:"comet-verify"},next:"tweak.archive.confirm"},{id:"tweak.archive.confirm",action:{type:"invoke_skill",ref:"comet-archive"},next:"tweak.archive.execute"},{id:"tweak.archive.execute",action:{type:"invoke_skill",ref:"comet-archive"},next:"completed"},{id:"completed",action:{type:"checkpoint"},completionEvals:["classic-completed"]}]},skills:[{id:"comet-open"},{id:"comet-design"},{id:"comet-build"},{id:"comet-verify"},{id:"comet-archive"},{id:"comet-hotfix"},{id:"comet-tweak"}],agents:[],tools:[]},guardrails:{allowedSkills:["comet-open","comet-design","comet-build","comet-verify","comet-archive","comet-hotfix","comet-tweak"],allowedAgents:[],allowedTools:[],maxIterations:500,maxRetriesPerAction:3,confirmationRequiredFor:[]},evals:[{id:"classic-completed",scope:"completion",type:"state_equals",field:"status",equals:"completed"}]}}async function Cy(){let t=Q.dirname(pf(import.meta.url)),e=[process.env.COMET_RUNTIME_CLASSIC_ROOT,Q.resolve(t,"..","runtime","classic"),Q.resolve(t,"..","..","comet","runtime","classic"),Q.resolve(t,"..","..","assets","skills","comet","runtime","classic"),Q.resolve("assets","skills","comet","runtime","classic"),process.env.COMET_CLASSIC_SKILL_ROOT,Q.resolve(t,"..","..","comet-classic"),Q.resolve(t,"..","..","assets","skills","comet-classic"),Q.resolve("assets","skills","comet-classic")].filter(n=>!!n);for(let n of e)if(await ky(n))return n;return null}async function Ey(t){return await yr(Q.join(t,"skill.yaml"))?sf(t):rf(t)}async function mf(t,e){let n=e??await me(t,{migrate:!1}),i=Array.from(new Set(n.unknownKeys)).sort();if(i.length>0)throw new Error(`Invalid Classic state: unknown field(s): ${i.join(", ")}`);if(!n.classic||!n.run)throw new Error("Classic runtime validation requires synchronized Classic and Run projections");if(n.classic.classicMigration!==Pn)throw new Error("Classic Run exists without a supported classic_migration marker");let r=await Cy(),s=r?await Ey(r):Sy(Q.dirname(pf(import.meta.url)));if(n.run.skill!==s.definition.metadata.name)throw new Error(`Classic Run skill mismatch: expected ${s.definition.metadata.name}, got ${n.run.skill}`);let o=await Uo(t,n.run.skillHash);if(o.definition.metadata.name!==n.run.skill)throw new Error(`Classic Run snapshot skill mismatch: expected ${n.run.skill}, got ${o.definition.metadata.name}`);let a=await Pt(t,n),c=Ot(n.classic,a);if(n.run.currentStep!==c)throw new Error(`Classic Run step mismatch: expected ${c}, got ${n.run.currentStep}`);return{classic:n.classic,run:n.run,evidence:a,migrated:!1,snapshotDir:Q.join(t,".comet","skill-snapshots",n.run.skillHash)}}async function hf(t,e,n,i){let r=await me(t);if(!r.classic||!r.run)throw new Error("Classic transition requires synchronized Classic and Run projections");let s=await Pt(t,{classic:e,run:n,unknownKeys:r.unknownKeys}),o=Ot(e,s),a={...n,currentStep:o,iteration:n.iteration+1,status:o==="completed"?"completed":"running"};await xt(t,{classic:e,run:a,unknownKeys:r.unknownKeys});let c=await Nt(t,a.trajectoryRef);return await rt(t,a.trajectoryRef,{sequence:c.length+1,timestamp:new Date().toISOString(),type:"state_transitioned",runId:a.runId,data:{kind:"classic",fromStep:n.currentStep,toStep:o,...i}}),a}or();import Ry from"path";var _y=Ry.join(".comet","state-events.jsonl"),xy=8*1024*1024;async function Yo(t,e){let n={schemaVersion:1,timestamp:new Date().toISOString(),...e};return await sr(t,_y,`${JSON.stringify(n)} +`,xy,"Classic state event log"),n}var gf=["open-complete","design-complete","build-complete","verify-pass","verify-fail","archive-confirm","archive-reopen","archived","preset-escalate"],Py={"open-complete":{event:"open-complete",from:"open",guardRefs:["open-artifacts-present"]},"design-complete":{event:"design-complete",from:"design",guardRefs:["design-evidence-present"]},"build-complete":{event:"build-complete",from:"build",guardRefs:["build-decisions-selected"]},"verify-pass":{event:"verify-pass",from:"verify",guardRefs:["verification-report-present"]},"verify-fail":{event:"verify-fail",from:"verify",guardRefs:["verification-failed"]},"archive-confirm":{event:"archive-confirm",from:"archive",guardRefs:["archive-final-confirmation"]},"archive-reopen":{event:"archive-reopen",from:"archive",guardRefs:["archive-not-finalized"]},archived:{event:"archived",from:"archive",guardRefs:["verify-result-pass","archive-confirmed"]},"preset-escalate":{event:"preset-escalate",from:"build",guardRefs:["preset-workflow"]}};function Oy(t){return t.toISOString().slice(0,10)}function x(t,e,n,i){let r=t[n];t[n]=i,r!==i&&e.push({field:n,from:r,to:i})}function wf(t,e,n={}){let i=Py[e];if(t.phase!==i.from)throw new Error(`Cannot apply ${e}: phase is '${t.phase}', expected '${i.from}'`);let r={...t},s=[],o=n.now??new Date;if(e==="open-complete")x(r,s,"phase",r.workflow==="full"?"design":"build");else if(e==="design-complete")x(r,s,"phase","build");else if(e==="build-complete"){let a=r.verifyResult==="fail";x(r,s,"phase","verify"),x(r,s,"verifyResult","pending"),x(r,s,"branchStatus","pending"),a||x(r,s,"verificationReport",null)}else if(e==="verify-pass")x(r,s,"verifyResult","pass"),x(r,s,"verifyFailures",0),x(r,s,"phase","archive"),x(r,s,"verifiedAt",Oy(o)),x(r,s,"archiveConfirmation","pending"),x(r,s,"branchStatus","pending");else if(e==="verify-fail")x(r,s,"verifyResult","fail"),x(r,s,"verifyFailures",r.verifyFailures+1),x(r,s,"phase","build"),x(r,s,"branchStatus","pending");else if(e==="preset-escalate"){if(r.workflow!=="hotfix"&&r.workflow!=="tweak")throw new Error(`Cannot apply ${e}: workflow must be hotfix or tweak, got '${r.workflow}'`);x(r,s,"workflow","full"),x(r,s,"classicProfile","full"),x(r,s,"phase","design"),x(r,s,"designDoc",null),x(r,s,"buildPause",null),x(r,s,"buildMode",null),x(r,s,"subagentDispatch",null),x(r,s,"tddMode",null),x(r,s,"reviewMode",null),x(r,s,"isolation",null),x(r,s,"boundBranch",null),x(r,s,"verifyMode",null),x(r,s,"directOverride",null)}else if(e==="archive-confirm"){if(r.verifyResult!=="pass")throw new Error(`Cannot apply ${e}: verifyResult must be pass`);if(r.archived)throw new Error(`Cannot apply ${e}: already archived`);x(r,s,"archiveConfirmation","confirmed")}else if(e==="archive-reopen"){if(r.archived)throw new Error(`Cannot apply ${e}: already archived`);x(r,s,"verifyResult","pending"),x(r,s,"verifyFailures",0),x(r,s,"phase","verify"),x(r,s,"verifiedAt",null),x(r,s,"archiveConfirmation",null),x(r,s,"branchStatus","pending")}else{if(r.verifyResult!=="pass")throw new Error(`Cannot apply ${e}: verifyResult must be pass`);if(r.archiveConfirmation!=="confirmed")throw new Error(`Cannot apply ${e}: archiveConfirmation must be confirmed`);x(r,s,"archived",!0)}return{classic:r,effects:s,definition:i}}xn();import vr from"path";function Ny(t){if(t!=="build"&&t!=="verify")throw new Error(`Invalid command check scope: '${String(t)}'`)}function Ay(t,e="."){if(e.trim().length===0)throw new Error("Command check cwd cannot be blank");let n=vr.resolve(t),i=vr.resolve(n,e);if(i!==n&&!i.startsWith(n+vr.sep))throw new Error(`Command check cwd must resolve within the project root: '${e}'`);return vr.relative(n,i).replaceAll("\\","/")||"."}async function yf(t,e,n,i){if(Ny(i.scope),typeof i.command!="string"||i.command.trim().length===0)throw new Error("Command check command cannot be blank");if(!Number.isInteger(i.exitCode))throw new Error("Command check exitCode must be an integer");let s={sequence:(await Nt(e,n.trajectoryRef)).reduce((o,a)=>Math.max(o,a.sequence),0)+1,timestamp:new Date().toISOString(),runId:n.runId,scope:i.scope,command:i.command,exitCode:i.exitCode,cwd:Ay(t,i.cwd)};return await rt(e,n.trajectoryRef,{sequence:s.sequence,timestamp:s.timestamp,type:"command_check_recorded",runId:s.runId,data:{scope:s.scope,command:s.command,exitCode:s.exitCode,cwd:s.cwd}}),s}jo();St();import Ty from"os";import br from"path";function Iy(t={}){let e=t.cwd??process.cwd(),n=t.homeDir??Ty.homedir(),i=[{file:br.resolve(e,".comet","config.yaml"),source:".comet/config.yaml",scope:"project"},{file:br.resolve(n,".comet","config.yaml"),source:"~/.comet/config.yaml",scope:"global"}];return i.filter((r,s)=>i.findIndex(o=>o.file===r.file)===s)}async function Vo(t,e={}){for(let n of Iy(e)){let i=br.dirname(br.dirname(n.file)),r=n.scope==="global"?(await Io(i))?.classic:(await kt(i,{allowPartialProject:!0}))?.value.classic;if(!r||typeof r!="object"||Array.isArray(r))continue;let s=r[t];if(s!=null)return{value:String(s),source:n.source}}return null}import ot from"node:path";async function vf(t,e){if(!e||e==="null")return{status:"missing",recordedPath:null};let n=await ee(t),i=ot.resolve(t,e),r=ot.relative(n.superpowersPlansDir,i);return ot.isAbsolute(e)||!r||r.startsWith(`..${ot.sep}`)||ot.isAbsolute(r)||r.includes(ot.sep)||ot.extname(r).toLowerCase()!==".md"?{status:"broken",recordedPath:e}:await kn(t,e,{label:`Classic build plan ${e}`,expected:"file"})?{status:"ready",recordedPath:e}:{status:"broken",recordedPath:e}}var qy="\x1B[32m",Ly="\x1B[31m",Dy="\x1B[33m",Xo="\x1B[0m",Ln=["full","hotfix","tweak"],Qo=["open","design","build","verify","archive"],kf=["en","zh-CN"],My=gf,Ho=new Set([...Fo,"archive_confirmation","verify_failures","classic_profile","classic_migration","bound_branch"]),Fy=new Set(_t.filter(t=>!Ho.has(t))),Wy={workflow:Ln,phase:Qo,context_compression:["off","beta"],build_mode:["subagent-driven-development","executing-plans","direct"],build_pause:["null","plan-ready"],subagent_dispatch:["null","confirmed"],tdd_mode:["tdd","direct"],review_mode:["off","standard","thorough"],isolation:["current","branch","worktree"],verify_mode:["light","full"],auto_transition:["true","false"],verify_result:["pending","pass","fail"],branch_status:["pending","handled"],archive_confirmation:["pending","confirmed"],archived:["true","false"],direct_override:["true","false"],classic_profile:Ln,classic_migration:["1"]},By=new Set(["design_doc","plan","verification_report","handoff_context"]),Ky={archived:"archived",branchStatus:"branch_status",classicProfile:"classic_profile",designDoc:"design_doc",language:"language",phase:"phase",verificationReport:"verification_report",verifiedAt:"verified_at",archiveConfirmation:"archive_confirmation",verifyResult:"verify_result",verifyFailures:"verify_failures",workflow:"workflow"},Dn=class extends Error{constructor(n,i=1){super(n);this.exitCode=i}exitCode},Sr=class{stdout=[];stderr=[];result(e=0){return{exitCode:e,...this.stdout.length>0?{stdout:this.stdout.join(` `)+` `}:{},...this.stderr.length>0?{stderr:this.stderr.join(` -`)}:{}}}};function ue(t){return`${qy}${t}${Xo}`}function Go(t){return`${Ly}${t}${Xo}`}function vf(t){return`${Dy}${t}${Xo}`}function b(t){throw new Dn(t)}function fe(t){let e=No(t);e&&b(`ERROR: ${e}`)}function Cr(t,e){e.includes(t)||b(`ERROR: Invalid value: '${t}' -Valid values: ${e.join(" ")}`)}function Sr(t,e){if(bf.includes(t))return t;b(`ERROR: Invalid language from ${e}: '${t}' -Valid values: en, zh-CN`)}function kf(t,e){!t||t==="null"||(/^(?:[A-Za-z]:|[\\/]|~)/u.test(t)&&b(`ERROR: ${e} must be a relative path within the repo: '${t}'`),t.split(/[\\/]/u).includes("..")&&b(`ERROR: ${e} cannot contain '..' (path traversal not allowed): '${t}'`))}async function K(t){let e=T();return kn(e,t,{label:`Classic project path ${O.relative(e,O.resolve(e,t)).replaceAll("\\","/")}`})}async function Re(t){let e=T();return hu(e,t,`Classic project file ${O.relative(e,O.resolve(e,t)).replaceAll("\\","/")}`)}async function Uy(t){return ku(t,T())}async function Er(t){let e,n=T();try{e=await Ue(n,t,{label:`Classic state ${O.relative(n,t).replaceAll("\\","/")}`})}catch(r){throw r.code==="ENOENT"&&b(`ERROR: .comet.yaml not found at ${O.relative(n,t).replaceAll("\\","/")}`),r}let i=(0,Mn.parseDocument)(e,{uniqueKeys:!1});return i.errors.length>0&&b(`ERROR: Invalid .comet.yaml: ${i.errors[0].message}`),i}async function Zo(t,e){await yu(T(),t,e,{label:"Classic state write target"})}function zo(t){return t===null?"null":t===void 0?"":typeof t=="object"?JSON.stringify(t):String(t)}function Sf(t){return Ky[t]??String(t)}function Cf(t){return t===null?"null":zo(t)}function H(t,e,n,i){let r=t[e];return typeof r=="string"&&n.includes(r)?r:i}function Se(t,e){let n=t[e];return n==null||n===""?null:typeof n=="string"?n:String(n)}function Jo(t,e){let n=t[e];return n==null||n===""?null:typeof n=="boolean"?n:n==="true"?!0:n==="false"?!1:null}function Yy(t,e,n=0){let i=t[e];return typeof i=="number"&&Number.isInteger(i)&&i>=0?i:n}function Vy(t){let e=H(t,"workflow",Ln,"full");return{workflow:e,language:H(t,"language",bf,null),phase:H(t,"phase",Qo,"open"),contextCompression:H(t,"context_compression",["off","beta"],null),buildMode:H(t,"build_mode",["subagent-driven-development","executing-plans","direct"],null),buildPause:H(t,"build_pause",["plan-ready"],null),subagentDispatch:H(t,"subagent_dispatch",["confirmed"],null),tddMode:H(t,"tdd_mode",["tdd","direct"],null),reviewMode:H(t,"review_mode",["off","standard","thorough"],null),isolation:H(t,"isolation",["current","branch","worktree"],null),boundBranch:Se(t,"bound_branch"),verifyMode:H(t,"verify_mode",["light","full"],null),autoTransition:Jo(t,"auto_transition"),baseRef:Se(t,"base_ref"),designDoc:Se(t,"design_doc"),plan:Se(t,"plan"),verifyResult:H(t,"verify_result",["pending","pass","fail"],"pending"),verifyFailures:Yy(t,"verify_failures"),verificationReport:Se(t,"verification_report"),branchStatus:H(t,"branch_status",["pending","handled"],null),createdAt:Se(t,"created_at"),verifiedAt:Se(t,"verified_at"),archiveConfirmation:H(t,"archive_confirmation",["pending","confirmed"],null),archived:Jo(t,"archived")??!1,directOverride:Jo(t,"direct_override"),handoffContext:Se(t,"handoff_context"),handoffHash:Se(t,"handoff_hash"),classicProfile:H(t,"classic_profile",Ln,e),classicMigration:typeof t.classic_migration=="number"?t.classic_migration:null}}async function ea(t){return(await Vo(t,{cwd:T()}))?.value??null}async function Ef(){if(process.env.COMET_LANGUAGE)return Sr(process.env.COMET_LANGUAGE,"COMET_LANGUAGE");let t=await Vo("language",{cwd:T()});return t?Sr(t.value,t.source):"en"}async function Jy(){let t=process.env.COMET_CONTEXT_COMPRESSION??await ea("context_compression")??"off";return["off","beta"].includes(t)||b(`ERROR: Invalid context_compression: '${t}' -Valid values: off, beta`),t}async function Rf(){let t=process.env.COMET_AUTO_TRANSITION??await ea("auto_transition")??"true";return["true","false"].includes(t)||b(`ERROR: Invalid auto_transition: '${t}' +`)}:{}}}};function ue(t){return`${qy}${t}${Xo}`}function Go(t){return`${Ly}${t}${Xo}`}function bf(t){return`${Dy}${t}${Xo}`}function b(t){throw new Dn(t)}function fe(t){let e=Ao(t);e&&b(`ERROR: ${e}`)}function Er(t,e){e.includes(t)||b(`ERROR: Invalid value: '${t}' +Valid values: ${e.join(" ")}`)}function Cr(t,e){if(kf.includes(t))return t;b(`ERROR: Invalid language from ${e}: '${t}' +Valid values: en, zh-CN`)}function Sf(t,e){!t||t==="null"||(/^(?:[A-Za-z]:|[\\/]|~)/u.test(t)&&b(`ERROR: ${e} must be a relative path within the repo: '${t}'`),t.split(/[\\/]/u).includes("..")&&b(`ERROR: ${e} cannot contain '..' (path traversal not allowed): '${t}'`))}async function K(t){let e=T();return kn(e,t,{label:`Classic project path ${O.relative(e,O.resolve(e,t)).replaceAll("\\","/")}`})}async function Re(t){let e=T();return gu(e,t,`Classic project file ${O.relative(e,O.resolve(e,t)).replaceAll("\\","/")}`)}async function Uy(t){return Su(t,T())}async function Rr(t){let e,n=T();try{e=await Ue(n,t,{label:`Classic state ${O.relative(n,t).replaceAll("\\","/")}`})}catch(r){throw r.code==="ENOENT"&&b(`ERROR: .comet.yaml not found at ${O.relative(n,t).replaceAll("\\","/")}`),r}let i=(0,Mn.parseDocument)(e,{uniqueKeys:!1});return i.errors.length>0&&b(`ERROR: Invalid .comet.yaml: ${i.errors[0].message}`),i}async function Zo(t,e){await vu(T(),t,e,{label:"Classic state write target"})}function zo(t){return t===null?"null":t===void 0?"":typeof t=="object"?JSON.stringify(t):String(t)}function Cf(t){return Ky[t]??String(t)}function Ef(t){return t===null?"null":zo(t)}function H(t,e,n,i){let r=t[e];return typeof r=="string"&&n.includes(r)?r:i}function Se(t,e){let n=t[e];return n==null||n===""?null:typeof n=="string"?n:String(n)}function Jo(t,e){let n=t[e];return n==null||n===""?null:typeof n=="boolean"?n:n==="true"?!0:n==="false"?!1:null}function Yy(t,e,n=0){let i=t[e];return typeof i=="number"&&Number.isInteger(i)&&i>=0?i:n}function Vy(t){let e=H(t,"workflow",Ln,"full");return{workflow:e,language:H(t,"language",kf,null),phase:H(t,"phase",Qo,"open"),contextCompression:H(t,"context_compression",["off","beta"],null),buildMode:H(t,"build_mode",["subagent-driven-development","executing-plans","direct"],null),buildPause:H(t,"build_pause",["plan-ready"],null),subagentDispatch:H(t,"subagent_dispatch",["confirmed"],null),tddMode:H(t,"tdd_mode",["tdd","direct"],null),reviewMode:H(t,"review_mode",["off","standard","thorough"],null),isolation:H(t,"isolation",["current","branch","worktree"],null),boundBranch:Se(t,"bound_branch"),verifyMode:H(t,"verify_mode",["light","full"],null),autoTransition:Jo(t,"auto_transition"),baseRef:Se(t,"base_ref"),designDoc:Se(t,"design_doc"),plan:Se(t,"plan"),verifyResult:H(t,"verify_result",["pending","pass","fail"],"pending"),verifyFailures:Yy(t,"verify_failures"),verificationReport:Se(t,"verification_report"),branchStatus:H(t,"branch_status",["pending","handled"],null),createdAt:Se(t,"created_at"),verifiedAt:Se(t,"verified_at"),archiveConfirmation:H(t,"archive_confirmation",["pending","confirmed"],null),archived:Jo(t,"archived")??!1,directOverride:Jo(t,"direct_override"),handoffContext:Se(t,"handoff_context"),handoffHash:Se(t,"handoff_hash"),classicProfile:H(t,"classic_profile",Ln,e),classicMigration:typeof t.classic_migration=="number"?t.classic_migration:null}}async function ea(t){return(await Vo(t,{cwd:T()}))?.value??null}async function Rf(){if(process.env.COMET_LANGUAGE)return Cr(process.env.COMET_LANGUAGE,"COMET_LANGUAGE");let t=await Vo("language",{cwd:T()});return t?Cr(t.value,t.source):"en"}async function Jy(){let t=process.env.COMET_CONTEXT_COMPRESSION??await ea("context_compression")??"off";return["off","beta"].includes(t)||b(`ERROR: Invalid context_compression: '${t}' +Valid values: off, beta`),t}async function _f(){let t=process.env.COMET_AUTO_TRANSITION??await ea("auto_transition")??"true";return["true","false"].includes(t)||b(`ERROR: Invalid auto_transition: '${t}' Valid values: true, false`),t}async function Hy(){let t=process.env.COMET_REVIEW_MODE??await ea("review_mode")??"standard";return["null","off","standard","thorough"].includes(t)||b(`ERROR: Invalid review_mode: '${t}' -Valid values: off, standard, thorough`),t==="null"?null:t}function _f(t){let e=Iy("git",t,{encoding:"utf8"});return e.status===0?e.stdout.trim():null}async function ge(t){let e=await Uy(t);return await Ke(T(),O.join(e.directory,".comet"),{label:`Classic runtime directory for ${t}`,expected:"directory"}),{...e,file:O.join(e.directory,".comet.yaml")}}async function C(t,e){let{file:n}=await ge(t),s=(await Er(n)).toJS()[e];return e==="language"?s==null||s===""?Ef():Sr(zo(s),".comet.yaml"):e==="auto_transition"&&(s==null||s==="")?Rf():zo(s)}function xf(t,e){let n=(0,Mn.parseDocument)(`${t}: ${e} -`);return n.errors.length>0&&b(`ERROR: Invalid value: '${e}'`),n.get(t)}async function Gy(t,e){if(t==="language"){Sr(e,"language");return}let n=Wy[t];n&&Cr(e,n),By.has(t)&&(kf(e,t),e&&e!=="null"&&await Ke(T(),e,{label:`${t} artifact pointer`,expected:"file"})),(t==="skill_hash"||t==="handoff_hash")&&!/^[a-f0-9]{64}$/u.test(e)&&b(`ERROR: ${t} must be a sha256 hex digest`),t==="iteration"&&!/^[0-9]+$/u.test(e)&&b("ERROR: iteration must be a non-negative integer")}async function Pf(t,e,n,i,r={}){Ho.has(n)&&!r.machineOwned&&b(`ERROR: '${n}' is a machine-owned field and cannot be set directly`),!Fy.has(n)&&!Ho.has(n)&&b(`ERROR: Unknown field: '${n}'`),n==="phase"&&!r.internal&&process.env.COMET_FORCE_PHASE!=="1"&&b(`ERROR: Setting 'phase' directly is not allowed; it bypasses state machine evidence checks. +Valid values: off, standard, thorough`),t==="null"?null:t}function xf(t){let e=jy("git",t,{encoding:"utf8"});return e.status===0?e.stdout.trim():null}async function ge(t){let e=await Uy(t);return await Ke(T(),O.join(e.directory,".comet"),{label:`Classic runtime directory for ${t}`,expected:"directory"}),{...e,file:O.join(e.directory,".comet.yaml")}}async function C(t,e){let{file:n}=await ge(t),s=(await Rr(n)).toJS()[e];return e==="language"?s==null||s===""?Rf():Cr(zo(s),".comet.yaml"):e==="auto_transition"&&(s==null||s==="")?_f():zo(s)}function Pf(t,e){let n=(0,Mn.parseDocument)(`${t}: ${e} +`);return n.errors.length>0&&b(`ERROR: Invalid value: '${e}'`),n.get(t)}async function Gy(t,e){if(t==="language"){Cr(e,"language");return}let n=Wy[t];n&&Er(e,n),By.has(t)&&(Sf(e,t),e&&e!=="null"&&await Ke(T(),e,{label:`${t} artifact pointer`,expected:"file"})),(t==="skill_hash"||t==="handoff_hash")&&!/^[a-f0-9]{64}$/u.test(e)&&b(`ERROR: ${t} must be a sha256 hex digest`),t==="iteration"&&!/^[0-9]+$/u.test(e)&&b("ERROR: iteration must be a non-negative integer")}async function Of(t,e,n,i,r={}){Ho.has(n)&&!r.machineOwned&&b(`ERROR: '${n}' is a machine-owned field and cannot be set directly`),!Fy.has(n)&&!Ho.has(n)&&b(`ERROR: Unknown field: '${n}'`),n==="phase"&&!r.internal&&process.env.COMET_FORCE_PHASE!=="1"&&b(`ERROR: Setting 'phase' directly is not allowed; it bypasses state machine evidence checks. Use: comet-state.mjs transition - Repair-only escape hatch: COMET_FORCE_PHASE=1 comet-state.mjs set phase `),await Gy(n,i);let{file:s,directory:o}=await ge(e),a=await Er(s),c=a.toJS()??{};if(a.set(n,xf(n,i)),n==="isolation")if(Vi(i)){let u=typeof c.isolation=="string"?c.isolation:null,d=c.bound_branch;if(!(typeof d=="string"&&d!=="")||u!==i){let g=qn(),p=Yi(g),h=mo({isolation:i,boundBranch:null,currentBranch:p,gitWorkTree:p===null?po(g):!0});h.status==="needs-heal"?a.set("bound_branch",h.branch):h.status==="unbound-detached"?b(`ERROR: cannot bind isolation=${i} while HEAD is detached; checkout a branch first`):a.set("bound_branch",null)}}else a.set("bound_branch",null);let l=await _n(o),f=On(a.toJS(),l);if(f.run){f.classic||b("ERROR: migrated Run is missing its Classic projection");let u=await Pt(o,f),d=Ot(f.classic,u),m=d!==f.run.currentStep,g={...f.run,currentStep:d,iteration:f.run.iteration+(m?1:0),status:d==="completed"?"completed":"running"};if(await xt(o,{classic:f.classic,run:g,unknownKeys:f.unknownKeys}),m){let p=await At(o,g.trajectoryRef);await rt(o,g.trajectoryRef,{sequence:p.length+1,timestamp:new Date().toISOString(),type:"state_transitioned",runId:g.runId,data:{kind:"classic-config",field:n,fromStep:f.run.currentStep,toStep:d}})}}else await Zo(s,a.toString());n==="phase"&&!r.internal&&t.stderr.push(vf("WARNING: Setting 'phase' directly bypasses state machine constraints."),vf(" Consider using: comet-state.mjs transition ")),t.stderr.push(ue(`[SET] ${n}=${i}`))}async function zy(t,e,n){fe(e),Cr(n,Ln);let i=await bu(e,T()),{label:r,directory:s}=i,o=O.join(s,".comet.yaml");await K(o)&&b(`ERROR: .comet.yaml already exists at ${r}/.comet.yaml`);let a=n!=="full",c=a?"off":await Hy(),l=new Mn.Document({workflow:n,language:await Ef(),phase:"open",context_compression:await Jy(),build_mode:a?"direct":null,build_pause:null,subagent_dispatch:null,tdd_mode:a?"direct":null,review_mode:c,isolation:null,verify_mode:a?"light":null,auto_transition:await Rf()==="true",base_ref:_f(["rev-parse","--verify","HEAD"]),design_doc:null,plan:null,verify_result:"pending",verify_failures:0,verification_report:null,branch_status:"pending",created_at:new Date().toISOString().slice(0,10),verified_at:null,archive_confirmation:null,archived:!1});await Zo(o,l.toString()),t.stdout.push(ue(`Initialized: ${r}/.comet.yaml (workflow=${n})`))}async function Ce(t,e){let n=await C(t,"phase");n!==e&&b(`ERROR: Cannot transition '${t}': expected phase ${e}, got ${n}`)}async function Xy(t){let e=await C(t,"workflow"),n=await C(t,"build_mode"),i=await C(t,"isolation"),r=await C(t,"direct_override"),s=await C(t,"subagent_dispatch"),o=await C(t,"tdd_mode"),a=await C(t,"review_mode");["current","branch","worktree"].includes(i)||b(`ERROR: Cannot transition '${t}': isolation must be current, branch, or worktree, got '${i||"null"}'`),["subagent-driven-development","executing-plans","direct"].includes(n)||b(`ERROR: Cannot transition '${t}': build_mode must be selected before leaving build, got '${n||"null"}'`),n==="direct"&&!["hotfix","tweak"].includes(e)&&r!=="true"&&b(`ERROR: Cannot transition '${t}': build_mode=direct is only allowed for hotfix/tweak unless direct_override=true`),n==="subagent-driven-development"&&s!=="confirmed"&&b(`ERROR: Cannot transition '${t}': subagent_dispatch must be confirmed before using build_mode=subagent-driven-development`),e==="full"&&(!o||o==="null")&&b(`ERROR: Cannot transition '${t}': tdd_mode must be selected before leaving build (full workflow)`),e==="full"&&!["off","standard","thorough"].includes(a)&&b(`ERROR: Cannot transition '${t}': review_mode must be selected before leaving build (full workflow); review_mode must be off, standard, or thorough, got '${a||"null"}'`)}async function Qy(t){let{directory:e}=await ge(t),n=await C(t,"workflow");for(let i of["proposal.md","tasks.md"])await Re(O.join(e,i))||b(`ERROR: Cannot transition '${t}': ${i} must exist and be non-empty before leaving open`);n==="full"&&!await Re(O.join(e,"design.md"))&&b(`ERROR: Cannot transition '${t}': design.md must exist and be non-empty before leaving open`)}async function Zy(t){let e=await C(t,"design_doc");(!e||e==="null"||!await Re(O.resolve(e)))&&b(`ERROR: Cannot transition '${t}': design_doc must point to an existing Design Doc before leaving design`)}async function ev(t,e){let n=O.join(t,".comet.yaml"),i=await Er(n);for(let r of e){let s=Sf(r.field);i.set(s,xf(s,Cf(r.to)))}await Zo(n,i.toString())}async function tv(t,e,n){let{directory:i}=await ge(e),r=await me(i),s=r.classic,o=!1;if(!s){r.run&&b("ERROR: Classic state projection is missing");let c=await Er(O.join(i,".comet.yaml"));s=Vy(c.toJS()),o=!0}let a=gf(s,n);r.run?await mf(i,a.classic,r.run,{event:n,source:"comet-state"}):o?await ev(i,a.effects):await xt(i,{classic:a.classic,run:null,unknownKeys:r.unknownKeys}),await Yo(i,{change:e,event:n,source:"comet-state",from:s,to:a.classic,effects:a.effects});for(let c of a.effects)t.stderr.push(ue(`[SET] ${Sf(c.field)}=${Cf(c.to)}`));t.stderr.push(ue(`[TRANSITION] ${n}`))}async function nv(t,e,n){if(fe(e),Cr(n,My),n==="open-complete")await Ce(e,"open"),await Qy(e);else if(n==="design-complete")await Ce(e,"design"),await Zy(e);else if(n==="build-complete")await Ce(e,"build"),await Xy(e);else if(n==="verify-pass"){await Ce(e,"verify");let i=await C(e,"verification_report");(!i||!await K(O.resolve(i)))&&b(`ERROR: Cannot transition '${e}': verification_report must point to an existing report file`)}else if(n==="verify-fail")await Ce(e,"verify");else if(n==="archive-confirm")await Ce(e,"archive"),await C(e,"verify_result")!=="pass"&&b(`ERROR: Cannot transition '${e}': verify_result must be pass before archiving`),await C(e,"archived")==="true"&&b(`ERROR: Cannot transition '${e}': already archived`);else if(n==="preset-escalate"){await Ce(e,"build");let i=await C(e,"workflow");["hotfix","tweak"].includes(i)||b(`ERROR: Cannot transition '${e}': preset-escalate only applies to hotfix/tweak, got workflow='${i}'`)}else n==="archive-reopen"?(await Ce(e,"archive"),await C(e,"archived")==="true"&&b(`ERROR: Cannot transition '${e}': already archived`)):(await Ce(e,"archive"),await C(e,"verify_result")!=="pass"&&b(`ERROR: Cannot transition '${e}': verify_result must be pass before archiving`),await C(e,"archive_confirmation")!=="confirmed"&&b(`ERROR: Cannot transition '${e}': archive_confirmation must be confirmed before archiving`));await tv(t,e,n)}async function iv(t,e){fe(e);let{file:n,label:i}=await ge(e);await K(n)||b(`ERROR: .comet.yaml not found at ${i}/.comet.yaml`);let r=await C(e,"phase"),s=await C(e,"workflow"),o=await C(e,"auto_transition");if(await C(e,"archived")==="true"){t.stdout.push("NEXT: done");return}let a=r==="open"?"comet-open":r==="design"?"comet-design":r==="verify"?"comet-verify":r==="archive"?"comet-archive":r==="build"?s==="hotfix"?"comet-hotfix":s==="tweak"?"comet-tweak":"comet-build":null;a||b(`ERROR: Cannot resolve next step for '${e}': unknown phase '${r||"null"}'`),t.stdout.push(`NEXT: ${o==="false"?"manual":"auto"}`,`SKILL: ${a}`),o==="false"&&t.stdout.push(`HINT: phase is '${r}'; run /${a} manually to continue`)}async function rv(t,e,n){kf(e,"task file"),n||b("ERROR: Task text cannot be empty");let i=O.resolve(T(),e);await K(i)||b(`ERROR: Task file not found: ${e}`);let s=(await Ue(T(),i,{label:"Classic task-checkoff file"})).split(/\r?\n/u).filter(a=>[`- [ ] ${n}`,`- [x] ${n}`,`- [X] ${n}`].includes(a)),o=s.filter(a=>/^- \[[xX]\] /u.test(a));s.length!==1&&b(`ERROR: task text must appear exactly once in ${e} (found ${s.length}): ${n}`),o.length!==1&&b(`ERROR: task is not checked in ${e}: ${n}`),t.stdout.push("TASK_CHECKOFF: PASS",`FILE: ${e}`,`TASK: ${n}`)}async function sv(t,e,n){fe(e),Cr(n,Qo);let{file:i,directory:r,label:s}=await ge(e);t.stdout.push(`=== Entry Check: comet-${n} ===`),await K(i)||b(`ERROR: .comet.yaml not found at ${s}/.comet.yaml`);let o=!1,a=u=>t.stdout.push(` ${ue("[PASS]")} ${u}`),c=u=>{t.stdout.push(` ${Go("[FAIL]")} ${u}`),o=!0},l=async(u,d)=>{let m=await C(e,u);(m===d?a:c)(`${u}=${m} (expected: ${d})`)};if(a(".comet.yaml exists"),await l("phase",n),n==="design"){await l("workflow","full");let u=await C(e,"design_doc");(!u||u==="null"?a:c)(u?`design_doc=${u} (expected: empty/null)`:"design_doc is empty/null");for(let d of["proposal.md","design.md","tasks.md"])(await Re(O.join(r,d))?a:c)(`${d} ${await Re(O.join(r,d))?"non-empty":"missing or empty"}`)}else if(n==="build"){let u=await C(e,"workflow"),d=await C(e,"design_doc");u==="full"?(d&&d!=="null"&&await K(O.resolve(d))?a:c)(`design_doc=${d} (expected: non-null and file exists)`):a(`workflow=${u} (design_doc not required)`);for(let m of["proposal.md","tasks.md"])(await Re(O.join(r,m))?a:c)(`${m} ${await Re(O.join(r,m))?"non-empty":"missing or empty"}`)}else if(n==="verify"){let u=await C(e,"verify_result");(["","null","pending"].includes(u)?a:c)(`verify_result=${u} (expected: pending or null)`)}else if(n==="archive"){await l("verify_result","pass");let u=await C(e,"archived");(u!=="true"?a:c)(`archived=${u} (expected: not true)`)}let f=await dn(r,{heal:!0,cwd:qn()});if(f.bindingRequired)switch(f.status){case"drift":c(nu(e,f.boundBranch,f.currentBranch));break;case"unbound-detached":c(pn(e));break;case"healed":a(`bound_branch lazily set to ${f.branch}`);break;case"needs-heal":case"ok":case"not-applicable":a("bound_branch matches current branch");break;default:{let u=f;throw new Error(`unhandled branch binding status: ${JSON.stringify(u)}`)}}if(t.stdout.push(""),o)throw t.stderr.push(Go("BLOCKED — fix failing checks before proceeding")),new Dn("",1);t.stderr.push(ue("ALL CHECKS PASSED — ready to proceed"))}async function Y(t,e,n){return!e||e==="null"?` - ${t}: PENDING`:n&&!await K(O.resolve(n))?` - ${t}: BROKEN (path ${e} does not exist)`:` - ${t}: DONE (${e})`}async function ov(t,e){t.stdout.push(" Artifacts:");let n=0;for(let i of["proposal.md","design.md","tasks.md"]){let r=await Re(O.join(e,i));r&&(n+=1),t.stdout.push(` - ${i}: ${r?"DONE":"PENDING"}`)}t.stdout.push("",n===3?"Recovery action: All artifacts complete. Run /comet-open user confirmation, then guard to transition.":n===0?"Recovery action: No artifacts created yet. Start from /comet-open Step 1 (explore and clarify).":"Recovery action: Some artifacts incomplete. Resume /comet-open from the first missing artifact.")}async function av(t,e,n){t.stdout.push(" Artifacts:");for(let o of["proposal.md","design.md","tasks.md"])t.stdout.push(` - ${o}: ${await Re(O.join(n,o))?"DONE":"MISSING (unexpected in design phase)"}`);let i=await C(e,"handoff_context"),r=await C(e,"handoff_hash"),s=await C(e,"design_doc");t.stdout.push(""," Design progress:",await Y("handoff_context",i,i),await Y("handoff_hash",r),await Y("design_doc",s,s),""),s&&s!=="null"&&await K(O.resolve(s))?t.stdout.push("Recovery action: Design Doc already created and linked. Run guard to transition to build."):i&&i!=="null"&&await K(O.resolve(i))?t.stdout.push("Recovery action: Handoff generated but Design Doc not yet created. Resume from brainstorming confirmation (Step 1c)."):t.stdout.push("Recovery action: No handoff generated yet. Start from Step 1a (generate handoff package).")}async function cv(t,e,n,i){let r=await C(e,"isolation"),s=await C(e,"build_mode"),o=await C(e,"build_pause"),a=await C(e,"subagent_dispatch"),c=await C(e,"tdd_mode"),l=await C(e,"review_mode"),f=await C(e,"plan"),u=await yf(T(),f),d=[" Build decisions:",await Y("isolation",r),await Y("build_mode",s),await Y("build_pause",o),await Y("tdd_mode",c),await Y("review_mode",l)];(s==="subagent-driven-development"||a&&a!=="null")&&d.push(await Y("subagent_dispatch",a)),t.stdout.push(...d,""," Plan:",await Y("plan",f,f),"");let m=O.join(n,"tasks.md");if(!await K(m)){t.stdout.push(" Tasks: tasks.md MISSING","","Recovery action: tasks.md missing. Verify change directory integrity.");return}let g=(await Ue(T(),m,{label:"Classic change tasks"})).split(/\r?\n/u),p=g.filter(E=>/^\s*- \[[ xX]\] /u.test(E)).length,h=g.filter(E=>/^\s*- \[[xX]\] /u.test(E)).length,v=p-h,y=0,S=0;if(u.status==="ready"){let E=(await Ue(T(),f,{label:"Classic build plan"})).split(/\r?\n/u);y=E.filter(A=>/^\s*- \[[ xX]\] /u.test(A)).length,S=E.filter(A=>/^\s*- \[[xX]\] /u.test(A)).length}let R=y-S;t.stdout.push(` Tasks: ${h}/${p} done, ${v} pending`),y>0&&t.stdout.push(` Plan tasks: ${S}/${y} done, ${R} pending`),t.stdout.push("");let _=lv(e,O.relative(T(),n).replaceAll("\\","/"),i,r,s,o,a,c,l,u,v,R);t.stdout.push(_)}function Je(t){return!t||t==="null"}function lv(t,e,n,i,r,s,o,a,c,l,f,u){let d=l.status==="ready",m=n==="full"&&(Je(a)||Je(c));return s==="plan-ready"&&d&&(Je(i)||Je(r)||m)?n==="full"?"Recovery action: Plan-ready pause detected. Ask the user whether to continue, then choose isolation, build mode, TDD mode, and review mode without regenerating the plan.":"Recovery action: Plan-ready pause detected. Ask the user whether to continue, then choose isolation and build mode without regenerating the plan.":n==="full"&&!d?uv(t,e,l):s==="plan-ready"?r==="subagent-driven-development"&&(f>0||u>0)?o==="confirmed"?"Recovery action: Plan-ready pause is stale because build decisions are already selected. Clear build_pause to null, then inspect the first unchecked task (OpenSpec or plan additions) against recent git history/diff. If implemented, check it off; otherwise dispatch a subagent. Do not execute the pending task directly in the main window.":"Recovery action: Plan-ready pause is stale and selected subagent execution is not recorded. Run comet state set subagent_dispatch confirmed, then continue from the first unchecked task through subagent execution.":f>0||u>0?"Recovery action: Plan-ready pause is stale because build decisions are already selected. Clear build_pause to null, then continue from the first unchecked task.":"Recovery action: Plan-ready pause is stale and all tasks are done. Clear build_pause to null, then run guard to transition to verify.":Je(i)?"Recovery action: Isolation not selected. Use the current platform's user confirmation mechanism to ask user for branch/worktree choice.":Je(r)?"Recovery action: Build mode not selected. Use the current platform's user confirmation mechanism to ask user for execution method.":n==="full"&&Je(a)?"Recovery action: TDD mode not selected. Use the current platform's user confirmation mechanism to ask user for tdd or direct.":n==="full"&&Je(c)?"Recovery action: Review mode not selected. Use the current platform's user confirmation mechanism to ask user for off, standard, or thorough.":f>0?r==="subagent-driven-development"?o==="confirmed"?"Recovery action: Read tasks.md and the Superpowers plan (which may include additions beyond OpenSpec), then inspect the first unchecked task against recent git history/diff. If implemented, check it off; otherwise dispatch a subagent. Do not execute the pending task directly in the main window.":"Recovery action: Selected subagent execution is not recorded. Run comet state set subagent_dispatch confirmed, then continue from the first unchecked task through subagent execution.":"Recovery action: Read tasks.md and continue from first unchecked task.":u>0?r==="subagent-driven-development"?o==="confirmed"?"Recovery action: Read the Superpowers plan, then inspect the first unchecked Superpowers plan task against recent git history/diff. If implemented, check it off; otherwise dispatch a subagent. Do not execute the pending task directly in the main window.":"Recovery action: Selected subagent execution is not recorded. Run comet state set subagent_dispatch confirmed, then continue from the first unchecked task through subagent execution.":"Recovery action: Read the Superpowers plan and continue from the first unchecked plan task.":"Recovery action: All tasks done. Run guard to transition to verify."}function uv(t,e,n){let i=n.status==="missing",r=i?"classic-build-plan-missing":"classic-build-plan-broken",s=i?"plan is not recorded":"the recorded plan path does not resolve to a file",o=i?[]:[`RECORDED_PLAN: ${n.recordedPath}`],a=i?`comet state set ${t} plan `:`comet state set ${t} plan `,c=i?["2. Load the Superpowers writing-plans Skill.",`3. Read the Design Doc path from "comet state get ${t} design_doc" and read ${e}/tasks.md.`,"4. Create the implementation plan under docs/superpowers/plans/.","5. Record the plan path:",` ${a}`]:[`2. Restore the plan file at ${n.recordedPath}, or load the Superpowers writing-plans Skill and create a replacement under docs/superpowers/plans/.`,"3. When creating a replacement, record its path:",` ${a}`];return["COMET_RECOVERY: required",`ERROR_CODE: ${r}`,`CHANGE: ${t}`,"WORKFLOW: full","PHASE: build",`STATE: ${s}`,...o,"","ALLOWED_RECOVERY_WRITES:","- docs/superpowers/plans/.md","- Comet state updates performed by the comet CLI",`- ${e} artifacts allowed by the build phase`,"","RECOVERY:",`1. Resume /comet-build for ${t} and return to Step 1.`,...c,`${i?"6":"4"}. Verify recovery:`,` comet state check ${t} build --recover`,"","SUCCESS: plan is reported as DONE and recovery no longer returns classic-build-plan-missing or classic-build-plan-broken.","RETRY: resume build configuration or retry the blocked Write/Edit only after SUCCESS.","PROHIBITED: do not execute tasks.md or write project source before SUCCESS; tasks.md is not a substitute for the implementation plan.","If writing-plans is unavailable, stop and report the missing Skill instead of bypassing this recovery."].join(` -`)}async function fv(t,e){let n=await C(e,"verify_result"),i=await C(e,"verify_failures"),r=await C(e,"verify_mode"),s=await C(e,"verification_report"),o=await C(e,"branch_status");t.stdout.push(" Verification:",await Y("verify_result",n),` - verify_failures: ${i||"0"}`,await Y("verify_mode",r),await Y("verification_report",s,s),o==="handled"?" - branch_status: LEGACY (handled before archive; archive still owns final closure)":" - branch_status: DEFERRED (handled after the archive commit)","",n==="pass"?"Recovery action: Verification complete. Continue to archive; branch handling happens after archive changes are committed.":n==="fail"?"Recovery action: Verification failed and rolled back to build. Resume from /comet-build.":"Recovery action: Verification not yet started or in progress. Run scale assessment then verify.")}async function dv(t,e){let n=await C(e,"archive_confirmation");t.stdout.push(" Archive:",await Y("verify_result",await C(e,"verify_result")),await Y("archive_confirmation",n),await Y("archived",await C(e,"archived")),"",n==="confirmed"?"Recovery action: Archive is confirmed. Run /comet-archive to complete archiving.":"Recovery action: Ask for final archive confirmation in /comet-archive before running the archive command.")}async function pv(t,e){fe(e);let{file:n,directory:i,label:r}=await ge(e);await K(n)||b(`ERROR: .comet.yaml not found at ${r}/.comet.yaml`);let s=await C(e,"phase"),o=await C(e,"workflow");t.stdout.push(`=== Recovery Context: ${e} ===`,`Phase: ${s}`,`Workflow: ${o}`,"","State fields:"),s==="open"?await ov(t,i):s==="design"?await av(t,e,i):s==="build"?await cv(t,e,i,o):s==="verify"?await fv(t,e):s==="archive"?await dv(t,e):b(`ERROR: Unknown phase: ${s}`),t.stdout.push("","=== End Recovery Context ===")}async function mv(t,e){fe(e);let{file:n,directory:i,label:r}=await ge(e);await K(n)||b(`ERROR: .comet.yaml not found at ${r}/.comet.yaml`);let s=O.join(i,"tasks.md"),o=await K(s)?(await Ue(T(),s,{label:"Classic scale task file"})).split(/\r?\n/u).filter(g=>/^- \[/u.test(g)).length:0,a=O.join(i,"specs"),c=0;if(await K(a))for(let g of await $y.readdir(a))await K(O.join(a,g,"spec.md"))&&(c+=1);let l=await C(e,"plan"),f="";l&&l!=="null"&&await K(l)&&(f=(await Ue(T(),l,{label:"Classic scale plan"})).match(/^base-ref:\s*(.+)$/mu)?.[1].trim()??""),f||(f=await C(e,"base_ref"));let u=_f(["diff","--name-only",...f&&f!=="null"?[`${f}...HEAD`]:["HEAD"]]),d=u?u.split(/\r?\n/u).filter(Boolean).length:0,m=o>3||c>1||d>8?"full":"light";await Pf(new kr,e,"verify_mode",m),t.stderr.push(`=== Scale Assessment: ${e} ===`,` Tasks: ${o} (threshold: 3)`,` Delta specs: ${c} capabilities (threshold: 1)`,` Changed files: ${d} (threshold: 8)`,` → Result: ${m}`,ue(`[SCALE] verify_mode=${m}`))}function hv(t){let e,n,i;for(let r=0;r' to establish the first binding`);let r=Yi(qn());r===null&&b("ERROR: cannot rebind while HEAD is detached; checkout a branch first");let s=await me(n);s.classic||b("ERROR: Classic state projection is missing"),await ho(n,r);let o={...s.classic,boundBranch:r};await Yo(n,{change:e,event:"rebind",source:"comet-state",from:s.classic,to:o,effects:[{field:"boundBranch",from:i,to:r}]}),t.stderr.push(ue(`[REBIND] bound_branch: ${i} → ${r}`))}async function kv(t){let e=await Fu(T());if(e.status==="selected"){t.stdout.push(e.selection.change);return}e.status==="missing"&&b(`ERROR: no current change selected + Repair-only escape hatch: COMET_FORCE_PHASE=1 comet-state.mjs set phase `),await Gy(n,i);let{file:s,directory:o}=await ge(e),a=await Rr(s),c=a.toJS()??{};if(a.set(n,Pf(n,i)),n==="isolation")if(Vi(i)){let u=typeof c.isolation=="string"?c.isolation:null,d=c.bound_branch;if(!(typeof d=="string"&&d!=="")||u!==i){let g=qn(),p=Yi(g),h=ho({isolation:i,boundBranch:null,currentBranch:p,gitWorkTree:p===null?mo(g):!0});h.status==="needs-heal"?a.set("bound_branch",h.branch):h.status==="unbound-detached"?b(`ERROR: cannot bind isolation=${i} while HEAD is detached; checkout a branch first`):a.set("bound_branch",null)}}else a.set("bound_branch",null);let l=await _n(o),f=On(a.toJS(),l);if(f.run){f.classic||b("ERROR: migrated Run is missing its Classic projection");let u=await Pt(o,f),d=Ot(f.classic,u),m=d!==f.run.currentStep,g={...f.run,currentStep:d,iteration:f.run.iteration+(m?1:0),status:d==="completed"?"completed":"running"};if(await xt(o,{classic:f.classic,run:g,unknownKeys:f.unknownKeys}),m){let p=await Nt(o,g.trajectoryRef);await rt(o,g.trajectoryRef,{sequence:p.length+1,timestamp:new Date().toISOString(),type:"state_transitioned",runId:g.runId,data:{kind:"classic-config",field:n,fromStep:f.run.currentStep,toStep:d}})}}else await Zo(s,a.toString());n==="phase"&&!r.internal&&t.stderr.push(bf("WARNING: Setting 'phase' directly bypasses state machine constraints."),bf(" Consider using: comet-state.mjs transition ")),t.stderr.push(ue(`[SET] ${n}=${i}`))}async function zy(t,e,n){fe(e),Er(n,Ln);let i=await ku(e,T()),{label:r,directory:s}=i,o=O.join(s,".comet.yaml");await K(o)&&b(`ERROR: .comet.yaml already exists at ${r}/.comet.yaml`);let a=n!=="full",c=a?"off":await Hy(),l=new Mn.Document({workflow:n,language:await Rf(),phase:"open",context_compression:await Jy(),build_mode:a?"direct":null,build_pause:null,subagent_dispatch:null,tdd_mode:a?"direct":null,review_mode:c,isolation:null,verify_mode:a?"light":null,auto_transition:await _f()==="true",base_ref:xf(["rev-parse","--verify","HEAD"]),design_doc:null,plan:null,verify_result:"pending",verify_failures:0,verification_report:null,branch_status:"pending",created_at:new Date().toISOString().slice(0,10),verified_at:null,archive_confirmation:null,archived:!1});await Zo(o,l.toString()),t.stdout.push(ue(`Initialized: ${r}/.comet.yaml (workflow=${n})`))}async function Ce(t,e){let n=await C(t,"phase");n!==e&&b(`ERROR: Cannot transition '${t}': expected phase ${e}, got ${n}`)}async function Xy(t){let e=await C(t,"workflow"),n=await C(t,"build_mode"),i=await C(t,"isolation"),r=await C(t,"direct_override"),s=await C(t,"subagent_dispatch"),o=await C(t,"tdd_mode"),a=await C(t,"review_mode");["current","branch","worktree"].includes(i)||b(`ERROR: Cannot transition '${t}': isolation must be current, branch, or worktree, got '${i||"null"}'`),["subagent-driven-development","executing-plans","direct"].includes(n)||b(`ERROR: Cannot transition '${t}': build_mode must be selected before leaving build, got '${n||"null"}'`),n==="direct"&&!["hotfix","tweak"].includes(e)&&r!=="true"&&b(`ERROR: Cannot transition '${t}': build_mode=direct is only allowed for hotfix/tweak unless direct_override=true`),n==="subagent-driven-development"&&s!=="confirmed"&&b(`ERROR: Cannot transition '${t}': subagent_dispatch must be confirmed before using build_mode=subagent-driven-development`),e==="full"&&(!o||o==="null")&&b(`ERROR: Cannot transition '${t}': tdd_mode must be selected before leaving build (full workflow)`),e==="full"&&!["off","standard","thorough"].includes(a)&&b(`ERROR: Cannot transition '${t}': review_mode must be selected before leaving build (full workflow); review_mode must be off, standard, or thorough, got '${a||"null"}'`)}async function Qy(t){let{directory:e}=await ge(t),n=await C(t,"workflow");for(let i of["proposal.md","tasks.md"])await Re(O.join(e,i))||b(`ERROR: Cannot transition '${t}': ${i} must exist and be non-empty before leaving open`);n==="full"&&!await Re(O.join(e,"design.md"))&&b(`ERROR: Cannot transition '${t}': design.md must exist and be non-empty before leaving open`)}async function Zy(t){let e=await C(t,"design_doc");(!e||e==="null"||!await Re(O.resolve(e)))&&b(`ERROR: Cannot transition '${t}': design_doc must point to an existing Design Doc before leaving design`)}async function ev(t,e){let n=O.join(t,".comet.yaml"),i=await Rr(n);for(let r of e){let s=Cf(r.field);i.set(s,Pf(s,Ef(r.to)))}await Zo(n,i.toString())}async function tv(t,e,n){let{directory:i}=await ge(e),r=await me(i),s=r.classic,o=!1;if(!s){r.run&&b("ERROR: Classic state projection is missing");let c=await Rr(O.join(i,".comet.yaml"));s=Vy(c.toJS()),o=!0}let a=wf(s,n);r.run?await hf(i,a.classic,r.run,{event:n,source:"comet-state"}):o?await ev(i,a.effects):await xt(i,{classic:a.classic,run:null,unknownKeys:r.unknownKeys}),await Yo(i,{change:e,event:n,source:"comet-state",from:s,to:a.classic,effects:a.effects});for(let c of a.effects)t.stderr.push(ue(`[SET] ${Cf(c.field)}=${Ef(c.to)}`));t.stderr.push(ue(`[TRANSITION] ${n}`))}async function nv(t,e,n){if(fe(e),Er(n,My),n==="open-complete")await Ce(e,"open"),await Qy(e);else if(n==="design-complete")await Ce(e,"design"),await Zy(e);else if(n==="build-complete")await Ce(e,"build"),await Xy(e);else if(n==="verify-pass"){await Ce(e,"verify");let i=await C(e,"verification_report");(!i||!await K(O.resolve(i)))&&b(`ERROR: Cannot transition '${e}': verification_report must point to an existing report file`)}else if(n==="verify-fail")await Ce(e,"verify");else if(n==="archive-confirm")await Ce(e,"archive"),await C(e,"verify_result")!=="pass"&&b(`ERROR: Cannot transition '${e}': verify_result must be pass before archiving`),await C(e,"archived")==="true"&&b(`ERROR: Cannot transition '${e}': already archived`);else if(n==="preset-escalate"){await Ce(e,"build");let i=await C(e,"workflow");["hotfix","tweak"].includes(i)||b(`ERROR: Cannot transition '${e}': preset-escalate only applies to hotfix/tweak, got workflow='${i}'`)}else n==="archive-reopen"?(await Ce(e,"archive"),await C(e,"archived")==="true"&&b(`ERROR: Cannot transition '${e}': already archived`)):(await Ce(e,"archive"),await C(e,"verify_result")!=="pass"&&b(`ERROR: Cannot transition '${e}': verify_result must be pass before archiving`),await C(e,"archive_confirmation")!=="confirmed"&&b(`ERROR: Cannot transition '${e}': archive_confirmation must be confirmed before archiving`));await tv(t,e,n)}async function iv(t,e){fe(e);let{file:n,label:i}=await ge(e);await K(n)||b(`ERROR: .comet.yaml not found at ${i}/.comet.yaml`);let r=await C(e,"phase"),s=await C(e,"workflow"),o=await C(e,"auto_transition");if(await C(e,"archived")==="true"){t.stdout.push("NEXT: done");return}let a=r==="open"?"comet-open":r==="design"?"comet-design":r==="verify"?"comet-verify":r==="archive"?"comet-archive":r==="build"?s==="hotfix"?"comet-hotfix":s==="tweak"?"comet-tweak":"comet-build":null;a||b(`ERROR: Cannot resolve next step for '${e}': unknown phase '${r||"null"}'`),t.stdout.push(`NEXT: ${o==="false"?"manual":"auto"}`,`SKILL: ${a}`),o==="false"&&t.stdout.push(`HINT: phase is '${r}'; run /${a} manually to continue`)}async function rv(t,e,n){Sf(e,"task file"),n||b("ERROR: Task text cannot be empty");let i=O.resolve(T(),e);await K(i)||b(`ERROR: Task file not found: ${e}`);let s=(await Ue(T(),i,{label:"Classic task-checkoff file"})).split(/\r?\n/u).filter(a=>[`- [ ] ${n}`,`- [x] ${n}`,`- [X] ${n}`].includes(a)),o=s.filter(a=>/^- \[[xX]\] /u.test(a));s.length!==1&&b(`ERROR: task text must appear exactly once in ${e} (found ${s.length}): ${n}`),o.length!==1&&b(`ERROR: task is not checked in ${e}: ${n}`),t.stdout.push("TASK_CHECKOFF: PASS",`FILE: ${e}`,`TASK: ${n}`)}async function sv(t,e,n){fe(e),Er(n,Qo);let{file:i,directory:r,label:s}=await ge(e);t.stdout.push(`=== Entry Check: comet-${n} ===`),await K(i)||b(`ERROR: .comet.yaml not found at ${s}/.comet.yaml`);let o=!1,a=u=>t.stdout.push(` ${ue("[PASS]")} ${u}`),c=u=>{t.stdout.push(` ${Go("[FAIL]")} ${u}`),o=!0},l=async(u,d)=>{let m=await C(e,u);(m===d?a:c)(`${u}=${m} (expected: ${d})`)};if(a(".comet.yaml exists"),await l("phase",n),n==="design"){await l("workflow","full");let u=await C(e,"design_doc");(!u||u==="null"?a:c)(u?`design_doc=${u} (expected: empty/null)`:"design_doc is empty/null");for(let d of["proposal.md","design.md","tasks.md"])(await Re(O.join(r,d))?a:c)(`${d} ${await Re(O.join(r,d))?"non-empty":"missing or empty"}`)}else if(n==="build"){let u=await C(e,"workflow"),d=await C(e,"design_doc");u==="full"?(d&&d!=="null"&&await K(O.resolve(d))?a:c)(`design_doc=${d} (expected: non-null and file exists)`):a(`workflow=${u} (design_doc not required)`);for(let m of["proposal.md","tasks.md"])(await Re(O.join(r,m))?a:c)(`${m} ${await Re(O.join(r,m))?"non-empty":"missing or empty"}`)}else if(n==="verify"){let u=await C(e,"verify_result");(["","null","pending"].includes(u)?a:c)(`verify_result=${u} (expected: pending or null)`)}else if(n==="archive"){await l("verify_result","pass");let u=await C(e,"archived");(u!=="true"?a:c)(`archived=${u} (expected: not true)`)}let f=await dn(r,{heal:!0,cwd:qn()});if(f.bindingRequired)switch(f.status){case"drift":c(nu(e,f.boundBranch,f.currentBranch));break;case"unbound-detached":c(pn(e));break;case"healed":a(`bound_branch lazily set to ${f.branch}`);break;case"needs-heal":case"ok":case"not-applicable":a("bound_branch matches current branch");break;default:{let u=f;throw new Error(`unhandled branch binding status: ${JSON.stringify(u)}`)}}if(t.stdout.push(""),o)throw t.stderr.push(Go("BLOCKED — fix failing checks before proceeding")),new Dn("",1);t.stderr.push(ue("ALL CHECKS PASSED — ready to proceed"))}async function Y(t,e,n){return!e||e==="null"?` - ${t}: PENDING`:n&&!await K(O.resolve(n))?` - ${t}: BROKEN (path ${e} does not exist)`:` - ${t}: DONE (${e})`}async function ov(t,e){t.stdout.push(" Artifacts:");let n=0;for(let i of["proposal.md","design.md","tasks.md"]){let r=await Re(O.join(e,i));r&&(n+=1),t.stdout.push(` - ${i}: ${r?"DONE":"PENDING"}`)}t.stdout.push("",n===3?"Recovery action: All artifacts complete. Run /comet-open user confirmation, then guard to transition.":n===0?"Recovery action: No artifacts created yet. Start from /comet-open Step 1 (explore and clarify).":"Recovery action: Some artifacts incomplete. Resume /comet-open from the first missing artifact.")}async function av(t,e,n){t.stdout.push(" Artifacts:");for(let o of["proposal.md","design.md","tasks.md"])t.stdout.push(` - ${o}: ${await Re(O.join(n,o))?"DONE":"MISSING (unexpected in design phase)"}`);let i=await C(e,"handoff_context"),r=await C(e,"handoff_hash"),s=await C(e,"design_doc");t.stdout.push(""," Design progress:",await Y("handoff_context",i,i),await Y("handoff_hash",r),await Y("design_doc",s,s),""),s&&s!=="null"&&await K(O.resolve(s))?t.stdout.push("Recovery action: Design Doc already created and linked. Run guard to transition to build."):i&&i!=="null"&&await K(O.resolve(i))?t.stdout.push("Recovery action: Handoff generated but Design Doc not yet created. Resume from brainstorming confirmation (Step 1c)."):t.stdout.push("Recovery action: No handoff generated yet. Start from Step 1a (generate handoff package).")}async function cv(t,e,n,i){let r=await C(e,"isolation"),s=await C(e,"build_mode"),o=await C(e,"build_pause"),a=await C(e,"subagent_dispatch"),c=await C(e,"tdd_mode"),l=await C(e,"review_mode"),f=await C(e,"plan"),u=await vf(T(),f),d=[" Build decisions:",await Y("isolation",r),await Y("build_mode",s),await Y("build_pause",o),await Y("tdd_mode",c),await Y("review_mode",l)];(s==="subagent-driven-development"||a&&a!=="null")&&d.push(await Y("subagent_dispatch",a)),t.stdout.push(...d,""," Plan:",await Y("plan",f,f),"");let m=O.join(n,"tasks.md");if(!await K(m)){t.stdout.push(" Tasks: tasks.md MISSING","","Recovery action: tasks.md missing. Verify change directory integrity.");return}let g=(await Ue(T(),m,{label:"Classic change tasks"})).split(/\r?\n/u),p=g.filter(E=>/^\s*- \[[ xX]\] /u.test(E)).length,h=g.filter(E=>/^\s*- \[[xX]\] /u.test(E)).length,v=p-h,y=0,S=0;if(u.status==="ready"){let E=(await Ue(T(),f,{label:"Classic build plan"})).split(/\r?\n/u);y=E.filter(N=>/^\s*- \[[ xX]\] /u.test(N)).length,S=E.filter(N=>/^\s*- \[[xX]\] /u.test(N)).length}let R=y-S;t.stdout.push(` Tasks: ${h}/${p} done, ${v} pending`),y>0&&t.stdout.push(` Plan tasks: ${S}/${y} done, ${R} pending`),t.stdout.push("");let _=lv(e,O.relative(T(),n).replaceAll("\\","/"),i,r,s,o,a,c,l,u,v,R);t.stdout.push(_)}function Je(t){return!t||t==="null"}function lv(t,e,n,i,r,s,o,a,c,l,f,u){let d=l.status==="ready",m=n==="full"&&(Je(a)||Je(c));return s==="plan-ready"&&d&&(Je(i)||Je(r)||m)?n==="full"?"Recovery action: Plan-ready pause detected. Ask the user whether to continue, then choose isolation, build mode, TDD mode, and review mode without regenerating the plan.":"Recovery action: Plan-ready pause detected. Ask the user whether to continue, then choose isolation and build mode without regenerating the plan.":n==="full"&&!d?uv(t,e,l):s==="plan-ready"?r==="subagent-driven-development"&&(f>0||u>0)?o==="confirmed"?"Recovery action: Plan-ready pause is stale because build decisions are already selected. Clear build_pause to null, then inspect the first unchecked task (OpenSpec or plan additions) against recent git history/diff. If implemented, check it off; otherwise dispatch a subagent. Do not execute the pending task directly in the main window.":"Recovery action: Plan-ready pause is stale and selected subagent execution is not recorded. Run comet state set subagent_dispatch confirmed, then continue from the first unchecked task through subagent execution.":f>0||u>0?"Recovery action: Plan-ready pause is stale because build decisions are already selected. Clear build_pause to null, then continue from the first unchecked task.":"Recovery action: Plan-ready pause is stale and all tasks are done. Clear build_pause to null, then run guard to transition to verify.":Je(i)?"Recovery action: Isolation not selected. Use the current platform's user confirmation mechanism to ask user for branch/worktree choice.":Je(r)?"Recovery action: Build mode not selected. Use the current platform's user confirmation mechanism to ask user for execution method.":n==="full"&&Je(a)?"Recovery action: TDD mode not selected. Use the current platform's user confirmation mechanism to ask user for tdd or direct.":n==="full"&&Je(c)?"Recovery action: Review mode not selected. Use the current platform's user confirmation mechanism to ask user for off, standard, or thorough.":f>0?r==="subagent-driven-development"?o==="confirmed"?"Recovery action: Read tasks.md and the Superpowers plan (which may include additions beyond OpenSpec), then inspect the first unchecked task against recent git history/diff. If implemented, check it off; otherwise dispatch a subagent. Do not execute the pending task directly in the main window.":"Recovery action: Selected subagent execution is not recorded. Run comet state set subagent_dispatch confirmed, then continue from the first unchecked task through subagent execution.":"Recovery action: Read tasks.md and continue from first unchecked task.":u>0?r==="subagent-driven-development"?o==="confirmed"?"Recovery action: Read the Superpowers plan, then inspect the first unchecked Superpowers plan task against recent git history/diff. If implemented, check it off; otherwise dispatch a subagent. Do not execute the pending task directly in the main window.":"Recovery action: Selected subagent execution is not recorded. Run comet state set subagent_dispatch confirmed, then continue from the first unchecked task through subagent execution.":"Recovery action: Read the Superpowers plan and continue from the first unchecked plan task.":"Recovery action: All tasks done. Run guard to transition to verify."}function uv(t,e,n){let i=n.status==="missing",r=i?"classic-build-plan-missing":"classic-build-plan-broken",s=i?"plan is not recorded":"the recorded plan path does not resolve to a file",o=i?[]:[`RECORDED_PLAN: ${n.recordedPath}`],a=i?`comet state set ${t} plan `:`comet state set ${t} plan `,c=i?["2. Load the Superpowers writing-plans Skill.",`3. Read the Design Doc path from "comet state get ${t} design_doc" and read ${e}/tasks.md.`,"4. Create the implementation plan under docs/superpowers/plans/.","5. Record the plan path:",` ${a}`]:[`2. Restore the plan file at ${n.recordedPath}, or load the Superpowers writing-plans Skill and create a replacement under docs/superpowers/plans/.`,"3. When creating a replacement, record its path:",` ${a}`];return["COMET_RECOVERY: required",`ERROR_CODE: ${r}`,`CHANGE: ${t}`,"WORKFLOW: full","PHASE: build",`STATE: ${s}`,...o,"","ALLOWED_RECOVERY_WRITES:","- docs/superpowers/plans/.md","- Comet state updates performed by the comet CLI",`- ${e} artifacts allowed by the build phase`,"","RECOVERY:",`1. Resume /comet-build for ${t} and return to Step 1.`,...c,`${i?"6":"4"}. Verify recovery:`,` comet state check ${t} build --recover`,"","SUCCESS: plan is reported as DONE and recovery no longer returns classic-build-plan-missing or classic-build-plan-broken.","RETRY: resume build configuration or retry the blocked Write/Edit only after SUCCESS.","PROHIBITED: do not execute tasks.md or write project source before SUCCESS; tasks.md is not a substitute for the implementation plan.","If writing-plans is unavailable, stop and report the missing Skill instead of bypassing this recovery."].join(` +`)}async function fv(t,e){let n=await C(e,"verify_result"),i=await C(e,"verify_failures"),r=await C(e,"verify_mode"),s=await C(e,"verification_report"),o=await C(e,"branch_status");t.stdout.push(" Verification:",await Y("verify_result",n),` - verify_failures: ${i||"0"}`,await Y("verify_mode",r),await Y("verification_report",s,s),o==="handled"?" - branch_status: LEGACY (handled before archive; archive still owns final closure)":" - branch_status: DEFERRED (handled after the archive commit)","",n==="pass"?"Recovery action: Verification complete. Continue to archive; branch handling happens after archive changes are committed.":n==="fail"?"Recovery action: Verification failed and rolled back to build. Resume from /comet-build.":"Recovery action: Verification not yet started or in progress. Run scale assessment then verify.")}async function dv(t,e){let n=await C(e,"archive_confirmation");t.stdout.push(" Archive:",await Y("verify_result",await C(e,"verify_result")),await Y("archive_confirmation",n),await Y("archived",await C(e,"archived")),"",n==="confirmed"?"Recovery action: Archive is confirmed. Run /comet-archive to complete archiving.":"Recovery action: Ask for final archive confirmation in /comet-archive before running the archive command.")}async function pv(t,e){fe(e);let{file:n,directory:i,label:r}=await ge(e);await K(n)||b(`ERROR: .comet.yaml not found at ${r}/.comet.yaml`);let s=await C(e,"phase"),o=await C(e,"workflow");t.stdout.push(`=== Recovery Context: ${e} ===`,`Phase: ${s}`,`Workflow: ${o}`,"","State fields:"),s==="open"?await ov(t,i):s==="design"?await av(t,e,i):s==="build"?await cv(t,e,i,o):s==="verify"?await fv(t,e):s==="archive"?await dv(t,e):b(`ERROR: Unknown phase: ${s}`),t.stdout.push("","=== End Recovery Context ===")}async function mv(t,e){fe(e);let{file:n,directory:i,label:r}=await ge(e);await K(n)||b(`ERROR: .comet.yaml not found at ${r}/.comet.yaml`);let s=O.join(i,"tasks.md"),o=await K(s)?(await Ue(T(),s,{label:"Classic scale task file"})).split(/\r?\n/u).filter(g=>/^- \[/u.test(g)).length:0,a=O.join(i,"specs"),c=0;if(await K(a))for(let g of await $y.readdir(a))await K(O.join(a,g,"spec.md"))&&(c+=1);let l=await C(e,"plan"),f="";l&&l!=="null"&&await K(l)&&(f=(await Ue(T(),l,{label:"Classic scale plan"})).match(/^base-ref:\s*(.+)$/mu)?.[1].trim()??""),f||(f=await C(e,"base_ref"));let u=xf(["diff","--name-only",...f&&f!=="null"?[`${f}...HEAD`]:["HEAD"]]),d=u?u.split(/\r?\n/u).filter(Boolean).length:0,m=o>3||c>1||d>8?"full":"light";await Of(new Sr,e,"verify_mode",m),t.stderr.push(`=== Scale Assessment: ${e} ===`,` Tasks: ${o} (threshold: 3)`,` Delta specs: ${c} capabilities (threshold: 1)`,` Changed files: ${d} (threshold: 8)`,` → Result: ${m}`,ue(`[SCALE] verify_mode=${m}`))}function hv(t){let e,n,i;for(let r=0;r' to establish the first binding`);let r=Yi(qn());r===null&&b("ERROR: cannot rebind while HEAD is detached; checkout a branch first");let s=await me(n);s.classic||b("ERROR: Classic state projection is missing"),await go(n,r);let o={...s.classic,boundBranch:r};await Yo(n,{change:e,event:"rebind",source:"comet-state",from:s.classic,to:o,effects:[{field:"boundBranch",from:i,to:r}]}),t.stderr.push(ue(`[REBIND] bound_branch: ${i} → ${r}`))}async function kv(t){let e=await Wu(T());if(e.status==="selected"){t.stdout.push(e.selection.change);return}e.status==="missing"&&b(`ERROR: no current change selected Use: comet-state.mjs select `),b(`ERROR: current change selection is stale: ${e.reason} -Use: comet-state.mjs select `)}async function Sv(t){await Wu(T()),t.stderr.push(ue("[CLEARED] current change selection"))}var Of=async(t,e)=>Yu(e,async()=>{let n=new kr;try{let[i,...r]=t;return await yv(i),i==="init"?(Ee(r,2,"Usage: comet-state.mjs init "),await zy(n,r[0],r[1])):i==="get"?(Ee(r,2,"Usage: comet-state.mjs get "),fe(r[0]),n.stdout.push(await C(r[0],r[1]))):i==="set"?(Ee(r,3,"Usage: comet-state.mjs set "),fe(r[0]),await Pf(n,r[0],r[1],r[2])):i==="transition"?(Ee(r,2,"Usage: comet-state.mjs transition "),await nv(n,r[0],r[1])):i==="check"?(Ee(r,2,"Usage: comet-state.mjs check [--recover]"),r[2]==="--recover"?await pv(n,r[0]):await sv(n,r[0],r[1])):i==="scale"?(Ee(r,1,"Usage: comet-state.mjs scale "),await mv(n,r[0])):i==="record-check"?(Ee(r,2,"Usage: comet state record-check --command --exit-code [--cwd ]"),await gv(n,r[0],r[1],r.slice(2))):i==="task-checkoff"?(Ee(r,2,"Usage: comet-state.mjs task-checkoff "),await rv(n,r[0],r[1])):i==="rebind"?(br(r,1,"Usage: comet-state.mjs rebind "),await bv(n,r[0])):i==="select"?(br(r,1,"Usage: comet-state.mjs select "),await vv(n,r[0])):i==="current"?(br(r,0,"Usage: comet-state.mjs current"),await kv(n)):i==="clear-selection"?(br(r,0,"Usage: comet-state.mjs clear-selection"),await Sv(n)):i==="next"?(Ee(r,1,"Usage: comet-state.mjs next "),await iv(n,r[0])):b(`Unknown subcommand: ${i??""}`),n.result()}catch(i){if(!(i instanceof Dn))throw i;if(i.message)for(let r of i.message.split(` +Use: comet-state.mjs select `)}async function Sv(t){await Bu(T()),t.stderr.push(ue("[CLEARED] current change selection"))}var Nf=async(t,e)=>Vu(e,async()=>{let n=new Sr;try{let[i,...r]=t;return await yv(i),i==="init"?(Ee(r,2,"Usage: comet-state.mjs init "),await zy(n,r[0],r[1])):i==="get"?(Ee(r,2,"Usage: comet-state.mjs get "),fe(r[0]),n.stdout.push(await C(r[0],r[1]))):i==="set"?(Ee(r,3,"Usage: comet-state.mjs set "),fe(r[0]),await Of(n,r[0],r[1],r[2])):i==="transition"?(Ee(r,2,"Usage: comet-state.mjs transition "),await nv(n,r[0],r[1])):i==="check"?(Ee(r,2,"Usage: comet-state.mjs check [--recover]"),r[2]==="--recover"?await pv(n,r[0]):await sv(n,r[0],r[1])):i==="scale"?(Ee(r,1,"Usage: comet-state.mjs scale "),await mv(n,r[0])):i==="record-check"?(Ee(r,2,"Usage: comet state record-check --command --exit-code [--cwd ]"),await gv(n,r[0],r[1],r.slice(2))):i==="task-checkoff"?(Ee(r,2,"Usage: comet-state.mjs task-checkoff "),await rv(n,r[0],r[1])):i==="rebind"?(kr(r,1,"Usage: comet-state.mjs rebind "),await bv(n,r[0])):i==="select"?(kr(r,1,"Usage: comet-state.mjs select "),await vv(n,r[0])):i==="current"?(kr(r,0,"Usage: comet-state.mjs current"),await kv(n)):i==="clear-selection"?(kr(r,0,"Usage: comet-state.mjs clear-selection"),await Sv(n)):i==="next"?(Ee(r,1,"Usage: comet-state.mjs next "),await iv(n,r[0])):b(`Unknown subcommand: ${i??""}`),n.result()}catch(i){if(!(i instanceof Dn))throw i;if(i.message)for(let r of i.message.split(` `))n.stderr.push(Go(r));return n.result(i.exitCode)}});function Cv(t,e){return{exitCode:e.exitCode,stdout:JSON.stringify({command:t,exitCode:e.exitCode,...e.stdout===void 0?{}:{stdout:e.stdout},...e.stderr===void 0?{}:{stderr:e.stderr}})+` `}}async function Af(t,e,n=process.argv.slice(2)){let i=n.includes("--json"),r=n.filter(a=>a!=="--json"),s;try{s=await e(r,{json:i})}catch(a){s={exitCode:70,stderr:a instanceof Error?a.message:String(a)}}let o=i?Cv(t,s):s;return o.stdout&&process.stdout.write(o.stdout),o.stderr&&process.stderr.write(o.stderr+(o.stderr.endsWith(` `)?"":` -`)),o.exitCode}process.exitCode=await Af("state",Of); +`)),o.exitCode}process.exitCode=await Af("state",Nf); diff --git a/assets/skills/comet/scripts/comet-yaml-validate.mjs b/assets/skills/comet/scripts/comet-yaml-validate.mjs index fbbb3d26a..178b81c9b 100644 --- a/assets/skills/comet/scripts/comet-yaml-validate.mjs +++ b/assets/skills/comet/scripts/comet-yaml-validate.mjs @@ -1,75 +1,75 @@ #!/usr/bin/env node import { createRequire as __cometCreateRequire } from 'module'; const require = __cometCreateRequire(import.meta.url); -var Wa=Object.create;var Er=Object.defineProperty;var Ma=Object.getOwnPropertyDescriptor;var Fa=Object.getOwnPropertyNames;var Ba=Object.getPrototypeOf,Ka=Object.prototype.hasOwnProperty;var yt=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var y=(n,e)=>()=>{try{return e||n((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}};var Ya=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Fa(e))!Ka.call(n,r)&&r!==t&&Er(n,r,{get:()=>e[r],enumerable:!(i=Ma(e,r))||i.enumerable});return n};var Nn=(n,e,t)=>(t=n!=null?Wa(Ba(n)):{},Ya(e||!n||!n.__esModule?Er(t,"default",{value:n,enumerable:!0}):t,n));var _=y(j=>{"use strict";var On=Symbol.for("yaml.alias"),_r=Symbol.for("yaml.document"),vt=Symbol.for("yaml.map"),Pr=Symbol.for("yaml.pair"),xn=Symbol.for("yaml.scalar"),bt=Symbol.for("yaml.seq"),B=Symbol.for("yaml.node.type"),Ua=n=>!!n&&typeof n=="object"&&n[B]===On,Ja=n=>!!n&&typeof n=="object"&&n[B]===_r,Va=n=>!!n&&typeof n=="object"&&n[B]===vt,Ha=n=>!!n&&typeof n=="object"&&n[B]===Pr,Nr=n=>!!n&&typeof n=="object"&&n[B]===xn,Ga=n=>!!n&&typeof n=="object"&&n[B]===bt;function Or(n){if(n&&typeof n=="object")switch(n[B]){case vt:case bt:return!0}return!1}function za(n){if(n&&typeof n=="object")switch(n[B]){case On:case vt:case xn:case bt:return!0}return!1}var Qa=n=>(Nr(n)||Or(n))&&!!n.anchor;j.ALIAS=On;j.DOC=_r;j.MAP=vt;j.NODE_TYPE=B;j.PAIR=Pr;j.SCALAR=xn;j.SEQ=bt;j.hasAnchor=Qa;j.isAlias=Ua;j.isCollection=Or;j.isDocument=Ja;j.isMap=Va;j.isNode=za;j.isPair=Ha;j.isScalar=Nr;j.isSeq=Ga});var Oe=y(An=>{"use strict";var R=_(),T=Symbol("break visit"),xr=Symbol("skip children"),M=Symbol("remove node");function kt(n,e){let t=Ar(e);R.isDocument(n)?ge(null,n.contents,t,Object.freeze([n]))===M&&(n.contents=null):ge(null,n,t,Object.freeze([]))}kt.BREAK=T;kt.SKIP=xr;kt.REMOVE=M;function ge(n,e,t,i){let r=Ir(n,e,t,i);if(R.isNode(r)||R.isPair(r))return Rr(n,i,r),ge(n,r,t,i);if(typeof r!="symbol"){if(R.isCollection(e)){i=Object.freeze(i.concat(e));for(let s=0;s{"use strict";var jr=_(),Xa=Oe(),Za={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},ec=n=>n.replace(/[!,[\]{}]/g,e=>Za[e]),xe=class n{constructor(e,t){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},n.defaultYaml,e),this.tags=Object.assign({},n.defaultTags,t)}clone(){let e=new n(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){let e=new n(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:n.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},n.defaultTags);break}return e}add(e,t){this.atNextDocument&&(this.yaml={explicit:n.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},n.defaultTags),this.atNextDocument=!1);let i=e.trim().split(/[ \t]+/),r=i.shift();switch(r){case"%TAG":{if(i.length!==2&&(t(0,"%TAG directive should contain exactly two parts"),i.length<2))return!1;let[s,o]=i;return this.tags[s]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,i.length!==1)return t(0,"%YAML directive should contain exactly one part"),!1;let[s]=i;if(s==="1.1"||s==="1.2")return this.yaml.version=s,!0;{let o=/^\d+\.\d+$/.test(s);return t(6,`Unsupported YAML version ${s}`,o),!1}}default:return t(0,`Unknown directive ${r}`,!0),!1}}tagName(e,t){if(e==="!")return"!";if(e[0]!=="!")return t(`Not a valid tag: ${e}`),null;if(e[1]==="<"){let o=e.slice(2,-1);return o==="!"||o==="!!"?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&t("Verbatim tags must end with a >"),o)}let[,i,r]=e.match(/^(.*!)([^!]*)$/s);r||t(`The ${e} tag has no suffix`);let s=this.tags[i];if(s)try{return s+decodeURIComponent(r)}catch(o){return t(String(o)),null}return i==="!"?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[t,i]of Object.entries(this.tags))if(e.startsWith(i))return t+ec(e.substring(i.length));return e[0]==="!"?e:`!<${e}>`}toString(e){let t=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],i=Object.entries(this.tags),r;if(e&&i.length>0&&jr.isNode(e.contents)){let s={};Xa.visit(e.contents,(o,a)=>{jr.isNode(a)&&a.tag&&(s[a.tag]=!0)}),r=Object.keys(s)}else r=[];for(let[s,o]of i)s==="!!"&&o==="tag:yaml.org,2002:"||(!e||r.some(a=>a.startsWith(o)))&&t.push(`%TAG ${s} ${o}`);return t.join(` -`)}};xe.defaultYaml={explicit:!1,version:"1.2"};xe.defaultTags={"!!":"tag:yaml.org,2002:"};Tr.Directives=xe});var Ct=y(Ae=>{"use strict";var qr=_(),tc=Oe();function nc(n){if(/[\x00-\x19\s,[\]{}]/.test(n)){let t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(n)}`;throw new Error(t)}return!0}function Lr(n){let e=new Set;return tc.visit(n,{Value(t,i){i.anchor&&e.add(i.anchor)}}),e}function Dr(n,e){for(let t=1;;++t){let i=`${n}${t}`;if(!e.has(i))return i}}function ic(n,e){let t=[],i=new Map,r=null;return{onAnchor:s=>{t.push(s),r??(r=Lr(n));let o=Dr(e,r);return r.add(o),o},setAnchors:()=>{for(let s of t){let o=i.get(s);if(typeof o=="object"&&o.anchor&&(qr.isScalar(o.node)||qr.isCollection(o.node)))o.node.anchor=o.anchor;else{let a=new Error("Failed to resolve repeated object (this should not happen)");throw a.source=s,a}}},sourceObjects:i}}Ae.anchorIsValid=nc;Ae.anchorNames=Lr;Ae.createNodeAnchors=ic;Ae.findNewAnchor=Dr});var Rn=y($r=>{"use strict";function Ie(n,e,t,i){if(i&&typeof i=="object")if(Array.isArray(i))for(let r=0,s=i.length;r{"use strict";var rc=_();function Wr(n,e,t){if(Array.isArray(n))return n.map((i,r)=>Wr(i,String(r),t));if(n&&typeof n.toJSON=="function"){if(!t||!rc.hasAnchor(n))return n.toJSON(e,t);let i={aliasCount:0,count:1,res:void 0};t.anchors.set(n,i),t.onCreate=s=>{i.res=s,delete t.onCreate};let r=n.toJSON(e,t);return t.onCreate&&t.onCreate(r),r}return typeof n=="bigint"&&!t?.keep?Number(n):n}Mr.toJS=Wr});var Et=y(Br=>{"use strict";var sc=Rn(),Fr=_(),oc=H(),jn=class{constructor(e){Object.defineProperty(this,Fr.NODE_TYPE,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:t,maxAliasCount:i,onAnchor:r,reviver:s}={}){if(!Fr.isDocument(e))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:e,keep:!0,mapAsMap:t===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},a=oc.toJS(this,"",o);if(typeof r=="function")for(let{count:c,res:l}of o.anchors.values())r(l,c);return typeof s=="function"?sc.applyReviver(s,{"":a},"",a):a}};Br.NodeBase=jn});var Re=y(Kr=>{"use strict";var ac=Ct(),cc=Oe(),ye=_(),lc=Et(),uc=H(),Tn=class extends lc.NodeBase{constructor(e){super(ye.ALIAS),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,t){if(t?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let i;t?.aliasResolveCache?i=t.aliasResolveCache:(i=[],cc.visit(e,{Node:(s,o)=>{(ye.isAlias(o)||ye.hasAnchor(o))&&i.push(o)}}),t&&(t.aliasResolveCache=i));let r;for(let s of i){if(s===this)break;s.anchor===this.source&&(r=s)}return r}toJSON(e,t){if(!t)return{source:this.source};let{anchors:i,doc:r,maxAliasCount:s}=t,o=this.resolve(r,t);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let a=i.get(o);if(a||(uc.toJS(o,null,t),a=i.get(o)),a?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(s>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=_t(r,o,i)),a.count*a.aliasCount>s)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return a.res}toString(e,t,i){let r=`*${this.source}`;if(e){if(ac.anchorIsValid(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let s=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(s)}if(e.implicitKey)return`${r} `}return r}};function _t(n,e,t){if(ye.isAlias(e)){let i=e.resolve(n),r=t&&i&&t.get(i);return r?r.count*r.aliasCount:0}else if(ye.isCollection(e)){let i=0;for(let r of e.items){let s=_t(n,r,t);s>i&&(i=s)}return i}else if(ye.isPair(e)){let i=_t(n,e.key,t),r=_t(n,e.value,t);return Math.max(i,r)}return 1}Kr.Alias=Tn});var O=y(qn=>{"use strict";var fc=_(),dc=Et(),pc=H(),mc=n=>!n||typeof n!="function"&&typeof n!="object",G=class extends dc.NodeBase{constructor(e){super(fc.SCALAR),this.value=e}toJSON(e,t){return t?.keep?this.value:pc.toJS(this.value,e,t)}toString(){return String(this.value)}};G.BLOCK_FOLDED="BLOCK_FOLDED";G.BLOCK_LITERAL="BLOCK_LITERAL";G.PLAIN="PLAIN";G.QUOTE_DOUBLE="QUOTE_DOUBLE";G.QUOTE_SINGLE="QUOTE_SINGLE";qn.Scalar=G;qn.isScalarValue=mc});var je=y(Ur=>{"use strict";var hc=Re(),ae=_(),Yr=O(),gc="tag:yaml.org,2002:";function wc(n,e,t){if(e){let i=t.filter(s=>s.tag===e),r=i.find(s=>!s.format)??i[0];if(!r)throw new Error(`Tag ${e} not found`);return r}return t.find(i=>i.identify?.(n)&&!i.format)}function yc(n,e,t){if(ae.isDocument(n)&&(n=n.contents),ae.isNode(n))return n;if(ae.isPair(n)){let u=t.schema[ae.MAP].createNode?.(t.schema,null,t);return u.items.push(n),u}(n instanceof String||n instanceof Number||n instanceof Boolean||typeof BigInt<"u"&&n instanceof BigInt)&&(n=n.valueOf());let{aliasDuplicateObjects:i,onAnchor:r,onTagObj:s,schema:o,sourceObjects:a}=t,c;if(i&&n&&typeof n=="object"){if(c=a.get(n),c)return c.anchor??(c.anchor=r(n)),new hc.Alias(c.anchor);c={anchor:null,node:null},a.set(n,c)}e?.startsWith("!!")&&(e=gc+e.slice(2));let l=wc(n,e,o.tags);if(!l){if(n&&typeof n.toJSON=="function"&&(n=n.toJSON()),!n||typeof n!="object"){let u=new Yr.Scalar(n);return c&&(c.node=u),u}l=n instanceof Map?o[ae.MAP]:Symbol.iterator in Object(n)?o[ae.SEQ]:o[ae.MAP]}s&&(s(l),delete t.onTagObj);let m=l?.createNode?l.createNode(t.schema,n,t):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(t.schema,n,t):new Yr.Scalar(n);return e?m.tag=e:l.default||(m.tag=l.tag),c&&(c.node=m),m}Ur.createNode=yc});var Nt=y(Pt=>{"use strict";var vc=je(),F=_(),bc=Et();function Ln(n,e,t){let i=t;for(let r=e.length-1;r>=0;--r){let s=e[r];if(typeof s=="number"&&Number.isInteger(s)&&s>=0){let o=[];o[s]=i,i=o}else i=new Map([[s,i]])}return vc.createNode(i,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:n,sourceObjects:new Map})}var Jr=n=>n==null||typeof n=="object"&&!!n[Symbol.iterator]().next().done,Dn=class extends bc.NodeBase{constructor(e,t){super(e),Object.defineProperty(this,"schema",{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(t.schema=e),t.items=t.items.map(i=>F.isNode(i)||F.isPair(i)?i.clone(e):i),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(Jr(e))this.add(t);else{let[i,...r]=e,s=this.get(i,!0);if(F.isCollection(s))s.addIn(r,t);else if(s===void 0&&this.schema)this.set(i,Ln(this.schema,r,t));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${r}`)}}deleteIn(e){let[t,...i]=e;if(i.length===0)return this.delete(t);let r=this.get(t,!0);if(F.isCollection(r))return r.deleteIn(i);throw new Error(`Expected YAML collection at ${t}. Remaining path: ${i}`)}getIn(e,t){let[i,...r]=e,s=this.get(i,!0);return r.length===0?!t&&F.isScalar(s)?s.value:s:F.isCollection(s)?s.getIn(r,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!F.isPair(t))return!1;let i=t.value;return i==null||e&&F.isScalar(i)&&i.value==null&&!i.commentBefore&&!i.comment&&!i.tag})}hasIn(e){let[t,...i]=e;if(i.length===0)return this.has(t);let r=this.get(t,!0);return F.isCollection(r)?r.hasIn(i):!1}setIn(e,t){let[i,...r]=e;if(r.length===0)this.set(i,t);else{let s=this.get(i,!0);if(F.isCollection(s))s.setIn(r,t);else if(s===void 0&&this.schema)this.set(i,Ln(this.schema,r,t));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${r}`)}}};Pt.Collection=Dn;Pt.collectionFromPath=Ln;Pt.isEmptyPath=Jr});var Te=y(Ot=>{"use strict";var kc=n=>n.replace(/^(?!$)(?: $)?/gm,"#");function $n(n,e){return/^\n+$/.test(n)?n.substring(1):e?n.replace(/^(?! *$)/gm,e):n}var Sc=(n,e,t)=>n.endsWith(` +var Ma=Object.create;var Cr=Object.defineProperty;var Fa=Object.getOwnPropertyDescriptor;var Ba=Object.getOwnPropertyNames;var Ka=Object.getPrototypeOf,Ya=Object.prototype.hasOwnProperty;var yt=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var y=(n,e)=>()=>{try{return e||n((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}};var Ua=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Ba(e))!Ya.call(n,r)&&r!==t&&Cr(n,r,{get:()=>e[r],enumerable:!(i=Fa(e,r))||i.enumerable});return n};var Nn=(n,e,t)=>(t=n!=null?Ma(Ka(n)):{},Ua(e||!n||!n.__esModule?Cr(t,"default",{value:n,enumerable:!0}):t,n));var _=y(j=>{"use strict";var On=Symbol.for("yaml.alias"),Er=Symbol.for("yaml.document"),vt=Symbol.for("yaml.map"),_r=Symbol.for("yaml.pair"),xn=Symbol.for("yaml.scalar"),bt=Symbol.for("yaml.seq"),B=Symbol.for("yaml.node.type"),Ja=n=>!!n&&typeof n=="object"&&n[B]===On,Va=n=>!!n&&typeof n=="object"&&n[B]===Er,Ha=n=>!!n&&typeof n=="object"&&n[B]===vt,Ga=n=>!!n&&typeof n=="object"&&n[B]===_r,Pr=n=>!!n&&typeof n=="object"&&n[B]===xn,za=n=>!!n&&typeof n=="object"&&n[B]===bt;function Nr(n){if(n&&typeof n=="object")switch(n[B]){case vt:case bt:return!0}return!1}function Qa(n){if(n&&typeof n=="object")switch(n[B]){case On:case vt:case xn:case bt:return!0}return!1}var Xa=n=>(Pr(n)||Nr(n))&&!!n.anchor;j.ALIAS=On;j.DOC=Er;j.MAP=vt;j.NODE_TYPE=B;j.PAIR=_r;j.SCALAR=xn;j.SEQ=bt;j.hasAnchor=Xa;j.isAlias=Ja;j.isCollection=Nr;j.isDocument=Va;j.isMap=Ha;j.isNode=Qa;j.isPair=Ga;j.isScalar=Pr;j.isSeq=za});var Oe=y(An=>{"use strict";var R=_(),T=Symbol("break visit"),Or=Symbol("skip children"),M=Symbol("remove node");function kt(n,e){let t=xr(e);R.isDocument(n)?he(null,n.contents,t,Object.freeze([n]))===M&&(n.contents=null):he(null,n,t,Object.freeze([]))}kt.BREAK=T;kt.SKIP=Or;kt.REMOVE=M;function he(n,e,t,i){let r=Ar(n,e,t,i);if(R.isNode(r)||R.isPair(r))return Ir(n,i,r),he(n,r,t,i);if(typeof r!="symbol"){if(R.isCollection(e)){i=Object.freeze(i.concat(e));for(let s=0;s{"use strict";var Rr=_(),Za=Oe(),ec={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},tc=n=>n.replace(/[!,[\]{}]/g,e=>ec[e]),xe=class n{constructor(e,t){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},n.defaultYaml,e),this.tags=Object.assign({},n.defaultTags,t)}clone(){let e=new n(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){let e=new n(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:n.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},n.defaultTags);break}return e}add(e,t){this.atNextDocument&&(this.yaml={explicit:n.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},n.defaultTags),this.atNextDocument=!1);let i=e.trim().split(/[ \t]+/),r=i.shift();switch(r){case"%TAG":{if(i.length!==2&&(t(0,"%TAG directive should contain exactly two parts"),i.length<2))return!1;let[s,o]=i;return this.tags[s]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,i.length!==1)return t(0,"%YAML directive should contain exactly one part"),!1;let[s]=i;if(s==="1.1"||s==="1.2")return this.yaml.version=s,!0;{let o=/^\d+\.\d+$/.test(s);return t(6,`Unsupported YAML version ${s}`,o),!1}}default:return t(0,`Unknown directive ${r}`,!0),!1}}tagName(e,t){if(e==="!")return"!";if(e[0]!=="!")return t(`Not a valid tag: ${e}`),null;if(e[1]==="<"){let o=e.slice(2,-1);return o==="!"||o==="!!"?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&t("Verbatim tags must end with a >"),o)}let[,i,r]=e.match(/^(.*!)([^!]*)$/s);r||t(`The ${e} tag has no suffix`);let s=this.tags[i];if(s)try{return s+decodeURIComponent(r)}catch(o){return t(String(o)),null}return i==="!"?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[t,i]of Object.entries(this.tags))if(e.startsWith(i))return t+tc(e.substring(i.length));return e[0]==="!"?e:`!<${e}>`}toString(e){let t=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],i=Object.entries(this.tags),r;if(e&&i.length>0&&Rr.isNode(e.contents)){let s={};Za.visit(e.contents,(o,a)=>{Rr.isNode(a)&&a.tag&&(s[a.tag]=!0)}),r=Object.keys(s)}else r=[];for(let[s,o]of i)s==="!!"&&o==="tag:yaml.org,2002:"||(!e||r.some(a=>a.startsWith(o)))&&t.push(`%TAG ${s} ${o}`);return t.join(` +`)}};xe.defaultYaml={explicit:!1,version:"1.2"};xe.defaultTags={"!!":"tag:yaml.org,2002:"};jr.Directives=xe});var Ct=y(Ae=>{"use strict";var Tr=_(),nc=Oe();function ic(n){if(/[\x00-\x19\s,[\]{}]/.test(n)){let t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(n)}`;throw new Error(t)}return!0}function qr(n){let e=new Set;return nc.visit(n,{Value(t,i){i.anchor&&e.add(i.anchor)}}),e}function Lr(n,e){for(let t=1;;++t){let i=`${n}${t}`;if(!e.has(i))return i}}function rc(n,e){let t=[],i=new Map,r=null;return{onAnchor:s=>{t.push(s),r??(r=qr(n));let o=Lr(e,r);return r.add(o),o},setAnchors:()=>{for(let s of t){let o=i.get(s);if(typeof o=="object"&&o.anchor&&(Tr.isScalar(o.node)||Tr.isCollection(o.node)))o.node.anchor=o.anchor;else{let a=new Error("Failed to resolve repeated object (this should not happen)");throw a.source=s,a}}},sourceObjects:i}}Ae.anchorIsValid=ic;Ae.anchorNames=qr;Ae.createNodeAnchors=rc;Ae.findNewAnchor=Lr});var Rn=y(Dr=>{"use strict";function Ie(n,e,t,i){if(i&&typeof i=="object")if(Array.isArray(i))for(let r=0,s=i.length;r{"use strict";var sc=_();function $r(n,e,t){if(Array.isArray(n))return n.map((i,r)=>$r(i,String(r),t));if(n&&typeof n.toJSON=="function"){if(!t||!sc.hasAnchor(n))return n.toJSON(e,t);let i={aliasCount:0,count:1,res:void 0};t.anchors.set(n,i),t.onCreate=s=>{i.res=s,delete t.onCreate};let r=n.toJSON(e,t);return t.onCreate&&t.onCreate(r),r}return typeof n=="bigint"&&!t?.keep?Number(n):n}Wr.toJS=$r});var Et=y(Fr=>{"use strict";var oc=Rn(),Mr=_(),ac=V(),jn=class{constructor(e){Object.defineProperty(this,Mr.NODE_TYPE,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:t,maxAliasCount:i,onAnchor:r,reviver:s}={}){if(!Mr.isDocument(e))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:e,keep:!0,mapAsMap:t===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},a=ac.toJS(this,"",o);if(typeof r=="function")for(let{count:c,res:l}of o.anchors.values())r(l,c);return typeof s=="function"?oc.applyReviver(s,{"":a},"",a):a}};Fr.NodeBase=jn});var Re=y(Br=>{"use strict";var cc=Ct(),lc=Oe(),we=_(),uc=Et(),fc=V(),Tn=class extends uc.NodeBase{constructor(e){super(we.ALIAS),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,t){if(t?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let i;t?.aliasResolveCache?i=t.aliasResolveCache:(i=[],lc.visit(e,{Node:(s,o)=>{(we.isAlias(o)||we.hasAnchor(o))&&i.push(o)}}),t&&(t.aliasResolveCache=i));let r;for(let s of i){if(s===this)break;s.anchor===this.source&&(r=s)}return r}toJSON(e,t){if(!t)return{source:this.source};let{anchors:i,doc:r,maxAliasCount:s}=t,o=this.resolve(r,t);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let a=i.get(o);if(a||(fc.toJS(o,null,t),a=i.get(o)),a?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(s>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=_t(r,o,i)),a.count*a.aliasCount>s)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return a.res}toString(e,t,i){let r=`*${this.source}`;if(e){if(cc.anchorIsValid(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let s=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(s)}if(e.implicitKey)return`${r} `}return r}};function _t(n,e,t){if(we.isAlias(e)){let i=e.resolve(n),r=t&&i&&t.get(i);return r?r.count*r.aliasCount:0}else if(we.isCollection(e)){let i=0;for(let r of e.items){let s=_t(n,r,t);s>i&&(i=s)}return i}else if(we.isPair(e)){let i=_t(n,e.key,t),r=_t(n,e.value,t);return Math.max(i,r)}return 1}Br.Alias=Tn});var O=y(qn=>{"use strict";var dc=_(),pc=Et(),mc=V(),hc=n=>!n||typeof n!="function"&&typeof n!="object",H=class extends pc.NodeBase{constructor(e){super(dc.SCALAR),this.value=e}toJSON(e,t){return t?.keep?this.value:mc.toJS(this.value,e,t)}toString(){return String(this.value)}};H.BLOCK_FOLDED="BLOCK_FOLDED";H.BLOCK_LITERAL="BLOCK_LITERAL";H.PLAIN="PLAIN";H.QUOTE_DOUBLE="QUOTE_DOUBLE";H.QUOTE_SINGLE="QUOTE_SINGLE";qn.Scalar=H;qn.isScalarValue=hc});var je=y(Yr=>{"use strict";var gc=Re(),oe=_(),Kr=O(),wc="tag:yaml.org,2002:";function yc(n,e,t){if(e){let i=t.filter(s=>s.tag===e),r=i.find(s=>!s.format)??i[0];if(!r)throw new Error(`Tag ${e} not found`);return r}return t.find(i=>i.identify?.(n)&&!i.format)}function vc(n,e,t){if(oe.isDocument(n)&&(n=n.contents),oe.isNode(n))return n;if(oe.isPair(n)){let u=t.schema[oe.MAP].createNode?.(t.schema,null,t);return u.items.push(n),u}(n instanceof String||n instanceof Number||n instanceof Boolean||typeof BigInt<"u"&&n instanceof BigInt)&&(n=n.valueOf());let{aliasDuplicateObjects:i,onAnchor:r,onTagObj:s,schema:o,sourceObjects:a}=t,c;if(i&&n&&typeof n=="object"){if(c=a.get(n),c)return c.anchor??(c.anchor=r(n)),new gc.Alias(c.anchor);c={anchor:null,node:null},a.set(n,c)}e?.startsWith("!!")&&(e=wc+e.slice(2));let l=yc(n,e,o.tags);if(!l){if(n&&typeof n.toJSON=="function"&&(n=n.toJSON()),!n||typeof n!="object"){let u=new Kr.Scalar(n);return c&&(c.node=u),u}l=n instanceof Map?o[oe.MAP]:Symbol.iterator in Object(n)?o[oe.SEQ]:o[oe.MAP]}s&&(s(l),delete t.onTagObj);let m=l?.createNode?l.createNode(t.schema,n,t):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(t.schema,n,t):new Kr.Scalar(n);return e?m.tag=e:l.default||(m.tag=l.tag),c&&(c.node=m),m}Yr.createNode=vc});var Nt=y(Pt=>{"use strict";var bc=je(),F=_(),kc=Et();function Ln(n,e,t){let i=t;for(let r=e.length-1;r>=0;--r){let s=e[r];if(typeof s=="number"&&Number.isInteger(s)&&s>=0){let o=[];o[s]=i,i=o}else i=new Map([[s,i]])}return bc.createNode(i,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:n,sourceObjects:new Map})}var Ur=n=>n==null||typeof n=="object"&&!!n[Symbol.iterator]().next().done,Dn=class extends kc.NodeBase{constructor(e,t){super(e),Object.defineProperty(this,"schema",{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(t.schema=e),t.items=t.items.map(i=>F.isNode(i)||F.isPair(i)?i.clone(e):i),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(Ur(e))this.add(t);else{let[i,...r]=e,s=this.get(i,!0);if(F.isCollection(s))s.addIn(r,t);else if(s===void 0&&this.schema)this.set(i,Ln(this.schema,r,t));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${r}`)}}deleteIn(e){let[t,...i]=e;if(i.length===0)return this.delete(t);let r=this.get(t,!0);if(F.isCollection(r))return r.deleteIn(i);throw new Error(`Expected YAML collection at ${t}. Remaining path: ${i}`)}getIn(e,t){let[i,...r]=e,s=this.get(i,!0);return r.length===0?!t&&F.isScalar(s)?s.value:s:F.isCollection(s)?s.getIn(r,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!F.isPair(t))return!1;let i=t.value;return i==null||e&&F.isScalar(i)&&i.value==null&&!i.commentBefore&&!i.comment&&!i.tag})}hasIn(e){let[t,...i]=e;if(i.length===0)return this.has(t);let r=this.get(t,!0);return F.isCollection(r)?r.hasIn(i):!1}setIn(e,t){let[i,...r]=e;if(r.length===0)this.set(i,t);else{let s=this.get(i,!0);if(F.isCollection(s))s.setIn(r,t);else if(s===void 0&&this.schema)this.set(i,Ln(this.schema,r,t));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${r}`)}}};Pt.Collection=Dn;Pt.collectionFromPath=Ln;Pt.isEmptyPath=Ur});var Te=y(Ot=>{"use strict";var Sc=n=>n.replace(/^(?!$)(?: $)?/gm,"#");function $n(n,e){return/^\n+$/.test(n)?n.substring(1):e?n.replace(/^(?! *$)/gm,e):n}var Cc=(n,e,t)=>n.endsWith(` `)?$n(t,e):t.includes(` `)?` -`+$n(t,e):(n.endsWith(" ")?"":" ")+t;Ot.indentComment=$n;Ot.lineComment=Sc;Ot.stringifyComment=kc});var Hr=y(qe=>{"use strict";var Cc="flow",Wn="block",xt="quoted";function Ec(n,e,t="flow",{indentAtStart:i,lineWidth:r=80,minContentWidth:s=20,onFold:o,onOverflow:a}={}){if(!r||r<0)return n;rr-Math.max(2,s)?l.push(0):u=r-i);let d,h,w=!1,f=-1,p=-1,g=-1;t===Wn&&(f=Vr(n,f,e.length),f!==-1&&(u=f+c));for(let k;k=n[f+=1];){if(t===xt&&k==="\\"){switch(p=f,n[f+1]){case"x":f+=3;break;case"u":f+=5;break;case"U":f+=9;break;default:f+=1}g=f}if(k===` -`)t===Wn&&(f=Vr(n,f,e.length)),u=f+e.length+c,d=void 0;else{if(k===" "&&h&&h!==" "&&h!==` +`+$n(t,e):(n.endsWith(" ")?"":" ")+t;Ot.indentComment=$n;Ot.lineComment=Cc;Ot.stringifyComment=Sc});var Vr=y(qe=>{"use strict";var Ec="flow",Wn="block",xt="quoted";function _c(n,e,t="flow",{indentAtStart:i,lineWidth:r=80,minContentWidth:s=20,onFold:o,onOverflow:a}={}){if(!r||r<0)return n;rr-Math.max(2,s)?l.push(0):u=r-i);let d,h,w=!1,f=-1,p=-1,g=-1;t===Wn&&(f=Jr(n,f,e.length),f!==-1&&(u=f+c));for(let k;k=n[f+=1];){if(t===xt&&k==="\\"){switch(p=f,n[f+1]){case"x":f+=3;break;case"u":f+=5;break;case"U":f+=9;break;default:f+=1}g=f}if(k===` +`)t===Wn&&(f=Jr(n,f,e.length)),u=f+e.length+c,d=void 0;else{if(k===" "&&h&&h!==" "&&h!==` `&&h!==" "){let S=n[f+1];S&&S!==" "&&S!==` `&&S!==" "&&(d=f)}if(f>=u)if(d)l.push(d),u=d+c,d=void 0;else if(t===xt){for(;h===" "||h===" ";)h=k,k=n[f+=1],w=!0;let S=f>g+1?f-2:p-1;if(m[S])return n;l.push(S),m[S]=!0,u=S+c,d=void 0}else w=!0}h=k}if(w&&a&&a(),l.length===0)return n;o&&o();let v=n.slice(0,l[0]);for(let k=0;k{"use strict";var $=O(),z=Hr(),It=(n,e)=>({indentAtStart:e?n.indent.length:n.indentAtStart,lineWidth:n.options.lineWidth,minContentWidth:n.options.minContentWidth}),Rt=n=>/^(%|---|\.\.\.)/m.test(n);function _c(n,e,t){if(!e||e<0)return!1;let i=e-t,r=n.length;if(r<=i)return!1;for(let s=0,o=0;s{"use strict";var D=O(),G=Vr(),It=(n,e)=>({indentAtStart:e?n.indent.length:n.indentAtStart,lineWidth:n.options.lineWidth,minContentWidth:n.options.minContentWidth}),Rt=n=>/^(%|---|\.\.\.)/m.test(n);function Pc(n,e,t){if(!e||e<0)return!1;let i=e-t,r=n.length;if(r<=i)return!1;for(let s=0,o=0;si)return!0;if(o=s+1,r-o<=i)return!1}return!0}function Le(n,e){let t=JSON.stringify(n);if(e.options.doubleQuotedAsJSON)return t;let{implicitKey:i}=e,r=e.options.doubleQuotedMinMultiLineLength,s=e.indent||(Rt(n)?" ":""),o="",a=0;for(let c=0,l=t[c];l;l=t[++c])if(l===" "&&t[c+1]==="\\"&&t[c+2]==="n"&&(o+=t.slice(a,c)+"\\ ",c+=1,a=c,l="\\"),l==="\\")switch(t[c+1]){case"u":{o+=t.slice(a,c);let m=t.substr(c+2,4);switch(m){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:m.substr(0,2)==="00"?o+="\\x"+m.substr(2):o+=t.substr(c,6)}c+=5,a=c+1}break;case"n":if(i||t[c+2]==='"'||t.length `;let u,d;for(d=t.length;d>0;--d){let C=t[d-1];if(C!==` `&&C!==" "&&C!==" ")break}let h=t.substring(d),w=h.indexOf(` `);w===-1?u="-":t===h||w!==h.length-1?(u="+",s&&s()):u="",h&&(t=t.slice(0,-h.length),h[h.length-1]===` `&&(h=h.slice(0,-1)),h=h.replace(Fn,`$&${l}`));let f=!1,p,g=-1;for(p=0;p{E=!0});let b=z.foldFlowLines(`${v}${C}${h}`,l,z.FOLD_BLOCK,N);if(!E)return`>${S} +$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),E=!1,N=It(i,!0);o!=="folded"&&e!==D.Scalar.BLOCK_FOLDED&&(N.onOverflow=()=>{E=!0});let b=G.foldFlowLines(`${v}${C}${h}`,l,G.FOLD_BLOCK,N);if(!E)return`>${S} ${l}${b}`}return t=t.replace(/\n+/g,`$&${l}`),`|${S} -${l}${v}${t}${h}`}function Pc(n,e,t,i){let{type:r,value:s}=n,{actualString:o,implicitKey:a,indent:c,indentStep:l,inFlow:m}=e;if(a&&s.includes(` -`)||m&&/[[\]{},]/.test(s))return ve(s,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(s))return a||m||!s.includes(` -`)?ve(s,e):At(n,e,t,i);if(!a&&!m&&r!==$.Scalar.PLAIN&&s.includes(` -`))return At(n,e,t,i);if(Rt(s)){if(c==="")return e.forceBlockIndent=!0,At(n,e,t,i);if(a&&c===l)return ve(s,e)}let u=s.replace(/\n+/g,`$& -${c}`);if(o){let d=f=>f.default&&f.tag!=="tag:yaml.org,2002:str"&&f.test?.test(u),{compat:h,tags:w}=e.doc.schema;if(w.some(d)||h?.some(d))return ve(s,e)}return a?u:z.foldFlowLines(u,c,z.FOLD_FLOW,It(e,!1))}function Nc(n,e,t,i){let{implicitKey:r,inFlow:s}=e,o=typeof n.value=="string"?n:Object.assign({},n,{value:String(n.value)}),{type:a}=n;a!==$.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=$.Scalar.QUOTE_DOUBLE);let c=m=>{switch(m){case $.Scalar.BLOCK_FOLDED:case $.Scalar.BLOCK_LITERAL:return r||s?ve(o.value,e):At(o,e,t,i);case $.Scalar.QUOTE_DOUBLE:return Le(o.value,e);case $.Scalar.QUOTE_SINGLE:return Mn(o.value,e);case $.Scalar.PLAIN:return Pc(o,e,t,i);default:return null}},l=c(a);if(l===null){let{defaultKeyType:m,defaultStringType:u}=e.options,d=r&&m||u;if(l=c(d),l===null)throw new Error(`Unsupported default string type ${d}`)}return l}Gr.stringifyString=Nc});var $e=y(Bn=>{"use strict";var Oc=Ct(),Q=_(),xc=Te(),Ac=De();function Ic(n,e){let t=Object.assign({blockQuote:!0,commentString:xc.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},n.schema.toStringOptions,e),i;switch(t.collectionStyle){case"block":i=!1;break;case"flow":i=!0;break;default:i=null}return{anchors:new Set,doc:n,flowCollectionPadding:t.flowCollectionPadding?" ":"",indent:"",indentStep:typeof t.indent=="number"?" ".repeat(t.indent):" ",inFlow:i,options:t}}function Rc(n,e){if(e.tag){let r=n.filter(s=>s.tag===e.tag);if(r.length>0)return r.find(s=>s.format===e.format)??r[0]}let t,i;if(Q.isScalar(e)){i=e.value;let r=n.filter(s=>s.identify?.(i));if(r.length>1){let s=r.filter(o=>o.test);s.length>0&&(r=s)}t=r.find(s=>s.format===e.format)??r.find(s=>!s.format)}else i=e,t=n.find(r=>r.nodeClass&&i instanceof r.nodeClass);if(!t){let r=i?.constructor?.name??(i===null?"null":typeof i);throw new Error(`Tag not resolved for ${r} value`)}return t}function jc(n,e,{anchors:t,doc:i}){if(!i.directives)return"";let r=[],s=(Q.isScalar(n)||Q.isCollection(n))&&n.anchor;s&&Oc.anchorIsValid(s)&&(t.add(s),r.push(`&${s}`));let o=n.tag??(e.default?null:e.tag);return o&&r.push(i.directives.tagString(o)),r.join(" ")}function Tc(n,e,t,i){if(Q.isPair(n))return n.toString(e,t,i);if(Q.isAlias(n)){if(e.doc.directives)return n.toString(e);if(e.resolvedAliases?.has(n))throw new TypeError("Cannot stringify circular structure without alias nodes");e.resolvedAliases?e.resolvedAliases.add(n):e.resolvedAliases=new Set([n]),n=n.resolve(e.doc)}let r,s=Q.isNode(n)?n:e.doc.createNode(n,{onTagObj:c=>r=c});r??(r=Rc(e.doc.schema.tags,s));let o=jc(s,r,e);o.length>0&&(e.indentAtStart=(e.indentAtStart??0)+o.length+1);let a=typeof r.stringify=="function"?r.stringify(s,e,t,i):Q.isScalar(s)?Ac.stringifyString(s,e,t,i):s.toString(e,t,i);return o?Q.isScalar(s)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o} -${e.indent}${a}`:a}Bn.createStringifyContext=Ic;Bn.stringify=Tc});var Zr=y(Xr=>{"use strict";var K=_(),zr=O(),Qr=$e(),We=Te();function qc({key:n,value:e},t,i,r){let{allNullValues:s,doc:o,indent:a,indentStep:c,options:{commentString:l,indentSeq:m,simpleKeys:u}}=t,d=K.isNode(n)&&n.comment||null;if(u){if(d)throw new Error("With simple keys, key nodes cannot have comments");if(K.isCollection(n)||!K.isNode(n)&&typeof n=="object"){let N="With simple keys, collection cannot be used as a key value";throw new Error(N)}}let h=!u&&(!n||d&&e==null&&!t.inFlow||K.isCollection(n)||(K.isScalar(n)?n.type===zr.Scalar.BLOCK_FOLDED||n.type===zr.Scalar.BLOCK_LITERAL:typeof n=="object"));t=Object.assign({},t,{allNullValues:!1,implicitKey:!h&&(u||!s),indent:a+c});let w=!1,f=!1,p=Qr.stringify(n,t,()=>w=!0,()=>f=!0);if(!h&&!t.inFlow&&p.length>1024){if(u)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");h=!0}if(t.inFlow){if(s||e==null)return w&&i&&i(),p===""?"?":h?`? ${p}`:p}else if(s&&!u||e==null&&h)return p=`? ${p}`,d&&!w?p+=We.lineComment(p,t.indent,l(d)):f&&r&&r(),p;w&&(d=null),h?(d&&(p+=We.lineComment(p,t.indent,l(d))),p=`? ${p} -${a}:`):(p=`${p}:`,d&&(p+=We.lineComment(p,t.indent,l(d))));let g,v,k;K.isNode(e)?(g=!!e.spaceBefore,v=e.commentBefore,k=e.comment):(g=!1,v=null,k=null,e&&typeof e=="object"&&(e=o.createNode(e))),t.implicitKey=!1,!h&&!d&&K.isScalar(e)&&(t.indentAtStart=p.length+1),f=!1,!m&&c.length>=2&&!t.inFlow&&!h&&K.isSeq(e)&&!e.flow&&!e.tag&&!e.anchor&&(t.indent=t.indent.substring(2));let S=!1,C=Qr.stringify(e,t,()=>S=!0,()=>f=!0),E=" ";if(d||g||v){if(E=g?` +${l}${v}${t}${h}`}function Nc(n,e,t,i){let{type:r,value:s}=n,{actualString:o,implicitKey:a,indent:c,indentStep:l,inFlow:m}=e;if(a&&s.includes(` +`)||m&&/[[\]{},]/.test(s))return ye(s,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(s))return a||m||!s.includes(` +`)?ye(s,e):At(n,e,t,i);if(!a&&!m&&r!==D.Scalar.PLAIN&&s.includes(` +`))return At(n,e,t,i);if(Rt(s)){if(c==="")return e.forceBlockIndent=!0,At(n,e,t,i);if(a&&c===l)return ye(s,e)}let u=s.replace(/\n+/g,`$& +${c}`);if(o){let d=f=>f.default&&f.tag!=="tag:yaml.org,2002:str"&&f.test?.test(u),{compat:h,tags:w}=e.doc.schema;if(w.some(d)||h?.some(d))return ye(s,e)}return a?u:G.foldFlowLines(u,c,G.FOLD_FLOW,It(e,!1))}function Oc(n,e,t,i){let{implicitKey:r,inFlow:s}=e,o=typeof n.value=="string"?n:Object.assign({},n,{value:String(n.value)}),{type:a}=n;a!==D.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=D.Scalar.QUOTE_DOUBLE);let c=m=>{switch(m){case D.Scalar.BLOCK_FOLDED:case D.Scalar.BLOCK_LITERAL:return r||s?ye(o.value,e):At(o,e,t,i);case D.Scalar.QUOTE_DOUBLE:return Le(o.value,e);case D.Scalar.QUOTE_SINGLE:return Mn(o.value,e);case D.Scalar.PLAIN:return Nc(o,e,t,i);default:return null}},l=c(a);if(l===null){let{defaultKeyType:m,defaultStringType:u}=e.options,d=r&&m||u;if(l=c(d),l===null)throw new Error(`Unsupported default string type ${d}`)}return l}Hr.stringifyString=Oc});var $e=y(Bn=>{"use strict";var xc=Ct(),z=_(),Ac=Te(),Ic=De();function Rc(n,e){let t=Object.assign({blockQuote:!0,commentString:Ac.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},n.schema.toStringOptions,e),i;switch(t.collectionStyle){case"block":i=!1;break;case"flow":i=!0;break;default:i=null}return{anchors:new Set,doc:n,flowCollectionPadding:t.flowCollectionPadding?" ":"",indent:"",indentStep:typeof t.indent=="number"?" ".repeat(t.indent):" ",inFlow:i,options:t}}function jc(n,e){if(e.tag){let r=n.filter(s=>s.tag===e.tag);if(r.length>0)return r.find(s=>s.format===e.format)??r[0]}let t,i;if(z.isScalar(e)){i=e.value;let r=n.filter(s=>s.identify?.(i));if(r.length>1){let s=r.filter(o=>o.test);s.length>0&&(r=s)}t=r.find(s=>s.format===e.format)??r.find(s=>!s.format)}else i=e,t=n.find(r=>r.nodeClass&&i instanceof r.nodeClass);if(!t){let r=i?.constructor?.name??(i===null?"null":typeof i);throw new Error(`Tag not resolved for ${r} value`)}return t}function Tc(n,e,{anchors:t,doc:i}){if(!i.directives)return"";let r=[],s=(z.isScalar(n)||z.isCollection(n))&&n.anchor;s&&xc.anchorIsValid(s)&&(t.add(s),r.push(`&${s}`));let o=n.tag??(e.default?null:e.tag);return o&&r.push(i.directives.tagString(o)),r.join(" ")}function qc(n,e,t,i){if(z.isPair(n))return n.toString(e,t,i);if(z.isAlias(n)){if(e.doc.directives)return n.toString(e);if(e.resolvedAliases?.has(n))throw new TypeError("Cannot stringify circular structure without alias nodes");e.resolvedAliases?e.resolvedAliases.add(n):e.resolvedAliases=new Set([n]),n=n.resolve(e.doc)}let r,s=z.isNode(n)?n:e.doc.createNode(n,{onTagObj:c=>r=c});r??(r=jc(e.doc.schema.tags,s));let o=Tc(s,r,e);o.length>0&&(e.indentAtStart=(e.indentAtStart??0)+o.length+1);let a=typeof r.stringify=="function"?r.stringify(s,e,t,i):z.isScalar(s)?Ic.stringifyString(s,e,t,i):s.toString(e,t,i);return o?z.isScalar(s)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o} +${e.indent}${a}`:a}Bn.createStringifyContext=Rc;Bn.stringify=qc});var Xr=y(Qr=>{"use strict";var K=_(),Gr=O(),zr=$e(),We=Te();function Lc({key:n,value:e},t,i,r){let{allNullValues:s,doc:o,indent:a,indentStep:c,options:{commentString:l,indentSeq:m,simpleKeys:u}}=t,d=K.isNode(n)&&n.comment||null;if(u){if(d)throw new Error("With simple keys, key nodes cannot have comments");if(K.isCollection(n)||!K.isNode(n)&&typeof n=="object"){let N="With simple keys, collection cannot be used as a key value";throw new Error(N)}}let h=!u&&(!n||d&&e==null&&!t.inFlow||K.isCollection(n)||(K.isScalar(n)?n.type===Gr.Scalar.BLOCK_FOLDED||n.type===Gr.Scalar.BLOCK_LITERAL:typeof n=="object"));t=Object.assign({},t,{allNullValues:!1,implicitKey:!h&&(u||!s),indent:a+c});let w=!1,f=!1,p=zr.stringify(n,t,()=>w=!0,()=>f=!0);if(!h&&!t.inFlow&&p.length>1024){if(u)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");h=!0}if(t.inFlow){if(s||e==null)return w&&i&&i(),p===""?"?":h?`? ${p}`:p}else if(s&&!u||e==null&&h)return p=`? ${p}`,d&&!w?p+=We.lineComment(p,t.indent,l(d)):f&&r&&r(),p;w&&(d=null),h?(d&&(p+=We.lineComment(p,t.indent,l(d))),p=`? ${p} +${a}:`):(p=`${p}:`,d&&(p+=We.lineComment(p,t.indent,l(d))));let g,v,k;K.isNode(e)?(g=!!e.spaceBefore,v=e.commentBefore,k=e.comment):(g=!1,v=null,k=null,e&&typeof e=="object"&&(e=o.createNode(e))),t.implicitKey=!1,!h&&!d&&K.isScalar(e)&&(t.indentAtStart=p.length+1),f=!1,!m&&c.length>=2&&!t.inFlow&&!h&&K.isSeq(e)&&!e.flow&&!e.tag&&!e.anchor&&(t.indent=t.indent.substring(2));let S=!1,C=zr.stringify(e,t,()=>S=!0,()=>f=!0),E=" ";if(d||g||v){if(E=g?` `:"",v){let N=l(v);E+=` ${We.indentComment(N,t.indent)}`}C===""&&!t.inFlow?E===` `&&k&&(E=` `):E+=` ${t.indent}`}else if(!h&&K.isCollection(e)){let N=C[0],b=C.indexOf(` -`),A=b!==-1,V=t.inFlow??e.flow??e.items.length===0;if(A||!V){let he=!1;if(A&&(N==="&"||N==="!")){let I=C.indexOf(" ");N==="&"&&I!==-1&&I{"use strict";var es=yt("process");function Lc(n,...e){n==="debug"&&console.log(...e)}function Dc(n,e){(n==="debug"||n==="warn")&&(typeof es.emitWarning=="function"?es.emitWarning(e):console.warn(e))}Kn.debug=Lc;Kn.warn=Dc});var Dt=y(Lt=>{"use strict";var qt=_(),ts=O(),jt="<<",Tt={identify:n=>n===jt||typeof n=="symbol"&&n.description===jt,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new ts.Scalar(Symbol(jt)),{addToJSMap:ns}),stringify:()=>jt},$c=(n,e)=>(Tt.identify(e)||qt.isScalar(e)&&(!e.type||e.type===ts.Scalar.PLAIN)&&Tt.identify(e.value))&&n?.doc.schema.tags.some(t=>t.tag===Tt.tag&&t.default);function ns(n,e,t){let i=is(n,t);if(qt.isSeq(i))for(let r of i.items)Un(n,e,r);else if(Array.isArray(i))for(let r of i)Un(n,e,r);else Un(n,e,i)}function Un(n,e,t){let i=is(n,t);if(!qt.isMap(i))throw new Error("Merge sources must be maps or map aliases");let r=i.toJSON(null,n,Map);for(let[s,o]of r)e instanceof Map?e.has(s)||e.set(s,o):e instanceof Set?e.add(s):Object.prototype.hasOwnProperty.call(e,s)||Object.defineProperty(e,s,{value:o,writable:!0,enumerable:!0,configurable:!0});return e}function is(n,e){return n&&qt.isAlias(e)?e.resolve(n.doc,n):e}Lt.addMergeToJSMap=ns;Lt.isMergeKey=$c;Lt.merge=Tt});var Vn=y(os=>{"use strict";var Wc=Yn(),rs=Dt(),Mc=$e(),ss=_(),Jn=H();function Fc(n,e,{key:t,value:i}){if(ss.isNode(t)&&t.addToJSMap)t.addToJSMap(n,e,i);else if(rs.isMergeKey(n,t))rs.addMergeToJSMap(n,e,i);else{let r=Jn.toJS(t,"",n);if(e instanceof Map)e.set(r,Jn.toJS(i,r,n));else if(e instanceof Set)e.add(r);else{let s=Bc(t,r,n),o=Jn.toJS(i,s,n);s in e?Object.defineProperty(e,s,{value:o,writable:!0,enumerable:!0,configurable:!0}):e[s]=o}}return e}function Bc(n,e,t){if(e===null)return"";if(typeof e!="object")return String(e);if(ss.isNode(n)&&t?.doc){let i=Mc.createStringifyContext(t.doc,{});i.anchors=new Set;for(let s of t.anchors.keys())i.anchors.add(s.anchor);i.inFlow=!0,i.inStringifyKey=!0;let r=n.toString(i);if(!t.mapKeyWarned){let s=JSON.stringify(r);s.length>40&&(s=s.substring(0,36)+'..."'),Wc.warn(t.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${s}. Set mapAsMap: true to use object keys.`),t.mapKeyWarned=!0}return r}return JSON.stringify(e)}os.addPairToJSMap=Fc});var X=y(Hn=>{"use strict";var as=je(),Kc=Zr(),Yc=Vn(),$t=_();function Uc(n,e,t){let i=as.createNode(n,void 0,t),r=as.createNode(e,void 0,t);return new Wt(i,r)}var Wt=class n{constructor(e,t=null){Object.defineProperty(this,$t.NODE_TYPE,{value:$t.PAIR}),this.key=e,this.value=t}clone(e){let{key:t,value:i}=this;return $t.isNode(t)&&(t=t.clone(e)),$t.isNode(i)&&(i=i.clone(e)),new n(t,i)}toJSON(e,t){let i=t?.mapAsMap?new Map:{};return Yc.addPairToJSMap(t,i,this)}toString(e,t,i){return e?.doc?Kc.stringifyPair(this,e,t,i):JSON.stringify(this)}};Hn.Pair=Wt;Hn.createPair=Uc});var Gn=y(ls=>{"use strict";var ce=_(),cs=$e(),Mt=Te();function Jc(n,e,t){return(e.inFlow??n.flow?Hc:Vc)(n,e,t)}function Vc({comment:n,items:e},t,{blockItemPrefix:i,flowChars:r,itemIndent:s,onChompKeep:o,onComment:a}){let{indent:c,options:{commentString:l}}=t,m=Object.assign({},t,{indent:s,type:null}),u=!1,d=[];for(let w=0;wp=null,()=>u=!0);p&&(g+=Mt.lineComment(g,s,l(p))),u&&p&&(u=!1),d.push(i+g)}let h;if(d.length===0)h=r.start+r.end;else{h=d[0];for(let w=1;w{"use strict";var Zr=yt("process");function Dc(n,...e){n==="debug"&&console.log(...e)}function $c(n,e){(n==="debug"||n==="warn")&&(typeof Zr.emitWarning=="function"?Zr.emitWarning(e):console.warn(e))}Kn.debug=Dc;Kn.warn=$c});var Dt=y(Lt=>{"use strict";var qt=_(),es=O(),jt="<<",Tt={identify:n=>n===jt||typeof n=="symbol"&&n.description===jt,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new es.Scalar(Symbol(jt)),{addToJSMap:ts}),stringify:()=>jt},Wc=(n,e)=>(Tt.identify(e)||qt.isScalar(e)&&(!e.type||e.type===es.Scalar.PLAIN)&&Tt.identify(e.value))&&n?.doc.schema.tags.some(t=>t.tag===Tt.tag&&t.default);function ts(n,e,t){let i=ns(n,t);if(qt.isSeq(i))for(let r of i.items)Un(n,e,r);else if(Array.isArray(i))for(let r of i)Un(n,e,r);else Un(n,e,i)}function Un(n,e,t){let i=ns(n,t);if(!qt.isMap(i))throw new Error("Merge sources must be maps or map aliases");let r=i.toJSON(null,n,Map);for(let[s,o]of r)e instanceof Map?e.has(s)||e.set(s,o):e instanceof Set?e.add(s):Object.prototype.hasOwnProperty.call(e,s)||Object.defineProperty(e,s,{value:o,writable:!0,enumerable:!0,configurable:!0});return e}function ns(n,e){return n&&qt.isAlias(e)?e.resolve(n.doc,n):e}Lt.addMergeToJSMap=ts;Lt.isMergeKey=Wc;Lt.merge=Tt});var Vn=y(ss=>{"use strict";var Mc=Yn(),is=Dt(),Fc=$e(),rs=_(),Jn=V();function Bc(n,e,{key:t,value:i}){if(rs.isNode(t)&&t.addToJSMap)t.addToJSMap(n,e,i);else if(is.isMergeKey(n,t))is.addMergeToJSMap(n,e,i);else{let r=Jn.toJS(t,"",n);if(e instanceof Map)e.set(r,Jn.toJS(i,r,n));else if(e instanceof Set)e.add(r);else{let s=Kc(t,r,n),o=Jn.toJS(i,s,n);s in e?Object.defineProperty(e,s,{value:o,writable:!0,enumerable:!0,configurable:!0}):e[s]=o}}return e}function Kc(n,e,t){if(e===null)return"";if(typeof e!="object")return String(e);if(rs.isNode(n)&&t?.doc){let i=Fc.createStringifyContext(t.doc,{});i.anchors=new Set;for(let s of t.anchors.keys())i.anchors.add(s.anchor);i.inFlow=!0,i.inStringifyKey=!0;let r=n.toString(i);if(!t.mapKeyWarned){let s=JSON.stringify(r);s.length>40&&(s=s.substring(0,36)+'..."'),Mc.warn(t.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${s}. Set mapAsMap: true to use object keys.`),t.mapKeyWarned=!0}return r}return JSON.stringify(e)}ss.addPairToJSMap=Bc});var Q=y(Hn=>{"use strict";var os=je(),Yc=Xr(),Uc=Vn(),$t=_();function Jc(n,e,t){let i=os.createNode(n,void 0,t),r=os.createNode(e,void 0,t);return new Wt(i,r)}var Wt=class n{constructor(e,t=null){Object.defineProperty(this,$t.NODE_TYPE,{value:$t.PAIR}),this.key=e,this.value=t}clone(e){let{key:t,value:i}=this;return $t.isNode(t)&&(t=t.clone(e)),$t.isNode(i)&&(i=i.clone(e)),new n(t,i)}toJSON(e,t){let i=t?.mapAsMap?new Map:{};return Uc.addPairToJSMap(t,i,this)}toString(e,t,i){return e?.doc?Yc.stringifyPair(this,e,t,i):JSON.stringify(this)}};Hn.Pair=Wt;Hn.createPair=Jc});var Gn=y(cs=>{"use strict";var ae=_(),as=$e(),Mt=Te();function Vc(n,e,t){return(e.inFlow??n.flow?Gc:Hc)(n,e,t)}function Hc({comment:n,items:e},t,{blockItemPrefix:i,flowChars:r,itemIndent:s,onChompKeep:o,onComment:a}){let{indent:c,options:{commentString:l}}=t,m=Object.assign({},t,{indent:s,type:null}),u=!1,d=[];for(let w=0;wp=null,()=>u=!0);p&&(g+=Mt.lineComment(g,s,l(p))),u&&p&&(u=!1),d.push(i+g)}let h;if(d.length===0)h=r.start+r.end;else{h=d[0];for(let w=1;wp=null);l||(l=u.length>m||g.includes(` +`+Mt.indentComment(l(n),c),a&&a()):u&&o&&o(),h}function Gc({items:n},e,{flowChars:t,itemIndent:i}){let{indent:r,indentStep:s,flowCollectionPadding:o,options:{commentString:a}}=e;i+=s;let c=Object.assign({},e,{indent:i,inFlow:!0,type:null}),l=!1,m=0,u=[];for(let w=0;wp=null);l||(l=u.length>m||g.includes(` `)),w0&&(l||(l=u.reduce((v,k)=>v+k.length+2,2)+(g.length+2)>e.options.lineWidth)),l&&(g+=",")),p&&(g+=Mt.lineComment(g,i,a(p))),u.push(g),m=u.length}let{start:d,end:h}=t;if(u.length===0)return d+h;if(!l){let w=u.reduce((f,p)=>f+p.length+2,2);l=e.options.lineWidth>0&&w>e.options.lineWidth}if(l){let w=d;for(let f of u)w+=f?` ${s}${r}${f}`:` `;return`${w} -${r}${h}`}else return`${d}${o}${u.join(" ")}${o}${h}`}function Ft({indent:n,options:{commentString:e}},t,i,r){if(i&&r&&(i=i.replace(/^\n+/,"")),i){let s=Mt.indentComment(e(i),n);t.push(s.trimStart())}}ls.stringifyCollection=Jc});var ee=y(Qn=>{"use strict";var Gc=Gn(),zc=Vn(),Qc=Nt(),Z=_(),Bt=X(),Xc=O();function Me(n,e){let t=Z.isScalar(e)?e.value:e;for(let i of n)if(Z.isPair(i)&&(i.key===e||i.key===t||Z.isScalar(i.key)&&i.key.value===t))return i}var zn=class extends Qc.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(Z.MAP,e),this.items=[]}static from(e,t,i){let{keepUndefined:r,replacer:s}=i,o=new this(e),a=(c,l)=>{if(typeof s=="function")l=s.call(t,c,l);else if(Array.isArray(s)&&!s.includes(c))return;(l!==void 0||r)&&o.items.push(Bt.createPair(c,l,i))};if(t instanceof Map)for(let[c,l]of t)a(c,l);else if(t&&typeof t=="object")for(let c of Object.keys(t))a(c,t[c]);return typeof e.sortMapEntries=="function"&&o.items.sort(e.sortMapEntries),o}add(e,t){let i;Z.isPair(e)?i=e:!e||typeof e!="object"||!("key"in e)?i=new Bt.Pair(e,e?.value):i=new Bt.Pair(e.key,e.value);let r=Me(this.items,i.key),s=this.schema?.sortMapEntries;if(r){if(!t)throw new Error(`Key ${i.key} already set`);Z.isScalar(r.value)&&Xc.isScalarValue(i.value)?r.value.value=i.value:r.value=i.value}else if(s){let o=this.items.findIndex(a=>s(i,a)<0);o===-1?this.items.push(i):this.items.splice(o,0,i)}else this.items.push(i)}delete(e){let t=Me(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){let r=Me(this.items,e)?.value;return(!t&&Z.isScalar(r)?r.value:r)??void 0}has(e){return!!Me(this.items,e)}set(e,t){this.add(new Bt.Pair(e,t),!0)}toJSON(e,t,i){let r=i?new i:t?.mapAsMap?new Map:{};t?.onCreate&&t.onCreate(r);for(let s of this.items)zc.addPairToJSMap(t,r,s);return r}toString(e,t,i){if(!e)return JSON.stringify(this);for(let r of this.items)if(!Z.isPair(r))throw new Error(`Map items must all be pairs; found ${JSON.stringify(r)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),Gc.stringifyCollection(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:i,onComment:t})}};Qn.YAMLMap=zn;Qn.findPair=Me});var be=y(fs=>{"use strict";var Zc=_(),us=ee(),el={collection:"map",default:!0,nodeClass:us.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(n,e){return Zc.isMap(n)||e("Expected a mapping for this tag"),n},createNode:(n,e,t)=>us.YAMLMap.from(n,e,t)};fs.map=el});var te=y(ds=>{"use strict";var tl=je(),nl=Gn(),il=Nt(),Yt=_(),rl=O(),sl=H(),Xn=class extends il.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(Yt.SEQ,e),this.items=[]}add(e){this.items.push(e)}delete(e){let t=Kt(e);return typeof t!="number"?!1:this.items.splice(t,1).length>0}get(e,t){let i=Kt(e);if(typeof i!="number")return;let r=this.items[i];return!t&&Yt.isScalar(r)?r.value:r}has(e){let t=Kt(e);return typeof t=="number"&&t=0?e:null}ds.YAMLSeq=Xn});var ke=y(ms=>{"use strict";var ol=_(),ps=te(),al={collection:"seq",default:!0,nodeClass:ps.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(n,e){return ol.isSeq(n)||e("Expected a sequence for this tag"),n},createNode:(n,e,t)=>ps.YAMLSeq.from(n,e,t)};ms.seq=al});var Fe=y(hs=>{"use strict";var cl=De(),ll={identify:n=>typeof n=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:n=>n,stringify(n,e,t,i){return e=Object.assign({actualString:!0},e),cl.stringifyString(n,e,t,i)}};hs.string=ll});var Ut=y(ys=>{"use strict";var gs=O(),ws={identify:n=>n==null,createNode:()=>new gs.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new gs.Scalar(null),stringify:({source:n},e)=>typeof n=="string"&&ws.test.test(n)?n:e.options.nullStr};ys.nullTag=ws});var Zn=y(bs=>{"use strict";var ul=O(),vs={identify:n=>typeof n=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:n=>new ul.Scalar(n[0]==="t"||n[0]==="T"),stringify({source:n,value:e},t){if(n&&vs.test.test(n)){let i=n[0]==="t"||n[0]==="T";if(e===i)return n}return e?t.options.trueStr:t.options.falseStr}};bs.boolTag=vs});var Se=y(ks=>{"use strict";function fl({format:n,minFractionDigits:e,tag:t,value:i}){if(typeof i=="bigint")return String(i);let r=typeof i=="number"?i:Number(i);if(!isFinite(r))return isNaN(r)?".nan":r<0?"-.inf":".inf";let s=Object.is(i,-0)?"-0":JSON.stringify(i);if(!n&&e&&(!t||t==="tag:yaml.org,2002:float")&&/^-?\d/.test(s)&&!s.includes("e")){let o=s.indexOf(".");o<0&&(o=s.length,s+=".");let a=e-(s.length-o-1);for(;a-- >0;)s+="0"}return s}ks.stringifyNumber=fl});var ti=y(Jt=>{"use strict";var dl=O(),ei=Se(),pl={identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:n=>n.slice(-3).toLowerCase()==="nan"?NaN:n[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:ei.stringifyNumber},ml={identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:n=>parseFloat(n),stringify(n){let e=Number(n.value);return isFinite(e)?e.toExponential():ei.stringifyNumber(n)}},hl={identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(n){let e=new dl.Scalar(parseFloat(n)),t=n.indexOf(".");return t!==-1&&n[n.length-1]==="0"&&(e.minFractionDigits=n.length-t-1),e},stringify:ei.stringifyNumber};Jt.float=hl;Jt.floatExp=ml;Jt.floatNaN=pl});var ii=y(Ht=>{"use strict";var Ss=Se(),Vt=n=>typeof n=="bigint"||Number.isInteger(n),ni=(n,e,t,{intAsBigInt:i})=>i?BigInt(n):parseInt(n.substring(e),t);function Cs(n,e,t){let{value:i}=n;return Vt(i)&&i>=0?t+i.toString(e):Ss.stringifyNumber(n)}var gl={identify:n=>Vt(n)&&n>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(n,e,t)=>ni(n,2,8,t),stringify:n=>Cs(n,8,"0o")},wl={identify:Vt,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(n,e,t)=>ni(n,0,10,t),stringify:Ss.stringifyNumber},yl={identify:n=>Vt(n)&&n>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(n,e,t)=>ni(n,2,16,t),stringify:n=>Cs(n,16,"0x")};Ht.int=wl;Ht.intHex=yl;Ht.intOct=gl});var _s=y(Es=>{"use strict";var vl=be(),bl=Ut(),kl=ke(),Sl=Fe(),Cl=Zn(),ri=ti(),si=ii(),El=[vl.map,kl.seq,Sl.string,bl.nullTag,Cl.boolTag,si.intOct,si.int,si.intHex,ri.floatNaN,ri.floatExp,ri.float];Es.schema=El});var Os=y(Ns=>{"use strict";var _l=O(),Pl=be(),Nl=ke();function Ps(n){return typeof n=="bigint"||Number.isInteger(n)}var Gt=({value:n})=>JSON.stringify(n),Ol=[{identify:n=>typeof n=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:n=>n,stringify:Gt},{identify:n=>n==null,createNode:()=>new _l.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Gt},{identify:n=>typeof n=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:n=>n==="true",stringify:Gt},{identify:Ps,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(n,e,{intAsBigInt:t})=>t?BigInt(n):parseInt(n,10),stringify:({value:n})=>Ps(n)?n.toString():JSON.stringify(n)},{identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:n=>parseFloat(n),stringify:Gt}],xl={default:!0,tag:"",test:/^/,resolve(n,e){return e(`Unresolved plain scalar ${JSON.stringify(n)}`),n}},Al=[Pl.map,Nl.seq].concat(Ol,xl);Ns.schema=Al});var ai=y(xs=>{"use strict";var Be=yt("buffer"),oi=O(),Il=De(),Rl={identify:n=>n instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(n,e){if(typeof Be.Buffer=="function")return Be.Buffer.from(n,"base64");if(typeof atob=="function"){let t=atob(n.replace(/[\n\r]/g,"")),i=new Uint8Array(t.length);for(let r=0;r{"use strict";var zt=_(),ci=X(),jl=O(),Tl=te();function As(n,e){if(zt.isSeq(n))for(let t=0;t1&&e("Each pair must have its own sequence indicator");let r=i.items[0]||new ci.Pair(new jl.Scalar(null));if(i.commentBefore&&(r.key.commentBefore=r.key.commentBefore?`${i.commentBefore} +${r}${h}`}else return`${d}${o}${u.join(" ")}${o}${h}`}function Ft({indent:n,options:{commentString:e}},t,i,r){if(i&&r&&(i=i.replace(/^\n+/,"")),i){let s=Mt.indentComment(e(i),n);t.push(s.trimStart())}}cs.stringifyCollection=Vc});var Z=y(Qn=>{"use strict";var zc=Gn(),Qc=Vn(),Xc=Nt(),X=_(),Bt=Q(),Zc=O();function Me(n,e){let t=X.isScalar(e)?e.value:e;for(let i of n)if(X.isPair(i)&&(i.key===e||i.key===t||X.isScalar(i.key)&&i.key.value===t))return i}var zn=class extends Xc.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(X.MAP,e),this.items=[]}static from(e,t,i){let{keepUndefined:r,replacer:s}=i,o=new this(e),a=(c,l)=>{if(typeof s=="function")l=s.call(t,c,l);else if(Array.isArray(s)&&!s.includes(c))return;(l!==void 0||r)&&o.items.push(Bt.createPair(c,l,i))};if(t instanceof Map)for(let[c,l]of t)a(c,l);else if(t&&typeof t=="object")for(let c of Object.keys(t))a(c,t[c]);return typeof e.sortMapEntries=="function"&&o.items.sort(e.sortMapEntries),o}add(e,t){let i;X.isPair(e)?i=e:!e||typeof e!="object"||!("key"in e)?i=new Bt.Pair(e,e?.value):i=new Bt.Pair(e.key,e.value);let r=Me(this.items,i.key),s=this.schema?.sortMapEntries;if(r){if(!t)throw new Error(`Key ${i.key} already set`);X.isScalar(r.value)&&Zc.isScalarValue(i.value)?r.value.value=i.value:r.value=i.value}else if(s){let o=this.items.findIndex(a=>s(i,a)<0);o===-1?this.items.push(i):this.items.splice(o,0,i)}else this.items.push(i)}delete(e){let t=Me(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){let r=Me(this.items,e)?.value;return(!t&&X.isScalar(r)?r.value:r)??void 0}has(e){return!!Me(this.items,e)}set(e,t){this.add(new Bt.Pair(e,t),!0)}toJSON(e,t,i){let r=i?new i:t?.mapAsMap?new Map:{};t?.onCreate&&t.onCreate(r);for(let s of this.items)Qc.addPairToJSMap(t,r,s);return r}toString(e,t,i){if(!e)return JSON.stringify(this);for(let r of this.items)if(!X.isPair(r))throw new Error(`Map items must all be pairs; found ${JSON.stringify(r)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),zc.stringifyCollection(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:i,onComment:t})}};Qn.YAMLMap=zn;Qn.findPair=Me});var ve=y(us=>{"use strict";var el=_(),ls=Z(),tl={collection:"map",default:!0,nodeClass:ls.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(n,e){return el.isMap(n)||e("Expected a mapping for this tag"),n},createNode:(n,e,t)=>ls.YAMLMap.from(n,e,t)};us.map=tl});var ee=y(fs=>{"use strict";var nl=je(),il=Gn(),rl=Nt(),Yt=_(),sl=O(),ol=V(),Xn=class extends rl.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(Yt.SEQ,e),this.items=[]}add(e){this.items.push(e)}delete(e){let t=Kt(e);return typeof t!="number"?!1:this.items.splice(t,1).length>0}get(e,t){let i=Kt(e);if(typeof i!="number")return;let r=this.items[i];return!t&&Yt.isScalar(r)?r.value:r}has(e){let t=Kt(e);return typeof t=="number"&&t=0?e:null}fs.YAMLSeq=Xn});var be=y(ps=>{"use strict";var al=_(),ds=ee(),cl={collection:"seq",default:!0,nodeClass:ds.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(n,e){return al.isSeq(n)||e("Expected a sequence for this tag"),n},createNode:(n,e,t)=>ds.YAMLSeq.from(n,e,t)};ps.seq=cl});var Fe=y(ms=>{"use strict";var ll=De(),ul={identify:n=>typeof n=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:n=>n,stringify(n,e,t,i){return e=Object.assign({actualString:!0},e),ll.stringifyString(n,e,t,i)}};ms.string=ul});var Ut=y(ws=>{"use strict";var hs=O(),gs={identify:n=>n==null,createNode:()=>new hs.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new hs.Scalar(null),stringify:({source:n},e)=>typeof n=="string"&&gs.test.test(n)?n:e.options.nullStr};ws.nullTag=gs});var Zn=y(vs=>{"use strict";var fl=O(),ys={identify:n=>typeof n=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:n=>new fl.Scalar(n[0]==="t"||n[0]==="T"),stringify({source:n,value:e},t){if(n&&ys.test.test(n)){let i=n[0]==="t"||n[0]==="T";if(e===i)return n}return e?t.options.trueStr:t.options.falseStr}};vs.boolTag=ys});var ke=y(bs=>{"use strict";function dl({format:n,minFractionDigits:e,tag:t,value:i}){if(typeof i=="bigint")return String(i);let r=typeof i=="number"?i:Number(i);if(!isFinite(r))return isNaN(r)?".nan":r<0?"-.inf":".inf";let s=Object.is(i,-0)?"-0":JSON.stringify(i);if(!n&&e&&(!t||t==="tag:yaml.org,2002:float")&&/^-?\d/.test(s)&&!s.includes("e")){let o=s.indexOf(".");o<0&&(o=s.length,s+=".");let a=e-(s.length-o-1);for(;a-- >0;)s+="0"}return s}bs.stringifyNumber=dl});var ti=y(Jt=>{"use strict";var pl=O(),ei=ke(),ml={identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:n=>n.slice(-3).toLowerCase()==="nan"?NaN:n[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:ei.stringifyNumber},hl={identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:n=>parseFloat(n),stringify(n){let e=Number(n.value);return isFinite(e)?e.toExponential():ei.stringifyNumber(n)}},gl={identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(n){let e=new pl.Scalar(parseFloat(n)),t=n.indexOf(".");return t!==-1&&n[n.length-1]==="0"&&(e.minFractionDigits=n.length-t-1),e},stringify:ei.stringifyNumber};Jt.float=gl;Jt.floatExp=hl;Jt.floatNaN=ml});var ii=y(Ht=>{"use strict";var ks=ke(),Vt=n=>typeof n=="bigint"||Number.isInteger(n),ni=(n,e,t,{intAsBigInt:i})=>i?BigInt(n):parseInt(n.substring(e),t);function Ss(n,e,t){let{value:i}=n;return Vt(i)&&i>=0?t+i.toString(e):ks.stringifyNumber(n)}var wl={identify:n=>Vt(n)&&n>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(n,e,t)=>ni(n,2,8,t),stringify:n=>Ss(n,8,"0o")},yl={identify:Vt,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(n,e,t)=>ni(n,0,10,t),stringify:ks.stringifyNumber},vl={identify:n=>Vt(n)&&n>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(n,e,t)=>ni(n,2,16,t),stringify:n=>Ss(n,16,"0x")};Ht.int=yl;Ht.intHex=vl;Ht.intOct=wl});var Es=y(Cs=>{"use strict";var bl=ve(),kl=Ut(),Sl=be(),Cl=Fe(),El=Zn(),ri=ti(),si=ii(),_l=[bl.map,Sl.seq,Cl.string,kl.nullTag,El.boolTag,si.intOct,si.int,si.intHex,ri.floatNaN,ri.floatExp,ri.float];Cs.schema=_l});var Ns=y(Ps=>{"use strict";var Pl=O(),Nl=ve(),Ol=be();function _s(n){return typeof n=="bigint"||Number.isInteger(n)}var Gt=({value:n})=>JSON.stringify(n),xl=[{identify:n=>typeof n=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:n=>n,stringify:Gt},{identify:n=>n==null,createNode:()=>new Pl.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Gt},{identify:n=>typeof n=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:n=>n==="true",stringify:Gt},{identify:_s,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(n,e,{intAsBigInt:t})=>t?BigInt(n):parseInt(n,10),stringify:({value:n})=>_s(n)?n.toString():JSON.stringify(n)},{identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:n=>parseFloat(n),stringify:Gt}],Al={default:!0,tag:"",test:/^/,resolve(n,e){return e(`Unresolved plain scalar ${JSON.stringify(n)}`),n}},Il=[Nl.map,Ol.seq].concat(xl,Al);Ps.schema=Il});var ai=y(Os=>{"use strict";var Be=yt("buffer"),oi=O(),Rl=De(),jl={identify:n=>n instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(n,e){if(typeof Be.Buffer=="function")return Be.Buffer.from(n,"base64");if(typeof atob=="function"){let t=atob(n.replace(/[\n\r]/g,"")),i=new Uint8Array(t.length);for(let r=0;r{"use strict";var zt=_(),ci=Q(),Tl=O(),ql=ee();function xs(n,e){if(zt.isSeq(n))for(let t=0;t1&&e("Each pair must have its own sequence indicator");let r=i.items[0]||new ci.Pair(new Tl.Scalar(null));if(i.commentBefore&&(r.key.commentBefore=r.key.commentBefore?`${i.commentBefore} ${r.key.commentBefore}`:i.commentBefore),i.comment){let s=r.value??r.key;s.comment=s.comment?`${i.comment} -${s.comment}`:i.comment}i=r}n.items[t]=zt.isPair(i)?i:new ci.Pair(i)}}else e("Expected a sequence for this tag");return n}function Is(n,e,t){let{replacer:i}=t,r=new Tl.YAMLSeq(n);r.tag="tag:yaml.org,2002:pairs";let s=0;if(e&&Symbol.iterator in Object(e))for(let o of e){typeof i=="function"&&(o=i.call(e,String(s++),o));let a,c;if(Array.isArray(o))if(o.length===2)a=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)a=l[0],c=o[a];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else a=o;r.items.push(ci.createPair(a,c,t))}return r}var ql={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:As,createNode:Is};Qt.createPairs=Is;Qt.pairs=ql;Qt.resolvePairs=As});var fi=y(ui=>{"use strict";var Rs=_(),li=H(),Ke=ee(),Ll=te(),js=Xt(),le=class n extends Ll.YAMLSeq{constructor(){super(),this.add=Ke.YAMLMap.prototype.add.bind(this),this.delete=Ke.YAMLMap.prototype.delete.bind(this),this.get=Ke.YAMLMap.prototype.get.bind(this),this.has=Ke.YAMLMap.prototype.has.bind(this),this.set=Ke.YAMLMap.prototype.set.bind(this),this.tag=n.tag}toJSON(e,t){if(!t)return super.toJSON(e);let i=new Map;t?.onCreate&&t.onCreate(i);for(let r of this.items){let s,o;if(Rs.isPair(r)?(s=li.toJS(r.key,"",t),o=li.toJS(r.value,s,t)):s=li.toJS(r,"",t),i.has(s))throw new Error("Ordered maps must not include duplicate keys");i.set(s,o)}return i}static from(e,t,i){let r=js.createPairs(e,t,i),s=new this;return s.items=r.items,s}};le.tag="tag:yaml.org,2002:omap";var Dl={collection:"seq",identify:n=>n instanceof Map,nodeClass:le,default:!1,tag:"tag:yaml.org,2002:omap",resolve(n,e){let t=js.resolvePairs(n,e),i=[];for(let{key:r}of t.items)Rs.isScalar(r)&&(i.includes(r.value)?e(`Ordered maps must not include duplicate keys: ${r.value}`):i.push(r.value));return Object.assign(new le,t)},createNode:(n,e,t)=>le.from(n,e,t)};ui.YAMLOMap=le;ui.omap=Dl});var $s=y(di=>{"use strict";var Ts=O();function qs({value:n,source:e},t){return e&&(n?Ls:Ds).test.test(e)?e:n?t.options.trueStr:t.options.falseStr}var Ls={identify:n=>n===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new Ts.Scalar(!0),stringify:qs},Ds={identify:n=>n===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new Ts.Scalar(!1),stringify:qs};di.falseTag=Ds;di.trueTag=Ls});var Ws=y(Zt=>{"use strict";var $l=O(),pi=Se(),Wl={identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:n=>n.slice(-3).toLowerCase()==="nan"?NaN:n[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:pi.stringifyNumber},Ml={identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:n=>parseFloat(n.replace(/_/g,"")),stringify(n){let e=Number(n.value);return isFinite(e)?e.toExponential():pi.stringifyNumber(n)}},Fl={identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(n){let e=new $l.Scalar(parseFloat(n.replace(/_/g,""))),t=n.indexOf(".");if(t!==-1){let i=n.substring(t+1).replace(/_/g,"");i[i.length-1]==="0"&&(e.minFractionDigits=i.length)}return e},stringify:pi.stringifyNumber};Zt.float=Fl;Zt.floatExp=Ml;Zt.floatNaN=Wl});var Fs=y(Ue=>{"use strict";var Ms=Se(),Ye=n=>typeof n=="bigint"||Number.isInteger(n);function en(n,e,t,{intAsBigInt:i}){let r=n[0];if((r==="-"||r==="+")&&(e+=1),n=n.substring(e).replace(/_/g,""),i){switch(t){case 2:n=`0b${n}`;break;case 8:n=`0o${n}`;break;case 16:n=`0x${n}`;break}let o=BigInt(n);return r==="-"?BigInt(-1)*o:o}let s=parseInt(n,t);return r==="-"?-1*s:s}function mi(n,e,t){let{value:i}=n;if(Ye(i)){let r=i.toString(e);return i<0?"-"+t+r.substr(1):t+r}return Ms.stringifyNumber(n)}var Bl={identify:Ye,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(n,e,t)=>en(n,2,2,t),stringify:n=>mi(n,2,"0b")},Kl={identify:Ye,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(n,e,t)=>en(n,1,8,t),stringify:n=>mi(n,8,"0")},Yl={identify:Ye,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(n,e,t)=>en(n,0,10,t),stringify:Ms.stringifyNumber},Ul={identify:Ye,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(n,e,t)=>en(n,2,16,t),stringify:n=>mi(n,16,"0x")};Ue.int=Yl;Ue.intBin=Bl;Ue.intHex=Ul;Ue.intOct=Kl});var gi=y(hi=>{"use strict";var rn=_(),tn=X(),nn=ee(),ue=class n extends nn.YAMLMap{constructor(e){super(e),this.tag=n.tag}add(e){let t;rn.isPair(e)?t=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?t=new tn.Pair(e.key,null):t=new tn.Pair(e,null),nn.findPair(this.items,t.key)||this.items.push(t)}get(e,t){let i=nn.findPair(this.items,e);return!t&&rn.isPair(i)?rn.isScalar(i.key)?i.key.value:i.key:i}set(e,t){if(typeof t!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof t}`);let i=nn.findPair(this.items,e);i&&!t?this.items.splice(this.items.indexOf(i),1):!i&&t&&this.items.push(new tn.Pair(e))}toJSON(e,t){return super.toJSON(e,t,Set)}toString(e,t,i){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),t,i);throw new Error("Set items must all have null values")}static from(e,t,i){let{replacer:r}=i,s=new this(e);if(t&&Symbol.iterator in Object(t))for(let o of t)typeof r=="function"&&(o=r.call(t,o,o)),s.items.push(tn.createPair(o,null,i));return s}};ue.tag="tag:yaml.org,2002:set";var Jl={collection:"map",identify:n=>n instanceof Set,nodeClass:ue,default:!1,tag:"tag:yaml.org,2002:set",createNode:(n,e,t)=>ue.from(n,e,t),resolve(n,e){if(rn.isMap(n)){if(n.hasAllNullValues(!0))return Object.assign(new ue,n);e("Set items must all have null values")}else e("Expected a mapping for this tag");return n}};hi.YAMLSet=ue;hi.set=Jl});var yi=y(sn=>{"use strict";var Vl=Se();function wi(n,e){let t=n[0],i=t==="-"||t==="+"?n.substring(1):n,r=o=>e?BigInt(o):Number(o),s=i.replace(/_/g,"").split(":").reduce((o,a)=>o*r(60)+r(a),r(0));return t==="-"?r(-1)*s:s}function Bs(n){let{value:e}=n,t=o=>o;if(typeof e=="bigint")t=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return Vl.stringifyNumber(n);let i="";e<0&&(i="-",e*=t(-1));let r=t(60),s=[e%r];return e<60?s.unshift(0):(e=(e-s[0])/r,s.unshift(e%r),e>=60&&(e=(e-s[0])/r,s.unshift(e))),i+s.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var Hl={identify:n=>typeof n=="bigint"||Number.isInteger(n),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(n,e,{intAsBigInt:t})=>wi(n,t),stringify:Bs},Gl={identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:n=>wi(n,!1),stringify:Bs},Ks={identify:n=>n instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(n){let e=n.match(Ks.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,t,i,r,s,o,a]=e.map(Number),c=e[7]?Number((e[7]+"00").substr(1,3)):0,l=Date.UTC(t,i-1,r,s||0,o||0,a||0,c),m=e[8];if(m&&m!=="Z"){let u=wi(m,!1);Math.abs(u)<30&&(u*=60),l-=6e4*u}return new Date(l)},stringify:({value:n})=>n?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};sn.floatTime=Gl;sn.intTime=Hl;sn.timestamp=Ks});var Js=y(Us=>{"use strict";var zl=be(),Ql=Ut(),Xl=ke(),Zl=Fe(),eu=ai(),Ys=$s(),vi=Ws(),on=Fs(),tu=Dt(),nu=fi(),iu=Xt(),ru=gi(),bi=yi(),su=[zl.map,Xl.seq,Zl.string,Ql.nullTag,Ys.trueTag,Ys.falseTag,on.intBin,on.intOct,on.int,on.intHex,vi.floatNaN,vi.floatExp,vi.float,eu.binary,tu.merge,nu.omap,iu.pairs,ru.set,bi.intTime,bi.floatTime,bi.timestamp];Us.schema=su});var no=y(Ci=>{"use strict";var zs=be(),ou=Ut(),Qs=ke(),au=Fe(),cu=Zn(),ki=ti(),Si=ii(),lu=_s(),uu=Os(),Xs=ai(),Je=Dt(),Zs=fi(),eo=Xt(),Vs=Js(),to=gi(),an=yi(),Hs=new Map([["core",lu.schema],["failsafe",[zs.map,Qs.seq,au.string]],["json",uu.schema],["yaml11",Vs.schema],["yaml-1.1",Vs.schema]]),Gs={binary:Xs.binary,bool:cu.boolTag,float:ki.float,floatExp:ki.floatExp,floatNaN:ki.floatNaN,floatTime:an.floatTime,int:Si.int,intHex:Si.intHex,intOct:Si.intOct,intTime:an.intTime,map:zs.map,merge:Je.merge,null:ou.nullTag,omap:Zs.omap,pairs:eo.pairs,seq:Qs.seq,set:to.set,timestamp:an.timestamp},fu={"tag:yaml.org,2002:binary":Xs.binary,"tag:yaml.org,2002:merge":Je.merge,"tag:yaml.org,2002:omap":Zs.omap,"tag:yaml.org,2002:pairs":eo.pairs,"tag:yaml.org,2002:set":to.set,"tag:yaml.org,2002:timestamp":an.timestamp};function du(n,e,t){let i=Hs.get(e);if(i&&!n)return t&&!i.includes(Je.merge)?i.concat(Je.merge):i.slice();let r=i;if(!r)if(Array.isArray(n))r=[];else{let s=Array.from(Hs.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${e}"; use one of ${s} or define customTags array`)}if(Array.isArray(n))for(let s of n)r=r.concat(s);else typeof n=="function"&&(r=n(r.slice()));return t&&(r=r.concat(Je.merge)),r.reduce((s,o)=>{let a=typeof o=="string"?Gs[o]:o;if(!a){let c=JSON.stringify(o),l=Object.keys(Gs).map(m=>JSON.stringify(m)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return s.includes(a)||s.push(a),s},[])}Ci.coreKnownTags=fu;Ci.getTags=du});var Pi=y(io=>{"use strict";var Ei=_(),pu=be(),mu=ke(),hu=Fe(),cn=no(),gu=(n,e)=>n.keye.key?1:0,_i=class n{constructor({compat:e,customTags:t,merge:i,resolveKnownTags:r,schema:s,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?cn.getTags(e,"compat"):e?cn.getTags(null,e):null,this.name=typeof s=="string"&&s||"core",this.knownTags=r?cn.coreKnownTags:{},this.tags=cn.getTags(t,this.name,i),this.toStringOptions=a??null,Object.defineProperty(this,Ei.MAP,{value:pu.map}),Object.defineProperty(this,Ei.SCALAR,{value:hu.string}),Object.defineProperty(this,Ei.SEQ,{value:mu.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?gu:null}clone(){let e=Object.create(n.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};io.Schema=_i});var so=y(ro=>{"use strict";var wu=_(),Ni=$e(),Ve=Te();function yu(n,e){let t=[],i=e.directives===!0;if(e.directives!==!1&&n.directives){let c=n.directives.toString(n);c?(t.push(c),i=!0):n.directives.docStart&&(i=!0)}i&&t.push("---");let r=Ni.createStringifyContext(n,e),{commentString:s}=r.options;if(n.commentBefore){t.length!==1&&t.unshift("");let c=s(n.commentBefore);t.unshift(Ve.indentComment(c,""))}let o=!1,a=null;if(n.contents){if(wu.isNode(n.contents)){if(n.contents.spaceBefore&&i&&t.push(""),n.contents.commentBefore){let m=s(n.contents.commentBefore);t.push(Ve.indentComment(m,""))}r.forceBlockIndent=!!n.comment,a=n.contents.comment}let c=a?void 0:()=>o=!0,l=Ni.stringify(n.contents,r,()=>a=null,c);a&&(l+=Ve.lineComment(l,"",s(a))),(l[0]==="|"||l[0]===">")&&t[t.length-1]==="---"?t[t.length-1]=`--- ${l}`:t.push(l)}else t.push(Ni.stringify(n.contents,r));if(n.directives?.docEnd)if(n.comment){let c=s(n.comment);c.includes(` +${s.comment}`:i.comment}i=r}n.items[t]=zt.isPair(i)?i:new ci.Pair(i)}}else e("Expected a sequence for this tag");return n}function As(n,e,t){let{replacer:i}=t,r=new ql.YAMLSeq(n);r.tag="tag:yaml.org,2002:pairs";let s=0;if(e&&Symbol.iterator in Object(e))for(let o of e){typeof i=="function"&&(o=i.call(e,String(s++),o));let a,c;if(Array.isArray(o))if(o.length===2)a=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)a=l[0],c=o[a];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else a=o;r.items.push(ci.createPair(a,c,t))}return r}var Ll={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:xs,createNode:As};Qt.createPairs=As;Qt.pairs=Ll;Qt.resolvePairs=xs});var fi=y(ui=>{"use strict";var Is=_(),li=V(),Ke=Z(),Dl=ee(),Rs=Xt(),ce=class n extends Dl.YAMLSeq{constructor(){super(),this.add=Ke.YAMLMap.prototype.add.bind(this),this.delete=Ke.YAMLMap.prototype.delete.bind(this),this.get=Ke.YAMLMap.prototype.get.bind(this),this.has=Ke.YAMLMap.prototype.has.bind(this),this.set=Ke.YAMLMap.prototype.set.bind(this),this.tag=n.tag}toJSON(e,t){if(!t)return super.toJSON(e);let i=new Map;t?.onCreate&&t.onCreate(i);for(let r of this.items){let s,o;if(Is.isPair(r)?(s=li.toJS(r.key,"",t),o=li.toJS(r.value,s,t)):s=li.toJS(r,"",t),i.has(s))throw new Error("Ordered maps must not include duplicate keys");i.set(s,o)}return i}static from(e,t,i){let r=Rs.createPairs(e,t,i),s=new this;return s.items=r.items,s}};ce.tag="tag:yaml.org,2002:omap";var $l={collection:"seq",identify:n=>n instanceof Map,nodeClass:ce,default:!1,tag:"tag:yaml.org,2002:omap",resolve(n,e){let t=Rs.resolvePairs(n,e),i=[];for(let{key:r}of t.items)Is.isScalar(r)&&(i.includes(r.value)?e(`Ordered maps must not include duplicate keys: ${r.value}`):i.push(r.value));return Object.assign(new ce,t)},createNode:(n,e,t)=>ce.from(n,e,t)};ui.YAMLOMap=ce;ui.omap=$l});var Ds=y(di=>{"use strict";var js=O();function Ts({value:n,source:e},t){return e&&(n?qs:Ls).test.test(e)?e:n?t.options.trueStr:t.options.falseStr}var qs={identify:n=>n===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new js.Scalar(!0),stringify:Ts},Ls={identify:n=>n===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new js.Scalar(!1),stringify:Ts};di.falseTag=Ls;di.trueTag=qs});var $s=y(Zt=>{"use strict";var Wl=O(),pi=ke(),Ml={identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:n=>n.slice(-3).toLowerCase()==="nan"?NaN:n[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:pi.stringifyNumber},Fl={identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:n=>parseFloat(n.replace(/_/g,"")),stringify(n){let e=Number(n.value);return isFinite(e)?e.toExponential():pi.stringifyNumber(n)}},Bl={identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(n){let e=new Wl.Scalar(parseFloat(n.replace(/_/g,""))),t=n.indexOf(".");if(t!==-1){let i=n.substring(t+1).replace(/_/g,"");i[i.length-1]==="0"&&(e.minFractionDigits=i.length)}return e},stringify:pi.stringifyNumber};Zt.float=Bl;Zt.floatExp=Fl;Zt.floatNaN=Ml});var Ms=y(Ue=>{"use strict";var Ws=ke(),Ye=n=>typeof n=="bigint"||Number.isInteger(n);function en(n,e,t,{intAsBigInt:i}){let r=n[0];if((r==="-"||r==="+")&&(e+=1),n=n.substring(e).replace(/_/g,""),i){switch(t){case 2:n=`0b${n}`;break;case 8:n=`0o${n}`;break;case 16:n=`0x${n}`;break}let o=BigInt(n);return r==="-"?BigInt(-1)*o:o}let s=parseInt(n,t);return r==="-"?-1*s:s}function mi(n,e,t){let{value:i}=n;if(Ye(i)){let r=i.toString(e);return i<0?"-"+t+r.substr(1):t+r}return Ws.stringifyNumber(n)}var Kl={identify:Ye,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(n,e,t)=>en(n,2,2,t),stringify:n=>mi(n,2,"0b")},Yl={identify:Ye,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(n,e,t)=>en(n,1,8,t),stringify:n=>mi(n,8,"0")},Ul={identify:Ye,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(n,e,t)=>en(n,0,10,t),stringify:Ws.stringifyNumber},Jl={identify:Ye,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(n,e,t)=>en(n,2,16,t),stringify:n=>mi(n,16,"0x")};Ue.int=Ul;Ue.intBin=Kl;Ue.intHex=Jl;Ue.intOct=Yl});var gi=y(hi=>{"use strict";var rn=_(),tn=Q(),nn=Z(),le=class n extends nn.YAMLMap{constructor(e){super(e),this.tag=n.tag}add(e){let t;rn.isPair(e)?t=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?t=new tn.Pair(e.key,null):t=new tn.Pair(e,null),nn.findPair(this.items,t.key)||this.items.push(t)}get(e,t){let i=nn.findPair(this.items,e);return!t&&rn.isPair(i)?rn.isScalar(i.key)?i.key.value:i.key:i}set(e,t){if(typeof t!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof t}`);let i=nn.findPair(this.items,e);i&&!t?this.items.splice(this.items.indexOf(i),1):!i&&t&&this.items.push(new tn.Pair(e))}toJSON(e,t){return super.toJSON(e,t,Set)}toString(e,t,i){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),t,i);throw new Error("Set items must all have null values")}static from(e,t,i){let{replacer:r}=i,s=new this(e);if(t&&Symbol.iterator in Object(t))for(let o of t)typeof r=="function"&&(o=r.call(t,o,o)),s.items.push(tn.createPair(o,null,i));return s}};le.tag="tag:yaml.org,2002:set";var Vl={collection:"map",identify:n=>n instanceof Set,nodeClass:le,default:!1,tag:"tag:yaml.org,2002:set",createNode:(n,e,t)=>le.from(n,e,t),resolve(n,e){if(rn.isMap(n)){if(n.hasAllNullValues(!0))return Object.assign(new le,n);e("Set items must all have null values")}else e("Expected a mapping for this tag");return n}};hi.YAMLSet=le;hi.set=Vl});var yi=y(sn=>{"use strict";var Hl=ke();function wi(n,e){let t=n[0],i=t==="-"||t==="+"?n.substring(1):n,r=o=>e?BigInt(o):Number(o),s=i.replace(/_/g,"").split(":").reduce((o,a)=>o*r(60)+r(a),r(0));return t==="-"?r(-1)*s:s}function Fs(n){let{value:e}=n,t=o=>o;if(typeof e=="bigint")t=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return Hl.stringifyNumber(n);let i="";e<0&&(i="-",e*=t(-1));let r=t(60),s=[e%r];return e<60?s.unshift(0):(e=(e-s[0])/r,s.unshift(e%r),e>=60&&(e=(e-s[0])/r,s.unshift(e))),i+s.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var Gl={identify:n=>typeof n=="bigint"||Number.isInteger(n),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(n,e,{intAsBigInt:t})=>wi(n,t),stringify:Fs},zl={identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:n=>wi(n,!1),stringify:Fs},Bs={identify:n=>n instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(n){let e=n.match(Bs.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,t,i,r,s,o,a]=e.map(Number),c=e[7]?Number((e[7]+"00").substr(1,3)):0,l=Date.UTC(t,i-1,r,s||0,o||0,a||0,c),m=e[8];if(m&&m!=="Z"){let u=wi(m,!1);Math.abs(u)<30&&(u*=60),l-=6e4*u}return new Date(l)},stringify:({value:n})=>n?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};sn.floatTime=zl;sn.intTime=Gl;sn.timestamp=Bs});var Us=y(Ys=>{"use strict";var Ql=ve(),Xl=Ut(),Zl=be(),eu=Fe(),tu=ai(),Ks=Ds(),vi=$s(),on=Ms(),nu=Dt(),iu=fi(),ru=Xt(),su=gi(),bi=yi(),ou=[Ql.map,Zl.seq,eu.string,Xl.nullTag,Ks.trueTag,Ks.falseTag,on.intBin,on.intOct,on.int,on.intHex,vi.floatNaN,vi.floatExp,vi.float,tu.binary,nu.merge,iu.omap,ru.pairs,su.set,bi.intTime,bi.floatTime,bi.timestamp];Ys.schema=ou});var to=y(Ci=>{"use strict";var Gs=ve(),au=Ut(),zs=be(),cu=Fe(),lu=Zn(),ki=ti(),Si=ii(),uu=Es(),fu=Ns(),Qs=ai(),Je=Dt(),Xs=fi(),Zs=Xt(),Js=Us(),eo=gi(),an=yi(),Vs=new Map([["core",uu.schema],["failsafe",[Gs.map,zs.seq,cu.string]],["json",fu.schema],["yaml11",Js.schema],["yaml-1.1",Js.schema]]),Hs={binary:Qs.binary,bool:lu.boolTag,float:ki.float,floatExp:ki.floatExp,floatNaN:ki.floatNaN,floatTime:an.floatTime,int:Si.int,intHex:Si.intHex,intOct:Si.intOct,intTime:an.intTime,map:Gs.map,merge:Je.merge,null:au.nullTag,omap:Xs.omap,pairs:Zs.pairs,seq:zs.seq,set:eo.set,timestamp:an.timestamp},du={"tag:yaml.org,2002:binary":Qs.binary,"tag:yaml.org,2002:merge":Je.merge,"tag:yaml.org,2002:omap":Xs.omap,"tag:yaml.org,2002:pairs":Zs.pairs,"tag:yaml.org,2002:set":eo.set,"tag:yaml.org,2002:timestamp":an.timestamp};function pu(n,e,t){let i=Vs.get(e);if(i&&!n)return t&&!i.includes(Je.merge)?i.concat(Je.merge):i.slice();let r=i;if(!r)if(Array.isArray(n))r=[];else{let s=Array.from(Vs.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${e}"; use one of ${s} or define customTags array`)}if(Array.isArray(n))for(let s of n)r=r.concat(s);else typeof n=="function"&&(r=n(r.slice()));return t&&(r=r.concat(Je.merge)),r.reduce((s,o)=>{let a=typeof o=="string"?Hs[o]:o;if(!a){let c=JSON.stringify(o),l=Object.keys(Hs).map(m=>JSON.stringify(m)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return s.includes(a)||s.push(a),s},[])}Ci.coreKnownTags=du;Ci.getTags=pu});var Pi=y(no=>{"use strict";var Ei=_(),mu=ve(),hu=be(),gu=Fe(),cn=to(),wu=(n,e)=>n.keye.key?1:0,_i=class n{constructor({compat:e,customTags:t,merge:i,resolveKnownTags:r,schema:s,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?cn.getTags(e,"compat"):e?cn.getTags(null,e):null,this.name=typeof s=="string"&&s||"core",this.knownTags=r?cn.coreKnownTags:{},this.tags=cn.getTags(t,this.name,i),this.toStringOptions=a??null,Object.defineProperty(this,Ei.MAP,{value:mu.map}),Object.defineProperty(this,Ei.SCALAR,{value:gu.string}),Object.defineProperty(this,Ei.SEQ,{value:hu.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?wu:null}clone(){let e=Object.create(n.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};no.Schema=_i});var ro=y(io=>{"use strict";var yu=_(),Ni=$e(),Ve=Te();function vu(n,e){let t=[],i=e.directives===!0;if(e.directives!==!1&&n.directives){let c=n.directives.toString(n);c?(t.push(c),i=!0):n.directives.docStart&&(i=!0)}i&&t.push("---");let r=Ni.createStringifyContext(n,e),{commentString:s}=r.options;if(n.commentBefore){t.length!==1&&t.unshift("");let c=s(n.commentBefore);t.unshift(Ve.indentComment(c,""))}let o=!1,a=null;if(n.contents){if(yu.isNode(n.contents)){if(n.contents.spaceBefore&&i&&t.push(""),n.contents.commentBefore){let m=s(n.contents.commentBefore);t.push(Ve.indentComment(m,""))}r.forceBlockIndent=!!n.comment,a=n.contents.comment}let c=a?void 0:()=>o=!0,l=Ni.stringify(n.contents,r,()=>a=null,c);a&&(l+=Ve.lineComment(l,"",s(a))),(l[0]==="|"||l[0]===">")&&t[t.length-1]==="---"?t[t.length-1]=`--- ${l}`:t.push(l)}else t.push(Ni.stringify(n.contents,r));if(n.directives?.docEnd)if(n.comment){let c=s(n.comment);c.includes(` `)?(t.push("..."),t.push(Ve.indentComment(c,""))):t.push(`... ${c}`)}else t.push("...");else{let c=n.comment;c&&o&&(c=c.replace(/^\n+/,"")),c&&((!o||a)&&t[t.length-1]!==""&&t.push(""),t.push(Ve.indentComment(s(c),"")))}return t.join(` `)+` -`}ro.stringifyDocument=yu});var He=y(oo=>{"use strict";var vu=Re(),Ce=Nt(),L=_(),bu=X(),ku=H(),Su=Pi(),Cu=so(),Oi=Ct(),Eu=Rn(),_u=je(),xi=In(),Ai=class n{constructor(e,t,i){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,L.NODE_TYPE,{value:L.DOC});let r=null;typeof t=="function"||Array.isArray(t)?r=t:i===void 0&&t&&(i=t,t=void 0);let s=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},i);this.options=s;let{version:o}=s;i?._directives?(this.directives=i._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new xi.Directives({version:o}),this.setSchema(o,i),this.contents=e===void 0?null:this.createNode(e,r,i)}clone(){let e=Object.create(n.prototype,{[L.NODE_TYPE]:{value:L.DOC}});return e.commentBefore=this.commentBefore,e.comment=this.comment,e.errors=this.errors.slice(),e.warnings=this.warnings.slice(),e.options=Object.assign({},this.options),this.directives&&(e.directives=this.directives.clone()),e.schema=this.schema.clone(),e.contents=L.isNode(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){Ee(this.contents)&&this.contents.add(e)}addIn(e,t){Ee(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){let i=Oi.anchorNames(this);e.anchor=!t||i.has(t)?Oi.findNewAnchor(t||"a",i):t}return new vu.Alias(e.anchor)}createNode(e,t,i){let r;if(typeof t=="function")e=t.call({"":e},"",e),r=t;else if(Array.isArray(t)){let p=v=>typeof v=="number"||v instanceof String||v instanceof Number,g=t.filter(p).map(String);g.length>0&&(t=t.concat(g)),r=t}else i===void 0&&t&&(i=t,t=void 0);let{aliasDuplicateObjects:s,anchorPrefix:o,flow:a,keepUndefined:c,onTagObj:l,tag:m}=i??{},{onAnchor:u,setAnchors:d,sourceObjects:h}=Oi.createNodeAnchors(this,o||"a"),w={aliasDuplicateObjects:s??!0,keepUndefined:c??!1,onAnchor:u,onTagObj:l,replacer:r,schema:this.schema,sourceObjects:h},f=_u.createNode(e,m,w);return a&&L.isCollection(f)&&(f.flow=!0),d(),f}createPair(e,t,i={}){let r=this.createNode(e,null,i),s=this.createNode(t,null,i);return new bu.Pair(r,s)}delete(e){return Ee(this.contents)?this.contents.delete(e):!1}deleteIn(e){return Ce.isEmptyPath(e)?this.contents==null?!1:(this.contents=null,!0):Ee(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return L.isCollection(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return Ce.isEmptyPath(e)?!t&&L.isScalar(this.contents)?this.contents.value:this.contents:L.isCollection(this.contents)?this.contents.getIn(e,t):void 0}has(e){return L.isCollection(this.contents)?this.contents.has(e):!1}hasIn(e){return Ce.isEmptyPath(e)?this.contents!==void 0:L.isCollection(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=Ce.collectionFromPath(this.schema,[e],t):Ee(this.contents)&&this.contents.set(e,t)}setIn(e,t){Ce.isEmptyPath(e)?this.contents=t:this.contents==null?this.contents=Ce.collectionFromPath(this.schema,Array.from(e),t):Ee(this.contents)&&this.contents.setIn(e,t)}setSchema(e,t={}){typeof e=="number"&&(e=String(e));let i;switch(e){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new xi.Directives({version:"1.1"}),i={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=e:this.directives=new xi.Directives({version:e}),i={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,i=null;break;default:{let r=JSON.stringify(e);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${r}`)}}if(t.schema instanceof Object)this.schema=t.schema;else if(i)this.schema=new Su.Schema(Object.assign(i,t));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:e,jsonArg:t,mapAsMap:i,maxAliasCount:r,onAnchor:s,reviver:o}={}){let a={anchors:new Map,doc:this,keep:!e,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},c=ku.toJS(this.contents,t??"",a);if(typeof s=="function")for(let{count:l,res:m}of a.anchors.values())s(m,l);return typeof o=="function"?Eu.applyReviver(o,{"":c},"",c):c}toJSON(e,t){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:t})}toString(e={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let t=JSON.stringify(e.indent);throw new Error(`"indent" option must be a positive integer, not ${t}`)}return Cu.stringifyDocument(this,e)}};function Ee(n){if(L.isCollection(n))return!0;throw new Error("Expected a YAML collection as document contents")}oo.Document=Ai});var Qe=y(ze=>{"use strict";var Ge=class extends Error{constructor(e,t,i,r){super(),this.name=e,this.code=i,this.message=r,this.pos=t}},Ii=class extends Ge{constructor(e,t,i){super("YAMLParseError",e,t,i)}},Ri=class extends Ge{constructor(e,t,i){super("YAMLWarning",e,t,i)}},Pu=(n,e)=>t=>{if(t.pos[0]===-1)return;t.linePos=t.pos.map(a=>e.linePos(a));let{line:i,col:r}=t.linePos[0];t.message+=` at line ${i}, column ${r}`;let s=r-1,o=n.substring(e.lineStarts[i-1],e.lineStarts[i]).replace(/[\n\r]+$/,"");if(s>=60&&o.length>80){let a=Math.min(s-39,o.length-79);o="…"+o.substring(a),s-=a-1}if(o.length>80&&(o=o.substring(0,79)+"…"),i>1&&/^ *$/.test(o.substring(0,s))){let a=n.substring(e.lineStarts[i-2],e.lineStarts[i-1]);a.length>80&&(a=a.substring(0,79)+`… +`}io.stringifyDocument=vu});var He=y(so=>{"use strict";var bu=Re(),Se=Nt(),L=_(),ku=Q(),Su=V(),Cu=Pi(),Eu=ro(),Oi=Ct(),_u=Rn(),Pu=je(),xi=In(),Ai=class n{constructor(e,t,i){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,L.NODE_TYPE,{value:L.DOC});let r=null;typeof t=="function"||Array.isArray(t)?r=t:i===void 0&&t&&(i=t,t=void 0);let s=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},i);this.options=s;let{version:o}=s;i?._directives?(this.directives=i._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new xi.Directives({version:o}),this.setSchema(o,i),this.contents=e===void 0?null:this.createNode(e,r,i)}clone(){let e=Object.create(n.prototype,{[L.NODE_TYPE]:{value:L.DOC}});return e.commentBefore=this.commentBefore,e.comment=this.comment,e.errors=this.errors.slice(),e.warnings=this.warnings.slice(),e.options=Object.assign({},this.options),this.directives&&(e.directives=this.directives.clone()),e.schema=this.schema.clone(),e.contents=L.isNode(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){Ce(this.contents)&&this.contents.add(e)}addIn(e,t){Ce(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){let i=Oi.anchorNames(this);e.anchor=!t||i.has(t)?Oi.findNewAnchor(t||"a",i):t}return new bu.Alias(e.anchor)}createNode(e,t,i){let r;if(typeof t=="function")e=t.call({"":e},"",e),r=t;else if(Array.isArray(t)){let p=v=>typeof v=="number"||v instanceof String||v instanceof Number,g=t.filter(p).map(String);g.length>0&&(t=t.concat(g)),r=t}else i===void 0&&t&&(i=t,t=void 0);let{aliasDuplicateObjects:s,anchorPrefix:o,flow:a,keepUndefined:c,onTagObj:l,tag:m}=i??{},{onAnchor:u,setAnchors:d,sourceObjects:h}=Oi.createNodeAnchors(this,o||"a"),w={aliasDuplicateObjects:s??!0,keepUndefined:c??!1,onAnchor:u,onTagObj:l,replacer:r,schema:this.schema,sourceObjects:h},f=Pu.createNode(e,m,w);return a&&L.isCollection(f)&&(f.flow=!0),d(),f}createPair(e,t,i={}){let r=this.createNode(e,null,i),s=this.createNode(t,null,i);return new ku.Pair(r,s)}delete(e){return Ce(this.contents)?this.contents.delete(e):!1}deleteIn(e){return Se.isEmptyPath(e)?this.contents==null?!1:(this.contents=null,!0):Ce(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return L.isCollection(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return Se.isEmptyPath(e)?!t&&L.isScalar(this.contents)?this.contents.value:this.contents:L.isCollection(this.contents)?this.contents.getIn(e,t):void 0}has(e){return L.isCollection(this.contents)?this.contents.has(e):!1}hasIn(e){return Se.isEmptyPath(e)?this.contents!==void 0:L.isCollection(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=Se.collectionFromPath(this.schema,[e],t):Ce(this.contents)&&this.contents.set(e,t)}setIn(e,t){Se.isEmptyPath(e)?this.contents=t:this.contents==null?this.contents=Se.collectionFromPath(this.schema,Array.from(e),t):Ce(this.contents)&&this.contents.setIn(e,t)}setSchema(e,t={}){typeof e=="number"&&(e=String(e));let i;switch(e){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new xi.Directives({version:"1.1"}),i={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=e:this.directives=new xi.Directives({version:e}),i={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,i=null;break;default:{let r=JSON.stringify(e);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${r}`)}}if(t.schema instanceof Object)this.schema=t.schema;else if(i)this.schema=new Cu.Schema(Object.assign(i,t));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:e,jsonArg:t,mapAsMap:i,maxAliasCount:r,onAnchor:s,reviver:o}={}){let a={anchors:new Map,doc:this,keep:!e,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},c=Su.toJS(this.contents,t??"",a);if(typeof s=="function")for(let{count:l,res:m}of a.anchors.values())s(m,l);return typeof o=="function"?_u.applyReviver(o,{"":c},"",c):c}toJSON(e,t){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:t})}toString(e={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let t=JSON.stringify(e.indent);throw new Error(`"indent" option must be a positive integer, not ${t}`)}return Eu.stringifyDocument(this,e)}};function Ce(n){if(L.isCollection(n))return!0;throw new Error("Expected a YAML collection as document contents")}so.Document=Ai});var Qe=y(ze=>{"use strict";var Ge=class extends Error{constructor(e,t,i,r){super(),this.name=e,this.code=i,this.message=r,this.pos=t}},Ii=class extends Ge{constructor(e,t,i){super("YAMLParseError",e,t,i)}},Ri=class extends Ge{constructor(e,t,i){super("YAMLWarning",e,t,i)}},Nu=(n,e)=>t=>{if(t.pos[0]===-1)return;t.linePos=t.pos.map(a=>e.linePos(a));let{line:i,col:r}=t.linePos[0];t.message+=` at line ${i}, column ${r}`;let s=r-1,o=n.substring(e.lineStarts[i-1],e.lineStarts[i]).replace(/[\n\r]+$/,"");if(s>=60&&o.length>80){let a=Math.min(s-39,o.length-79);o="…"+o.substring(a),s-=a-1}if(o.length>80&&(o=o.substring(0,79)+"…"),i>1&&/^ *$/.test(o.substring(0,s))){let a=n.substring(e.lineStarts[i-2],e.lineStarts[i-1]);a.length>80&&(a=a.substring(0,79)+`… `),o=a+o}if(/[^ ]/.test(o)){let a=1,c=t.linePos[1];c?.line===i&&c.col>r&&(a=Math.max(1,Math.min(c.col-r,80-s)));let l=" ".repeat(s)+"^".repeat(a);t.message+=`: ${o} ${l} -`}};ze.YAMLError=Ge;ze.YAMLParseError=Ii;ze.YAMLWarning=Ri;ze.prettifyError=Pu});var Xe=y(ao=>{"use strict";function Nu(n,{flow:e,indicator:t,next:i,offset:r,onError:s,parentIndent:o,startOnNewline:a}){let c=!1,l=a,m=a,u="",d="",h=!1,w=!1,f=null,p=null,g=null,v=null,k=null,S=null,C=null;for(let b of n)switch(w&&(b.type!=="space"&&b.type!=="newline"&&b.type!=="comma"&&s(b.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),w=!1),f&&(l&&b.type!=="comment"&&b.type!=="newline"&&s(f,"TAB_AS_INDENT","Tabs are not allowed as indentation"),f=null),b.type){case"space":!e&&(t!=="doc-start"||i?.type!=="flow-collection")&&b.source.includes(" ")&&(f=b),m=!0;break;case"comment":{m||s(b,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let A=b.source.substring(1)||" ";u?u+=d+A:u=A,d="",l=!1;break}case"newline":l?u?u+=b.source:(!S||t!=="seq-item-ind")&&(c=!0):d+=b.source,l=!0,h=!0,(p||g)&&(v=b),m=!0;break;case"anchor":p&&s(b,"MULTIPLE_ANCHORS","A node can have at most one anchor"),b.source.endsWith(":")&&s(b.offset+b.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),p=b,C??(C=b.offset),l=!1,m=!1,w=!0;break;case"tag":{g&&s(b,"MULTIPLE_TAGS","A node can have at most one tag"),g=b,C??(C=b.offset),l=!1,m=!1,w=!0;break}case t:(p||g)&&s(b,"BAD_PROP_ORDER",`Anchors and tags must be after the ${b.source} indicator`),S&&s(b,"UNEXPECTED_TOKEN",`Unexpected ${b.source} in ${e??"collection"}`),S=b,l=t==="seq-item-ind"||t==="explicit-key-ind",m=!1;break;case"comma":if(e){k&&s(b,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),k=b,l=!1,m=!1;break}default:s(b,"UNEXPECTED_TOKEN",`Unexpected ${b.type} token`),l=!1,m=!1}let E=n[n.length-1],N=E?E.offset+E.source.length:r;return w&&i&&i.type!=="space"&&i.type!=="newline"&&i.type!=="comma"&&(i.type!=="scalar"||i.source!=="")&&s(i.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),f&&(l&&f.indent<=o||i?.type==="block-map"||i?.type==="block-seq")&&s(f,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:k,found:S,spaceBefore:c,comment:u,hasNewline:h,anchor:p,tag:g,newlineAfterProp:v,end:N,start:C??N}}ao.resolveProps=Nu});var ln=y(co=>{"use strict";function ji(n){if(!n)return null;switch(n.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(n.source.includes(` -`))return!0;if(n.end){for(let e of n.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(let e of n.items){for(let t of e.start)if(t.type==="newline")return!0;if(e.sep){for(let t of e.sep)if(t.type==="newline")return!0}if(ji(e.key)||ji(e.value))return!0}return!1;default:return!0}}co.containsNewline=ji});var Ti=y(lo=>{"use strict";var Ou=ln();function xu(n,e,t){if(e?.type==="flow-collection"){let i=e.end[0];i.indent===n&&(i.source==="]"||i.source==="}")&&Ou.containsNewline(e)&&t(i,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}lo.flowIndentCheck=xu});var qi=y(fo=>{"use strict";var uo=_();function Au(n,e,t){let{uniqueKeys:i}=n.options;if(i===!1)return!1;let r=typeof i=="function"?i:(s,o)=>s===o||uo.isScalar(s)&&uo.isScalar(o)&&s.value===o.value;return e.some(s=>r(s.key,t))}fo.mapIncludes=Au});var yo=y(wo=>{"use strict";var po=X(),Iu=ee(),mo=Xe(),Ru=ln(),ho=Ti(),ju=qi(),go="All mapping items must start at the same column";function Tu({composeNode:n,composeEmptyNode:e},t,i,r,s){let o=s?.nodeClass??Iu.YAMLMap,a=new o(t.schema);t.atRoot&&(t.atRoot=!1);let c=i.offset,l=null;for(let m of i.items){let{start:u,key:d,sep:h,value:w}=m,f=mo.resolveProps(u,{indicator:"explicit-key-ind",next:d??h?.[0],offset:c,onError:r,parentIndent:i.indent,startOnNewline:!0}),p=!f.found;if(p){if(d&&(d.type==="block-seq"?r(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in d&&d.indent!==i.indent&&r(c,"BAD_INDENT",go)),!f.anchor&&!f.tag&&!h){l=f.end,f.comment&&(a.comment?a.comment+=` -`+f.comment:a.comment=f.comment);continue}(f.newlineAfterProp||Ru.containsNewline(d))&&r(d??u[u.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else f.found?.indent!==i.indent&&r(c,"BAD_INDENT",go);t.atKey=!0;let g=f.end,v=d?n(t,d,f,r):e(t,g,u,null,f,r);t.schema.compat&&ho.flowIndentCheck(i.indent,d,r),t.atKey=!1,ju.mapIncludes(t,a.items,v)&&r(g,"DUPLICATE_KEY","Map keys must be unique");let k=mo.resolveProps(h??[],{indicator:"map-value-ind",next:w,offset:v.range[2],onError:r,parentIndent:i.indent,startOnNewline:!d||d.type==="block-scalar"});if(c=k.end,k.found){p&&(w?.type==="block-map"&&!k.hasNewline&&r(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),t.options.strict&&f.start{"use strict";var qu=te(),Lu=Xe(),Du=Ti();function $u({composeNode:n,composeEmptyNode:e},t,i,r,s){let o=s?.nodeClass??qu.YAMLSeq,a=new o(t.schema);t.atRoot&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let c=i.offset,l=null;for(let{start:m,value:u}of i.items){let d=Lu.resolveProps(m,{indicator:"seq-item-ind",next:u,offset:c,onError:r,parentIndent:i.indent,startOnNewline:!0});if(!d.found)if(d.anchor||d.tag||u)u?.type==="block-seq"?r(d.end,"BAD_INDENT","All sequence items must start at the same column"):r(c,"MISSING_CHAR","Sequence item without - indicator");else{l=d.end,d.comment&&(a.comment=d.comment);continue}let h=u?n(t,u,d,r):e(t,d.end,m,null,d,r);t.schema.compat&&Du.flowIndentCheck(i.indent,u,r),c=h.range[2],a.items.push(h)}return a.range=[i.offset,c,l??c],a}vo.resolveBlockSeq=$u});var _e=y(ko=>{"use strict";function Wu(n,e,t,i){let r="";if(n){let s=!1,o="";for(let a of n){let{source:c,type:l}=a;switch(l){case"space":s=!0;break;case"comment":{t&&!s&&i(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let m=c.substring(1)||" ";r?r+=o+m:r=m,o="";break}case"newline":r&&(o+=c),s=!0;break;default:i(a,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}e+=c.length}}return{comment:r,offset:e}}ko.resolveEnd=Wu});var _o=y(Eo=>{"use strict";var Mu=_(),Fu=X(),So=ee(),Bu=te(),Ku=_e(),Co=Xe(),Yu=ln(),Uu=qi(),Li="Block collections are not allowed within flow collections",Di=n=>n&&(n.type==="block-map"||n.type==="block-seq");function Ju({composeNode:n,composeEmptyNode:e},t,i,r,s){let o=i.start.source==="{",a=o?"flow map":"flow sequence",c=s?.nodeClass??(o?So.YAMLMap:Bu.YAMLSeq),l=new c(t.schema);l.flow=!0;let m=t.atRoot;m&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let u=i.offset+i.start.source.length;for(let p=0;p0){let p=Ku.resolveEnd(w,f,t.options.strict,r);p.comment&&(l.comment?l.comment+=` -`+p.comment:l.comment=p.comment),l.range=[i.offset,f,p.offset]}else l.range=[i.offset,f,f];return l}Eo.resolveFlowCollection=Ju});var No=y(Po=>{"use strict";var Vu=_(),Hu=O(),Gu=ee(),zu=te(),Qu=yo(),Xu=bo(),Zu=_o();function $i(n,e,t,i,r,s){let o=t.type==="block-map"?Qu.resolveBlockMap(n,e,t,i,s):t.type==="block-seq"?Xu.resolveBlockSeq(n,e,t,i,s):Zu.resolveFlowCollection(n,e,t,i,s),a=o.constructor;return r==="!"||r===a.tagName?(o.tag=a.tagName,o):(r&&(o.tag=r),o)}function ef(n,e,t,i,r){let s=i.tag,o=s?e.directives.tagName(s.source,d=>r(s,"TAG_RESOLVE_FAILED",d)):null;if(t.type==="block-seq"){let{anchor:d,newlineAfterProp:h}=i,w=d&&s?d.offset>s.offset?d:s:d??s;w&&(!h||h.offsetd.tag===o&&d.collection===a);if(!c){let d=e.schema.knownTags[o];if(d?.collection===a)e.schema.tags.push(Object.assign({},d,{default:!1})),c=d;else return d?r(s,"BAD_COLLECTION_TYPE",`${d.tag} used for ${a} collection, but expects ${d.collection??"scalar"}`,!0):r(s,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),$i(n,e,t,r,o)}let l=$i(n,e,t,r,o,c),m=c.resolve?.(l,d=>r(s,"TAG_RESOLVE_FAILED",d),e.options)??l,u=Vu.isNode(m)?m:new Hu.Scalar(m);return u.range=l.range,u.tag=o,c?.format&&(u.format=c.format),u}Po.composeCollection=ef});var Mi=y(Oo=>{"use strict";var Wi=O();function tf(n,e,t){let i=e.offset,r=nf(e,n.options.strict,t);if(!r)return{value:"",type:null,comment:"",range:[i,i,i]};let s=r.mode===">"?Wi.Scalar.BLOCK_FOLDED:Wi.Scalar.BLOCK_LITERAL,o=e.source?rf(e.source):[],a=o.length;for(let f=o.length-1;f>=0;--f){let p=o[f][1];if(p===""||p==="\r")a=f;else break}if(a===0){let f=r.chomp==="+"&&o.length>0?` +`}};ze.YAMLError=Ge;ze.YAMLParseError=Ii;ze.YAMLWarning=Ri;ze.prettifyError=Nu});var Xe=y(oo=>{"use strict";function Ou(n,{flow:e,indicator:t,next:i,offset:r,onError:s,parentIndent:o,startOnNewline:a}){let c=!1,l=a,m=a,u="",d="",h=!1,w=!1,f=null,p=null,g=null,v=null,k=null,S=null,C=null;for(let b of n)switch(w&&(b.type!=="space"&&b.type!=="newline"&&b.type!=="comma"&&s(b.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),w=!1),f&&(l&&b.type!=="comment"&&b.type!=="newline"&&s(f,"TAB_AS_INDENT","Tabs are not allowed as indentation"),f=null),b.type){case"space":!e&&(t!=="doc-start"||i?.type!=="flow-collection")&&b.source.includes(" ")&&(f=b),m=!0;break;case"comment":{m||s(b,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let A=b.source.substring(1)||" ";u?u+=d+A:u=A,d="",l=!1;break}case"newline":l?u?u+=b.source:(!S||t!=="seq-item-ind")&&(c=!0):d+=b.source,l=!0,h=!0,(p||g)&&(v=b),m=!0;break;case"anchor":p&&s(b,"MULTIPLE_ANCHORS","A node can have at most one anchor"),b.source.endsWith(":")&&s(b.offset+b.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),p=b,C??(C=b.offset),l=!1,m=!1,w=!0;break;case"tag":{g&&s(b,"MULTIPLE_TAGS","A node can have at most one tag"),g=b,C??(C=b.offset),l=!1,m=!1,w=!0;break}case t:(p||g)&&s(b,"BAD_PROP_ORDER",`Anchors and tags must be after the ${b.source} indicator`),S&&s(b,"UNEXPECTED_TOKEN",`Unexpected ${b.source} in ${e??"collection"}`),S=b,l=t==="seq-item-ind"||t==="explicit-key-ind",m=!1;break;case"comma":if(e){k&&s(b,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),k=b,l=!1,m=!1;break}default:s(b,"UNEXPECTED_TOKEN",`Unexpected ${b.type} token`),l=!1,m=!1}let E=n[n.length-1],N=E?E.offset+E.source.length:r;return w&&i&&i.type!=="space"&&i.type!=="newline"&&i.type!=="comma"&&(i.type!=="scalar"||i.source!=="")&&s(i.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),f&&(l&&f.indent<=o||i?.type==="block-map"||i?.type==="block-seq")&&s(f,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:k,found:S,spaceBefore:c,comment:u,hasNewline:h,anchor:p,tag:g,newlineAfterProp:v,end:N,start:C??N}}oo.resolveProps=Ou});var ln=y(ao=>{"use strict";function ji(n){if(!n)return null;switch(n.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(n.source.includes(` +`))return!0;if(n.end){for(let e of n.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(let e of n.items){for(let t of e.start)if(t.type==="newline")return!0;if(e.sep){for(let t of e.sep)if(t.type==="newline")return!0}if(ji(e.key)||ji(e.value))return!0}return!1;default:return!0}}ao.containsNewline=ji});var Ti=y(co=>{"use strict";var xu=ln();function Au(n,e,t){if(e?.type==="flow-collection"){let i=e.end[0];i.indent===n&&(i.source==="]"||i.source==="}")&&xu.containsNewline(e)&&t(i,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}co.flowIndentCheck=Au});var qi=y(uo=>{"use strict";var lo=_();function Iu(n,e,t){let{uniqueKeys:i}=n.options;if(i===!1)return!1;let r=typeof i=="function"?i:(s,o)=>s===o||lo.isScalar(s)&&lo.isScalar(o)&&s.value===o.value;return e.some(s=>r(s.key,t))}uo.mapIncludes=Iu});var wo=y(go=>{"use strict";var fo=Q(),Ru=Z(),po=Xe(),ju=ln(),mo=Ti(),Tu=qi(),ho="All mapping items must start at the same column";function qu({composeNode:n,composeEmptyNode:e},t,i,r,s){let o=s?.nodeClass??Ru.YAMLMap,a=new o(t.schema);t.atRoot&&(t.atRoot=!1);let c=i.offset,l=null;for(let m of i.items){let{start:u,key:d,sep:h,value:w}=m,f=po.resolveProps(u,{indicator:"explicit-key-ind",next:d??h?.[0],offset:c,onError:r,parentIndent:i.indent,startOnNewline:!0}),p=!f.found;if(p){if(d&&(d.type==="block-seq"?r(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in d&&d.indent!==i.indent&&r(c,"BAD_INDENT",ho)),!f.anchor&&!f.tag&&!h){l=f.end,f.comment&&(a.comment?a.comment+=` +`+f.comment:a.comment=f.comment);continue}(f.newlineAfterProp||ju.containsNewline(d))&&r(d??u[u.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else f.found?.indent!==i.indent&&r(c,"BAD_INDENT",ho);t.atKey=!0;let g=f.end,v=d?n(t,d,f,r):e(t,g,u,null,f,r);t.schema.compat&&mo.flowIndentCheck(i.indent,d,r),t.atKey=!1,Tu.mapIncludes(t,a.items,v)&&r(g,"DUPLICATE_KEY","Map keys must be unique");let k=po.resolveProps(h??[],{indicator:"map-value-ind",next:w,offset:v.range[2],onError:r,parentIndent:i.indent,startOnNewline:!d||d.type==="block-scalar"});if(c=k.end,k.found){p&&(w?.type==="block-map"&&!k.hasNewline&&r(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),t.options.strict&&f.start{"use strict";var Lu=ee(),Du=Xe(),$u=Ti();function Wu({composeNode:n,composeEmptyNode:e},t,i,r,s){let o=s?.nodeClass??Lu.YAMLSeq,a=new o(t.schema);t.atRoot&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let c=i.offset,l=null;for(let{start:m,value:u}of i.items){let d=Du.resolveProps(m,{indicator:"seq-item-ind",next:u,offset:c,onError:r,parentIndent:i.indent,startOnNewline:!0});if(!d.found)if(d.anchor||d.tag||u)u?.type==="block-seq"?r(d.end,"BAD_INDENT","All sequence items must start at the same column"):r(c,"MISSING_CHAR","Sequence item without - indicator");else{l=d.end,d.comment&&(a.comment=d.comment);continue}let h=u?n(t,u,d,r):e(t,d.end,m,null,d,r);t.schema.compat&&$u.flowIndentCheck(i.indent,u,r),c=h.range[2],a.items.push(h)}return a.range=[i.offset,c,l??c],a}yo.resolveBlockSeq=Wu});var Ee=y(bo=>{"use strict";function Mu(n,e,t,i){let r="";if(n){let s=!1,o="";for(let a of n){let{source:c,type:l}=a;switch(l){case"space":s=!0;break;case"comment":{t&&!s&&i(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let m=c.substring(1)||" ";r?r+=o+m:r=m,o="";break}case"newline":r&&(o+=c),s=!0;break;default:i(a,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}e+=c.length}}return{comment:r,offset:e}}bo.resolveEnd=Mu});var Eo=y(Co=>{"use strict";var Fu=_(),Bu=Q(),ko=Z(),Ku=ee(),Yu=Ee(),So=Xe(),Uu=ln(),Ju=qi(),Li="Block collections are not allowed within flow collections",Di=n=>n&&(n.type==="block-map"||n.type==="block-seq");function Vu({composeNode:n,composeEmptyNode:e},t,i,r,s){let o=i.start.source==="{",a=o?"flow map":"flow sequence",c=s?.nodeClass??(o?ko.YAMLMap:Ku.YAMLSeq),l=new c(t.schema);l.flow=!0;let m=t.atRoot;m&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let u=i.offset+i.start.source.length;for(let p=0;p0){let p=Yu.resolveEnd(w,f,t.options.strict,r);p.comment&&(l.comment?l.comment+=` +`+p.comment:l.comment=p.comment),l.range=[i.offset,f,p.offset]}else l.range=[i.offset,f,f];return l}Co.resolveFlowCollection=Vu});var Po=y(_o=>{"use strict";var Hu=_(),Gu=O(),zu=Z(),Qu=ee(),Xu=wo(),Zu=vo(),ef=Eo();function $i(n,e,t,i,r,s){let o=t.type==="block-map"?Xu.resolveBlockMap(n,e,t,i,s):t.type==="block-seq"?Zu.resolveBlockSeq(n,e,t,i,s):ef.resolveFlowCollection(n,e,t,i,s),a=o.constructor;return r==="!"||r===a.tagName?(o.tag=a.tagName,o):(r&&(o.tag=r),o)}function tf(n,e,t,i,r){let s=i.tag,o=s?e.directives.tagName(s.source,d=>r(s,"TAG_RESOLVE_FAILED",d)):null;if(t.type==="block-seq"){let{anchor:d,newlineAfterProp:h}=i,w=d&&s?d.offset>s.offset?d:s:d??s;w&&(!h||h.offsetd.tag===o&&d.collection===a);if(!c){let d=e.schema.knownTags[o];if(d?.collection===a)e.schema.tags.push(Object.assign({},d,{default:!1})),c=d;else return d?r(s,"BAD_COLLECTION_TYPE",`${d.tag} used for ${a} collection, but expects ${d.collection??"scalar"}`,!0):r(s,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),$i(n,e,t,r,o)}let l=$i(n,e,t,r,o,c),m=c.resolve?.(l,d=>r(s,"TAG_RESOLVE_FAILED",d),e.options)??l,u=Hu.isNode(m)?m:new Gu.Scalar(m);return u.range=l.range,u.tag=o,c?.format&&(u.format=c.format),u}_o.composeCollection=tf});var Mi=y(No=>{"use strict";var Wi=O();function nf(n,e,t){let i=e.offset,r=rf(e,n.options.strict,t);if(!r)return{value:"",type:null,comment:"",range:[i,i,i]};let s=r.mode===">"?Wi.Scalar.BLOCK_FOLDED:Wi.Scalar.BLOCK_LITERAL,o=e.source?sf(e.source):[],a=o.length;for(let f=o.length-1;f>=0;--f){let p=o[f][1];if(p===""||p==="\r")a=f;else break}if(a===0){let f=r.chomp==="+"&&o.length>0?` `.repeat(Math.max(1,o.length-1)):"",p=i+r.length;return e.source&&(p+=e.source.length),{value:f,type:s,comment:r.comment,range:[i,p,p]}}let c=e.indent+r.indent,l=e.offset+r.length,m=0;for(let f=0;fc&&(c=p.length);else{p.length=a;--f)o[f][0].length>c&&(a=f+1);let u="",d="",h=!1;for(let f=0;fc||g[0]===" "?(d===" "?d=` @@ -84,67 +84,67 @@ ${l} `+o[f][0].slice(c);u[u.length-1]!==` `&&(u+=` `);break;default:u+=` -`}let w=i+r.length+e.source.length;return{value:u,type:s,comment:r.comment,range:[i,w,w]}}function nf({offset:n,props:e},t,i){if(e[0].type!=="block-scalar-header")return i(e[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:r}=e[0],s=r[0],o=0,a="",c=-1;for(let d=1;d{"use strict";var Fi=O(),sf=_e();function of(n,e,t){let{offset:i,type:r,source:s,end:o}=n,a,c,l=(d,h,w)=>t(i+d,h,w);switch(r){case"scalar":a=Fi.Scalar.PLAIN,c=af(s,l);break;case"single-quoted-scalar":a=Fi.Scalar.QUOTE_SINGLE,c=cf(s,l);break;case"double-quoted-scalar":a=Fi.Scalar.QUOTE_DOUBLE,c=lf(s,l);break;default:return t(n,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${r}`),{value:"",type:null,comment:"",range:[i,i+s.length,i+s.length]}}let m=i+s.length,u=sf.resolveEnd(o,m,e,t);return{value:c,type:a,comment:u.comment,range:[i,m,u.offset]}}function af(n,e){let t="";switch(n[0]){case" ":t="a tab character";break;case",":t="flow indicator character ,";break;case"%":t="directive indicator character %";break;case"|":case">":{t=`block scalar indicator ${n[0]}`;break}case"@":case"`":{t=`reserved character ${n[0]}`;break}}return t&&e(0,"BAD_SCALAR_START",`Plain value cannot start with ${t}`),xo(n)}function cf(n,e){return(n[n.length-1]!=="'"||n.length===1)&&e(n.length,"MISSING_CHAR","Missing closing 'quote"),xo(n.slice(1,-1)).replace(/''/g,"'")}function xo(n){let e,t;try{e=new RegExp(`(.*?)(?{"use strict";var Fi=O(),of=Ee();function af(n,e,t){let{offset:i,type:r,source:s,end:o}=n,a,c,l=(d,h,w)=>t(i+d,h,w);switch(r){case"scalar":a=Fi.Scalar.PLAIN,c=cf(s,l);break;case"single-quoted-scalar":a=Fi.Scalar.QUOTE_SINGLE,c=lf(s,l);break;case"double-quoted-scalar":a=Fi.Scalar.QUOTE_DOUBLE,c=uf(s,l);break;default:return t(n,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${r}`),{value:"",type:null,comment:"",range:[i,i+s.length,i+s.length]}}let m=i+s.length,u=of.resolveEnd(o,m,e,t);return{value:c,type:a,comment:u.comment,range:[i,m,u.offset]}}function cf(n,e){let t="";switch(n[0]){case" ":t="a tab character";break;case",":t="flow indicator character ,";break;case"%":t="directive indicator character %";break;case"|":case">":{t=`block scalar indicator ${n[0]}`;break}case"@":case"`":{t=`reserved character ${n[0]}`;break}}return t&&e(0,"BAD_SCALAR_START",`Plain value cannot start with ${t}`),Oo(n)}function lf(n,e){return(n[n.length-1]!=="'"||n.length===1)&&e(n.length,"MISSING_CHAR","Missing closing 'quote"),Oo(n.slice(1,-1)).replace(/''/g,"'")}function Oo(n){let e,t;try{e=new RegExp(`(.*?)(?s?n.slice(s,i+1):r)}else t+=r}return(n[n.length-1]!=='"'||n.length===1)&&e(n.length,"MISSING_CHAR",'Missing closing "quote'),t}function uf(n,e){let t="",i=n[e+1];for(;(i===" "||i===" "||i===` +`)&&(t+=i>s?n.slice(s,i+1):r)}else t+=r}return(n[n.length-1]!=='"'||n.length===1)&&e(n.length,"MISSING_CHAR",'Missing closing "quote'),t}function ff(n,e){let t="",i=n[e+1];for(;(i===" "||i===" "||i===` `||i==="\r")&&!(i==="\r"&&n[e+2]!==` `);)i===` `&&(t+=` -`),e+=1,i=n[e+1];return t||(t=" "),{fold:t,offset:e}}var ff={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:` -`,r:"\r",t:" ",v:"\v",N:"…",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function df(n,e,t,i){let r=n.substr(e,t),o=r.length===t&&/^[0-9a-fA-F]+$/.test(r)?parseInt(r,16):NaN;try{return String.fromCodePoint(o)}catch{let a=n.substr(e-2,t+2);return i(e-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),a}}Ao.resolveFlowScalar=of});var jo=y(Ro=>{"use strict";var fe=_(),Io=O(),pf=Mi(),mf=Bi();function hf(n,e,t,i){let{value:r,type:s,comment:o,range:a}=e.type==="block-scalar"?pf.resolveBlockScalar(n,e,i):mf.resolveFlowScalar(e,n.options.strict,i),c=t?n.directives.tagName(t.source,u=>i(t,"TAG_RESOLVE_FAILED",u)):null,l;n.options.stringKeys&&n.atKey?l=n.schema[fe.SCALAR]:c?l=gf(n.schema,r,c,t,i):e.type==="scalar"?l=wf(n,r,e,i):l=n.schema[fe.SCALAR];let m;try{let u=l.resolve(r,d=>i(t??e,"TAG_RESOLVE_FAILED",d),n.options);m=fe.isScalar(u)?u:new Io.Scalar(u)}catch(u){let d=u instanceof Error?u.message:String(u);i(t??e,"TAG_RESOLVE_FAILED",d),m=new Io.Scalar(r)}return m.range=a,m.source=r,s&&(m.type=s),c&&(m.tag=c),l.format&&(m.format=l.format),o&&(m.comment=o),m}function gf(n,e,t,i,r){if(t==="!")return n[fe.SCALAR];let s=[];for(let a of n.tags)if(!a.collection&&a.tag===t)if(a.default&&a.test)s.push(a);else return a;for(let a of s)if(a.test?.test(e))return a;let o=n.knownTags[t];return o&&!o.collection?(n.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(r(i,"TAG_RESOLVE_FAILED",`Unresolved tag: ${t}`,t!=="tag:yaml.org,2002:str"),n[fe.SCALAR])}function wf({atKey:n,directives:e,schema:t},i,r,s){let o=t.tags.find(a=>(a.default===!0||n&&a.default==="key")&&a.test?.test(i))||t[fe.SCALAR];if(t.compat){let a=t.compat.find(c=>c.default&&c.test?.test(i))??t[fe.SCALAR];if(o.tag!==a.tag){let c=e.tagString(o.tag),l=e.tagString(a.tag),m=`Value may be parsed as either ${c} or ${l}`;s(r,"TAG_RESOLVE_FAILED",m,!0)}}return o}Ro.composeScalar=hf});var qo=y(To=>{"use strict";function yf(n,e,t){if(e){t??(t=e.length);for(let i=t-1;i>=0;--i){let r=e[i];switch(r.type){case"space":case"comment":case"newline":n-=r.source.length;continue}for(r=e[++i];r?.type==="space";)n+=r.source.length,r=e[++i];break}}return n}To.emptyScalarPosition=yf});var $o=y(Yi=>{"use strict";var vf=Re(),bf=_(),kf=No(),Lo=jo(),Sf=_e(),Cf=qo(),Ef={composeNode:Do,composeEmptyNode:Ki};function Do(n,e,t,i){let r=n.atKey,{spaceBefore:s,comment:o,anchor:a,tag:c}=t,l,m=!0;switch(e.type){case"alias":l=_f(n,e,i),(a||c)&&i(e,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=Lo.composeScalar(n,e,c,i),a&&(l.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=kf.composeCollection(Ef,n,e,t,i),a&&(l.anchor=a.source.substring(1))}catch(u){let d=u instanceof Error?u.message:String(u);i(e,"RESOURCE_EXHAUSTION",d)}break;default:{let u=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;i(e,"UNEXPECTED_TOKEN",u),m=!1}}return l??(l=Ki(n,e.offset,void 0,null,t,i)),a&&l.anchor===""&&i(a,"BAD_ALIAS","Anchor cannot be an empty string"),r&&n.options.stringKeys&&(!bf.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&i(c??e,"NON_STRING_KEY","With stringKeys, all keys must be strings"),s&&(l.spaceBefore=!0),o&&(e.type==="scalar"&&e.source===""?l.comment=o:l.commentBefore=o),n.options.keepSourceTokens&&m&&(l.srcToken=e),l}function Ki(n,e,t,i,{spaceBefore:r,comment:s,anchor:o,tag:a,end:c},l){let m={type:"scalar",offset:Cf.emptyScalarPosition(e,t,i),indent:-1,source:""},u=Lo.composeScalar(n,m,a,l);return o&&(u.anchor=o.source.substring(1),u.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),r&&(u.spaceBefore=!0),s&&(u.comment=s,u.range[2]=c),u}function _f({options:n},{offset:e,source:t,end:i},r){let s=new vf.Alias(t.substring(1));s.source===""&&r(e,"BAD_ALIAS","Alias cannot be an empty string"),s.source.endsWith(":")&&r(e+t.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=e+t.length,a=Sf.resolveEnd(i,o,n.strict,r);return s.range=[e,o,a.offset],a.comment&&(s.comment=a.comment),s}Yi.composeEmptyNode=Ki;Yi.composeNode=Do});var Fo=y(Mo=>{"use strict";var Pf=He(),Wo=$o(),Nf=_e(),Of=Xe();function xf(n,e,{offset:t,start:i,value:r,end:s},o){let a=Object.assign({_directives:e},n),c=new Pf.Document(void 0,a),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},m=Of.resolveProps(i,{indicator:"doc-start",next:r??s?.[0],offset:t,onError:o,parentIndent:0,startOnNewline:!0});m.found&&(c.directives.docStart=!0,r&&(r.type==="block-map"||r.type==="block-seq")&&!m.hasNewline&&o(m.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=r?Wo.composeNode(l,r,m,o):Wo.composeEmptyNode(l,m.end,i,null,m,o);let u=c.contents.range[2],d=Nf.resolveEnd(s,u,!1,o);return d.comment&&(c.comment=d.comment),c.range=[t,u,d.offset],c}Mo.composeDoc=xf});var Ji=y(Yo=>{"use strict";var Af=yt("process"),If=In(),Rf=He(),Ze=Qe(),Bo=_(),jf=Fo(),Tf=_e();function et(n){if(typeof n=="number")return[n,n+1];if(Array.isArray(n))return n.length===2?n:[n[0],n[1]];let{offset:e,source:t}=n;return[e,e+(typeof t=="string"?t.length:1)]}function Ko(n){let e="",t=!1,i=!1;for(let r=0;r{"use strict";var ue=_(),Ao=O(),mf=Mi(),hf=Bi();function gf(n,e,t,i){let{value:r,type:s,comment:o,range:a}=e.type==="block-scalar"?mf.resolveBlockScalar(n,e,i):hf.resolveFlowScalar(e,n.options.strict,i),c=t?n.directives.tagName(t.source,u=>i(t,"TAG_RESOLVE_FAILED",u)):null,l;n.options.stringKeys&&n.atKey?l=n.schema[ue.SCALAR]:c?l=wf(n.schema,r,c,t,i):e.type==="scalar"?l=yf(n,r,e,i):l=n.schema[ue.SCALAR];let m;try{let u=l.resolve(r,d=>i(t??e,"TAG_RESOLVE_FAILED",d),n.options);m=ue.isScalar(u)?u:new Ao.Scalar(u)}catch(u){let d=u instanceof Error?u.message:String(u);i(t??e,"TAG_RESOLVE_FAILED",d),m=new Ao.Scalar(r)}return m.range=a,m.source=r,s&&(m.type=s),c&&(m.tag=c),l.format&&(m.format=l.format),o&&(m.comment=o),m}function wf(n,e,t,i,r){if(t==="!")return n[ue.SCALAR];let s=[];for(let a of n.tags)if(!a.collection&&a.tag===t)if(a.default&&a.test)s.push(a);else return a;for(let a of s)if(a.test?.test(e))return a;let o=n.knownTags[t];return o&&!o.collection?(n.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(r(i,"TAG_RESOLVE_FAILED",`Unresolved tag: ${t}`,t!=="tag:yaml.org,2002:str"),n[ue.SCALAR])}function yf({atKey:n,directives:e,schema:t},i,r,s){let o=t.tags.find(a=>(a.default===!0||n&&a.default==="key")&&a.test?.test(i))||t[ue.SCALAR];if(t.compat){let a=t.compat.find(c=>c.default&&c.test?.test(i))??t[ue.SCALAR];if(o.tag!==a.tag){let c=e.tagString(o.tag),l=e.tagString(a.tag),m=`Value may be parsed as either ${c} or ${l}`;s(r,"TAG_RESOLVE_FAILED",m,!0)}}return o}Io.composeScalar=gf});var To=y(jo=>{"use strict";function vf(n,e,t){if(e){t??(t=e.length);for(let i=t-1;i>=0;--i){let r=e[i];switch(r.type){case"space":case"comment":case"newline":n-=r.source.length;continue}for(r=e[++i];r?.type==="space";)n+=r.source.length,r=e[++i];break}}return n}jo.emptyScalarPosition=vf});var Do=y(Yi=>{"use strict";var bf=Re(),kf=_(),Sf=Po(),qo=Ro(),Cf=Ee(),Ef=To(),_f={composeNode:Lo,composeEmptyNode:Ki};function Lo(n,e,t,i){let r=n.atKey,{spaceBefore:s,comment:o,anchor:a,tag:c}=t,l,m=!0;switch(e.type){case"alias":l=Pf(n,e,i),(a||c)&&i(e,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=qo.composeScalar(n,e,c,i),a&&(l.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=Sf.composeCollection(_f,n,e,t,i),a&&(l.anchor=a.source.substring(1))}catch(u){let d=u instanceof Error?u.message:String(u);i(e,"RESOURCE_EXHAUSTION",d)}break;default:{let u=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;i(e,"UNEXPECTED_TOKEN",u),m=!1}}return l??(l=Ki(n,e.offset,void 0,null,t,i)),a&&l.anchor===""&&i(a,"BAD_ALIAS","Anchor cannot be an empty string"),r&&n.options.stringKeys&&(!kf.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&i(c??e,"NON_STRING_KEY","With stringKeys, all keys must be strings"),s&&(l.spaceBefore=!0),o&&(e.type==="scalar"&&e.source===""?l.comment=o:l.commentBefore=o),n.options.keepSourceTokens&&m&&(l.srcToken=e),l}function Ki(n,e,t,i,{spaceBefore:r,comment:s,anchor:o,tag:a,end:c},l){let m={type:"scalar",offset:Ef.emptyScalarPosition(e,t,i),indent:-1,source:""},u=qo.composeScalar(n,m,a,l);return o&&(u.anchor=o.source.substring(1),u.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),r&&(u.spaceBefore=!0),s&&(u.comment=s,u.range[2]=c),u}function Pf({options:n},{offset:e,source:t,end:i},r){let s=new bf.Alias(t.substring(1));s.source===""&&r(e,"BAD_ALIAS","Alias cannot be an empty string"),s.source.endsWith(":")&&r(e+t.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=e+t.length,a=Cf.resolveEnd(i,o,n.strict,r);return s.range=[e,o,a.offset],a.comment&&(s.comment=a.comment),s}Yi.composeEmptyNode=Ki;Yi.composeNode=Lo});var Mo=y(Wo=>{"use strict";var Nf=He(),$o=Do(),Of=Ee(),xf=Xe();function Af(n,e,{offset:t,start:i,value:r,end:s},o){let a=Object.assign({_directives:e},n),c=new Nf.Document(void 0,a),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},m=xf.resolveProps(i,{indicator:"doc-start",next:r??s?.[0],offset:t,onError:o,parentIndent:0,startOnNewline:!0});m.found&&(c.directives.docStart=!0,r&&(r.type==="block-map"||r.type==="block-seq")&&!m.hasNewline&&o(m.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=r?$o.composeNode(l,r,m,o):$o.composeEmptyNode(l,m.end,i,null,m,o);let u=c.contents.range[2],d=Of.resolveEnd(s,u,!1,o);return d.comment&&(c.comment=d.comment),c.range=[t,u,d.offset],c}Wo.composeDoc=Af});var Ji=y(Ko=>{"use strict";var If=yt("process"),Rf=In(),jf=He(),Ze=Qe(),Fo=_(),Tf=Mo(),qf=Ee();function et(n){if(typeof n=="number")return[n,n+1];if(Array.isArray(n))return n.length===2?n:[n[0],n[1]];let{offset:e,source:t}=n;return[e,e+(typeof t=="string"?t.length:1)]}function Bo(n){let e="",t=!1,i=!1;for(let r=0;r{let o=et(t);s?this.warnings.push(new Ze.YAMLWarning(o,i,r)):this.errors.push(new Ze.YAMLParseError(o,i,r))},this.directives=new If.Directives({version:e.version||"1.2"}),this.options=e}decorate(e,t){let{comment:i,afterEmptyLine:r}=Ko(this.prelude);if(i){let s=e.contents;if(t)e.comment=e.comment?`${e.comment} -${i}`:i;else if(r||e.directives.docStart||!s)e.commentBefore=i;else if(Bo.isCollection(s)&&!s.flow&&s.items.length>0){let o=s.items[0];Bo.isPair(o)&&(o=o.key);let a=o.commentBefore;o.commentBefore=a?`${i} +`)+(s.substring(1)||" "),t=!0,i=!1;break;case"%":n[r+1]?.[0]!=="#"&&(r+=1),t=!1;break;default:t||(i=!0),t=!1}}return{comment:e,afterEmptyLine:i}}var Ui=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(t,i,r,s)=>{let o=et(t);s?this.warnings.push(new Ze.YAMLWarning(o,i,r)):this.errors.push(new Ze.YAMLParseError(o,i,r))},this.directives=new Rf.Directives({version:e.version||"1.2"}),this.options=e}decorate(e,t){let{comment:i,afterEmptyLine:r}=Bo(this.prelude);if(i){let s=e.contents;if(t)e.comment=e.comment?`${e.comment} +${i}`:i;else if(r||e.directives.docStart||!s)e.commentBefore=i;else if(Fo.isCollection(s)&&!s.flow&&s.items.length>0){let o=s.items[0];Fo.isPair(o)&&(o=o.key);let a=o.commentBefore;o.commentBefore=a?`${i} ${a}`:i}else{let o=s.commentBefore;s.commentBefore=o?`${i} -${o}`:i}}if(t){for(let s=0;s{let s=et(e);s[0]+=t,this.onError(s,"BAD_DIRECTIVE",i,r)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let t=jf.composeDoc(this.options,this.directives,e,this.onError);this.atDirectives&&!t.directives.docStart&&this.onError(e,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(t,!1),this.doc&&(yield this.doc),this.doc=t,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(e.source);break;case"error":{let t=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,i=new Ze.YAMLParseError(et(e),"UNEXPECTED_TOKEN",t);this.atDirectives||!this.doc?this.errors.push(i):this.doc.errors.push(i);break}case"doc-end":{if(!this.doc){let i="Unexpected doc-end without preceding document";this.errors.push(new Ze.YAMLParseError(et(e),"UNEXPECTED_TOKEN",i));break}this.doc.directives.docEnd=!0;let t=Tf.resolveEnd(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),t.comment){let i=this.doc.comment;this.doc.comment=i?`${i} -${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.push(new Ze.YAMLParseError(et(e),"UNEXPECTED_TOKEN",`Unsupported token ${e.type}`))}}*end(e=!1,t=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let i=Object.assign({_directives:this.directives},this.options),r=new Rf.Document(void 0,i);this.atDirectives&&this.onError(t,"MISSING_CHAR","Missing directives-end indicator line"),r.range=[0,t,t],this.decorate(r,!1),yield r}}};Yo.Composer=Ui});var Vo=y(un=>{"use strict";var qf=Mi(),Lf=Bi(),Df=Qe(),Uo=De();function $f(n,e=!0,t){if(n){let i=(r,s,o)=>{let a=typeof r=="number"?r:Array.isArray(r)?r[0]:r.offset;if(t)t(a,s,o);else throw new Df.YAMLParseError([a,a+1],s,o)};switch(n.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return Lf.resolveFlowScalar(n,e,i);case"block-scalar":return qf.resolveBlockScalar({options:{strict:e}},n,i)}}return null}function Wf(n,e){let{implicitKey:t=!1,indent:i,inFlow:r=!1,offset:s=-1,type:o="PLAIN"}=e,a=Uo.stringifyString({type:o,value:n},{implicitKey:t,indent:i>0?" ".repeat(i):"",inFlow:r,options:{blockQuote:!0,lineWidth:-1}}),c=e.end??[{type:"newline",offset:-1,indent:i,source:` +${o}`:i}}if(t){for(let s=0;s{let s=et(e);s[0]+=t,this.onError(s,"BAD_DIRECTIVE",i,r)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let t=Tf.composeDoc(this.options,this.directives,e,this.onError);this.atDirectives&&!t.directives.docStart&&this.onError(e,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(t,!1),this.doc&&(yield this.doc),this.doc=t,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(e.source);break;case"error":{let t=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,i=new Ze.YAMLParseError(et(e),"UNEXPECTED_TOKEN",t);this.atDirectives||!this.doc?this.errors.push(i):this.doc.errors.push(i);break}case"doc-end":{if(!this.doc){let i="Unexpected doc-end without preceding document";this.errors.push(new Ze.YAMLParseError(et(e),"UNEXPECTED_TOKEN",i));break}this.doc.directives.docEnd=!0;let t=qf.resolveEnd(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),t.comment){let i=this.doc.comment;this.doc.comment=i?`${i} +${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.push(new Ze.YAMLParseError(et(e),"UNEXPECTED_TOKEN",`Unsupported token ${e.type}`))}}*end(e=!1,t=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let i=Object.assign({_directives:this.directives},this.options),r=new jf.Document(void 0,i);this.atDirectives&&this.onError(t,"MISSING_CHAR","Missing directives-end indicator line"),r.range=[0,t,t],this.decorate(r,!1),yield r}}};Ko.Composer=Ui});var Jo=y(un=>{"use strict";var Lf=Mi(),Df=Bi(),$f=Qe(),Yo=De();function Wf(n,e=!0,t){if(n){let i=(r,s,o)=>{let a=typeof r=="number"?r:Array.isArray(r)?r[0]:r.offset;if(t)t(a,s,o);else throw new $f.YAMLParseError([a,a+1],s,o)};switch(n.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return Df.resolveFlowScalar(n,e,i);case"block-scalar":return Lf.resolveBlockScalar({options:{strict:e}},n,i)}}return null}function Mf(n,e){let{implicitKey:t=!1,indent:i,inFlow:r=!1,offset:s=-1,type:o="PLAIN"}=e,a=Yo.stringifyString({type:o,value:n},{implicitKey:t,indent:i>0?" ".repeat(i):"",inFlow:r,options:{blockQuote:!0,lineWidth:-1}}),c=e.end??[{type:"newline",offset:-1,indent:i,source:` `}];switch(a[0]){case"|":case">":{let l=a.indexOf(` `),m=a.substring(0,l),u=a.substring(l+1)+` -`,d=[{type:"block-scalar-header",offset:s,indent:i,source:m}];return Jo(d,c)||d.push({type:"newline",offset:-1,indent:i,source:` -`}),{type:"block-scalar",offset:s,indent:i,props:d,source:u}}case'"':return{type:"double-quoted-scalar",offset:s,indent:i,source:a,end:c};case"'":return{type:"single-quoted-scalar",offset:s,indent:i,source:a,end:c};default:return{type:"scalar",offset:s,indent:i,source:a,end:c}}}function Mf(n,e,t={}){let{afterKey:i=!1,implicitKey:r=!1,inFlow:s=!1,type:o}=t,a="indent"in n?n.indent:null;if(i&&typeof a=="number"&&(a+=2),!o)switch(n.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let l=n.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let c=Uo.stringifyString({type:o,value:e},{implicitKey:r||a===null,indent:a!==null&&a>0?" ".repeat(a):"",inFlow:s,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":Ff(n,c);break;case'"':Vi(n,c,"double-quoted-scalar");break;case"'":Vi(n,c,"single-quoted-scalar");break;default:Vi(n,c,"scalar")}}function Ff(n,e){let t=e.indexOf(` +`,d=[{type:"block-scalar-header",offset:s,indent:i,source:m}];return Uo(d,c)||d.push({type:"newline",offset:-1,indent:i,source:` +`}),{type:"block-scalar",offset:s,indent:i,props:d,source:u}}case'"':return{type:"double-quoted-scalar",offset:s,indent:i,source:a,end:c};case"'":return{type:"single-quoted-scalar",offset:s,indent:i,source:a,end:c};default:return{type:"scalar",offset:s,indent:i,source:a,end:c}}}function Ff(n,e,t={}){let{afterKey:i=!1,implicitKey:r=!1,inFlow:s=!1,type:o}=t,a="indent"in n?n.indent:null;if(i&&typeof a=="number"&&(a+=2),!o)switch(n.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let l=n.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let c=Yo.stringifyString({type:o,value:e},{implicitKey:r||a===null,indent:a!==null&&a>0?" ".repeat(a):"",inFlow:s,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":Bf(n,c);break;case'"':Vi(n,c,"double-quoted-scalar");break;case"'":Vi(n,c,"single-quoted-scalar");break;default:Vi(n,c,"scalar")}}function Bf(n,e){let t=e.indexOf(` `),i=e.substring(0,t),r=e.substring(t+1)+` -`;if(n.type==="block-scalar"){let s=n.props[0];if(s.type!=="block-scalar-header")throw new Error("Invalid block scalar header");s.source=i,n.source=r}else{let{offset:s}=n,o="indent"in n?n.indent:-1,a=[{type:"block-scalar-header",offset:s,indent:o,source:i}];Jo(a,"end"in n?n.end:void 0)||a.push({type:"newline",offset:-1,indent:o,source:` -`});for(let c of Object.keys(n))c!=="type"&&c!=="offset"&&delete n[c];Object.assign(n,{type:"block-scalar",indent:o,props:a,source:r})}}function Jo(n,e){if(e)for(let t of e)switch(t.type){case"space":case"comment":n.push(t);break;case"newline":return n.push(t),!0}return!1}function Vi(n,e,t){switch(n.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":n.type=t,n.source=e;break;case"block-scalar":{let i=n.props.slice(1),r=e.length;n.props[0].type==="block-scalar-header"&&(r-=n.props[0].source.length);for(let s of i)s.offset+=r;delete n.props,Object.assign(n,{type:t,source:e,end:i});break}case"block-map":case"block-seq":{let r={type:"newline",offset:n.offset+e.length,indent:n.indent,source:` -`};delete n.items,Object.assign(n,{type:t,source:e,end:[r]});break}default:{let i="indent"in n?n.indent:-1,r="end"in n&&Array.isArray(n.end)?n.end.filter(s=>s.type==="space"||s.type==="comment"||s.type==="newline"):[];for(let s of Object.keys(n))s!=="type"&&s!=="offset"&&delete n[s];Object.assign(n,{type:t,indent:i,source:e,end:r})}}}un.createScalarToken=Wf;un.resolveAsScalar=$f;un.setScalarValue=Mf});var Go=y(Ho=>{"use strict";var Bf=n=>"type"in n?dn(n):fn(n);function dn(n){switch(n.type){case"block-scalar":{let e="";for(let t of n.props)e+=dn(t);return e+n.source}case"block-map":case"block-seq":{let e="";for(let t of n.items)e+=fn(t);return e}case"flow-collection":{let e=n.start.source;for(let t of n.items)e+=fn(t);for(let t of n.end)e+=t.source;return e}case"document":{let e=fn(n);if(n.end)for(let t of n.end)e+=t.source;return e}default:{let e=n.source;if("end"in n&&n.end)for(let t of n.end)e+=t.source;return e}}}function fn({start:n,key:e,sep:t,value:i}){let r="";for(let s of n)r+=s.source;if(e&&(r+=dn(e)),t)for(let s of t)r+=s.source;return i&&(r+=dn(i)),r}Ho.stringify=Bf});var Zo=y(Xo=>{"use strict";var Hi=Symbol("break visit"),Kf=Symbol("skip children"),zo=Symbol("remove item");function de(n,e){"type"in n&&n.type==="document"&&(n={start:n.start,value:n.value}),Qo(Object.freeze([]),n,e)}de.BREAK=Hi;de.SKIP=Kf;de.REMOVE=zo;de.itemAtPath=(n,e)=>{let t=n;for(let[i,r]of e){let s=t?.[i];if(s&&"items"in s)t=s.items[r];else return}return t};de.parentCollection=(n,e)=>{let t=de.itemAtPath(n,e.slice(0,-1)),i=e[e.length-1][0],r=t?.[i];if(r&&"items"in r)return r;throw new Error("Parent collection not found")};function Qo(n,e,t){let i=t(e,n);if(typeof i=="symbol")return i;for(let r of["key","value"]){let s=e[r];if(s&&"items"in s){for(let o=0;o{"use strict";var Gi=Vo(),Yf=Go(),Uf=Zo(),zi="\uFEFF",Qi="",Xi="",Zi="",Jf=n=>!!n&&"items"in n,Vf=n=>!!n&&(n.type==="scalar"||n.type==="single-quoted-scalar"||n.type==="double-quoted-scalar"||n.type==="block-scalar");function Hf(n){switch(n){case zi:return"";case Qi:return"";case Xi:return"";case Zi:return"";default:return JSON.stringify(n)}}function Gf(n){switch(n){case zi:return"byte-order-mark";case Qi:return"doc-mode";case Xi:return"flow-error-end";case Zi:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case` +`;if(n.type==="block-scalar"){let s=n.props[0];if(s.type!=="block-scalar-header")throw new Error("Invalid block scalar header");s.source=i,n.source=r}else{let{offset:s}=n,o="indent"in n?n.indent:-1,a=[{type:"block-scalar-header",offset:s,indent:o,source:i}];Uo(a,"end"in n?n.end:void 0)||a.push({type:"newline",offset:-1,indent:o,source:` +`});for(let c of Object.keys(n))c!=="type"&&c!=="offset"&&delete n[c];Object.assign(n,{type:"block-scalar",indent:o,props:a,source:r})}}function Uo(n,e){if(e)for(let t of e)switch(t.type){case"space":case"comment":n.push(t);break;case"newline":return n.push(t),!0}return!1}function Vi(n,e,t){switch(n.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":n.type=t,n.source=e;break;case"block-scalar":{let i=n.props.slice(1),r=e.length;n.props[0].type==="block-scalar-header"&&(r-=n.props[0].source.length);for(let s of i)s.offset+=r;delete n.props,Object.assign(n,{type:t,source:e,end:i});break}case"block-map":case"block-seq":{let r={type:"newline",offset:n.offset+e.length,indent:n.indent,source:` +`};delete n.items,Object.assign(n,{type:t,source:e,end:[r]});break}default:{let i="indent"in n?n.indent:-1,r="end"in n&&Array.isArray(n.end)?n.end.filter(s=>s.type==="space"||s.type==="comment"||s.type==="newline"):[];for(let s of Object.keys(n))s!=="type"&&s!=="offset"&&delete n[s];Object.assign(n,{type:t,indent:i,source:e,end:r})}}}un.createScalarToken=Mf;un.resolveAsScalar=Wf;un.setScalarValue=Ff});var Ho=y(Vo=>{"use strict";var Kf=n=>"type"in n?dn(n):fn(n);function dn(n){switch(n.type){case"block-scalar":{let e="";for(let t of n.props)e+=dn(t);return e+n.source}case"block-map":case"block-seq":{let e="";for(let t of n.items)e+=fn(t);return e}case"flow-collection":{let e=n.start.source;for(let t of n.items)e+=fn(t);for(let t of n.end)e+=t.source;return e}case"document":{let e=fn(n);if(n.end)for(let t of n.end)e+=t.source;return e}default:{let e=n.source;if("end"in n&&n.end)for(let t of n.end)e+=t.source;return e}}}function fn({start:n,key:e,sep:t,value:i}){let r="";for(let s of n)r+=s.source;if(e&&(r+=dn(e)),t)for(let s of t)r+=s.source;return i&&(r+=dn(i)),r}Vo.stringify=Kf});var Xo=y(Qo=>{"use strict";var Hi=Symbol("break visit"),Yf=Symbol("skip children"),Go=Symbol("remove item");function fe(n,e){"type"in n&&n.type==="document"&&(n={start:n.start,value:n.value}),zo(Object.freeze([]),n,e)}fe.BREAK=Hi;fe.SKIP=Yf;fe.REMOVE=Go;fe.itemAtPath=(n,e)=>{let t=n;for(let[i,r]of e){let s=t?.[i];if(s&&"items"in s)t=s.items[r];else return}return t};fe.parentCollection=(n,e)=>{let t=fe.itemAtPath(n,e.slice(0,-1)),i=e[e.length-1][0],r=t?.[i];if(r&&"items"in r)return r;throw new Error("Parent collection not found")};function zo(n,e,t){let i=t(e,n);if(typeof i=="symbol")return i;for(let r of["key","value"]){let s=e[r];if(s&&"items"in s){for(let o=0;o{"use strict";var Gi=Jo(),Uf=Ho(),Jf=Xo(),zi="\uFEFF",Qi="",Xi="",Zi="",Vf=n=>!!n&&"items"in n,Hf=n=>!!n&&(n.type==="scalar"||n.type==="single-quoted-scalar"||n.type==="double-quoted-scalar"||n.type==="block-scalar");function Gf(n){switch(n){case zi:return"";case Qi:return"";case Xi:return"";case Zi:return"";default:return JSON.stringify(n)}}function zf(n){switch(n){case zi:return"byte-order-mark";case Qi:return"doc-mode";case Xi:return"flow-error-end";case Zi:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case` `:case`\r -`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(n[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}q.createScalarToken=Gi.createScalarToken;q.resolveAsScalar=Gi.resolveAsScalar;q.setScalarValue=Gi.setScalarValue;q.stringify=Yf.stringify;q.visit=Uf.visit;q.BOM=zi;q.DOCUMENT=Qi;q.FLOW_END=Xi;q.SCALAR=Zi;q.isCollection=Jf;q.isScalar=Vf;q.prettyToken=Hf;q.tokenType=Gf});var nr=y(ta=>{"use strict";var tt=pn();function W(n){switch(n){case void 0:case" ":case` -`:case"\r":case" ":return!0;default:return!1}}var ea=new Set("0123456789ABCDEFabcdef"),zf=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),mn=new Set(",[]{}"),Qf=new Set(` ,[]{} -\r `),er=n=>!n||Qf.has(n),tr=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,t=!1){if(e){if(typeof e!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!t;let i=this.next??"stream";for(;i&&(t||this.hasChars(1));)i=yield*this.parseNext(i)}atLineEnd(){let e=this.pos,t=this.buffer[e];for(;t===" "||t===" ";)t=this.buffer[++e];return!t||t==="#"||t===` +`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(n[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}q.createScalarToken=Gi.createScalarToken;q.resolveAsScalar=Gi.resolveAsScalar;q.setScalarValue=Gi.setScalarValue;q.stringify=Uf.stringify;q.visit=Jf.visit;q.BOM=zi;q.DOCUMENT=Qi;q.FLOW_END=Xi;q.SCALAR=Zi;q.isCollection=Vf;q.isScalar=Hf;q.prettyToken=Gf;q.tokenType=zf});var nr=y(ea=>{"use strict";var tt=pn();function $(n){switch(n){case void 0:case" ":case` +`:case"\r":case" ":return!0;default:return!1}}var Zo=new Set("0123456789ABCDEFabcdef"),Qf=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),mn=new Set(",[]{}"),Xf=new Set(` ,[]{} +\r `),er=n=>!n||Xf.has(n),tr=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,t=!1){if(e){if(typeof e!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!t;let i=this.next??"stream";for(;i&&(t||this.hasChars(1));)i=yield*this.parseNext(i)}atLineEnd(){let e=this.pos,t=this.buffer[e];for(;t===" "||t===" ";)t=this.buffer[++e];return!t||t==="#"||t===` `?!0:t==="\r"?this.buffer[e+1]===` `:!1}charAt(e){return this.buffer[this.pos+e]}continueScalar(e){let t=this.buffer[e];if(this.indentNext>0){let i=0;for(;t===" ";)t=this.buffer[++i+e];if(t==="\r"){let r=this.buffer[i+e+1];if(r===` `||!r&&!this.atEnd)return e+i+1}return t===` -`||i>=this.indentNext||!t&&!this.atEnd?e+i:-1}if(t==="-"||t==="."){let i=this.buffer.substr(e,3);if((i==="---"||i==="...")&&W(this.buffer[e+3]))return-1}return e}getLine(){let e=this.lineEndPos;return(typeof e!="number"||e!==-1&&ethis.indentValue&&!W(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[e,t]=this.peek(2);if(!t&&!this.atEnd)return this.setNext("block-start");if((e==="-"||e==="?"||e===":")&&W(t)){let i=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=i,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let e=this.getLine();if(e===null)return this.setNext("doc");let t=yield*this.pushIndicators();switch(e[t]){case"#":yield*this.pushCount(e.length-t);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(er),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return t+=yield*this.parseBlockScalarHeader(),t+=yield*this.pushSpaces(!0),yield*this.pushCount(e.length-t),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,t,i=-1;do e=yield*this.pushNewline(),e>0?(t=yield*this.pushSpaces(!1),this.indentValue=i=t):t=0,t+=yield*this.pushSpaces(!0);while(e+t>0);let r=this.getLine();if(r===null)return this.setNext("flow");if((i!==-1&&i=this.indentNext||!t&&!this.atEnd?e+i:-1}if(t==="-"||t==="."){let i=this.buffer.substr(e,3);if((i==="---"||i==="...")&&$(this.buffer[e+3]))return-1}return e}getLine(){let e=this.lineEndPos;return(typeof e!="number"||e!==-1&&ethis.indentValue&&!$(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[e,t]=this.peek(2);if(!t&&!this.atEnd)return this.setNext("block-start");if((e==="-"||e==="?"||e===":")&&$(t)){let i=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=i,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let e=this.getLine();if(e===null)return this.setNext("doc");let t=yield*this.pushIndicators();switch(e[t]){case"#":yield*this.pushCount(e.length-t);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(er),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return t+=yield*this.parseBlockScalarHeader(),t+=yield*this.pushSpaces(!0),yield*this.pushCount(e.length-t),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,t,i=-1;do e=yield*this.pushNewline(),e>0?(t=yield*this.pushSpaces(!1),this.indentValue=i=t):t=0,t+=yield*this.pushSpaces(!0);while(e+t>0);let r=this.getLine();if(r===null)return this.setNext("flow");if((i!==-1&&i"0"&&t<="9")this.blockScalarIndent=Number(t)-1;else if(t!=="-")break}return yield*this.pushUntil(t=>W(t)||t==="#")}*parseBlockScalar(){let e=this.pos-1,t=0,i;e:for(let s=this.pos;i=this.buffer[s];++s)switch(i){case" ":t+=1;break;case` +`,s)}r!==-1&&(t=r-(i[r-1]==="\r"?2:1))}if(t===-1){if(!this.atEnd)return this.setNext("quoted-scalar");t=this.buffer.length}return yield*this.pushToIndex(t+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let e=this.pos;for(;;){let t=this.buffer[++e];if(t==="+")this.blockScalarKeep=!0;else if(t>"0"&&t<="9")this.blockScalarIndent=Number(t)-1;else if(t!=="-")break}return yield*this.pushUntil(t=>$(t)||t==="#")}*parseBlockScalar(){let e=this.pos-1,t=0,i;e:for(let s=this.pos;i=this.buffer[s];++s)switch(i){case" ":t+=1;break;case` `:e=s,t=0;break;case"\r":{let o=this.buffer[s+1];if(!o&&!this.atEnd)return this.setNext("block-scalar");if(o===` `)break}default:break e}if(!i&&!this.atEnd)return this.setNext("block-scalar");if(t>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=t:this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let s=this.continueScalar(e+1);if(s===-1)break;e=this.buffer.indexOf(` `,s)}while(e!==-1);if(e===-1){if(!this.atEnd)return this.setNext("block-scalar");e=this.buffer.length}}let r=e+1;for(i=this.buffer[r];i===" ";)i=this.buffer[++r];if(i===" "){for(;i===" "||i===" "||i==="\r"||i===` `;)i=this.buffer[++r];e=r-1}else if(!this.blockScalarKeep)do{let s=e-1,o=this.buffer[s];o==="\r"&&(o=this.buffer[--s]);let a=s;for(;o===" ";)o=this.buffer[--s];if(o===` -`&&s>=this.pos&&s+1+t>a)e=s;else break}while(!0);return yield tt.SCALAR,yield*this.pushToIndex(e+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let e=this.flowLevel>0,t=this.pos-1,i=this.pos-1,r;for(;r=this.buffer[++i];)if(r===":"){let s=this.buffer[i+1];if(W(s)||e&&mn.has(s))break;t=i}else if(W(r)){let s=this.buffer[i+1];if(r==="\r"&&(s===` +`&&s>=this.pos&&s+1+t>a)e=s;else break}while(!0);return yield tt.SCALAR,yield*this.pushToIndex(e+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let e=this.flowLevel>0,t=this.pos-1,i=this.pos-1,r;for(;r=this.buffer[++i];)if(r===":"){let s=this.buffer[i+1];if($(s)||e&&mn.has(s))break;t=i}else if($(r)){let s=this.buffer[i+1];if(r==="\r"&&(s===` `?(i+=1,r=` `,s=this.buffer[i+1]):t=i),s==="#"||e&&mn.has(s))break;if(r===` -`){let o=this.continueScalar(i+1);if(o===-1)break;i=Math.max(i,o-2)}}else{if(e&&mn.has(r))break;t=i}return!r&&!this.atEnd?this.setNext("plain-scalar"):(yield tt.SCALAR,yield*this.pushToIndex(t+1,!0),e?"flow":"doc")}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,t){let i=this.buffer.slice(this.pos,e);return i?(yield i,this.pos+=i.length,i.length):(t&&(yield""),0)}*pushIndicators(){let e=0;e:for(;;){switch(this.charAt(0)){case"!":e+=yield*this.pushTag(),e+=yield*this.pushSpaces(!0);continue e;case"&":e+=yield*this.pushUntil(er),e+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let t=this.flowLevel>0,i=this.charAt(1);if(W(i)||t&&mn.has(i)){t?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,e+=yield*this.pushCount(1),e+=yield*this.pushSpaces(!0);continue e}}}break e}return e}*pushTag(){if(this.charAt(1)==="<"){let e=this.pos+2,t=this.buffer[e];for(;!W(t)&&t!==">";)t=this.buffer[++e];return yield*this.pushToIndex(t===">"?e+1:e,!1)}else{let e=this.pos+1,t=this.buffer[e];for(;t;)if(zf.has(t))t=this.buffer[++e];else if(t==="%"&&ea.has(this.buffer[e+1])&&ea.has(this.buffer[e+2]))t=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];return e===` +`){let o=this.continueScalar(i+1);if(o===-1)break;i=Math.max(i,o-2)}}else{if(e&&mn.has(r))break;t=i}return!r&&!this.atEnd?this.setNext("plain-scalar"):(yield tt.SCALAR,yield*this.pushToIndex(t+1,!0),e?"flow":"doc")}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,t){let i=this.buffer.slice(this.pos,e);return i?(yield i,this.pos+=i.length,i.length):(t&&(yield""),0)}*pushIndicators(){let e=0;e:for(;;){switch(this.charAt(0)){case"!":e+=yield*this.pushTag(),e+=yield*this.pushSpaces(!0);continue e;case"&":e+=yield*this.pushUntil(er),e+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let t=this.flowLevel>0,i=this.charAt(1);if($(i)||t&&mn.has(i)){t?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,e+=yield*this.pushCount(1),e+=yield*this.pushSpaces(!0);continue e}}}break e}return e}*pushTag(){if(this.charAt(1)==="<"){let e=this.pos+2,t=this.buffer[e];for(;!$(t)&&t!==">";)t=this.buffer[++e];return yield*this.pushToIndex(t===">"?e+1:e,!1)}else{let e=this.pos+1,t=this.buffer[e];for(;t;)if(Qf.has(t))t=this.buffer[++e];else if(t==="%"&&Zo.has(this.buffer[e+1])&&Zo.has(this.buffer[e+2]))t=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];return e===` `?yield*this.pushCount(1):e==="\r"&&this.charAt(1)===` -`?yield*this.pushCount(2):0}*pushSpaces(e){let t=this.pos-1,i;do i=this.buffer[++t];while(i===" "||e&&i===" ");let r=t-this.pos;return r>0&&(yield this.buffer.substr(this.pos,r),this.pos=t),r}*pushUntil(e){let t=this.pos,i=this.buffer[t];for(;!e(i);)i=this.buffer[++t];return yield*this.pushToIndex(t,!1)}};ta.Lexer=tr});var rr=y(na=>{"use strict";var ir=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let t=0,i=this.lineStarts.length;for(;t>1;this.lineStarts[s]{"use strict";var Xf=yt("process"),ia=pn(),Zf=nr();function ne(n,e){for(let t=0;t=0;)switch(n[e].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;n[++e]?.type==="space";);return n.splice(e,n.length)}function gn(n,e){if(e.length<1e5)Array.prototype.push.apply(n,e);else for(let t=0;t0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let e=this.peek(1);if(this.type==="doc-end"&&e?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!e)return yield*this.stream();switch(e.type){case"document":return yield*this.document(e);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(e);case"block-scalar":return yield*this.blockScalar(e);case"block-map":return yield*this.blockMap(e);case"block-seq":return yield*this.blockSequence(e);case"flow-collection":return yield*this.flowCollection(e);case"doc-end":return yield*this.documentEnd(e)}yield*this.pop()}peek(e){return this.stack[this.stack.length-e]}*pop(e){let t=e??this.stack.pop();if(!t)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield t;else{let i=this.peek(1);switch(t.type==="block-scalar"?t.indent="indent"in i?i.indent:0:t.type==="flow-collection"&&i.type==="document"&&(t.indent=0),t.type==="flow-collection"&&sa(t),i.type){case"document":i.value=t;break;case"block-scalar":i.props.push(t);break;case"block-map":{let r=i.items[i.items.length-1];if(r.value){i.items.push({start:[],key:t,sep:[]}),this.onKeyLine=!0;return}else if(r.sep)r.value=t;else{Object.assign(r,{key:t,sep:[]}),this.onKeyLine=!r.explicitKey;return}break}case"block-seq":{let r=i.items[i.items.length-1];r.value?i.items.push({start:[],value:t}):r.value=t;break}case"flow-collection":{let r=i.items[i.items.length-1];!r||r.value?i.items.push({start:[],key:t,sep:[]}):r.sep?r.value=t:Object.assign(r,{key:t,sep:[]});return}default:yield*this.pop(),yield*this.pop(t)}if((i.type==="document"||i.type==="block-map"||i.type==="block-seq")&&(t.type==="block-map"||t.type==="block-seq")){let r=t.items[t.items.length-1];r&&!r.sep&&!r.value&&r.start.length>0&&ra(r.start)===-1&&(t.indent===0||r.start.every(s=>s.type!=="comment"||s.indent0&&(yield this.buffer.substr(this.pos,r),this.pos=t),r}*pushUntil(e){let t=this.pos,i=this.buffer[t];for(;!e(i);)i=this.buffer[++t];return yield*this.pushToIndex(t,!1)}};ea.Lexer=tr});var rr=y(ta=>{"use strict";var ir=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let t=0,i=this.lineStarts.length;for(;t>1;this.lineStarts[s]{"use strict";var Zf=yt("process"),na=pn(),ed=nr();function te(n,e){for(let t=0;t=0;)switch(n[e].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;n[++e]?.type==="space";);return n.splice(e,n.length)}function gn(n,e){if(e.length<1e5)Array.prototype.push.apply(n,e);else for(let t=0;t0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let e=this.peek(1);if(this.type==="doc-end"&&e?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!e)return yield*this.stream();switch(e.type){case"document":return yield*this.document(e);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(e);case"block-scalar":return yield*this.blockScalar(e);case"block-map":return yield*this.blockMap(e);case"block-seq":return yield*this.blockSequence(e);case"flow-collection":return yield*this.flowCollection(e);case"doc-end":return yield*this.documentEnd(e)}yield*this.pop()}peek(e){return this.stack[this.stack.length-e]}*pop(e){let t=e??this.stack.pop();if(!t)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield t;else{let i=this.peek(1);switch(t.type==="block-scalar"?t.indent="indent"in i?i.indent:0:t.type==="flow-collection"&&i.type==="document"&&(t.indent=0),t.type==="flow-collection"&&ra(t),i.type){case"document":i.value=t;break;case"block-scalar":i.props.push(t);break;case"block-map":{let r=i.items[i.items.length-1];if(r.value){i.items.push({start:[],key:t,sep:[]}),this.onKeyLine=!0;return}else if(r.sep)r.value=t;else{Object.assign(r,{key:t,sep:[]}),this.onKeyLine=!r.explicitKey;return}break}case"block-seq":{let r=i.items[i.items.length-1];r.value?i.items.push({start:[],value:t}):r.value=t;break}case"flow-collection":{let r=i.items[i.items.length-1];!r||r.value?i.items.push({start:[],key:t,sep:[]}):r.sep?r.value=t:Object.assign(r,{key:t,sep:[]});return}default:yield*this.pop(),yield*this.pop(t)}if((i.type==="document"||i.type==="block-map"||i.type==="block-seq")&&(t.type==="block-map"||t.type==="block-seq")){let r=t.items[t.items.length-1];r&&!r.sep&&!r.value&&r.start.length>0&&ia(r.start)===-1&&(t.indent===0||r.start.every(s=>s.type!=="comment"||s.indent=e.indent){let i=!this.onKeyLine&&this.indent===e.indent,r=i&&(t.sep||t.explicitKey)&&this.type!=="seq-item-ind",s=[];if(r&&t.sep&&!t.value){let o=[];for(let a=0;ae.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(s=t.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":r||t.value?(s.push(this.sourceToken),e.items.push({start:s}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"explicit-key-ind":!t.sep&&!t.explicitKey?(t.start.push(this.sourceToken),t.explicitKey=!0):r||t.value?(s.push(this.sourceToken),e.items.push({start:s,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(t.explicitKey)if(t.sep)if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(ne(t.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:s,key:null,sep:[this.sourceToken]}]});else if(oa(t.key)&&!ne(t.sep,"newline")){let o=Pe(t.start),a=t.key,c=t.sep;c.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:a,sep:c}]})}else s.length>0?t.sep=t.sep.concat(s,this.sourceToken):t.sep.push(this.sourceToken);else if(ne(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let o=Pe(t.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else t.sep?t.value||r?e.items.push({start:s,key:null,sep:[this.sourceToken]}):ne(t.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);r||t.value?(e.items.push({start:s,key:o,sep:[]}),this.onKeyLine=!0):t.sep?this.stack.push(o):(Object.assign(t,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(e);if(o){if(o.type==="block-seq"){if(!t.explicitKey&&t.sep&&!ne(t.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else i&&e.items.push({start:s});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let t=e.items[e.items.length-1];switch(this.type){case"newline":if(t.value){let i="end"in t.value?t.value.end:void 0;(Array.isArray(i)?i[i.length-1]:void 0)?.type==="comment"?i?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(t.start,e.indent)){let r=e.items[e.items.length-2]?.value?.end;if(Array.isArray(r)){gn(r,t.start),r.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return;case"anchor":case"tag":if(t.value||this.indent<=e.indent)break;t.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;t.value||ne(t.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return}if(this.indent>e.indent){let i=this.startBlockValue(e);if(i){this.stack.push(i);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let t=e.items[e.items.length-1];if(this.type==="flow-error-end"){let i;do yield*this.pop(),i=this.peek(1);while(i?.type==="flow-collection")}else if(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!t||t.sep?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return;case"map-value-ind":!t||t.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!t||t.value?e.items.push({start:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let r=this.flowScalar(this.type);!t||t.value?e.items.push({start:[],key:r,sep:[]}):t.sep?this.stack.push(r):Object.assign(t,{key:r,sep:[]});return}case"flow-map-end":case"flow-seq-end":e.end.push(this.sourceToken);return}let i=this.startBlockValue(e);i?this.stack.push(i):(yield*this.pop(),yield*this.step())}else{let i=this.peek(2);if(i.type==="block-map"&&(this.type==="map-value-ind"&&i.indent===e.indent||this.type==="newline"&&!i.items[i.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&i.type!=="flow-collection"){let r=hn(i),s=Pe(r);sa(e);let o=e.end.splice(1,e.end.length);o.push(this.sourceToken);let a={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:s,key:e,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let t=this.source.indexOf(` +`,t)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let t=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,t.value){let i="end"in t.value?t.value.end:void 0;(Array.isArray(i)?i[i.length-1]:void 0)?.type==="comment"?i?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){let r=e.items[e.items.length-2]?.value?.end;if(Array.isArray(r)){gn(r,t.start),r.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let i=!this.onKeyLine&&this.indent===e.indent,r=i&&(t.sep||t.explicitKey)&&this.type!=="seq-item-ind",s=[];if(r&&t.sep&&!t.value){let o=[];for(let a=0;ae.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(s=t.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":r||t.value?(s.push(this.sourceToken),e.items.push({start:s}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"explicit-key-ind":!t.sep&&!t.explicitKey?(t.start.push(this.sourceToken),t.explicitKey=!0):r||t.value?(s.push(this.sourceToken),e.items.push({start:s,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(t.explicitKey)if(t.sep)if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(te(t.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:s,key:null,sep:[this.sourceToken]}]});else if(sa(t.key)&&!te(t.sep,"newline")){let o=_e(t.start),a=t.key,c=t.sep;c.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:a,sep:c}]})}else s.length>0?t.sep=t.sep.concat(s,this.sourceToken):t.sep.push(this.sourceToken);else if(te(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let o=_e(t.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else t.sep?t.value||r?e.items.push({start:s,key:null,sep:[this.sourceToken]}):te(t.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);r||t.value?(e.items.push({start:s,key:o,sep:[]}),this.onKeyLine=!0):t.sep?this.stack.push(o):(Object.assign(t,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(e);if(o){if(o.type==="block-seq"){if(!t.explicitKey&&t.sep&&!te(t.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else i&&e.items.push({start:s});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let t=e.items[e.items.length-1];switch(this.type){case"newline":if(t.value){let i="end"in t.value?t.value.end:void 0;(Array.isArray(i)?i[i.length-1]:void 0)?.type==="comment"?i?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(t.start,e.indent)){let r=e.items[e.items.length-2]?.value?.end;if(Array.isArray(r)){gn(r,t.start),r.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return;case"anchor":case"tag":if(t.value||this.indent<=e.indent)break;t.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;t.value||te(t.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return}if(this.indent>e.indent){let i=this.startBlockValue(e);if(i){this.stack.push(i);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let t=e.items[e.items.length-1];if(this.type==="flow-error-end"){let i;do yield*this.pop(),i=this.peek(1);while(i?.type==="flow-collection")}else if(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!t||t.sep?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return;case"map-value-ind":!t||t.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!t||t.value?e.items.push({start:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let r=this.flowScalar(this.type);!t||t.value?e.items.push({start:[],key:r,sep:[]}):t.sep?this.stack.push(r):Object.assign(t,{key:r,sep:[]});return}case"flow-map-end":case"flow-seq-end":e.end.push(this.sourceToken);return}let i=this.startBlockValue(e);i?this.stack.push(i):(yield*this.pop(),yield*this.step())}else{let i=this.peek(2);if(i.type==="block-map"&&(this.type==="map-value-ind"&&i.indent===e.indent||this.type==="newline"&&!i.items[i.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&i.type!=="flow-collection"){let r=hn(i),s=_e(r);ra(e);let o=e.end.splice(1,e.end.length);o.push(this.sourceToken);let a={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:s,key:e,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let t=this.source.indexOf(` `)+1;for(;t!==0;)this.onNewLine(this.offset+t),t=this.source.indexOf(` -`,t)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let t=hn(e),i=Pe(t);return i.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let t=hn(e),i=Pe(t);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!=="comment"||this.indent<=t?!1:e.every(i=>i.type==="newline"||i.type==="space")}*documentEnd(e){this.type!=="doc-mode"&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};aa.Parser=sr});var da=y(it=>{"use strict";var ca=Ji(),ed=He(),nt=Qe(),td=Yn(),nd=_(),id=rr(),la=or();function ua(n){let e=n.prettyErrors!==!1;return{lineCounter:n.lineCounter||e&&new id.LineCounter||null,prettyErrors:e}}function rd(n,e={}){let{lineCounter:t,prettyErrors:i}=ua(e),r=new la.Parser(t?.addNewLine),s=new ca.Composer(e),o=Array.from(s.compose(r.parse(n)));if(i&&t)for(let a of o)a.errors.forEach(nt.prettifyError(n,t)),a.warnings.forEach(nt.prettifyError(n,t));return o.length>0?o:Object.assign([],{empty:!0},s.streamInfo())}function fa(n,e={}){let{lineCounter:t,prettyErrors:i}=ua(e),r=new la.Parser(t?.addNewLine),s=new ca.Composer(e),o=null;for(let a of s.compose(r.parse(n),!0,n.length))if(!o)o=a;else if(o.options.logLevel!=="silent"){o.errors.push(new nt.YAMLParseError(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return i&&t&&(o.errors.forEach(nt.prettifyError(n,t)),o.warnings.forEach(nt.prettifyError(n,t))),o}function sd(n,e,t){let i;typeof e=="function"?i=e:t===void 0&&e&&typeof e=="object"&&(t=e);let r=fa(n,t);if(!r)return null;if(r.warnings.forEach(s=>td.warn(r.options.logLevel,s)),r.errors.length>0){if(r.options.logLevel!=="silent")throw r.errors[0];r.errors=[]}return r.toJS(Object.assign({reviver:i},t))}function od(n,e,t){let i=null;if(typeof e=="function"||Array.isArray(e)?i=e:t===void 0&&e&&(t=e),typeof t=="string"&&(t=t.length),typeof t=="number"){let r=Math.round(t);t=r<1?void 0:r>8?{indent:8}:{indent:r}}if(n===void 0){let{keepUndefined:r}=t??e??{};if(!r)return}return nd.isDocument(n)&&!i?n.toString(t):new ed.Document(n,i,t).toString(t)}it.parse=sd;it.parseAllDocuments=rd;it.parseDocument=fa;it.stringify=od});var yn=y(P=>{"use strict";var ad=Ji(),cd=He(),ld=Pi(),ar=Qe(),ud=Re(),ie=_(),fd=X(),dd=O(),pd=ee(),md=te(),hd=pn(),gd=nr(),wd=rr(),yd=or(),wn=da(),pa=Oe();P.Composer=ad.Composer;P.Document=cd.Document;P.Schema=ld.Schema;P.YAMLError=ar.YAMLError;P.YAMLParseError=ar.YAMLParseError;P.YAMLWarning=ar.YAMLWarning;P.Alias=ud.Alias;P.isAlias=ie.isAlias;P.isCollection=ie.isCollection;P.isDocument=ie.isDocument;P.isMap=ie.isMap;P.isNode=ie.isNode;P.isPair=ie.isPair;P.isScalar=ie.isScalar;P.isSeq=ie.isSeq;P.Pair=fd.Pair;P.Scalar=dd.Scalar;P.YAMLMap=pd.YAMLMap;P.YAMLSeq=md.YAMLSeq;P.CST=hd;P.Lexer=gd.Lexer;P.LineCounter=wd.LineCounter;P.Parser=yd.Parser;P.parse=wn.parse;P.parseAllDocuments=wn.parseAllDocuments;P.parseDocument=wn.parseDocument;P.stringify=wn.stringify;P.visit=pa.visit;P.visitAsync=pa.visitAsync});var wt=Nn(yn(),1);import La from"path";import{promises as Gd}from"fs";import Pn from"path";import{promises as Md}from"fs";import x from"path";import{promises as vd}from"fs";async function cr(n){try{return await vd.access(n),!0}catch(e){if(bd(e))return!1;throw e}}function bd(n){let e=n?.code;return e==="ENOENT"||e==="ENOTDIR"}var dr=Nn(yn(),1);import vn from"path";var st=64*1024,ur=1024,fr=64,kd=5,Sd=[".agents/skills/**",".amazonq/skills/**",".augment/skills/**",".bob/skills/**",".claude/skills/**",".cline/skills/**",".codebuddy/skills/**",".continue/skills/**",".cospec/skills/**",".crush/skills/**",".cursor/skills/**",".factory/skills/**",".forge/skills/**",".gemini/skills/**",".github/skills/**",".iflow/skills/**",".junie/skills/**",".kilocode/skills/**",".kimi-code/skills/**",".kiro/skills/**",".lingma/skills/**",".mimocode/skills/**",".opencode/skills/**",".pi/skills/**",".qoder/skills/**",".qwen/skills/**",".roo/skills/**",".trae-cn/skills/**",".trae/skills/**",".windsurf/skills/**",".zcode/skills/**"],Y={include:["**/*"],exclude:[...Sd],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4};function Cd(n,e){if(typeof n!="string")throw new Error(`${e} must be a string`);let t=n.trim();if(t.length===0||vn.posix.isAbsolute(t)||vn.win32.isAbsolute(t)||/^(?:~|[\\/])/u.test(t))throw new Error(`${e} must be a project-relative path`);if(t===".")return[];let i=t.replaceAll("\\","/").split("/");if(i.some(r=>r===".."))throw new Error(`${e} must stay inside the project root`);if(i.some(r=>r===""||r==="."))throw new Error(`${e} must not contain empty or dot path segments`);return i}function bn(n){let e=Cd(n,"native.artifact_root");return e.length===0?".":e.join("/")}function ha(n,e="docs"){let t=n??e;if(t!=="legacy"&&t!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return t}function ot(n,e,t=!1){if(typeof n!="string")throw new Error(`${e} must be a string`);let i=n.trim().replaceAll("\\","/");if(i.length===0||vn.posix.isAbsolute(i)||vn.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${e} must be relative to its declared path base`);let r=i.split("/");if(r.some(s=>s===".."))throw new Error(`${e} must stay inside its declared path base`);if(r.some(s=>s===""||s==="."))throw new Error(`${e} must not contain empty or dot path segments`);if(!t&&/[*?]/u.test(i))throw new Error(`${e} cannot contain wildcards`);return r.join("/")}function rt(n,e){if(!n||typeof n!="object"||Array.isArray(n))throw new Error(`${e} must be a mapping`);return n}function ga(n,e,t){let i=n??e;if(i!=="en"&&i!=="zh-CN")throw new Error(`${t} must be en or zh-CN`);return i}function wa(n,e){if(typeof n!="string"||n.length===0||n.includes("\\")||n.includes("\0")||n.startsWith("/")||n.split("/").includes(".."))throw new Error(`${e} contains an unsafe pattern`);if(n.length>ur)throw new Error(`${e} exceeds ${ur} characters`);let t=0;for(let i=0;ifr)throw new Error(`${e} contains more than ${fr} wildcard tokens`);return n}function ma(n,e,t){if(n===void 0)return[...t];if(!Array.isArray(n))throw new Error(`${e} contains an unsafe pattern`);return[...new Set(n.map(i=>wa(i,e)))].sort((i,r)=>i.localeCompare(r,"en"))}function lr(n,e,t){let i=n??e;if(!Number.isSafeInteger(i)||i<1)throw new Error(`${t} must be a positive integer`);return i}function Ed(n){if(n===void 0)return{...Y,include:[...Y.include],exclude:[...Y.exclude]};let e=rt(n,"native.snapshot");return{include:ma(e.include,"native.snapshot.include",Y.include),exclude:ma(e.exclude,"native.snapshot.exclude",Y.exclude),max_files:lr(e.max_files,Y.max_files,"native.snapshot.max_files"),max_total_bytes:lr(e.max_total_bytes,Y.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:lr(e.max_duration_ms,Y.max_duration_ms,"native.snapshot.max_duration_ms")}}function _d(n){if(n===void 0)return;let e=rt(n,"native.pending_root_move"),t=e.id,i=e.from_artifact_root,r=e.to_artifact_root,s=e.stage;if(typeof t!="string"||!/^[a-f0-9-]{8,}$/u.test(t))throw new Error("native.pending_root_move.id is invalid");if(typeof i!="string"||typeof r!="string")throw new Error("native.pending_root_move roots must be strings");if(s!=="copying"&&s!=="ready"&&s!=="switched")throw new Error("native.pending_root_move.stage is invalid");let o;if(e.cleanup!==void 0){let a=rt(e.cleanup,"native.pending_root_move.cleanup"),c=a.kind,l=a.state,m=a.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof m!="string"||!/^[a-f0-9]{64}$/u.test(m))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:m}}return{id:t,fromArtifactRoot:bn(i),toArtifactRoot:bn(r),stage:s,...o?{cleanup:o}:{}}}function Pd(n,e={}){let t=rt(n,"native"),i=t.artifact_root??(e.allowMissingArtifactRoot?"docs":void 0);if(typeof i!="string")throw new Error("native.artifact_root must be a string");let r=t.clarification_mode??"sequential";if(r!=="sequential"&&r!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let s=t.archive_confirmation??"automatic";if(s!=="automatic"&&s!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=t.max_verify_failures??kd;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let a=_d(t.pending_root_move);return{artifact_root:bn(i),language:ga(t.language,"en","native.language"),clarification_mode:r,archive_confirmation:s,max_verify_failures:o,snapshot:Ed(t.snapshot),...a?{pending_root_move:a}:{}}}function Nd(n){let e=rt(n,"classic"),t=e.context_compression??"off";if(t!=="off"&&t!=="beta")throw new Error("classic.context_compression must be off or beta");let i=e.review_mode??"standard";if(i!=="off"&&i!=="standard"&&i!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let r=e.auto_transition??!0;if(typeof r!="boolean")throw new Error("classic.auto_transition must be true or false");return{artifact_layout:ha(e.artifact_layout),language:ga(e.language,"zh-CN","classic.language"),context_compression:t,review_mode:i,auto_transition:r}}function Od(n){let e=n??!0;if(typeof e!="boolean")throw new Error("ambient_resume must be true or false");return e}function xd(n,e,t,i,r){let s=n.schema!==void 0;if(!(s||n.default_workflow!==void 0||n.workflows!==void 0||!r.allowPartialProject&&n.native!==void 0)||r.allowPartialProject&&!s)return null;if(n.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(n.default_workflow!=="native"&&n.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let a=n.workflows??[n.default_workflow];if(!Array.isArray(a)||a.length===0||a.some(l=>l!=="native"&&l!=="classic"))throw new Error("workflows must contain native and/or classic");let c=[...new Set(a)];if(!c.includes(n.default_workflow))throw new Error("workflows must include default_workflow");if(c.includes("native")&&!e)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:n.default_workflow,workflows:c,ambient_resume:i,...e?{native:e}:{},...t?{classic:t}:{}}}function Ne(n,e={}){let t=(0,dr.parseDocument)(n,{uniqueKeys:!0});if(t.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${t.errors[0].message}`);let i=t.toJS();if(i==null)return{value:{},config:null,ambient_resume:!0};if(typeof i!="object"||Array.isArray(i))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let r=i,s=Od(r.ambient_resume),o=r.native===void 0?void 0:Pd(r.native,{allowMissingArtifactRoot:e.allowMissingNativeFields}),a=r.classic===void 0?void 0:Nd(r.classic),c=xd(r,o,a,s,{allowPartialProject:e.allowPartialProject??!1});return{value:r,config:c,ambient_resume:s,...o?{native:o}:{},...a?{classic:a}:{}}}import{createHash as Id}from"crypto";import{promises as Cn}from"fs";import oe from"path";import{constants as kn,promises as pe}from"fs";function re(n){return n!==0&&n!==0n&&n!=="0"}function pr(n,e){return re(n.dev)&&re(e.dev)&&re(n.ino)&&re(e.ino)}function at(n,e){let t=re(n.dev)&&re(e.dev);if(t&&n.dev!==e.dev)return!1;let i=re(n.ino)&&re(e.ino);return i&&n.ino!==e.ino?!1:t&&i?!0:n.birthtime===e.birthtime}var se=class extends Error{reason;constructor(e,t,i){super(t,i),this.name="RaceSafeReadError",this.reason=e}};function mr(n){return"birthtimeNs"in n&&typeof n.birthtimeNs=="bigint"?n.birthtimeNs:n.birthtimeMs}function ya(n){return"ctimeNs"in n&&typeof n.ctimeNs=="bigint"?n.ctimeNs:n.ctimeMs}function ct(n){return{dev:n.dev,ino:n.ino,birthtime:mr(n)}}function Sn(n,e){let t=ct(n),i=ct(e);return pr(t,i)?at(t,i):at(t,i)&&mr(n)===mr(e)&&ya(n)===ya(e)&&n.size===e.size}async function va(n,e,t={}){if(!Number.isSafeInteger(e)||e<1)throw new Error("race-safe read byte limit must be a positive integer");let i=t.label??"file",r=t.bigint===!0,s=await pe.lstat(n,{bigint:r});if(!s.isFile()||s.isSymbolicLink())throw new se("not-regular-file",`${i} must be a regular file`);if(BigInt(s.size)>BigInt(e))throw new se("too-large",`${i} exceeds ${e} bytes`);let o=await pe.realpath(n);await t.verify?.("pre-open",{realPath:o,identity:ct(s)});let a=process.platform==="win32"?kn.O_RDONLY:kn.O_RDONLY|kn.O_NOFOLLOW|kn.O_NONBLOCK,c;try{c=await pe.open(n,a)}catch(l){throw l.code==="ELOOP"?new se("not-regular-file",`${i} must be a regular file`,{cause:l}):l}try{let[l,m,u]=await Promise.all([c.stat({bigint:r}),pe.lstat(n,{bigint:r}),pe.realpath(n)]);if(!l.isFile()||!m.isFile()||m.isSymbolicLink()||u!==o||!Sn(s,l)||!Sn(s,m))throw new se("changed",`${i} changed while opening`);await t.verify?.("post-open",{realPath:u,identity:ct(l)}),await t.hooks?.afterOpen?.();let d=[],h=0,w=Buffer.allocUnsafe(Math.min(64*1024,e+1));for(;;){let v=e+1-h,{bytesRead:k}=await c.read(w,0,Math.min(w.length,v),null);if(k===0)break;if(h+=k,h>e)throw new se("too-large",`${i} exceeds ${e} bytes`);d.push(Buffer.from(w.subarray(0,k)))}await t.hooks?.beforeFinalCheck?.();let[f,p,g]=await Promise.all([c.stat({bigint:r}),pe.lstat(n,{bigint:r}),pe.realpath(n)]);if(!p.isFile()||p.isSymbolicLink()||g!==o||!Sn(s,f)||!Sn(s,p))throw new se("changed",`${i} changed while reading`);return await t.verify?.("post-read",{realPath:g,identity:ct(f)}),{bytes:Buffer.concat(d,h),stat:f,realPath:g}}finally{await c.close()}}function Ad(n){let e=n?.code;return e==="ENOENT"||e==="ENOTDIR"}function hr(n,e){let t=oe.relative(n,e);return t===""||!oe.isAbsolute(t)&&t!==".."&&!t.startsWith(`..${oe.sep}`)}async function ba(n,e){let t=oe.resolve(n),i=await Cn.lstat(t);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${e} project root must be a real directory`);return Cn.realpath(t)}async function ka(n,e,t,i){let r=n;for(let s=0;s{if(!hr(s,a.realPath))throw new Error(`${i.label} resolves outside the project root`);await ka(r.projectRoot,s,r.relative.split("/"),{label:i.label,expected:"file"})}})}var lt=".comet/config.yaml";function Rd(n){let e=n?.code;return e==="ENOENT"||e==="ENOTDIR"}async function En(n,e={}){return(await _n(n,e)).document}async function jd(n){try{return(await U(n,lt,st,{label:lt})).bytes}catch(e){if(Rd(e))return null;throw e}}function Td(n){return n?{exists:!0,sha256:Id("sha256").update(n).digest("hex")}:{exists:!1,sha256:null}}async function _n(n,e={}){let t=await jd(n);return{document:t?Ne(t.toString("utf8"),e):null,identity:Td(t)}}var sh=16*1024;var ft=class extends Error{code="classic-layout-unavailable";constructor(e="Classic artifact layout is unavailable from .comet/config.yaml"){super(e),this.name="ClassicLayoutUnavailableError"}},wr=class extends Error{constructor(t,i,r){let s=J(r,t),o=J(r,i);super(`Classic layout conflict: both ${s}/ and ${o}/ exist; run comet doctor and resolve the conflict before writing`);this.configuredRoot=t;this.alternateRoot=i;this.name="ClassicLayoutConflictError"}configuredRoot;alternateRoot;code="classic-layout-conflict"},Ea=".comet/config.yaml";function Fd(n){let e=n?.code;return e==="ENOENT"||e==="ENOTDIR"}async function _a(n){await D(n,Ea,{label:Ea,expected:"file"})}function Pa(n,e){let t=x.resolve(n),i=e==="docs"?x.join(t,"docs"):t,r=x.join(i,"openspec"),s=x.join(t,"docs","superpowers");return{projectRoot:t,artifactLayout:e,openSpecBase:i,openSpecRoot:r,changesDir:x.join(r,"changes"),archiveDir:x.join(r,"changes","archive"),specsDir:x.join(r,"specs"),superpowersRoot:s,superpowersSpecsDir:x.join(s,"specs"),superpowersPlansDir:x.join(s,"plans"),superpowersReportsDir:x.join(s,"reports")}}async function Bd(n){await _a(n);let e=await En(n,{allowPartialProject:!0,allowMissingNativeFields:!0});if(!e?.config)throw new ft;if(!(e.config.workflows??[e.config.default_workflow]).includes("classic"))throw new ft("Classic artifact layout is unavailable because Classic is not enabled");return e.classic?.artifact_layout??"legacy"}async function Kd(n,e){return Pa(n,e??await Bd(n))}async function Yd(n,e){let t=await Kd(n,e),i=t.artifactLayout==="legacy"?"docs":"legacy",r=Pa(n,i).openSpecRoot,[s,o]=await Promise.all([D(t.projectRoot,J(t.projectRoot,t.openSpecRoot),{label:"Configured Classic OpenSpec root",expected:"directory"}),D(t.projectRoot,J(t.projectRoot,r),{label:"Alternate Classic OpenSpec root",expected:"directory"})]),a=s.exists,c=o.exists;return{paths:t,configuredRootExists:a,alternateRoot:r,alternateRootExists:c,dualRoots:a&&c}}async function Ud(n,e){let t=[n.openSpecRoot,n.changesDir,n.archiveDir,n.specsDir,e,n.superpowersRoot,n.superpowersSpecsDir,n.superpowersPlansDir,n.superpowersReportsDir];for(let i of t){let r=J(n.projectRoot,i);await D(n.projectRoot,r,{label:`Classic managed physical path ${r}`,expected:"directory"})}}async function Na(n,e,t={}){let i=await Yd(n,e);if(await Ud(i.paths,i.alternateRoot),i.dualRoots&&!t.allowAlternateRoot)throw new wr(i.paths.openSpecRoot,i.alternateRoot,i.paths.projectRoot);if(!i.configuredRootExists){let r=J(i.paths.projectRoot,i.paths.openSpecRoot),s=J(i.paths.projectRoot,i.alternateRoot);throw new ft(`Configured Classic OpenSpec root is missing: ${r} (alternate ${s} is ${i.alternateRootExists?"present":"missing"})`)}return i.paths}async function Oa(n){let e=x.resolve(n),t=null;try{(await Md.lstat(e)).isDirectory()||(e=x.dirname(e))}catch(i){if(!Fd(i))throw i}for(;;){x.basename(e)==="openspec"&&(t=x.dirname(e));let i=x.join(e,".comet","config.yaml"),r=!1;if(await cr(i))try{await _a(e);let o=(await En(e))?.value;r=!!o&&typeof o=="object"&&!Array.isArray(o)&&(o.schema==="comet.project.v1"||o.default_workflow!==void 0||o.native!==void 0)}catch{}if(r||await cr(x.join(e,".git")))return e;let s=x.dirname(e);if(s===e)return t??x.resolve(n);e=s}}function J(n,e){return x.relative(x.resolve(n),e).replaceAll("\\","/")}import dt from"path";var Vd=2*1024*1024;function xa(n,e,t){let i=dt.resolve(n),r=dt.isAbsolute(e)?dt.resolve(e):dt.resolve(i,e),s=dt.relative(i,r).replaceAll("\\","/");return{root:i,relative:ot(s,t),target:r}}async function pt(n,e,t){let i=xa(n,e,t.label);return D(i.root,i.relative,t)}async function Aa(n,e,t){return(await pt(n,e,{label:t.label,expected:t.expected??"any"})).exists}async function Ia(n,e,t){return(await Hd(n,e,t)).toString("utf8")}async function Hd(n,e,t){let i=xa(n,e,t.label);return(await U(i.root,i.relative,t.maxBytes??Vd,{label:t.label,hooks:t.hooks})).bytes}function vr(n){return n?/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(n)?n.includes("..")?"Change name cannot contain '..' (path traversal not allowed)":null:`Invalid change name: '${n}' -Valid format: lowercase kebab-case (a-z, 0-9, single hyphens)`:"Change name cannot be empty"}function zd(n){let e=vr(n);if(e)throw new Error(e)}function Qd(n,e){return{label:J(n,e),directory:e}}async function yr(n,e,t){let i=Qd(n,e);if(!(await pt(n,e,{label:t,expected:"directory"})).exists)return{change:i,exists:!1,stateExists:!1};let s=await pt(n,Pn.join(e,".comet.yaml"),{label:`${t} state`,expected:"file"});return{change:i,exists:!0,stateExists:s.exists}}function Xd(n,e){let t=e.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&");return new RegExp(`^\\d{4}-\\d{2}-\\d{2}-${t}$`,"u").test(n)}async function Zd(n,e,t,i={}){if(!i.skipExactCompatibility){let o=await yr(n,Pn.join(e,t),`Classic archived change ${t}`);if(o.exists)return o.change}if(!(await pt(n,e,{label:"Classic archive directory",expected:"directory"})).exists)return null;let s=[];for(let o of await Gd.readdir(e,{withFileTypes:!0})){if(!Xd(o.name,t))continue;let a=await yr(n,Pn.join(e,o.name),`Classic archived change ${o.name}`);a.exists&&a.stateExists&&s.push(a.change)}return s.sort((o,a)=>a.directory.localeCompare(o.directory))[0]??null}async function Ra(n,e=process.cwd()){zd(n);let t=await Na(e),i=await yr(t.projectRoot,Pn.join(t.changesDir,n),`Classic active change ${n}`);if(i.exists)return i.change;let r=await Zd(t.projectRoot,t.archiveDir,n);return r||i.change}var op=Nn(yn(),1);var jg=256*1024;var br=["workflow","language","phase","context_compression","build_mode","build_pause","subagent_dispatch","tdd_mode","review_mode","isolation","bound_branch","verify_mode","auto_transition","base_ref","design_doc","plan","verify_result","verify_failures","verification_report","branch_status","created_at","verified_at","archive_confirmation","archived","direct_override","handoff_context","handoff_hash","classic_profile","classic_migration"],kr=["run_id"],Dg=new Set([...br,...kr]);import{AsyncLocalStorage as cp}from"async_hooks";import{promises as ja}from"fs";import mt from"path";var Sr=new cp;function lp(n,e){let t=mt.relative(n,e);return t===""||!mt.isAbsolute(t)&&t!==".."&&!t.startsWith(`..${mt.sep}`)}async function up(n){let e=mt.resolve(n.invocationCwd??process.cwd()),t=mt.resolve(n.projectRoot??await Oa(e)),[i,r]=await Promise.all([ja.realpath(e),ja.realpath(t)]);if(!lp(r,i))throw new Error(`Classic command invocation cwd is outside the discovered project: ${e}`);return{invocationCwd:e,projectRoot:t}}async function Ta(n,e){let t=Sr.getStore();if(t)return e(t);let i=await up(n);return Sr.run(i,()=>e(i))}function qa(){let n=Sr.getStore();if(!n)throw new Error("Classic command project context is unavailable");return n.projectRoot}var fp="\x1B[32m",ht="\x1B[31m",dp="\x1B[33m",pp="\x1B[0m",mp=["workflow","phase","design_doc","plan","build_mode","isolation","verify_mode","verify_result","verified_at","archived"],hp={workflow:["full","hotfix","tweak"],language:["en","zh-CN"],phase:["open","design","build","verify","archive"],context_compression:["off","beta"],build_mode:["subagent-driven-development","executing-plans","direct"],build_pause:["plan-ready"],subagent_dispatch:["confirmed"],tdd_mode:["tdd","direct"],review_mode:["off","standard","thorough"],isolation:["current","branch","worktree"],verify_mode:["light","full"],auto_transition:["true","false"],verify_result:["pending","pass","fail"],branch_status:["pending","handled"],archive_confirmation:["pending","confirmed"],archived:["true","false"],direct_override:["true","false"],classic_profile:["full","hotfix","tweak"],classic_migration:["1"]},gp=new Set([...br,...kr,"classic_profile","classic_migration"]);function me(n,e){return`${n}${e}${pp}`}function gt(n){return n==null?"":typeof n=="object"?JSON.stringify(n):String(n)}var Da=async(n,e)=>Ta(e,async()=>{let t=n[0],i=vr(t);if(i)return{exitCode:1,stderr:me(ht,`ERROR: ${i}`)};let r=qa(),{directory:s,label:o}=await Ra(t,r),a=La.join(s,".comet.yaml"),c=[`[VALIDATE] ${o}/.comet.yaml`],l=0,m=0,u=p=>{l+=1,c.push(me(ht,` FAIL: ${p}`))},d=p=>{m+=1,c.push(me(dp,` WARN: ${p}`))},h;try{h=await Ia(r,a,{label:`Classic state ${o}/.comet.yaml`})}catch(p){if(p.code==="ENOENT")return u(".comet.yaml does not exist"),c.push("",me(ht,`${l} error(s), ${m} warning(s) — validation FAILED`)),{exitCode:1,stderr:c.join(` -`)};throw p}let w=(0,wt.parseDocument)(h);if(w.errors.length>0||!(0,wt.isMap)(w.contents)){for(let p of w.errors)u(p.message);return(0,wt.isMap)(w.contents)||u("document root must be a mapping"),c.push("",me(ht,`${l} error(s), ${m} warning(s) — validation FAILED`)),{exitCode:1,stderr:c.join(` -`)}}let f=w.toJS();for(let p of mp)Object.prototype.hasOwnProperty.call(f,p)||u(`missing required field '${p}'`);for(let[p,g]of Object.entries(hp)){if(!Object.prototype.hasOwnProperty.call(f,p))continue;let v=gt(f[p]);if(!v){p==="auto_transition"&&u(`${p}='' is not valid. Expected: ${g.join(" ")}`);continue}g.includes(v)||u(`${p}='${v}' is not valid. Expected: ${g.join(" ")}`)}if(Object.prototype.hasOwnProperty.call(f,"bound_branch")){let p=f.bound_branch;p!==null&&typeof p!="string"&&u(`bound_branch='${gt(p)}' is not a string or null`)}if(Object.prototype.hasOwnProperty.call(f,"verify_failures")){let p=f.verify_failures;(typeof p!="number"||!Number.isInteger(p)||p<0)&&u(`verify_failures='${gt(p)}' is not a non-negative integer`)}for(let p of["design_doc","plan","handoff_context","verification_report"]){let g=gt(f[p]);if(g){if(/^(?:[A-Za-z]:|[\\/]|~)/u.test(g)||g.split(/[\\/]/u).includes("..")){u(`${p}='${g}' must be a relative repository path`);continue}try{await Aa(r,La.resolve(r,g),{label:`${p} artifact pointer`,expected:"file"})||u(`${p}='${g}' does not exist on disk`)}catch(v){u(`${p}='${g}' is unsafe: ${v instanceof Error?v.message:String(v)}`)}}}for(let p of["handoff_hash"]){let g=gt(f[p]);g&&!/^[a-f0-9]{64}$/u.test(g)&&u(`${p}='${g}' is not a sha256 hex digest`)}for(let p of Object.keys(f))gp.has(p)||d(`unknown field '${p}' found`);return c.push(""),l>0?(c.push(me(ht,`${l} error(s), ${m} warning(s) — validation FAILED`)),{exitCode:1,stderr:c.join(` -`)}):(c.push(me(fp,`0 errors, ${m} warning(s) — validation PASSED`)),{exitCode:0,stderr:c.join(` +`,t)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let t=hn(e),i=_e(t);return i.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let t=hn(e),i=_e(t);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!=="comment"||this.indent<=t?!1:e.every(i=>i.type==="newline"||i.type==="space")}*documentEnd(e){this.type!=="doc-mode"&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};oa.Parser=sr});var fa=y(it=>{"use strict";var aa=Ji(),td=He(),nt=Qe(),nd=Yn(),id=_(),rd=rr(),ca=or();function la(n){let e=n.prettyErrors!==!1;return{lineCounter:n.lineCounter||e&&new rd.LineCounter||null,prettyErrors:e}}function sd(n,e={}){let{lineCounter:t,prettyErrors:i}=la(e),r=new ca.Parser(t?.addNewLine),s=new aa.Composer(e),o=Array.from(s.compose(r.parse(n)));if(i&&t)for(let a of o)a.errors.forEach(nt.prettifyError(n,t)),a.warnings.forEach(nt.prettifyError(n,t));return o.length>0?o:Object.assign([],{empty:!0},s.streamInfo())}function ua(n,e={}){let{lineCounter:t,prettyErrors:i}=la(e),r=new ca.Parser(t?.addNewLine),s=new aa.Composer(e),o=null;for(let a of s.compose(r.parse(n),!0,n.length))if(!o)o=a;else if(o.options.logLevel!=="silent"){o.errors.push(new nt.YAMLParseError(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return i&&t&&(o.errors.forEach(nt.prettifyError(n,t)),o.warnings.forEach(nt.prettifyError(n,t))),o}function od(n,e,t){let i;typeof e=="function"?i=e:t===void 0&&e&&typeof e=="object"&&(t=e);let r=ua(n,t);if(!r)return null;if(r.warnings.forEach(s=>nd.warn(r.options.logLevel,s)),r.errors.length>0){if(r.options.logLevel!=="silent")throw r.errors[0];r.errors=[]}return r.toJS(Object.assign({reviver:i},t))}function ad(n,e,t){let i=null;if(typeof e=="function"||Array.isArray(e)?i=e:t===void 0&&e&&(t=e),typeof t=="string"&&(t=t.length),typeof t=="number"){let r=Math.round(t);t=r<1?void 0:r>8?{indent:8}:{indent:r}}if(n===void 0){let{keepUndefined:r}=t??e??{};if(!r)return}return id.isDocument(n)&&!i?n.toString(t):new td.Document(n,i,t).toString(t)}it.parse=od;it.parseAllDocuments=sd;it.parseDocument=ua;it.stringify=ad});var yn=y(P=>{"use strict";var cd=Ji(),ld=He(),ud=Pi(),ar=Qe(),fd=Re(),ne=_(),dd=Q(),pd=O(),md=Z(),hd=ee(),gd=pn(),wd=nr(),yd=rr(),vd=or(),wn=fa(),da=Oe();P.Composer=cd.Composer;P.Document=ld.Document;P.Schema=ud.Schema;P.YAMLError=ar.YAMLError;P.YAMLParseError=ar.YAMLParseError;P.YAMLWarning=ar.YAMLWarning;P.Alias=fd.Alias;P.isAlias=ne.isAlias;P.isCollection=ne.isCollection;P.isDocument=ne.isDocument;P.isMap=ne.isMap;P.isNode=ne.isNode;P.isPair=ne.isPair;P.isScalar=ne.isScalar;P.isSeq=ne.isSeq;P.Pair=dd.Pair;P.Scalar=pd.Scalar;P.YAMLMap=md.YAMLMap;P.YAMLSeq=hd.YAMLSeq;P.CST=gd;P.Lexer=wd.Lexer;P.LineCounter=yd.LineCounter;P.Parser=vd.Parser;P.parse=wn.parse;P.parseAllDocuments=wn.parseAllDocuments;P.parseDocument=wn.parseDocument;P.stringify=wn.stringify;P.visit=da.visit;P.visitAsync=da.visitAsync});var wt=Nn(yn(),1);import Da from"path";import{promises as Gd}from"fs";import Pn from"path";import{promises as Ea}from"fs";import x from"path";import{promises as bd}from"fs";async function cr(n){try{return await bd.access(n),!0}catch(e){if(kd(e))return!1;throw e}}function kd(n){let e=n?.code;return e==="ENOENT"||e==="ENOTDIR"}var dr=Nn(yn(),1);import vn from"path";var st=64*1024,ur=1024,fr=64,Sd=5,Cd=[".agents/skills/**",".amazonq/skills/**",".augment/skills/**",".bob/skills/**",".claude/skills/**",".cline/skills/**",".codebuddy/skills/**",".continue/skills/**",".cospec/skills/**",".crush/skills/**",".cursor/skills/**",".factory/skills/**",".forge/skills/**",".gemini/skills/**",".github/skills/**",".iflow/skills/**",".junie/skills/**",".kilocode/skills/**",".kimi-code/skills/**",".kiro/skills/**",".lingma/skills/**",".mimocode/skills/**",".opencode/skills/**",".pi/skills/**",".qoder/skills/**",".qwen/skills/**",".roo/skills/**",".trae-cn/skills/**",".trae/skills/**",".windsurf/skills/**",".zcode/skills/**"],Y={include:["**/*"],exclude:[...Cd],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4};function Ed(n,e){if(typeof n!="string")throw new Error(`${e} must be a string`);let t=n.trim();if(t.length===0||vn.posix.isAbsolute(t)||vn.win32.isAbsolute(t)||/^(?:~|[\\/])/u.test(t))throw new Error(`${e} must be a project-relative path`);if(t===".")return[];let i=t.replaceAll("\\","/").split("/");if(i.some(r=>r===".."))throw new Error(`${e} must stay inside the project root`);if(i.some(r=>r===""||r==="."))throw new Error(`${e} must not contain empty or dot path segments`);return i}function bn(n){let e=Ed(n,"native.artifact_root");return e.length===0?".":e.join("/")}function ma(n,e="docs"){let t=n??e;if(t!=="legacy"&&t!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return t}function ot(n,e,t=!1){if(typeof n!="string")throw new Error(`${e} must be a string`);let i=n.trim().replaceAll("\\","/");if(i.length===0||vn.posix.isAbsolute(i)||vn.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${e} must be relative to its declared path base`);let r=i.split("/");if(r.some(s=>s===".."))throw new Error(`${e} must stay inside its declared path base`);if(r.some(s=>s===""||s==="."))throw new Error(`${e} must not contain empty or dot path segments`);if(!t&&/[*?]/u.test(i))throw new Error(`${e} cannot contain wildcards`);return r.join("/")}function rt(n,e){if(!n||typeof n!="object"||Array.isArray(n))throw new Error(`${e} must be a mapping`);return n}function ha(n,e,t){let i=n??e;if(i!=="en"&&i!=="zh-CN")throw new Error(`${t} must be en or zh-CN`);return i}function ga(n,e){if(typeof n!="string"||n.length===0||n.includes("\\")||n.includes("\0")||n.startsWith("/")||n.split("/").includes(".."))throw new Error(`${e} contains an unsafe pattern`);if(n.length>ur)throw new Error(`${e} exceeds ${ur} characters`);let t=0;for(let i=0;ifr)throw new Error(`${e} contains more than ${fr} wildcard tokens`);return n}function pa(n,e,t){if(n===void 0)return[...t];if(!Array.isArray(n))throw new Error(`${e} contains an unsafe pattern`);return[...new Set(n.map(i=>ga(i,e)))].sort((i,r)=>i.localeCompare(r,"en"))}function lr(n,e,t){let i=n??e;if(!Number.isSafeInteger(i)||i<1)throw new Error(`${t} must be a positive integer`);return i}function _d(n){if(n===void 0)return{...Y,include:[...Y.include],exclude:[...Y.exclude]};let e=rt(n,"native.snapshot");return{include:pa(e.include,"native.snapshot.include",Y.include),exclude:pa(e.exclude,"native.snapshot.exclude",Y.exclude),max_files:lr(e.max_files,Y.max_files,"native.snapshot.max_files"),max_total_bytes:lr(e.max_total_bytes,Y.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:lr(e.max_duration_ms,Y.max_duration_ms,"native.snapshot.max_duration_ms")}}function Pd(n){if(n===void 0)return;let e=rt(n,"native.pending_root_move"),t=e.id,i=e.from_artifact_root,r=e.to_artifact_root,s=e.stage;if(typeof t!="string"||!/^[a-f0-9-]{8,}$/u.test(t))throw new Error("native.pending_root_move.id is invalid");if(typeof i!="string"||typeof r!="string")throw new Error("native.pending_root_move roots must be strings");if(s!=="copying"&&s!=="ready"&&s!=="switched")throw new Error("native.pending_root_move.stage is invalid");let o;if(e.cleanup!==void 0){let a=rt(e.cleanup,"native.pending_root_move.cleanup"),c=a.kind,l=a.state,m=a.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof m!="string"||!/^[a-f0-9]{64}$/u.test(m))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:m}}return{id:t,fromArtifactRoot:bn(i),toArtifactRoot:bn(r),stage:s,...o?{cleanup:o}:{}}}function Nd(n,e={}){let t=rt(n,"native"),i=t.artifact_root??(e.allowMissingArtifactRoot?"docs":void 0);if(typeof i!="string")throw new Error("native.artifact_root must be a string");let r=t.clarification_mode??"sequential";if(r!=="sequential"&&r!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let s=t.archive_confirmation??"automatic";if(s!=="automatic"&&s!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=t.max_verify_failures??Sd;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let a=Pd(t.pending_root_move);return{artifact_root:bn(i),language:ha(t.language,"en","native.language"),clarification_mode:r,archive_confirmation:s,max_verify_failures:o,snapshot:_d(t.snapshot),...a?{pending_root_move:a}:{}}}function Od(n){let e=rt(n,"classic"),t=e.context_compression??"off";if(t!=="off"&&t!=="beta")throw new Error("classic.context_compression must be off or beta");let i=e.review_mode??"standard";if(i!=="off"&&i!=="standard"&&i!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let r=e.auto_transition??!0;if(typeof r!="boolean")throw new Error("classic.auto_transition must be true or false");return{artifact_layout:ma(e.artifact_layout),language:ha(e.language,"zh-CN","classic.language"),context_compression:t,review_mode:i,auto_transition:r}}function xd(n){let e=n??!0;if(typeof e!="boolean")throw new Error("ambient_resume must be true or false");return e}function Ad(n,e,t,i,r){let s=n.schema!==void 0;if(!(s||n.default_workflow!==void 0||n.workflows!==void 0||!r.allowPartialProject&&n.native!==void 0)||r.allowPartialProject&&!s)return null;if(n.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(n.default_workflow!=="native"&&n.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let a=n.workflows??[n.default_workflow];if(!Array.isArray(a)||a.length===0||a.some(l=>l!=="native"&&l!=="classic"))throw new Error("workflows must contain native and/or classic");let c=[...new Set(a)];if(!c.includes(n.default_workflow))throw new Error("workflows must include default_workflow");if(c.includes("native")&&!e)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:n.default_workflow,workflows:c,ambient_resume:i,...e?{native:e}:{},...t?{classic:t}:{}}}function Pe(n,e={}){let t=(0,dr.parseDocument)(n,{uniqueKeys:!0});if(t.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${t.errors[0].message}`);let i=t.toJS();if(i==null)return{value:{},config:null,ambient_resume:!0};if(typeof i!="object"||Array.isArray(i))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let r=i,s=xd(r.ambient_resume),o=r.native===void 0?void 0:Nd(r.native,{allowMissingArtifactRoot:e.allowMissingNativeFields}),a=r.classic===void 0?void 0:Od(r.classic),c=Ad(r,o,a,s,{allowPartialProject:e.allowPartialProject??!1});return{value:r,config:c,ambient_resume:s,...o?{native:o}:{},...a?{classic:a}:{}}}import{createHash as Rd}from"crypto";import{promises as Cn}from"fs";import se from"path";import{constants as kn,promises as de}from"fs";function ie(n){return n!==0&&n!==0n&&n!=="0"}function pr(n,e){return ie(n.dev)&&ie(e.dev)&&ie(n.ino)&&ie(e.ino)}function at(n,e){let t=ie(n.dev)&&ie(e.dev);if(t&&n.dev!==e.dev)return!1;let i=ie(n.ino)&&ie(e.ino);return i&&n.ino!==e.ino?!1:t&&i?!0:n.birthtime===e.birthtime}var re=class extends Error{reason;constructor(e,t,i){super(t,i),this.name="RaceSafeReadError",this.reason=e}};function mr(n){return"birthtimeNs"in n&&typeof n.birthtimeNs=="bigint"?n.birthtimeNs:n.birthtimeMs}function wa(n){return"ctimeNs"in n&&typeof n.ctimeNs=="bigint"?n.ctimeNs:n.ctimeMs}function ct(n){return{dev:n.dev,ino:n.ino,birthtime:mr(n)}}function Sn(n,e){let t=ct(n),i=ct(e);return pr(t,i)?at(t,i):at(t,i)&&mr(n)===mr(e)&&wa(n)===wa(e)&&n.size===e.size}async function ya(n,e,t={}){if(!Number.isSafeInteger(e)||e<1)throw new Error("race-safe read byte limit must be a positive integer");let i=t.label??"file",r=t.bigint===!0,s=await de.lstat(n,{bigint:r});if(!s.isFile()||s.isSymbolicLink())throw new re("not-regular-file",`${i} must be a regular file`);if(BigInt(s.size)>BigInt(e))throw new re("too-large",`${i} exceeds ${e} bytes`);let o=await de.realpath(n);await t.verify?.("pre-open",{realPath:o,identity:ct(s)});let a=process.platform==="win32"?kn.O_RDONLY:kn.O_RDONLY|kn.O_NOFOLLOW|kn.O_NONBLOCK,c;try{c=await de.open(n,a)}catch(l){throw l.code==="ELOOP"?new re("not-regular-file",`${i} must be a regular file`,{cause:l}):l}try{let[l,m,u]=await Promise.all([c.stat({bigint:r}),de.lstat(n,{bigint:r}),de.realpath(n)]);if(!l.isFile()||!m.isFile()||m.isSymbolicLink()||u!==o||!Sn(s,l)||!Sn(s,m))throw new re("changed",`${i} changed while opening`);await t.verify?.("post-open",{realPath:u,identity:ct(l)}),await t.hooks?.afterOpen?.();let d=[],h=0,w=Buffer.allocUnsafe(Math.min(64*1024,e+1));for(;;){let v=e+1-h,{bytesRead:k}=await c.read(w,0,Math.min(w.length,v),null);if(k===0)break;if(h+=k,h>e)throw new re("too-large",`${i} exceeds ${e} bytes`);d.push(Buffer.from(w.subarray(0,k)))}await t.hooks?.beforeFinalCheck?.();let[f,p,g]=await Promise.all([c.stat({bigint:r}),de.lstat(n,{bigint:r}),de.realpath(n)]);if(!p.isFile()||p.isSymbolicLink()||g!==o||!Sn(s,f)||!Sn(s,p))throw new re("changed",`${i} changed while reading`);return await t.verify?.("post-read",{realPath:g,identity:ct(f)}),{bytes:Buffer.concat(d,h),stat:f,realPath:g}}finally{await c.close()}}function Id(n){let e=n?.code;return e==="ENOENT"||e==="ENOTDIR"}function hr(n,e){let t=se.relative(n,e);return t===""||!se.isAbsolute(t)&&t!==".."&&!t.startsWith(`..${se.sep}`)}async function va(n,e){let t=se.resolve(n),i=await Cn.lstat(t);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${e} project root must be a real directory`);return Cn.realpath(t)}async function ba(n,e,t,i){let r=n;for(let s=0;s{if(!hr(s,a.realPath))throw new Error(`${i.label} resolves outside the project root`);await ba(r.projectRoot,s,r.relative.split("/"),{label:i.label,expected:"file"})}})}var lt=".comet/config.yaml";function jd(n){let e=n?.code;return e==="ENOENT"||e==="ENOTDIR"}async function En(n,e={}){return(await _n(n,e)).document}async function Td(n){try{return(await U(n,lt,st,{label:lt})).bytes}catch(e){if(jd(e))return null;throw e}}function qd(n){return n?{exists:!0,sha256:Rd("sha256").update(n).digest("hex")}:{exists:!1,sha256:null}}async function _n(n,e={}){let t=await Td(n);return{document:t?Pe(t.toString("utf8"),e):null,identity:qd(t)}}var sh=16*1024;var ft=class extends Error{code="classic-layout-unavailable";constructor(e="Classic artifact layout is unavailable from .comet/config.yaml"){super(e),this.name="ClassicLayoutUnavailableError"}},Ca=".comet/config.yaml";function _a(n){let e=n?.code;return e==="ENOENT"||e==="ENOTDIR"}async function Pa(n){await W(n,Ca,{label:Ca,expected:"file"})}function Na(n,e){let t=x.resolve(n),i=e==="docs"?x.join(t,"docs"):t,r=x.join(i,"openspec"),s=x.join(t,"docs","superpowers");return{projectRoot:t,artifactLayout:e,openSpecBase:i,openSpecRoot:r,changesDir:x.join(r,"changes"),archiveDir:x.join(r,"changes","archive"),specsDir:x.join(r,"specs"),superpowersRoot:s,superpowersSpecsDir:x.join(s,"specs"),superpowersPlansDir:x.join(s,"plans"),superpowersReportsDir:x.join(s,"reports")}}async function Fd(n){await Pa(n);let e=await En(n,{allowPartialProject:!0,allowMissingNativeFields:!0});if(!e?.config)throw new ft;if(!(e.config.workflows??[e.config.default_workflow]).includes("classic"))throw new ft("Classic artifact layout is unavailable because Classic is not enabled");return e.classic?.artifact_layout??"legacy"}async function Bd(n,e){return Na(n,e??await Fd(n))}async function Kd(n){try{return await Ea.lstat(n),!0}catch(e){if(_a(e))return!1;throw e}}async function Yd(n,e){let t=await Bd(n,e),i=t.artifactLayout==="legacy"?"docs":"legacy",r=Na(n,i).openSpecRoot,[s,o]=await Promise.all([W(t.projectRoot,Ne(t.projectRoot,t.openSpecRoot),{label:"Configured Classic OpenSpec root",expected:"directory"}),Kd(r)]),a=s.exists;return{paths:t,configuredRootExists:a,alternateRoot:r,alternateRootExists:o,dualRoots:a&&o}}async function Ud(n){let e=[n.openSpecRoot,n.changesDir,n.archiveDir,n.specsDir,n.superpowersRoot,n.superpowersSpecsDir,n.superpowersPlansDir,n.superpowersReportsDir];for(let t of e){let i=Ne(n.projectRoot,t);await W(n.projectRoot,i,{label:`Classic managed physical path ${i}`,expected:"directory"})}}async function Oa(n,e){let t=await Yd(n,e);if(await Ud(t.paths),!t.configuredRootExists){let i=Ne(t.paths.projectRoot,t.paths.openSpecRoot),r=Ne(t.paths.projectRoot,t.alternateRoot);throw new ft(`Configured Classic OpenSpec root is missing: ${i} (alternate ${r} is ${t.alternateRootExists?"present":"missing"})`)}return t.paths}async function xa(n){let e=x.resolve(n),t=null;try{(await Ea.lstat(e)).isDirectory()||(e=x.dirname(e))}catch(i){if(!_a(i))throw i}for(;;){x.basename(e)==="openspec"&&(t=x.dirname(e));let i=x.join(e,".comet","config.yaml"),r=!1;if(await cr(i))try{await Pa(e);let o=(await En(e))?.value;r=!!o&&typeof o=="object"&&!Array.isArray(o)&&(o.schema==="comet.project.v1"||o.default_workflow!==void 0||o.native!==void 0)}catch{}if(r||await cr(x.join(e,".git")))return e;let s=x.dirname(e);if(s===e)return t??x.resolve(n);e=s}}function Ne(n,e){return x.relative(x.resolve(n),e).replaceAll("\\","/")}import dt from"path";var Vd=2*1024*1024;function Aa(n,e,t){let i=dt.resolve(n),r=dt.isAbsolute(e)?dt.resolve(e):dt.resolve(i,e),s=dt.relative(i,r).replaceAll("\\","/");return{root:i,relative:ot(s,t),target:r}}async function pt(n,e,t){let i=Aa(n,e,t.label);return W(i.root,i.relative,t)}async function Ia(n,e,t){return(await pt(n,e,{label:t.label,expected:t.expected??"any"})).exists}async function Ra(n,e,t){return(await Hd(n,e,t)).toString("utf8")}async function Hd(n,e,t){let i=Aa(n,e,t.label);return(await U(i.root,i.relative,t.maxBytes??Vd,{label:t.label,hooks:t.hooks})).bytes}function yr(n){return n?/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(n)?n.includes("..")?"Change name cannot contain '..' (path traversal not allowed)":null:`Invalid change name: '${n}' +Valid format: lowercase kebab-case (a-z, 0-9, single hyphens)`:"Change name cannot be empty"}function zd(n){let e=yr(n);if(e)throw new Error(e)}function Qd(n,e){return{label:Ne(n,e),directory:e}}async function wr(n,e,t){let i=Qd(n,e);if(!(await pt(n,e,{label:t,expected:"directory"})).exists)return{change:i,exists:!1,stateExists:!1};let s=await pt(n,Pn.join(e,".comet.yaml"),{label:`${t} state`,expected:"file"});return{change:i,exists:!0,stateExists:s.exists}}function Xd(n,e){let t=e.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&");return new RegExp(`^\\d{4}-\\d{2}-\\d{2}-${t}$`,"u").test(n)}async function Zd(n,e,t,i={}){if(!i.skipExactCompatibility){let o=await wr(n,Pn.join(e,t),`Classic archived change ${t}`);if(o.exists)return o.change}if(!(await pt(n,e,{label:"Classic archive directory",expected:"directory"})).exists)return null;let s=[];for(let o of await Gd.readdir(e,{withFileTypes:!0})){if(!Xd(o.name,t))continue;let a=await wr(n,Pn.join(e,o.name),`Classic archived change ${o.name}`);a.exists&&a.stateExists&&s.push(a.change)}return s.sort((o,a)=>a.directory.localeCompare(o.directory))[0]??null}async function ja(n,e=process.cwd()){zd(n);let t=await Oa(e),i=await wr(t.projectRoot,Pn.join(t.changesDir,n),`Classic active change ${n}`);if(i.exists)return i.change;let r=await Zd(t.projectRoot,t.archiveDir,n);return r||i.change}var op=Nn(yn(),1);var jg=256*1024;var vr=["workflow","language","phase","context_compression","build_mode","build_pause","subagent_dispatch","tdd_mode","review_mode","isolation","bound_branch","verify_mode","auto_transition","base_ref","design_doc","plan","verify_result","verify_failures","verification_report","branch_status","created_at","verified_at","archive_confirmation","archived","direct_override","handoff_context","handoff_hash","classic_profile","classic_migration"],br=["run_id"],Dg=new Set([...vr,...br]);import{AsyncLocalStorage as cp}from"async_hooks";import{promises as Ta}from"fs";import mt from"path";var kr=new cp;function lp(n,e){let t=mt.relative(n,e);return t===""||!mt.isAbsolute(t)&&t!==".."&&!t.startsWith(`..${mt.sep}`)}async function up(n){let e=mt.resolve(n.invocationCwd??process.cwd()),t=mt.resolve(n.projectRoot??await xa(e)),[i,r]=await Promise.all([Ta.realpath(e),Ta.realpath(t)]);if(!lp(r,i))throw new Error(`Classic command invocation cwd is outside the discovered project: ${e}`);return{invocationCwd:e,projectRoot:t}}async function qa(n,e){let t=kr.getStore();if(t)return e(t);let i=await up(n);return kr.run(i,()=>e(i))}function La(){let n=kr.getStore();if(!n)throw new Error("Classic command project context is unavailable");return n.projectRoot}var fp="\x1B[32m",ht="\x1B[31m",dp="\x1B[33m",pp="\x1B[0m",mp=["workflow","phase","design_doc","plan","build_mode","isolation","verify_mode","verify_result","verified_at","archived"],hp={workflow:["full","hotfix","tweak"],language:["en","zh-CN"],phase:["open","design","build","verify","archive"],context_compression:["off","beta"],build_mode:["subagent-driven-development","executing-plans","direct"],build_pause:["plan-ready"],subagent_dispatch:["confirmed"],tdd_mode:["tdd","direct"],review_mode:["off","standard","thorough"],isolation:["current","branch","worktree"],verify_mode:["light","full"],auto_transition:["true","false"],verify_result:["pending","pass","fail"],branch_status:["pending","handled"],archive_confirmation:["pending","confirmed"],archived:["true","false"],direct_override:["true","false"],classic_profile:["full","hotfix","tweak"],classic_migration:["1"]},gp=new Set([...vr,...br,"classic_profile","classic_migration"]);function pe(n,e){return`${n}${e}${pp}`}function gt(n){return n==null?"":typeof n=="object"?JSON.stringify(n):String(n)}var $a=async(n,e)=>qa(e,async()=>{let t=n[0],i=yr(t);if(i)return{exitCode:1,stderr:pe(ht,`ERROR: ${i}`)};let r=La(),{directory:s,label:o}=await ja(t,r),a=Da.join(s,".comet.yaml"),c=[`[VALIDATE] ${o}/.comet.yaml`],l=0,m=0,u=p=>{l+=1,c.push(pe(ht,` FAIL: ${p}`))},d=p=>{m+=1,c.push(pe(dp,` WARN: ${p}`))},h;try{h=await Ra(r,a,{label:`Classic state ${o}/.comet.yaml`})}catch(p){if(p.code==="ENOENT")return u(".comet.yaml does not exist"),c.push("",pe(ht,`${l} error(s), ${m} warning(s) — validation FAILED`)),{exitCode:1,stderr:c.join(` +`)};throw p}let w=(0,wt.parseDocument)(h);if(w.errors.length>0||!(0,wt.isMap)(w.contents)){for(let p of w.errors)u(p.message);return(0,wt.isMap)(w.contents)||u("document root must be a mapping"),c.push("",pe(ht,`${l} error(s), ${m} warning(s) — validation FAILED`)),{exitCode:1,stderr:c.join(` +`)}}let f=w.toJS();for(let p of mp)Object.prototype.hasOwnProperty.call(f,p)||u(`missing required field '${p}'`);for(let[p,g]of Object.entries(hp)){if(!Object.prototype.hasOwnProperty.call(f,p))continue;let v=gt(f[p]);if(!v){p==="auto_transition"&&u(`${p}='' is not valid. Expected: ${g.join(" ")}`);continue}g.includes(v)||u(`${p}='${v}' is not valid. Expected: ${g.join(" ")}`)}if(Object.prototype.hasOwnProperty.call(f,"bound_branch")){let p=f.bound_branch;p!==null&&typeof p!="string"&&u(`bound_branch='${gt(p)}' is not a string or null`)}if(Object.prototype.hasOwnProperty.call(f,"verify_failures")){let p=f.verify_failures;(typeof p!="number"||!Number.isInteger(p)||p<0)&&u(`verify_failures='${gt(p)}' is not a non-negative integer`)}for(let p of["design_doc","plan","handoff_context","verification_report"]){let g=gt(f[p]);if(g){if(/^(?:[A-Za-z]:|[\\/]|~)/u.test(g)||g.split(/[\\/]/u).includes("..")){u(`${p}='${g}' must be a relative repository path`);continue}try{await Ia(r,Da.resolve(r,g),{label:`${p} artifact pointer`,expected:"file"})||u(`${p}='${g}' does not exist on disk`)}catch(v){u(`${p}='${g}' is unsafe: ${v instanceof Error?v.message:String(v)}`)}}}for(let p of["handoff_hash"]){let g=gt(f[p]);g&&!/^[a-f0-9]{64}$/u.test(g)&&u(`${p}='${g}' is not a sha256 hex digest`)}for(let p of Object.keys(f))gp.has(p)||d(`unknown field '${p}' found`);return c.push(""),l>0?(c.push(pe(ht,`${l} error(s), ${m} warning(s) — validation FAILED`)),{exitCode:1,stderr:c.join(` +`)}):(c.push(pe(fp,`0 errors, ${m} warning(s) — validation PASSED`)),{exitCode:0,stderr:c.join(` `)})});function wp(n,e){return{exitCode:e.exitCode,stdout:JSON.stringify({command:n,exitCode:e.exitCode,...e.stdout===void 0?{}:{stdout:e.stdout},...e.stderr===void 0?{}:{stderr:e.stderr}})+` -`}}async function $a(n,e,t=process.argv.slice(2)){let i=t.includes("--json"),r=t.filter(a=>a!=="--json"),s;try{s=await e(r,{json:i})}catch(a){s={exitCode:70,stderr:a instanceof Error?a.message:String(a)}}let o=i?wp(n,s):s;return o.stdout&&process.stdout.write(o.stdout),o.stderr&&process.stderr.write(o.stderr+(o.stderr.endsWith(` +`}}async function Wa(n,e,t=process.argv.slice(2)){let i=t.includes("--json"),r=t.filter(a=>a!=="--json"),s;try{s=await e(r,{json:i})}catch(a){s={exitCode:70,stderr:a instanceof Error?a.message:String(a)}}let o=i?wp(n,s):s;return o.stdout&&process.stdout.write(o.stdout),o.stderr&&process.stderr.write(o.stderr+(o.stderr.endsWith(` `)?"":` -`)),o.exitCode}process.exitCode=await $a("validate",Da); +`)),o.exitCode}process.exitCode=await Wa("validate",$a); diff --git a/docs/comet/specs/unified-product-catalogue/spec.md b/docs/comet/specs/unified-product-catalogue/spec.md index 2add927cc..aaeb37946 100644 --- a/docs/comet/specs/unified-product-catalogue/spec.md +++ b/docs/comet/specs/unified-product-catalogue/spec.md @@ -20,7 +20,7 @@ docs: 布局由 `.comet/config.yaml` 的 `classic.artifact_layout` 唯一指定。Classic 的 OpenSpec root、changes、archive、specs 以及 Superpowers specs、plans、reports 都必须由同一个布局 resolver 推导。 -Runtime 不扫描另一布局来寻找 fallback,不根据哪个目录先出现决定所有权。配置指定布局与磁盘事实冲突、或 legacy/docs 两个 OpenSpec 根同时存在时,所有写操作失败关闭;只读 status / doctor 报告两个根及修复命令。配置缺失或无效时,只读消费者报告布局不可用,不猜测 legacy 路径继续扫描。 +Runtime 不扫描另一布局来寻找 fallback,不根据哪个目录先出现决定所有权。配置指定的布局是 Comet 的唯一写入和读取边界;另一个 OpenSpec 根可以由用户独立运行官方 OpenSpec CLI,二者同时存在不构成 Classic 冲突。配置缺失或无效时,只读消费者报告布局不可用,不猜测 legacy 路径继续扫描。 跨 workflow 的项目配置类型、字段规范化和相对路径边界属于 `domains/workflow-contract/`。Classic、Native、Entry、Factory、Dashboard 与 Skill 安装可以消费该契约,但不得分别以正则、字符串拼接或重复 YAML 解析重新定义它。 @@ -43,7 +43,7 @@ comet classic openspec -- 该命令发现项目根、读取并验证 Classic layout,将进程 cwd 设为解析后的 OpenSpec root,然后执行配置的 OpenSpec CLI。legacy 的 cwd 是项目根,docs 的 cwd 是 `/docs`。 -Adapter 原样转发 stdout、stderr 和退出码;命令不存在、配置无效、双根冲突或 root 不健康时返回明确错误,不切换另一布局重试。 +Adapter 原样转发 stdout、stderr 和退出码;命令不存在、配置无效或配置的 root 不健康时返回明确错误,不切换另一布局重试。另一个 OpenSpec 根不会被 Comet adapter 扫描或使用。 Comet-owned Skill、Rule、reference、runtime 与用户可复制的命令必须使用该 adapter。用户也可以在解析后的 OpenSpec root 直接运行官方 CLI。项目内 docs 布局不创建、注册或依赖 OpenSpec store ID。 @@ -56,12 +56,13 @@ OpenSpec CLI / 平台工具资产安装与项目 artifact root 初始化是两 - CLI 安装和平台 Skill / command 文件继续落在项目对应的平台目录。 - artifact root 初始化只在解析后的 OpenSpec root 创建官方 `openspec/` 结构,不把平台工具目录嵌套到 `docs/`。 - docs 布局可以通过 `openspec init /docs --tools none` 或等价的官方无工具初始化完成 root 创建。 +- 当项目尚无 Comet 配置、但已有用户管理的根级 `openspec/` 时,启用 Comet 的 docs 布局可以创建 `docs/openspec/`,不得移动、清理或扫描原有根级 OpenSpec 产物。 - 工具资产需要 OpenSpec 生成时,在隔离 staging project 生成并通过现有 platform adapter 合并;不得在真实项目根留下临时 `openspec/`。 - update 分别更新平台工具资产和配置的 artifact root,不以项目根存在 `openspec/` 为前提。 ## 路径消费者 -以下能力必须使用布局 resolver,并在写入前执行双根/配置可写断言: +以下能力必须使用布局 resolver,并在写入前执行配置 root 的可写断言: - Classic state、validate、guard、handoff、archive、resume probe、current selection 与 Hook Guard。 - Entry status、Ambient Resume 与 Hook Router 的 Classic change 枚举。 @@ -119,7 +120,7 @@ Doctor 检查: - layout 枚举、配置与启用 workflows 的一致性; - OpenSpec root 健康状态; -- legacy/docs 双根冲突; +- 配置 root 与物理目录的存在性、类型和安全边界;另一个 OpenSpec 根仅作为独立工具目录保留,不参与 Classic 状态判断; - 未完成迁移 journal 及其完整身份; - platform tool 资产与 artifact root 是否错误耦合。 diff --git a/domains/comet-classic/classic-evidence.ts b/domains/comet-classic/classic-evidence.ts index 76f7a813b..8d0a58a0d 100644 --- a/domains/comet-classic/classic-evidence.ts +++ b/domains/comet-classic/classic-evidence.ts @@ -1,7 +1,13 @@ import { promises as fs } from 'fs'; import path from 'path'; import type { ClassicStateProjection } from './classic-state.js'; -import { assertClassicLayoutReadable, discoverClassicProject } from './classic-layout.js'; +import { + assertClassicLayoutReadable, + classicLayoutPaths, + classicProjectRelative, + discoverClassicProject, + type ClassicLayoutPaths, +} from './classic-layout.js'; import { readLegacyArchivedHandoffFallback } from './classic-archive-pointer.js'; import { inspectProtectedProjectPath, @@ -27,10 +33,43 @@ async function linkedFileEvidence( projectRoot: string, code: string, relativePath: string | null, + layout?: ClassicLayoutPaths, + layoutError?: unknown, ): Promise { if (!relativePath) return { code, satisfied: false }; const source = relativePath.replaceAll('\\', '/'); + if (layoutError) { + return { + code, + satisfied: false, + source, + detail: `Classic layout is unsafe or unavailable: ${ + layoutError instanceof Error ? layoutError.message : String(layoutError) + }`, + }; + } try { + if (layout) { + const alternateLayout = layout.artifactLayout === 'legacy' ? 'docs' : 'legacy'; + const alternateRoot = classicProjectRelative( + projectRoot, + classicLayoutPaths(projectRoot, alternateLayout).openSpecRoot, + ); + if (source === alternateRoot || source.startsWith(`${alternateRoot}/`)) { + const alternate = await inspectProtectedProjectPath(projectRoot, source, { + label: `${code} artifact`, + expected: 'file', + }); + if (alternate.exists) { + return { + code, + satisfied: false, + source, + detail: 'standalone OpenSpec root is not a Comet artifact root', + }; + } + } + } const satisfied = await protectedProjectFileExists(projectRoot, source, { label: `${code} artifact`, }); @@ -56,9 +95,10 @@ async function archivedHandoffEvidence( projectRoot: string, changeDir: string, relativePath: string | null, + layout?: ClassicLayoutPaths, ): Promise { try { - await assertClassicLayoutReadable(projectRoot); + layout ??= await assertClassicLayoutReadable(projectRoot); } catch (error) { return { code: 'design.handoff', @@ -69,7 +109,7 @@ async function archivedHandoffEvidence( }`, }; } - const evidence = await linkedFileEvidence(projectRoot, 'design.handoff', relativePath); + const evidence = await linkedFileEvidence(projectRoot, 'design.handoff', relativePath, layout); if (!relativePath || evidence.satisfied || evidence.detail) return evidence; try { const mapped = await readLegacyArchivedHandoffFallback( @@ -197,17 +237,38 @@ export async function collectClassicEvidence( const checkpoint = projection.run ? path.resolve(changeDir, projection.run.checkpointRef) : path.join(changeDir, '.comet', 'checkpoint.json'); + let layout: ClassicLayoutPaths | undefined; + let layoutError: unknown; + try { + layout = await assertClassicLayoutReadable(projectRoot); + } catch (error) { + layoutError = error; + // The individual evidence item keeps reporting the precise unavailable + // layout error; pointers are only scoped when a valid layout is known. + } const evidence = await Promise.all([ directFileEvidence(projectRoot, 'openspec.proposal', proposal), directFileEvidence(projectRoot, 'openspec.design', design), directFileEvidence(projectRoot, 'openspec.tasks', tasks), deltaSpecEvidence(projectRoot, changeDir), - linkedFileEvidence(projectRoot, 'design.document', classic?.designDoc ?? null), - linkedFileEvidence(projectRoot, 'build.plan', classic?.plan ?? null), + linkedFileEvidence( + projectRoot, + 'design.document', + classic?.designDoc ?? null, + layout, + layoutError, + ), + linkedFileEvidence(projectRoot, 'build.plan', classic?.plan ?? null, layout, layoutError), taskEvidence(projectRoot, tasks), - linkedFileEvidence(projectRoot, 'verification.report', classic?.verificationReport ?? null), - archivedHandoffEvidence(projectRoot, changeDir, classic?.handoffContext ?? null), + linkedFileEvidence( + projectRoot, + 'verification.report', + classic?.verificationReport ?? null, + layout, + layoutError, + ), + archivedHandoffEvidence(projectRoot, changeDir, classic?.handoffContext ?? null, layout), directFileEvidence(projectRoot, 'run.checkpoint', checkpoint), ]); diff --git a/domains/comet-classic/classic-layout-initialization.ts b/domains/comet-classic/classic-layout-initialization.ts index 0ce252666..dee95cdf4 100644 --- a/domains/comet-classic/classic-layout-initialization.ts +++ b/domains/comet-classic/classic-layout-initialization.ts @@ -999,9 +999,10 @@ export async function repairClassicLayoutInitialization( } /** - * Validate the only two safe OpenSpec initialization states: - * an existing configured Classic layout that is already writable, or a truly - * fresh project where neither managed OpenSpec root exists. + * Validate OpenSpec initialization against the explicitly selected Classic + * root. A standalone OpenSpec root may already exist at the alternate + * location; initialization owns only the selected root and leaves the + * alternate root untouched. */ export async function assertClassicLayoutInitializationSafe( projectRoot: string, @@ -1085,11 +1086,6 @@ export async function assertClassicLayoutInitializationSafe( `Classic init ownership is ${ownership.stage}; recover it with comet doctor before continuing`, ); } - if (alternateRoot.exists) { - throw new Error( - 'Classic layout conflict: the alternate OpenSpec root appeared during initialization', - ); - } const originalConfigStillMatches = workflowProjectConfigIdentityEquals( configIdentity, ownership.configIdentity, @@ -1150,9 +1146,7 @@ export async function assertClassicLayoutInitializationSafe( `Configured Classic OpenSpec root is missing for ${desiredLayout} layout while the alternate root exists`, ); } - const configured = await assertClassicLayoutWritable(root, desiredLayout, { - allowAlternateRoot: true, - }); + const configured = await assertClassicLayoutWritable(root, desiredLayout); return { ...configured, initializationPermit: permitsDesiredRoot(permit, root, desiredLayout) @@ -1170,6 +1164,14 @@ export async function assertClassicLayoutInitializationSafe( : initializationPermit(root, desiredLayout, configIdentity), }; } + if (!desiredRoot.exists && alternateRoot.exists) { + return { + ...desired, + initializationPermit: permitsDesiredRoot(permit, root, desiredLayout) + ? permit + : initializationPermit(root, desiredLayout, configIdentity), + }; + } throw new Error( 'Cannot initialize Classic layout without .comet/config.yaml when openspec/ or docs/openspec/ already exists', ); diff --git a/domains/comet-classic/classic-layout.ts b/domains/comet-classic/classic-layout.ts index 41004af8a..56c2e174d 100644 --- a/domains/comet-classic/classic-layout.ts +++ b/domains/comet-classic/classic-layout.ts @@ -39,10 +39,6 @@ export interface ClassicLayoutInspection { dualRoots: boolean; } -interface ClassicLayoutAccessOptions { - allowAlternateRoot?: boolean; -} - export class ClassicLayoutUnavailableError extends Error { readonly code = 'classic-layout-unavailable'; @@ -52,23 +48,6 @@ export class ClassicLayoutUnavailableError extends Error { } } -export class ClassicLayoutConflictError extends Error { - readonly code = 'classic-layout-conflict'; - - constructor( - readonly configuredRoot: string, - readonly alternateRoot: string, - projectRoot: string, - ) { - const configured = classicProjectRelative(projectRoot, configuredRoot); - const alternate = classicProjectRelative(projectRoot, alternateRoot); - super( - `Classic layout conflict: both ${configured}/ and ${alternate}/ exist; run comet doctor and resolve the conflict before writing`, - ); - this.name = 'ClassicLayoutConflictError'; - } -} - const PROJECT_CONFIG_RELATIVE_PATH = '.comet/config.yaml'; function isMissingPath(error: unknown): boolean { @@ -184,6 +163,16 @@ export async function resolveClassicLayout( ); } +async function inspectUntrustedAlternateRoot(alternateRoot: string): Promise { + try { + await fs.lstat(alternateRoot); + return true; + } catch (error) { + if (isMissingPath(error)) return false; + throw error; + } +} + export async function inspectClassicLayout( projectRoot: string, artifactLayout?: ClassicArtifactLayout, @@ -192,7 +181,7 @@ export async function inspectClassicLayout( const alternateLayout: ClassicArtifactLayout = paths.artifactLayout === 'legacy' ? 'docs' : 'legacy'; const alternateRoot = classicLayoutPaths(projectRoot, alternateLayout).openSpecRoot; - const [configuredRoot, alternate] = await Promise.all([ + const [configuredRoot, alternateRootExists] = await Promise.all([ inspectProtectedProjectPath( paths.projectRoot, classicProjectRelative(paths.projectRoot, paths.openSpecRoot), @@ -201,17 +190,9 @@ export async function inspectClassicLayout( expected: 'directory', }, ), - inspectProtectedProjectPath( - paths.projectRoot, - classicProjectRelative(paths.projectRoot, alternateRoot), - { - label: 'Alternate Classic OpenSpec root', - expected: 'directory', - }, - ), + inspectUntrustedAlternateRoot(alternateRoot), ]); const configuredRootExists = configuredRoot.exists; - const alternateRootExists = alternate.exists; return { paths, configuredRootExists, @@ -221,16 +202,12 @@ export async function inspectClassicLayout( }; } -async function assertClassicManagedRootsPhysical( - paths: ClassicLayoutPaths, - alternateRoot: string, -): Promise { +async function assertClassicManagedRootsPhysical(paths: ClassicLayoutPaths): Promise { const managedRoots = [ paths.openSpecRoot, paths.changesDir, paths.archiveDir, paths.specsDir, - alternateRoot, paths.superpowersRoot, paths.superpowersSpecsDir, paths.superpowersPlansDir, @@ -248,17 +225,13 @@ async function assertClassicManagedRootsPhysical( export async function assertClassicLayoutReadable( projectRoot: string, artifactLayout?: ClassicArtifactLayout, - options: ClassicLayoutAccessOptions = {}, ): Promise { const inspection = await inspectClassicLayout(projectRoot, artifactLayout); - await assertClassicManagedRootsPhysical(inspection.paths, inspection.alternateRoot); - if (inspection.dualRoots && !options.allowAlternateRoot) { - throw new ClassicLayoutConflictError( - inspection.paths.openSpecRoot, - inspection.alternateRoot, - inspection.paths.projectRoot, - ); - } + await assertClassicManagedRootsPhysical(inspection.paths); + // `artifact_layout` is the ownership boundary. The alternate OpenSpec root + // may belong to a standalone OpenSpec workflow and must not block Comet from + // reading or writing its configured root. Explicit root migration remains + // responsible for handling a non-empty destination safely. if (!inspection.configuredRootExists) { const configured = classicProjectRelative( inspection.paths.projectRoot, @@ -280,7 +253,6 @@ export async function assertClassicLayoutReadable( export async function assertClassicLayoutWritable( projectRoot: string, artifactLayout?: ClassicArtifactLayout, - options: ClassicLayoutAccessOptions = {}, ): Promise { const pendingMove = path.join(path.resolve(projectRoot), '.comet', 'classic-root-move.json'); if (await fileExists(pendingMove)) { @@ -288,7 +260,7 @@ export async function assertClassicLayoutWritable( 'Classic root move transaction is incomplete; inspect it with comet doctor and recover it explicitly before writing', ); } - const paths = await assertClassicLayoutReadable(projectRoot, artifactLayout, options); + const paths = await assertClassicLayoutReadable(projectRoot, artifactLayout); if (!(await fileExists(paths.openSpecRoot))) { throw new Error( `Configured Classic OpenSpec root is missing: ${classicProjectRelative( diff --git a/domains/comet-classic/classic-root-command.ts b/domains/comet-classic/classic-root-command.ts index e1bad6c70..c47a4b8b6 100644 --- a/domains/comet-classic/classic-root-command.ts +++ b/domains/comet-classic/classic-root-command.ts @@ -8,6 +8,7 @@ import { assertClassicLayoutReadable, classicProjectRelative, discoverClassicProject, + inspectClassicLayout, type ClassicLayoutPaths, } from './classic-layout.js'; import { readWorkflowProjectConfig } from '../workflow-contract/project-config-reader.js'; @@ -178,6 +179,7 @@ export const classicRootCommand: ClassicCommandHandler = async (args) => { if (action === 'show' && target === undefined) { const projectRoot = await discoverClassicProject(process.cwd()); const layout = await assertClassicLayoutReadable(projectRoot); + const inspection = await inspectClassicLayout(projectRoot, layout.artifactLayout); return { exitCode: 0, stdout: @@ -185,6 +187,10 @@ export const classicRootCommand: ClassicCommandHandler = async (args) => { schema: 'comet.classic-layout.v1', artifactLayout: layout.artifactLayout, openSpecRoot: classicProjectRelative(projectRoot, layout.openSpecRoot), + alternateRoot: classicProjectRelative(projectRoot, inspection.alternateRoot), + configuredRootExists: inspection.configuredRootExists, + alternateRootExists: inspection.alternateRootExists, + dualRoots: inspection.dualRoots, changesRoot: classicProjectRelative(projectRoot, layout.changesDir), archiveRoot: classicProjectRelative(projectRoot, layout.archiveDir), specsRoot: classicProjectRelative(projectRoot, layout.specsDir), diff --git a/domains/comet-entry/hook-adapter.ts b/domains/comet-entry/hook-adapter.ts index d74e8e72f..383f8fb62 100644 --- a/domains/comet-entry/hook-adapter.ts +++ b/domains/comet-entry/hook-adapter.ts @@ -145,6 +145,10 @@ export function parseCometHookRequest(source: string, filePath?: string): CometH try { input = JSON.parse(source) as unknown; } catch { + const targets = patchTargets(source); + if (targets.length > 0) { + return { intent: 'write', targets: [...new Set(targets)], toolName: 'apply_patch' }; + } return { intent: 'unknown', targets: [], toolName: null }; } if (!isRecord(input)) return { intent: 'unknown', targets: [], toolName: null }; diff --git a/domains/factory/package.ts b/domains/factory/package.ts index 4eab685fe..9ee409c64 100644 --- a/domains/factory/package.ts +++ b/domains/factory/package.ts @@ -494,7 +494,6 @@ async function workflowPathBaseRoot(pathBase) { const config = await readWorkflowProjectPathConfig(runRoot); let resolved; let configuredClassicRoot = null; - let alternateClassicRoot = null; if (pathBase === 'classic-openspec-root' || pathBase === 'classic-superpowers-root') { if (!config.classicEnabled || config.classicArtifactLayout === null) { throw new Error('Classic workflow is not enabled by .comet/config.yaml'); @@ -502,9 +501,6 @@ async function workflowPathBaseRoot(pathBase) { configuredClassicRoot = config.classicArtifactLayout === 'docs' ? path.join(runRoot, 'docs', 'openspec') : path.join(runRoot, 'openspec'); - alternateClassicRoot = config.classicArtifactLayout === 'docs' - ? path.join(runRoot, 'openspec') - : path.join(runRoot, 'docs', 'openspec'); } if (pathBase === 'classic-openspec-root') { resolved = configuredClassicRoot; @@ -522,27 +518,16 @@ async function workflowPathBaseRoot(pathBase) { } else { resolved = runRoot; } - if (configuredClassicRoot !== null && alternateClassicRoot !== null) { - const [configuredInspection, alternateInspection] = await Promise.all([ - inspectWorkflowProtectedPath( - runRoot, - configuredClassicRoot, - 'configured Classic OpenSpec root', - 'directory', - ), - inspectWorkflowProtectedPath( - runRoot, - alternateClassicRoot, - 'alternate Classic OpenSpec root', - 'directory', - ), - ]); + if (configuredClassicRoot !== null) { + const configuredInspection = await inspectWorkflowProtectedPath( + runRoot, + configuredClassicRoot, + 'configured Classic OpenSpec root', + 'directory', + ); if (!configuredInspection.exists) { throw new Error('Configured Classic OpenSpec root does not exist: ' + configuredClassicRoot); } - if (alternateInspection.exists) { - throw new Error('Classic layout conflict: both configured and alternate OpenSpec roots exist'); - } } const rootInspection = await inspectWorkflowProtectedPath( runRoot, diff --git a/package-lock.json b/package-lock.json index dabd772fe..09dd2cb43 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@rpamis/comet", - "version": "0.4.0-beta.15", + "version": "0.4.0-beta.16", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@rpamis/comet", - "version": "0.4.0-beta.15", + "version": "0.4.0-beta.16", "hasInstallScript": true, "license": "MIT", "dependencies": { @@ -3790,9 +3790,9 @@ } }, "node_modules/brace-expansion": { - "version": "5.0.7", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.7.tgz", - "integrity": "sha512-7oFy703dxfY3/NLxC1fh2SUCQ0H9rmAY+5EpDVfXjUTTs+HEwR2nYaqLv+GWcTsumwxPfiz6CzCNkwXwBUwqCA==", + "version": "5.0.9", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.9.tgz", + "integrity": "sha512-ScQ4IuvIEF1TMlP7Zt+vjJ//9zlPb2SDcxWxM3bk8s6t6GGdJ7KO1dCcTidOPJKePW30LE/2cT7wCyPho9/Wxg==", "dev": true, "license": "MIT", "dependencies": { @@ -6474,9 +6474,9 @@ } }, "node_modules/postcss": { - "version": "8.5.18", - "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.18.tgz", - "integrity": "sha512-xdB1oSLHbz1vRWgCDalrCqEFTWzFlhqFC5tIHLMOSUIjhm3XXQ1qrFy8S/ESr1JYRRXqM3c1QFiMZUJdUTqyMQ==", + "version": "8.5.25", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.25.tgz", + "integrity": "sha512-DTPx3RWSSnWyzLxQnlH0rJP+EW5ekl16ZU4/psbIhA0e53kJfdgaN5vKM+xP7yJtXVu+nfdVFmlgFDEKAe4Pyw==", "dev": true, "funding": [ { @@ -7134,9 +7134,9 @@ } }, "node_modules/undici": { - "version": "7.28.0", - "resolved": "https://registry.npmmirror.com/undici/-/undici-7.28.0.tgz", - "integrity": "sha512-cRZYrTDwWznlnRiPjggAGxZXanty6M8RV1ff8Wm4LWXBp7/IG8v5DnOm74DtUBp9OONpK75YlPnIjQqX0dBDtA==", + "version": "7.29.0", + "resolved": "https://registry.npmmirror.com/undici/-/undici-7.29.0.tgz", + "integrity": "sha512-IDxfleLmmbSskfWSUATiN1nfn2rDuvnMOqb5CWR92iIfojA0Ud+ulOAAEQ57LPr9rWmsreUyf5lwyao+7GNNVw==", "dev": true, "license": "MIT", "engines": { diff --git a/package.json b/package.json index f04558efa..30c32a59b 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@rpamis/comet", - "version": "0.4.0-beta.15", + "version": "0.4.0-beta.16", "description": "Agent Skill Harness For Turning Ideas Into Evaluated Workflows", "keywords": [ "comet", @@ -97,15 +97,17 @@ }, "packageManager": "pnpm@10.18.3", "overrides": { - "brace-expansion": "5.0.7", + "brace-expansion": "5.0.9", "esbuild": "0.28.1", - "postcss": "8.5.18" + "postcss": "8.5.25", + "undici": "7.29.0" }, "pnpm": { "overrides": { - "brace-expansion": "5.0.7", + "brace-expansion": "5.0.9", "esbuild": "0.28.1", - "postcss": "8.5.18" + "postcss": "8.5.25", + "undici": "7.29.0" } }, "engines": { diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 66690f810..6e86e13e2 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -5,9 +5,10 @@ settings: excludeLinksFromLockfile: false overrides: - brace-expansion: 5.0.7 + brace-expansion: 5.0.9 esbuild: 0.28.1 - postcss: 8.5.18 + postcss: 8.5.25 + undici: 7.29.0 importers: .: @@ -2577,12 +2578,12 @@ packages: integrity: sha512-RKshQI1R3YQ+n9YJz2QQ147P66ELpa1FQEg20Dk8oW9t2KgLbpDLLp9aGZ7y8WHSshDknG0bknqGw5/tyCs5tw==, } - brace-expansion@5.0.7: + brace-expansion@5.0.9: resolution: { - integrity: sha512-7oFy703dxfY3/NLxC1fh2SUCQ0H9rmAY+5EpDVfXjUTTs+HEwR2nYaqLv+GWcTsumwxPfiz6CzCNkwXwBUwqCA==, + integrity: sha512-ScQ4IuvIEF1TMlP7Zt+vjJ//9zlPb2SDcxWxM3bk8s6t6GGdJ7KO1dCcTidOPJKePW30LE/2cT7wCyPho9/Wxg==, } - engines: { node: 18 || 20 || >=22 } + engines: { node: 20 || >=22 } braces@3.0.3: resolution: @@ -3928,10 +3929,10 @@ packages: } engines: { node: ^20.17.0 || >=22.9.0 } - nanoid@3.3.15: + nanoid@3.3.17: resolution: { - integrity: sha512-y7Wygv/7mEOvxTuEQDB8StXdMRBWf1kR/tlhAzBRUFkB2jfcLOAxO/SHmOO2zgz1pVgK29/kyupn059/bCHdjA==, + integrity: sha512-xQLf0A3HOMlgHq0n247/LRuAOYmB7dXJ/DvAxGvsSBij45XtBSmQycu+F8ODbHwns/XyFZagyL1+J0Offw1E0g==, } engines: { node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1 } hasBin: true @@ -4076,10 +4077,10 @@ packages: integrity: sha512-25ClnWWuw7JbWZcgqY/gJ4FQWadKxGWk+3kR/7kD0tCaDtPPMj7oHu2ToLaVhfpnHrZzYby2w6tUA0eOIuUg8g==, } - postcss@8.5.18: + postcss@8.5.25: resolution: { - integrity: sha512-xdB1oSLHbz1vRWgCDalrCqEFTWzFlhqFC5tIHLMOSUIjhm3XXQ1qrFy8S/ESr1JYRRXqM3c1QFiMZUJdUTqyMQ==, + integrity: sha512-DTPx3RWSSnWyzLxQnlH0rJP+EW5ekl16ZU4/psbIhA0e53kJfdgaN5vKM+xP7yJtXVu+nfdVFmlgFDEKAe4Pyw==, } engines: { node: ^10 || ^12 || >=14 } @@ -4526,10 +4527,10 @@ packages: integrity: sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw==, } - undici@7.28.0: + undici@7.29.0: resolution: { - integrity: sha512-cRZYrTDwWznlnRiPjggAGxZXanty6M8RV1ff8Wm4LWXBp7/IG8v5DnOm74DtUBp9OONpK75YlPnIjQqX0dBDtA==, + integrity: sha512-IDxfleLmmbSskfWSUATiN1nfn2rDuvnMOqb5CWR92iIfojA0Ud+ulOAAEQ57LPr9rWmsreUyf5lwyao+7GNNVw==, } engines: { node: '>=20.18.1' } @@ -6357,7 +6358,7 @@ snapshots: dependencies: require-from-string: 2.0.2 - brace-expansion@5.0.7: + brace-expansion@5.0.9: dependencies: balanced-match: 4.0.4 @@ -6940,7 +6941,7 @@ snapshots: saxes: 6.0.0 symbol-tree: 3.2.4 tough-cookie: 6.0.2 - undici: 7.28.0 + undici: 7.29.0 w3c-xmlserializer: 5.0.0 webidl-conversions: 8.0.1 whatwg-mimetype: 5.0.0 @@ -7128,7 +7129,7 @@ snapshots: minimatch@10.2.5: dependencies: - brace-expansion: 5.0.7 + brace-expansion: 5.0.9 ms@2.1.3: {} @@ -7136,7 +7137,7 @@ snapshots: mute-stream@3.0.0: {} - nanoid@3.3.15: {} + nanoid@3.3.17: {} natural-compare@1.4.0: {} @@ -7212,9 +7213,9 @@ snapshots: path-data-parser: 0.1.0 points-on-curve: 0.2.0 - postcss@8.5.18: + postcss@8.5.25: dependencies: - nanoid: 3.3.15 + nanoid: 3.3.17 picocolors: 1.1.1 source-map-js: 1.2.1 @@ -7446,7 +7447,7 @@ snapshots: undici-types@7.16.0: {} - undici@7.28.0: {} + undici@7.29.0: {} update-browserslist-db@1.2.3(browserslist@4.28.4): dependencies: @@ -7465,7 +7466,7 @@ snapshots: esbuild: 0.28.1 fdir: 6.5.0(picomatch@4.0.4) picomatch: 4.0.4 - postcss: 8.5.18 + postcss: 8.5.25 rollup: 4.62.2 tinyglobby: 0.2.17 optionalDependencies: diff --git a/test/app/cli-help.test.ts b/test/app/cli-help.test.ts index 2bd2b2640..9e7a098de 100644 --- a/test/app/cli-help.test.ts +++ b/test/app/cli-help.test.ts @@ -29,7 +29,7 @@ describe('CLI help text', () => { expect(help.status, help.stderr).toBe(0); expect(help.stdout).toContain(tagline); expect(packageJson.description).toBe(tagline); - expect(packageJson.version).toBe('0.4.0-beta.15'); + expect(packageJson.version).toBe('0.4.0-beta.16'); }); it('marks bundle as the advanced backend and skill Engine runs as advanced', () => { diff --git a/test/app/doctor.test.ts b/test/app/doctor.test.ts index 46473a91a..d7545d01b 100644 --- a/test/app/doctor.test.ts +++ b/test/app/doctor.test.ts @@ -953,7 +953,7 @@ describe('doctor command', () => { }); it.each(['configured', 'alternate'] as const)( - 'fails the Classic layout check when the %s root is a directory link', + 'handles the Classic layout check when the %s root is a directory link', async (kind) => { const outsideRoot = await fs.mkdtemp(path.join(os.tmpdir(), 'comet-doctor-root-link-')); try { @@ -1006,10 +1006,18 @@ describe('doctor command', () => { const results = await collectDoctorResults(tmpDir); - expect(results.find((result) => result.check === 'Classic artifact layout')).toMatchObject({ - status: 'fail', - message: expect.stringMatching(/symbolic link or junction/iu), - }); + const layoutResult = results.find((result) => result.check === 'Classic artifact layout'); + if (kind === 'configured') { + expect(layoutResult).toMatchObject({ + status: 'fail', + message: expect.stringMatching(/symbolic link or junction/iu), + }); + } else { + expect(layoutResult).toMatchObject({ + status: 'pass', + message: expect.stringMatching(/standalone OpenSpec root .* ignored by Comet/iu), + }); + } expect(results.some((result) => result.check.includes('external-marker'))).toBe(false); } finally { await fs.rm(outsideRoot, { recursive: true, force: true }); @@ -1087,7 +1095,7 @@ describe('doctor command', () => { await fs.rm(tmpDir, { recursive: true, force: true }); }); - it('accepts current comet state fields without mutating them during a layout conflict', async () => { + it('accepts current Comet state fields while a standalone OpenSpec root coexists', async () => { const changeDir = path.join(tmpDir, 'openspec', 'changes', 'current-state'); await state(tmpDir, 'init', 'current-state', 'full'); await state(tmpDir, 'set', 'current-state', 'phase', 'verify'); @@ -1108,9 +1116,12 @@ describe('doctor command', () => { status: string; message: string; }>; - expect(results.find((result) => result.check === 'Classic artifact layout')).toMatchObject({ - status: 'fail', - }); + const layoutResult = results.find((result) => result.check === 'Classic artifact layout'); + expect(layoutResult).toMatchObject({ status: 'pass' }); + expect(layoutResult?.message).toContain('openspec/'); + expect(layoutResult?.message).toContain('docs/openspec/'); + expect(layoutResult?.message).toContain('standalone OpenSpec root'); + expect(layoutResult?.message).toContain('ignored by Comet'); const stateResult = results.find((result) => result.check === '.comet.yaml: current-state'); expect(stateResult).toMatchObject({ status: 'pass', diff --git a/test/domains/comet-classic/classic-evidence.test.ts b/test/domains/comet-classic/classic-evidence.test.ts index 0666a42ac..55f723e1a 100644 --- a/test/domains/comet-classic/classic-evidence.test.ts +++ b/test/domains/comet-classic/classic-evidence.test.ts @@ -138,6 +138,20 @@ describe('Classic evidence collection', () => { expect(evidenceSatisfied(evidence, 'run.checkpoint')).toBe(false); }); + it('does not satisfy linked evidence when the configured layout is unavailable', async () => { + await fs.rm(path.join(projectRoot, 'openspec'), { recursive: true, force: true }); + await writeProjectFile('docs/superpowers/plans/demo-plan.md', '# Plan\n'); + + const evidence = await collectClassicEvidence(changeDir, projection); + const plan = evidence.find((item) => item.code === 'build.plan'); + + expect(plan).toMatchObject({ + satisfied: false, + source: 'docs/superpowers/plans/demo-plan.md', + }); + expect(plan?.detail).toContain('Classic layout'); + }); + it('does not satisfy linked evidence with a project traversal pointer', async () => { const outsideRoot = await fs.mkdtemp(path.join(os.tmpdir(), 'comet-classic-outside-')); try { @@ -228,7 +242,7 @@ describe('Classic evidence collection', () => { }); }); - it('does not satisfy a legacy handoff pointer from the alternate root during a dual-root conflict', async () => { + it('does not consume a handoff pointer from the standalone OpenSpec root', async () => { changeDir = path.join(projectRoot, 'docs', 'openspec', 'changes', 'demo'); await fs.mkdir(changeDir, { recursive: true }); await writeClassicConfig('docs'); @@ -243,7 +257,7 @@ describe('Classic evidence collection', () => { expect(handoff).toMatchObject({ satisfied: false, source: 'openspec/changes/demo/.comet/handoff/context.json', - detail: expect.stringContaining('Classic layout conflict'), + detail: expect.stringContaining('standalone OpenSpec root is not a Comet artifact root'), }); }); diff --git a/test/domains/comet-classic/classic-layout-initialization.test.ts b/test/domains/comet-classic/classic-layout-initialization.test.ts index 7e69616f2..b1634b92f 100644 --- a/test/domains/comet-classic/classic-layout-initialization.test.ts +++ b/test/domains/comet-classic/classic-layout-initialization.test.ts @@ -353,12 +353,15 @@ describe('Classic layout initialization safety', () => { ); }); - it('rejects a fresh project when the requested docs layout conflicts with a legacy root', async () => { + it('allows a fresh docs layout alongside a standalone legacy OpenSpec root', async () => { await fs.mkdir(path.join(projectRoot, 'openspec'), { recursive: true }); - await expect(assertClassicLayoutInitializationSafe(projectRoot, 'docs')).rejects.toThrow( - /cannot initialize Classic layout without.*config/iu, - ); + const initialization = await assertClassicLayoutInitializationSafe(projectRoot, 'docs'); + + expect(initialization).toMatchObject({ + artifactLayout: 'docs', + openSpecRoot: path.join(projectRoot, 'docs', 'openspec'), + }); }); it('rejects a fresh project when the alternate docs root is a directory link', async () => { diff --git a/test/domains/comet-classic/classic-layout.test.ts b/test/domains/comet-classic/classic-layout.test.ts index 17eb8fa1f..0d9e16248 100644 --- a/test/domains/comet-classic/classic-layout.test.ts +++ b/test/domains/comet-classic/classic-layout.test.ts @@ -6,7 +6,6 @@ import path from 'path'; import { assertClassicLayoutReadable, assertClassicLayoutWritable, - ClassicLayoutConflictError, classicLayoutPaths, discoverClassicProject, inspectClassicLayout, @@ -110,13 +109,16 @@ describe('Classic artifact layout', () => { await expect(readClassicArtifactLayout(root)).rejects.toThrow('Invalid .comet/config.yaml'); }); - it('fails closed for writes when both OpenSpec roots exist', async () => { + it('keeps the configured Classic root writable when a standalone OpenSpec root also exists', async () => { const root = await project(); await config(root, ' artifact_layout: docs\n'); await fs.mkdir(path.join(root, 'openspec'), { recursive: true }); await fs.mkdir(path.join(root, 'docs', 'openspec'), { recursive: true }); - await expect(assertClassicLayoutWritable(root)).rejects.toThrow('Classic layout conflict'); + await expect(assertClassicLayoutWritable(root)).resolves.toMatchObject({ + artifactLayout: 'docs', + openSpecRoot: path.join(root, 'docs', 'openspec'), + }); }); it('allows initialization to use its selected root without mutating an alternate root', async () => { @@ -125,27 +127,34 @@ describe('Classic artifact layout', () => { await fs.mkdir(path.join(root, 'openspec'), { recursive: true }); await fs.mkdir(path.join(root, 'docs', 'openspec'), { recursive: true }); - await expect( - assertClassicLayoutWritable(root, 'docs', { allowAlternateRoot: true }), - ).resolves.toMatchObject({ + await expect(assertClassicLayoutWritable(root, 'docs')).resolves.toMatchObject({ artifactLayout: 'docs', openSpecRoot: path.join(root, 'docs', 'openspec'), }); }); - it('reports a structured dual-root error from the read-only layout boundary', async () => { + it('reads the configured root without scanning the standalone OpenSpec root', async () => { const root = await project(); await config(root, ' artifact_layout: docs\n'); await fs.mkdir(path.join(root, 'openspec'), { recursive: true }); await fs.mkdir(path.join(root, 'docs', 'openspec'), { recursive: true }); - const error = await assertClassicLayoutReadable(root).catch((cause: unknown) => cause); + await expect(assertClassicLayoutReadable(root)).resolves.toMatchObject({ + artifactLayout: 'docs', + openSpecRoot: path.join(root, 'docs', 'openspec'), + }); + }); + + it('keeps the configured root readable when the standalone root is a directory link', async () => { + const root = await project(); + const outside = await externalDirectory(); + await config(root, ' artifact_layout: docs\n'); + await fs.mkdir(path.join(root, 'docs', 'openspec'), { recursive: true }); + await directoryLink(outside, path.join(root, 'openspec')); - expect(error).toBeInstanceOf(ClassicLayoutConflictError); - expect(error).toMatchObject({ - code: 'classic-layout-conflict', - configuredRoot: path.join(root, 'docs', 'openspec'), - alternateRoot: path.join(root, 'openspec'), + await expect(assertClassicLayoutReadable(root)).resolves.toMatchObject({ + artifactLayout: 'docs', + openSpecRoot: path.join(root, 'docs', 'openspec'), }); }); diff --git a/test/domains/comet-classic/classic-openspec-command.test.ts b/test/domains/comet-classic/classic-openspec-command.test.ts index 952723338..62f29f996 100644 --- a/test/domains/comet-classic/classic-openspec-command.test.ts +++ b/test/domains/comet-classic/classic-openspec-command.test.ts @@ -100,14 +100,29 @@ describe('Classic OpenSpec adapter', () => { }); }); - it('fails closed when legacy and docs roots coexist', async () => { + it('uses the configured docs root when a standalone OpenSpec root also exists', async () => { await fs.mkdir(path.join(projectRoot, 'openspec')); + mockedSpawnSync.mockReturnValue({ + pid: 1, + output: [null, 'standalone root is independent\n', ''], + stdout: 'standalone root is independent\n', + stderr: '', + status: 0, + signal: null, + }); const result = await runClassicCli(['openspec', 'status']); - expect(result.exitCode).toBe(70); - expect(result.stderr).toContain('Classic layout conflict'); - expect(mockedSpawnSync).not.toHaveBeenCalled(); + expect(result).toEqual({ + exitCode: 0, + stdout: 'standalone root is independent\n', + stderr: undefined, + }); + expect(mockedSpawnSync).toHaveBeenCalledWith( + 'openspec', + ['status'], + expect.objectContaining({ cwd: path.join(projectRoot, 'docs') }), + ); }); it('fails closed when the configured OpenSpec root is missing', async () => { diff --git a/test/domains/comet-classic/classic-resume-probe.test.ts b/test/domains/comet-classic/classic-resume-probe.test.ts index a57aa531f..7d70ec265 100644 --- a/test/domains/comet-classic/classic-resume-probe.test.ts +++ b/test/domains/comet-classic/classic-resume-probe.test.ts @@ -126,7 +126,7 @@ describe('resolveCometResumeProbe', () => { }); }); - it('fails closed instead of resuming from either root during a dual-root conflict', async () => { + it('resumes the configured Classic root without scanning the standalone OpenSpec root', async () => { await createChange('legacy-change', buildYaml); await writeFile( path.join(tmpDir, 'docs', 'openspec', 'changes', 'docs-change', 'proposal.md'), @@ -139,7 +139,11 @@ describe('resolveCometResumeProbe', () => { utterance: '继续刚才的任务', agent_context: { non_trivial_work: true, already_in_comet_flow: false }, }), - ).rejects.toThrow('Classic layout conflict'); + ).resolves.toMatchObject({ + action: 'auto_resume', + changeName: 'legacy-change', + phase: 'build', + }); }); it('fails closed when an active change directory is a junction', async () => { diff --git a/test/domains/comet-classic/classic-root-command.test.ts b/test/domains/comet-classic/classic-root-command.test.ts index 8456c2986..06d0fdbca 100644 --- a/test/domains/comet-classic/classic-root-command.test.ts +++ b/test/domains/comet-classic/classic-root-command.test.ts @@ -80,14 +80,47 @@ describe('Classic root show', () => { expect(result.stderr).toContain('Configured Classic OpenSpec root is missing'); }); - it('fails when both roots exist', async () => { + it('reports both roots without blocking read-only root inspection', async () => { await fs.mkdir(path.join(projectRoot, 'openspec'), { recursive: true }); await fs.mkdir(path.join(projectRoot, 'docs', 'openspec'), { recursive: true }); const result = await runClassicCli(['root', 'show']); - expect(result.exitCode).not.toBe(0); - expect(result.stderr).toContain('Classic layout conflict'); + expect(result.exitCode).toBe(0); + expect(JSON.parse(result.stdout ?? '{}')).toMatchObject({ + artifactLayout: 'legacy', + openSpecRoot: 'openspec', + alternateRoot: 'docs/openspec', + configuredRootExists: true, + alternateRootExists: true, + dualRoots: true, + }); + }); + + it('exposes a safe dry-run path when both roots exist', async () => { + await fs.mkdir(path.join(projectRoot, 'openspec', 'changes', 'legacy'), { + recursive: true, + }); + await fs.mkdir(path.join(projectRoot, 'docs', 'openspec', 'changes', 'docs'), { + recursive: true, + }); + + const result = await runClassicCli(['root', 'move', 'docs', '--dry-run']); + + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain('目标初始状态: 非空目录'); + expect(result.stdout).toContain('冲突:'); + expect(result.stdout).toContain('docs 目标目录非空'); + expect(result.stdout).toContain('请先解决上述冲突或阻塞项'); + + const configBefore = await fs.readFile(path.join(projectRoot, '.comet', 'config.yaml'), 'utf8'); + const apply = await runClassicCli(['root', 'move', 'docs', '--apply']); + + expect(apply.exitCode).toBe(70); + expect(apply.stderr).toContain('Classic 根目录迁移失败'); + expect(await fs.readFile(path.join(projectRoot, '.comet', 'config.yaml'), 'utf8')).toBe( + configBefore, + ); }); it('fails when a managed root is a directory link', async () => { diff --git a/test/domains/comet-classic/classic-runtime.test.ts b/test/domains/comet-classic/classic-runtime.test.ts index d56c2ccbf..c409d73b7 100644 --- a/test/domains/comet-classic/classic-runtime.test.ts +++ b/test/domains/comet-classic/classic-runtime.test.ts @@ -176,7 +176,7 @@ describe('Classic runtime CLI adapter', () => { } }); - it('rejects state initialization when both Classic roots exist without changing either root', async () => { + it('initializes state in the configured root while preserving a standalone OpenSpec root', async () => { const directory = await fs.mkdtemp(path.join(os.tmpdir(), 'comet-classic-dual-root-state-')); temporaryDirectories.push(directory); await fs.mkdir(path.join(directory, '.git')); @@ -201,20 +201,19 @@ describe('Classic runtime CLI adapter', () => { const { runClassicCli } = await import('../../../domains/comet-classic/classic-cli.js'); const result = await runClassicCli(['state', 'init', 'demo', 'full']); - expect(result.exitCode).not.toBe(0); - expect(result.stderr).toContain('Classic layout conflict'); + expect(result.exitCode).toBe(0); await expect( - fs.stat(path.join(directory, 'openspec', 'changes', 'demo')), - ).rejects.toMatchObject({ code: 'ENOENT' }); + fs.stat(path.join(directory, 'openspec', 'changes', 'demo', '.comet.yaml')), + ).resolves.toBeDefined(); await expect( - fs.stat(path.join(directory, 'docs', 'openspec', 'changes', 'demo')), - ).rejects.toMatchObject({ code: 'ENOENT' }); + fs.readdir(path.join(directory, 'docs', 'openspec', 'changes')), + ).resolves.toEqual([]); } finally { process.chdir(previous); } }); - it('blocks Hook Guard writes when both Classic roots exist', async () => { + it('allows Hook Guard writes for the configured root when a standalone root exists', async () => { const directory = await fs.mkdtemp(path.join(os.tmpdir(), 'comet-classic-dual-root-hook-')); temporaryDirectories.push(directory); await fs.mkdir(path.join(directory, '.git')); @@ -246,8 +245,7 @@ describe('Classic runtime CLI adapter', () => { toolName: 'Write', }); - expect(result).toMatchObject({ allowed: false, workflow: 'classic', change: 'demo' }); - expect(result.reason).toContain('Classic layout conflict'); + expect(result).toMatchObject({ allowed: true, workflow: 'classic', change: 'demo' }); }); it('creates and reads Classic state from a configured docs layout', async () => { diff --git a/test/domains/comet-classic/comet-scripts-guard.test.ts b/test/domains/comet-classic/comet-scripts-guard.test.ts index 94634ac57..0c35b482c 100644 --- a/test/domains/comet-classic/comet-scripts-guard.test.ts +++ b/test/domains/comet-classic/comet-scripts-guard.test.ts @@ -92,7 +92,7 @@ describe('comet guard', () => { execFileSync('git', ['commit', '-m', 'init'], { cwd: tmpDir, stdio: 'ignore' }); }); - it('fails closed before migrating state when both Classic roots exist', async () => { + it('keeps the configured guard active when a standalone OpenSpec root exists', async () => { await createChange( tmpDir, 'dual-root', @@ -123,11 +123,10 @@ describe('comet guard', () => { const result = runNode(tmpDir, guardScript, ['dual-root', 'open'], {}, 15000); - expect(result.status).not.toBe(0); - expect(result.stderr).toContain('Classic layout conflict'); + expect(result.status).toBe(0); await expect( fs.stat(path.join(tmpDir, 'openspec', 'changes', 'dual-root', '.comet')), - ).rejects.toMatchObject({ code: 'ENOENT' }); + ).resolves.toBeDefined(); }); describe('guard_open skips design.md for hotfix/tweak workflows', () => { diff --git a/test/domains/comet-entry/hook-adapter.test.ts b/test/domains/comet-entry/hook-adapter.test.ts index 0f400977b..a40214a0b 100644 --- a/test/domains/comet-entry/hook-adapter.test.ts +++ b/test/domains/comet-entry/hook-adapter.test.ts @@ -81,6 +81,32 @@ describe('Comet Hook platform adapter', () => { ).toEqual({ intent: 'write', targets: ['src/b.ts'], toolName: 'apply_patch' }); }); + it('normalizes raw Codex apply_patch input from Hook stdin', () => { + const patch = [ + '*** Begin Patch', + '*** Update File: src/existing.ts', + '*** Add File: src/new.ts', + '*** Delete File: src/old.ts', + '*** End Patch', + ].join('\n'); + + expect(parseCometHookRequest(patch)).toEqual({ + intent: 'write', + targets: ['src/existing.ts', 'src/new.ts', 'src/old.ts'], + toolName: 'apply_patch', + }); + }); + + it('normalizes standard unified-diff headers from raw patch input', () => { + const patch = ['--- a/src/old.ts', '+++ b/src/new.ts'].join('\n'); + + expect(parseCometHookRequest(patch)).toEqual({ + intent: 'write', + targets: ['src/new.ts'], + toolName: 'apply_patch', + }); + }); + it('keeps an absolute Hook working directory for linked-worktree routing', () => { const cwd = path.resolve('linked-worktree'); expect( diff --git a/test/domains/comet-entry/hook-router-runtime.test.ts b/test/domains/comet-entry/hook-router-runtime.test.ts index 4ea85b4c1..e3f88dff3 100644 --- a/test/domains/comet-entry/hook-router-runtime.test.ts +++ b/test/domains/comet-entry/hook-router-runtime.test.ts @@ -102,4 +102,26 @@ describe('packaged Hook Router worktree isolation', () => { expect(primaryRequest.status).toBe(2); expect(primaryRequest.stderr).toContain('primary-shape'); }); + + it('enforces Native Shape for raw Codex apply_patch input', async () => { + await configureChange(primary, 'raw-patch-shape', 'shape'); + const patch = [ + '*** Begin Patch', + '*** Update File: src/app.ts', + '@@', + '-old', + '+new', + '*** End Patch', + ].join('\n'); + + const result = spawnSync( + process.execPath, + [router, '--platform', 'codex', '--project-root', primary], + { cwd: primary, input: patch, encoding: 'utf8', timeout: 20_000 }, + ); + + expect(result.status, result.stderr).toBe(2); + expect(result.stderr).toContain('raw-patch-shape'); + expect(result.stderr).toContain('only allowed in build'); + }); }); diff --git a/test/domains/comet-entry/hook-router.test.ts b/test/domains/comet-entry/hook-router.test.ts index 557fc1ca1..785e703c7 100644 --- a/test/domains/comet-entry/hook-router.test.ts +++ b/test/domains/comet-entry/hook-router.test.ts @@ -193,18 +193,14 @@ describe('Comet Hook Router', () => { expect(listClassic).not.toHaveBeenCalled(); }); - it('fails closed when default owner enumeration sees both Classic roots', async () => { + it('ignores the standalone root when default owner enumeration checks Classic', async () => { await configureBoth(); await fs.mkdir(path.join(root, 'openspec', 'changes', 'legacy'), { recursive: true }); await fs.mkdir(path.join(root, 'docs', 'openspec', 'changes', 'docs'), { recursive: true }); const resolution = await resolveHookWorkflowOwner(root); - expect(resolution).toMatchObject({ - status: 'stale', - code: 'change-state-unreadable', - reason: expect.stringContaining('Classic layout conflict'), - }); + expect(resolution).toEqual({ status: 'none' }); }); it('routes one event to only the selected Classic Guard', async () => { diff --git a/test/domains/comet-entry/project-status.test.ts b/test/domains/comet-entry/project-status.test.ts index 65e435c6e..7be4f79a5 100644 --- a/test/domains/comet-entry/project-status.test.ts +++ b/test/domains/comet-entry/project-status.test.ts @@ -285,7 +285,7 @@ describe('Comet project status', () => { expect(status.unmanagedOpenSpec).toEqual([]); }); - it('reports Classic unavailable without scanning either root during a dual-root conflict', async () => { + it('reports only the configured Classic root when a standalone root coexists', async () => { const config = defaultProjectConfig('docs'); config.default_workflow = 'classic'; config.workflows = ['classic']; @@ -298,11 +298,10 @@ describe('Comet project status', () => { const status = await inspectCometProjectStatus(projectRoot); - expect(status.workflows.classic).toEqual({ - changes: [], - error: expect.stringContaining('Classic layout conflict'), - }); - expect(status.unmanagedOpenSpec).toEqual([]); + expect(status.workflows.classic).toEqual({ changes: [] }); + expect(status.unmanagedOpenSpec).toEqual([ + expect.objectContaining({ name: 'configured', cometManaged: false }), + ]); }); it.each(['changes-root', 'change-dir'] as const)( diff --git a/test/domains/factory/factory-package.test.ts b/test/domains/factory/factory-package.test.ts index a343d373b..485de374f 100644 --- a/test/domains/factory/factory-package.test.ts +++ b/test/domains/factory/factory-package.test.ts @@ -963,11 +963,11 @@ describe('Factory skill package generation', () => { } }); - it('rejects generated Classic routing when configured and alternate roots both exist', async () => { + it('uses the configured Classic root when a standalone OpenSpec root also exists', async () => { const workflow = normalizeWorkflowDefinition( builtinCometFivePhaseWorkflow({ name: 'classic-dual-root', - goal: 'Reject ambiguous Classic catalogues.', + goal: 'Keep standalone and Comet OpenSpec catalogues independent.', }), ); const output = await generateFactorySkillPackage( @@ -986,7 +986,7 @@ describe('Factory skill package generation', () => { [path.join(output.packageRoot, 'scripts', 'workflow-state.mjs'), 'next'], { env }, ), - ).rejects.toThrow(/Classic layout conflict/iu); + ).rejects.toThrow(/No active Comet change/iu); } finally { await fs.rm(runRoot, { recursive: true, force: true }); } diff --git a/test/repository/release-metadata.test.ts b/test/repository/release-metadata.test.ts index 1a7c50d89..04abd37f2 100644 --- a/test/repository/release-metadata.test.ts +++ b/test/repository/release-metadata.test.ts @@ -16,7 +16,7 @@ describe('release metadata', () => { readFileSync(path.join(repositoryRoot, 'assets', 'manifest.json'), 'utf8'), ) as { version: string }; - expect(packageJson.version).toBe('0.4.0-beta.15'); + expect(packageJson.version).toBe('0.4.0-beta.16'); expect(packageLock.version).toBe(packageJson.version); expect(packageLock.packages[''].version).toBe(packageJson.version); expect(assetsManifest.version).toBe(packageJson.version);