@rpamis/comet 0.4.0-beta.19 → 0.4.0-beta.20
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -21
- package/README.md +3 -0
- package/assets/manifest.json +1 -1
- package/assets/skills/comet/scripts/comet-hook-router.mjs +10 -10
- package/assets/skills/comet-archive/SKILL.md +0 -1
- package/assets/skills/comet-archive/agents/openai.yaml +1 -1
- package/assets/skills/comet-build/SKILL.md +0 -1
- package/assets/skills/comet-build/agents/openai.yaml +1 -1
- package/assets/skills/comet-design/SKILL.md +0 -1
- package/assets/skills/comet-design/agents/openai.yaml +1 -1
- package/assets/skills/comet-hotfix/SKILL.md +0 -1
- package/assets/skills/comet-hotfix/agents/openai.yaml +1 -1
- package/assets/skills/comet-native/SKILL.md +1 -1
- package/assets/skills/comet-native/scripts/comet-native-archive.mjs +56 -56
- package/assets/skills/comet-native/scripts/comet-native-doctor.mjs +77 -77
- package/assets/skills/comet-native/scripts/comet-native-hook-guard.mjs +11 -11
- package/assets/skills/comet-native/scripts/comet-native-init.mjs +3 -3
- package/assets/skills/comet-native/scripts/comet-native-new.mjs +55 -55
- package/assets/skills/comet-native/scripts/comet-native-next.mjs +54 -54
- package/assets/skills/comet-native/scripts/comet-native-root.mjs +6 -6
- package/assets/skills/comet-native/scripts/comet-native-runtime.mjs +91 -91
- package/assets/skills/comet-native/scripts/comet-native-select.mjs +63 -63
- package/assets/skills/comet-native/scripts/comet-native-show.mjs +45 -45
- package/assets/skills/comet-native/scripts/comet-native-spec.mjs +42 -42
- package/assets/skills/comet-native/scripts/comet-native-status.mjs +67 -67
- package/assets/skills/comet-open/SKILL.md +0 -1
- package/assets/skills/comet-open/agents/openai.yaml +1 -1
- package/assets/skills/comet-tweak/SKILL.md +0 -1
- package/assets/skills/comet-tweak/agents/openai.yaml +1 -1
- package/assets/skills/comet-verify/SKILL.md +0 -1
- package/assets/skills/comet-verify/agents/openai.yaml +1 -1
- package/assets/skills-zh/comet-archive/SKILL.md +0 -1
- package/assets/skills-zh/comet-archive/agents/openai.yaml +1 -1
- package/assets/skills-zh/comet-build/SKILL.md +0 -1
- package/assets/skills-zh/comet-build/agents/openai.yaml +1 -1
- package/assets/skills-zh/comet-design/SKILL.md +0 -1
- package/assets/skills-zh/comet-design/agents/openai.yaml +1 -1
- package/assets/skills-zh/comet-hotfix/SKILL.md +0 -1
- package/assets/skills-zh/comet-hotfix/agents/openai.yaml +1 -1
- package/assets/skills-zh/comet-native/SKILL.md +1 -1
- package/assets/skills-zh/comet-open/SKILL.md +0 -1
- package/assets/skills-zh/comet-open/agents/openai.yaml +1 -1
- package/assets/skills-zh/comet-tweak/SKILL.md +0 -1
- package/assets/skills-zh/comet-tweak/agents/openai.yaml +1 -1
- package/assets/skills-zh/comet-verify/SKILL.md +0 -1
- package/assets/skills-zh/comet-verify/agents/openai.yaml +1 -1
- package/dist/app/commands/doctor.d.ts.map +1 -1
- package/dist/app/commands/doctor.js +43 -24
- package/dist/app/commands/doctor.js.map +1 -1
- package/dist/app/commands/init.d.ts.map +1 -1
- package/dist/app/commands/init.js +32 -18
- package/dist/app/commands/init.js.map +1 -1
- package/dist/domains/comet-native/native-change.d.ts +0 -1
- package/dist/domains/comet-native/native-change.d.ts.map +1 -1
- package/dist/domains/comet-native/native-change.js +2 -2
- package/dist/domains/comet-native/native-change.js.map +1 -1
- package/dist/domains/comet-native/native-cli-help.js +1 -1
- package/dist/domains/comet-native/native-cli-help.js.map +1 -1
- package/dist/domains/comet-native/native-next-command.js +3 -3
- package/dist/domains/comet-native/native-next-command.js.map +1 -1
- package/dist/domains/comet-native/native-portable-continuation.d.ts.map +1 -1
- package/dist/domains/comet-native/native-portable-continuation.js +23 -0
- package/dist/domains/comet-native/native-portable-continuation.js.map +1 -1
- package/dist/domains/comet-native/native-portable-runtime.js +1 -1
- package/dist/domains/comet-native/native-portable-runtime.js.map +1 -1
- package/dist/domains/dashboard/web/index.html +14 -14
- package/dist/domains/integrations/codegraph.d.ts +24 -2
- package/dist/domains/integrations/codegraph.d.ts.map +1 -1
- package/dist/domains/integrations/codegraph.js +307 -1
- package/dist/domains/integrations/codegraph.js.map +1 -1
- package/package.json +1 -1
|
@@ -1,23 +1,23 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __cometCreateRequire } from 'module';
|
|
3
3
|
const require = __cometCreateRequire(import.meta.url);
|
|
4
|
-
var Jd=Object.create;var ms=Object.defineProperty;var Gd=Object.getOwnPropertyDescriptor;var Ud=Object.getOwnPropertyNames;var Kd=Object.getPrototypeOf,Yd=Object.prototype.hasOwnProperty;var
|
|
5
|
-
`)}};
|
|
4
|
+
var Jd=Object.create;var ms=Object.defineProperty;var Gd=Object.getOwnPropertyDescriptor;var Ud=Object.getOwnPropertyNames;var Kd=Object.getPrototypeOf,Yd=Object.prototype.hasOwnProperty;var Di=(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 g=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(i){throw e=0,i}};var Xd=(t,e,i,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Ud(e))!Yd.call(t,n)&&n!==i&&ms(t,n,{get:()=>e[n],enumerable:!(r=Gd(e,n))||r.enumerable});return t};var $t=(t,e,i)=>(i=t!=null?Jd(Kd(t)):{},Xd(e||!t||!t.__esModule?ms(i,"default",{value:t,enumerable:!0}):i,t));var P=g(H=>{"use strict";var Ln=Symbol.for("yaml.alias"),Ns=Symbol.for("yaml.document"),qi=Symbol.for("yaml.map"),bs=Symbol.for("yaml.pair"),Bn=Symbol.for("yaml.scalar"),Wi=Symbol.for("yaml.seq"),Se=Symbol.for("yaml.node.type"),gf=t=>!!t&&typeof t=="object"&&t[Se]===Ln,wf=t=>!!t&&typeof t=="object"&&t[Se]===Ns,yf=t=>!!t&&typeof t=="object"&&t[Se]===qi,Nf=t=>!!t&&typeof t=="object"&&t[Se]===bs,ks=t=>!!t&&typeof t=="object"&&t[Se]===Bn,bf=t=>!!t&&typeof t=="object"&&t[Se]===Wi;function Ss(t){if(t&&typeof t=="object")switch(t[Se]){case qi:case Wi:return!0}return!1}function kf(t){if(t&&typeof t=="object")switch(t[Se]){case Ln:case qi:case Bn:case Wi:return!0}return!1}var Sf=t=>(ks(t)||Ss(t))&&!!t.anchor;H.ALIAS=Ln;H.DOC=Ns;H.MAP=qi;H.NODE_TYPE=Se;H.PAIR=bs;H.SCALAR=Bn;H.SEQ=Wi;H.hasAnchor=Sf;H.isAlias=gf;H.isCollection=Ss;H.isDocument=wf;H.isMap=yf;H.isNode=kf;H.isPair=Nf;H.isScalar=ks;H.isSeq=bf});var Lt=g(Mn=>{"use strict";var O=P(),q=Symbol("break visit"),Es=Symbol("skip children"),fe=Symbol("remove node");function zi(t,e){let i=Ps(e);O.isDocument(t)?ct(null,t.contents,i,Object.freeze([t]))===fe&&(t.contents=null):ct(null,t,i,Object.freeze([]))}zi.BREAK=q;zi.SKIP=Es;zi.REMOVE=fe;function ct(t,e,i,r){let n=xs(t,e,i,r);if(O.isNode(n)||O.isPair(n))return Cs(t,r,n),ct(t,n,i,r);if(typeof n!="symbol"){if(O.isCollection(e)){r=Object.freeze(r.concat(e));for(let a=0;a<e.items.length;++a){let o=ct(a,e.items[a],i,r);if(typeof o=="number")a=o-1;else{if(o===q)return q;o===fe&&(e.items.splice(a,1),a-=1)}}}else if(O.isPair(e)){r=Object.freeze(r.concat(e));let a=ct("key",e.key,i,r);if(a===q)return q;a===fe&&(e.key=null);let o=ct("value",e.value,i,r);if(o===q)return q;o===fe&&(e.value=null)}}return n}async function Ji(t,e){let i=Ps(e);O.isDocument(t)?await lt(null,t.contents,i,Object.freeze([t]))===fe&&(t.contents=null):await lt(null,t,i,Object.freeze([]))}Ji.BREAK=q;Ji.SKIP=Es;Ji.REMOVE=fe;async function lt(t,e,i,r){let n=await xs(t,e,i,r);if(O.isNode(n)||O.isPair(n))return Cs(t,r,n),lt(t,n,i,r);if(typeof n!="symbol"){if(O.isCollection(e)){r=Object.freeze(r.concat(e));for(let a=0;a<e.items.length;++a){let o=await lt(a,e.items[a],i,r);if(typeof o=="number")a=o-1;else{if(o===q)return q;o===fe&&(e.items.splice(a,1),a-=1)}}}else if(O.isPair(e)){r=Object.freeze(r.concat(e));let a=await lt("key",e.key,i,r);if(a===q)return q;a===fe&&(e.key=null);let o=await lt("value",e.value,i,r);if(o===q)return q;o===fe&&(e.value=null)}}return n}function Ps(t){return typeof t=="object"&&(t.Collection||t.Node||t.Value)?Object.assign({Alias:t.Node,Map:t.Node,Scalar:t.Node,Seq:t.Node},t.Value&&{Map:t.Value,Scalar:t.Value,Seq:t.Value},t.Collection&&{Map:t.Collection,Seq:t.Collection},t):t}function xs(t,e,i,r){if(typeof i=="function")return i(t,e,r);if(O.isMap(e))return i.Map?.(t,e,r);if(O.isSeq(e))return i.Seq?.(t,e,r);if(O.isPair(e))return i.Pair?.(t,e,r);if(O.isScalar(e))return i.Scalar?.(t,e,r);if(O.isAlias(e))return i.Alias?.(t,e,r)}function Cs(t,e,i){let r=e[e.length-1];if(O.isCollection(r))r.items[t]=i;else if(O.isPair(r))t==="key"?r.key=i:r.value=i;else if(O.isDocument(r))r.contents=i;else{let n=O.isAlias(r)?"alias":"scalar";throw new Error(`Cannot replace node with ${n} parent`)}}Mn.visit=zi;Mn.visitAsync=Ji});var Fn=g(As=>{"use strict";var Rs=P(),Ef=Lt(),Pf={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},xf=t=>t.replace(/[!,[\]{}]/g,e=>Pf[e]),Bt=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[a,o]=r;return this.tags[a]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,r.length!==1)return i(0,"%YAML directive should contain exactly one part"),!1;let[a]=r;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 ${n}`,!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[,r,n]=e.match(/^(.*!)([^!]*)$/s);n||i(`The ${e} tag has no suffix`);let a=this.tags[r];if(a)try{return a+decodeURIComponent(n)}catch(o){return i(String(o)),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+xf(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&&Rs.isNode(e.contents)){let a={};Ef.visit(e.contents,(o,s)=>{Rs.isNode(s)&&s.tag&&(a[s.tag]=!0)}),n=Object.keys(a)}else n=[];for(let[a,o]of r)a==="!!"&&o==="tag:yaml.org,2002:"||(!e||n.some(s=>s.startsWith(o)))&&i.push(`%TAG ${a} ${o}`);return i.join(`
|
|
5
|
+
`)}};Bt.defaultYaml={explicit:!1,version:"1.2"};Bt.defaultTags={"!!":"tag:yaml.org,2002:"};As.Directives=Bt});var Gi=g(Mt=>{"use strict";var _s=P(),Cf=Lt();function Rf(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 Ts(t){let e=new Set;return Cf.visit(t,{Value(i,r){r.anchor&&e.add(r.anchor)}}),e}function Is(t,e){for(let i=1;;++i){let r=`${t}${i}`;if(!e.has(r))return r}}function Af(t,e){let i=[],r=new Map,n=null;return{onAnchor:a=>{i.push(a),n??(n=Ts(t));let o=Is(e,n);return n.add(o),o},setAnchors:()=>{for(let a of i){let o=r.get(a);if(typeof o=="object"&&o.anchor&&(_s.isScalar(o.node)||_s.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:r}}Mt.anchorIsValid=Rf;Mt.anchorNames=Ts;Mt.createNodeAnchors=Af;Mt.findNewAnchor=Is});var Vn=g(js=>{"use strict";function Ft(t,e,i,r){if(r&&typeof r=="object")if(Array.isArray(r))for(let n=0,a=r.length;n<a;++n){let o=r[n],s=Ft(t,r,String(n),o);s===void 0?delete r[n]:s!==o&&(r[n]=s)}else if(r instanceof Map)for(let n of Array.from(r.keys())){let a=r.get(n),o=Ft(t,r,n,a);o===void 0?r.delete(n):o!==a&&r.set(n,o)}else if(r instanceof Set)for(let n of Array.from(r)){let a=Ft(t,r,n,n);a===void 0?r.delete(n):a!==n&&(r.delete(n),r.add(a))}else for(let[n,a]of Object.entries(r)){let o=Ft(t,r,n,a);o===void 0?delete r[n]:o!==a&&(r[n]=o)}return t.call(e,i,r)}js.applyReviver=Ft});var Ie=g(Os=>{"use strict";var _f=P();function $s(t,e,i){if(Array.isArray(t))return t.map((r,n)=>$s(r,String(n),i));if(t&&typeof t.toJSON=="function"){if(!i||!_f.hasAnchor(t))return t.toJSON(e,i);let r={aliasCount:0,count:1,res:void 0};i.anchors.set(t,r),i.onCreate=a=>{r.res=a,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}Os.toJS=$s});var Ui=g(Ds=>{"use strict";var Tf=Vn(),Hs=P(),If=Ie(),qn=class{constructor(e){Object.defineProperty(this,Hs.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:a}={}){if(!Hs.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 r=="number"?r:100},s=If.toJS(this,"",o);if(typeof n=="function")for(let{count:c,res:l}of o.anchors.values())n(l,c);return typeof a=="function"?Tf.applyReviver(a,{"":s},"",s):s}};Ds.NodeBase=qn});var Vt=g(Ls=>{"use strict";var jf=Gi(),$f=Lt(),ut=P(),Of=Ui(),Hf=Ie(),Wn=class extends Of.NodeBase{constructor(e){super(ut.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=[],$f.visit(e,{Node:(a,o)=>{(ut.isAlias(o)||ut.hasAnchor(o))&&r.push(o)}}),i&&(i.aliasResolveCache=r));let n;for(let a of r){if(a===this)break;a.anchor===this.source&&(n=a)}return n}toJSON(e,i){if(!i)return{source:this.source};let{anchors:r,doc:n,maxAliasCount:a}=i,o=this.resolve(n,i);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let s=r.get(o);if(s||(Hf.toJS(o,null,i),s=r.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=Ki(n,o,r)),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,r){let n=`*${this.source}`;if(e){if(jf.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`${n} `}return n}};function Ki(t,e,i){if(ut.isAlias(e)){let r=e.resolve(t),n=i&&r&&i.get(r);return n?n.count*n.aliasCount:0}else if(ut.isCollection(e)){let r=0;for(let n of e.items){let a=Ki(t,n,i);a>r&&(r=a)}return r}else if(ut.isPair(e)){let r=Ki(t,e.key,i),n=Ki(t,e.value,i);return Math.max(r,n)}return 1}Ls.Alias=Wn});var I=g(zn=>{"use strict";var Df=P(),Lf=Ui(),Bf=Ie(),Mf=t=>!t||typeof t!="function"&&typeof t!="object",je=class extends Lf.NodeBase{constructor(e){super(Df.SCALAR),this.value=e}toJSON(e,i){return i?.keep?this.value:Bf.toJS(this.value,e,i)}toString(){return String(this.value)}};je.BLOCK_FOLDED="BLOCK_FOLDED";je.BLOCK_LITERAL="BLOCK_LITERAL";je.PLAIN="PLAIN";je.QUOTE_DOUBLE="QUOTE_DOUBLE";je.QUOTE_SINGLE="QUOTE_SINGLE";zn.Scalar=je;zn.isScalarValue=Mf});var qt=g(Ms=>{"use strict";var Ff=Vt(),Ge=P(),Bs=I(),Vf="tag:yaml.org,2002:";function qf(t,e,i){if(e){let r=i.filter(a=>a.tag===e),n=r.find(a=>!a.format)??r[0];if(!n)throw new Error(`Tag ${e} not found`);return n}return i.find(r=>r.identify?.(t)&&!r.format)}function Wf(t,e,i){if(Ge.isDocument(t)&&(t=t.contents),Ge.isNode(t))return t;if(Ge.isPair(t)){let d=i.schema[Ge.MAP].createNode?.(i.schema,null,i);return d.items.push(t),d}(t instanceof String||t instanceof Number||t instanceof Boolean||typeof BigInt<"u"&&t instanceof BigInt)&&(t=t.valueOf());let{aliasDuplicateObjects:r,onAnchor:n,onTagObj:a,schema:o,sourceObjects:s}=i,c;if(r&&t&&typeof t=="object"){if(c=s.get(t),c)return c.anchor??(c.anchor=n(t)),new Ff.Alias(c.anchor);c={anchor:null,node:null},s.set(t,c)}e?.startsWith("!!")&&(e=Vf+e.slice(2));let l=qf(t,e,o.tags);if(!l){if(t&&typeof t.toJSON=="function"&&(t=t.toJSON()),!t||typeof t!="object"){let d=new Bs.Scalar(t);return c&&(c.node=d),d}l=t instanceof Map?o[Ge.MAP]:Symbol.iterator in Object(t)?o[Ge.SEQ]:o[Ge.MAP]}a&&(a(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 Bs.Scalar(t);return e?f.tag=e:l.default||(f.tag=l.tag),c&&(c.node=f),f}Ms.createNode=Wf});var Xi=g(Yi=>{"use strict";var zf=qt(),he=P(),Jf=Ui();function Jn(t,e,i){let r=i;for(let n=e.length-1;n>=0;--n){let a=e[n];if(typeof a=="number"&&Number.isInteger(a)&&a>=0){let o=[];o[a]=r,r=o}else r=new Map([[a,r]])}return zf.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 Fs=t=>t==null||typeof t=="object"&&!!t[Symbol.iterator]().next().done,Gn=class extends Jf.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=>he.isNode(r)||he.isPair(r)?r.clone(e):r),this.range&&(i.range=this.range.slice()),i}addIn(e,i){if(Fs(e))this.add(i);else{let[r,...n]=e,a=this.get(r,!0);if(he.isCollection(a))a.addIn(n,i);else if(a===void 0&&this.schema)this.set(r,Jn(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(he.isCollection(n))return n.deleteIn(r);throw new Error(`Expected YAML collection at ${i}. Remaining path: ${r}`)}getIn(e,i){let[r,...n]=e,a=this.get(r,!0);return n.length===0?!i&&he.isScalar(a)?a.value:a:he.isCollection(a)?a.getIn(n,i):void 0}hasAllNullValues(e){return this.items.every(i=>{if(!he.isPair(i))return!1;let r=i.value;return r==null||e&&he.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 he.isCollection(n)?n.hasIn(r):!1}setIn(e,i){let[r,...n]=e;if(n.length===0)this.set(r,i);else{let a=this.get(r,!0);if(he.isCollection(a))a.setIn(n,i);else if(a===void 0&&this.schema)this.set(r,Jn(this.schema,n,i));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}}};Yi.Collection=Gn;Yi.collectionFromPath=Jn;Yi.isEmptyPath=Fs});var Wt=g(Qi=>{"use strict";var Gf=t=>t.replace(/^(?!$)(?: $)?/gm,"#");function Un(t,e){return/^\n+$/.test(t)?t.substring(1):e?t.replace(/^(?! *$)/gm,e):t}var Uf=(t,e,i)=>t.endsWith(`
|
|
6
6
|
`)?Un(i,e):i.includes(`
|
|
7
7
|
`)?`
|
|
8
|
-
`+Un(i,e):(t.endsWith(" ")?"":" ")+i;Qi.indentComment=Un;Qi.lineComment=Uf;Qi.stringifyComment=Gf});var qs=g(
|
|
8
|
+
`+Un(i,e):(t.endsWith(" ")?"":" ")+i;Qi.indentComment=Un;Qi.lineComment=Uf;Qi.stringifyComment=Gf});var qs=g(zt=>{"use strict";var Kf="flow",Kn="block",Zi="quoted";function Yf(t,e,i="flow",{indentAtStart:r,lineWidth:n=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!n||n<0)return t;n<a&&(a=0);let c=Math.max(1+a,1+n-e.length);if(t.length<=c)return t;let l=[],f={},d=n-e.length;typeof r=="number"&&(r>n-Math.max(2,a)?l.push(0):d=n-r);let u,p,v=!1,h=-1,m=-1,w=-1;i===Kn&&(h=Vs(t,h,e.length),h!==-1&&(d=h+c));for(let b;b=t[h+=1];){if(i===Zi&&b==="\\"){switch(m=h,t[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}w=h}if(b===`
|
|
9
9
|
`)i===Kn&&(h=Vs(t,h,e.length)),d=h+e.length+c,u=void 0;else{if(b===" "&&p&&p!==" "&&p!==`
|
|
10
10
|
`&&p!==" "){let k=t[h+1];k&&k!==" "&&k!==`
|
|
11
11
|
`&&k!==" "&&(u=h)}if(h>=d)if(u)l.push(u),d=u+c,u=void 0;else if(i===Zi){for(;p===" "||p===" ";)p=b,b=t[h+=1],v=!0;let k=h>w+1?h-2:m-1;if(f[k])return t;l.push(k),f[k]=!0,d=k+c,u=void 0}else v=!0}p=b}if(v&&s&&s(),l.length===0)return t;o&&o();let y=t.slice(0,l[0]);for(let b=0;b<l.length;++b){let k=l[b],S=l[b+1]||t.length;k===0?y=`
|
|
12
12
|
${e}${t.slice(0,S)}`:(i===Zi&&f[k]&&(y+=`${t[k]}\\`),y+=`
|
|
13
13
|
${e}${t.slice(k+1,S)}`)}return y}function Vs(t,e,i){let r=e,n=e+1,a=t[n];for(;a===" "||a===" ";)if(e<n+i)a=t[++e];else{do a=t[++e];while(a&&a!==`
|
|
14
|
-
`);r=e,n=e+1,a=t[n]}return r}
|
|
15
|
-
`){if(a-o>r)return!0;if(o=a+1,n-o<=r)return!1}return!0}function
|
|
14
|
+
`);r=e,n=e+1,a=t[n]}return r}zt.FOLD_BLOCK=Kn;zt.FOLD_FLOW=Kf;zt.FOLD_QUOTED=Zi;zt.foldFlowLines=Yf});var Gt=g(Ws=>{"use strict";var re=I(),$e=qs(),tr=(t,e)=>({indentAtStart:e?t.indent.length:t.indentAtStart,lineWidth:t.options.lineWidth,minContentWidth:t.options.minContentWidth}),ir=t=>/^(%|---|\.\.\.)/m.test(t);function Xf(t,e,i){if(!e||e<0)return!1;let r=e-i,n=t.length;if(n<=r)return!1;for(let a=0,o=0;a<n;++a)if(t[a]===`
|
|
15
|
+
`){if(a-o>r)return!0;if(o=a+1,n-o<=r)return!1}return!0}function Jt(t,e){let i=JSON.stringify(t);if(e.options.doubleQuotedAsJSON)return i;let{implicitKey:r}=e,n=e.options.doubleQuotedMinMultiLineLength,a=e.indent||(ir(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 f=i.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+=i.substr(c,6)}c+=5,s=c+1}break;case"n":if(r||i[c+2]==='"'||i.length<n)c+=1;else{for(o+=i.slice(s,c)+`
|
|
16
16
|
|
|
17
17
|
`;i[c+2]==="\\"&&i[c+3]==="n"&&i[c+4]!=='"';)o+=`
|
|
18
18
|
`,c+=2;o+=a,i[c+2]===" "&&(o+="\\"),c+=1,s=c+1}break;default:c+=1}return o=s?o+i.slice(s):i,r?o:$e.foldFlowLines(o,a,$e.FOLD_QUOTED,tr(e,!1))}function Yn(t,e){if(e.options.singleQuote===!1||e.implicitKey&&t.includes(`
|
|
19
|
-
`)||/[ \t]\n|\n[ \t]/.test(t))return
|
|
20
|
-
${i}`)+"'";return e.implicitKey?r:$e.foldFlowLines(r,i,$e.FOLD_FLOW,tr(e,!1))}function dt(t,e){let{singleQuote:i}=e.options,r;if(i===!1)r=
|
|
19
|
+
`)||/[ \t]\n|\n[ \t]/.test(t))return Jt(t,e);let i=e.indent||(ir(t)?" ":""),r="'"+t.replace(/'/g,"''").replace(/\n+/g,`$&
|
|
20
|
+
${i}`)+"'";return e.implicitKey?r:$e.foldFlowLines(r,i,$e.FOLD_FLOW,tr(e,!1))}function dt(t,e){let{singleQuote:i}=e.options,r;if(i===!1)r=Jt;else{let n=t.includes('"'),a=t.includes("'");n&&!a?r=Yn:a&&!n?r=Jt:r=i?Yn:Jt}return r(t,e)}var Xn;try{Xn=new RegExp(`(^|(?<!
|
|
21
21
|
))
|
|
22
22
|
+(?!
|
|
23
23
|
|$)`,"g")}catch{Xn=/\n+(?!\n|$)/g}function er({comment:t,type:e,value:i},r,n,a){let{blockQuote:o,commentString:s,lineWidth:c}=r.options;if(!o||/\n[\t ]+$/.test(i))return dt(i,r);let l=r.indent||(r.forceBlockIndent||ir(i)?" ":""),f=o==="literal"?!0:o==="folded"||e===re.Scalar.BLOCK_FOLDED?!1:e===re.Scalar.BLOCK_LITERAL?!0:!Xf(i,c,l.length);if(!i)return f?`|
|
|
@@ -33,39 +33,39 @@ ${l}${y}${i}${p}`}function Qf(t,e,i,r){let{type:n,value:a}=t,{actualString:o,imp
|
|
|
33
33
|
`)||f&&/[[\]{},]/.test(a))return dt(a,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||f||!a.includes(`
|
|
34
34
|
`)?dt(a,e):er(t,e,i,r);if(!s&&!f&&n!==re.Scalar.PLAIN&&a.includes(`
|
|
35
35
|
`))return er(t,e,i,r);if(ir(a)){if(c==="")return e.forceBlockIndent=!0,er(t,e,i,r);if(s&&c===l)return dt(a,e)}let d=a.replace(/\n+/g,`$&
|
|
36
|
-
${c}`);if(o){let u=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(d),{compat:p,tags:v}=e.doc.schema;if(v.some(u)||p?.some(u))return dt(a,e)}return s?d:$e.foldFlowLines(d,c,$e.FOLD_FLOW,tr(e,!1))}function Zf(t,e,i,r){let{implicitKey:n,inFlow:a}=e,o=typeof t.value=="string"?t:Object.assign({},t,{value:String(t.value)}),{type:s}=t;s!==re.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=re.Scalar.QUOTE_DOUBLE);let c=f=>{switch(f){case re.Scalar.BLOCK_FOLDED:case re.Scalar.BLOCK_LITERAL:return n||a?dt(o.value,e):er(o,e,i,r);case re.Scalar.QUOTE_DOUBLE:return
|
|
37
|
-
${e.indent}${s}`:s}Qn.createStringifyContext=rh;Qn.stringify=oh});var Us=g(Gs=>{"use strict";var Ee=P(),zs=I(),Js=
|
|
38
|
-
${s}:`):(m=`${m}:`,u&&(m+=
|
|
36
|
+
${c}`);if(o){let u=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(d),{compat:p,tags:v}=e.doc.schema;if(v.some(u)||p?.some(u))return dt(a,e)}return s?d:$e.foldFlowLines(d,c,$e.FOLD_FLOW,tr(e,!1))}function Zf(t,e,i,r){let{implicitKey:n,inFlow:a}=e,o=typeof t.value=="string"?t:Object.assign({},t,{value:String(t.value)}),{type:s}=t;s!==re.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=re.Scalar.QUOTE_DOUBLE);let c=f=>{switch(f){case re.Scalar.BLOCK_FOLDED:case re.Scalar.BLOCK_LITERAL:return n||a?dt(o.value,e):er(o,e,i,r);case re.Scalar.QUOTE_DOUBLE:return Jt(o.value,e);case re.Scalar.QUOTE_SINGLE:return Yn(o.value,e);case re.Scalar.PLAIN:return Qf(o,e,i,r);default:return null}},l=c(s);if(l===null){let{defaultKeyType:f,defaultStringType:d}=e.options,u=n&&f||d;if(l=c(u),l===null)throw new Error(`Unsupported default string type ${u}`)}return l}Ws.stringifyString=Zf});var Ut=g(Qn=>{"use strict";var eh=Gi(),Oe=P(),th=Wt(),ih=Gt();function rh(t,e){let i=Object.assign({blockQuote:!0,commentString:th.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 nh(t,e){if(e.tag){let n=t.filter(a=>a.tag===e.tag);if(n.length>0)return n.find(a=>a.format===e.format)??n[0]}let i,r;if(Oe.isScalar(e)){r=e.value;let n=t.filter(a=>a.identify?.(r));if(n.length>1){let a=n.filter(o=>o.test);a.length>0&&(n=a)}i=n.find(a=>a.format===e.format)??n.find(a=>!a.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 ah(t,e,{anchors:i,doc:r}){if(!r.directives)return"";let n=[],a=(Oe.isScalar(t)||Oe.isCollection(t))&&t.anchor;a&&eh.anchorIsValid(a)&&(i.add(a),n.push(`&${a}`));let o=t.tag??(e.default?null:e.tag);return o&&n.push(r.directives.tagString(o)),n.join(" ")}function oh(t,e,i,r){if(Oe.isPair(t))return t.toString(e,i,r);if(Oe.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,a=Oe.isNode(t)?t:e.doc.createNode(t,{onTagObj:c=>n=c});n??(n=nh(e.doc.schema.tags,a));let o=ah(a,n,e);o.length>0&&(e.indentAtStart=(e.indentAtStart??0)+o.length+1);let s=typeof n.stringify=="function"?n.stringify(a,e,i,r):Oe.isScalar(a)?ih.stringifyString(a,e,i,r):a.toString(e,i,r);return o?Oe.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
|
|
37
|
+
${e.indent}${s}`:s}Qn.createStringifyContext=rh;Qn.stringify=oh});var Us=g(Gs=>{"use strict";var Ee=P(),zs=I(),Js=Ut(),Kt=Wt();function sh({key:t,value:e},i,r,n){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:f,simpleKeys:d}}=i,u=Ee.isNode(t)&&t.comment||null;if(d){if(u)throw new Error("With simple keys, key nodes cannot have comments");if(Ee.isCollection(t)||!Ee.isNode(t)&&typeof t=="object"){let R="With simple keys, collection cannot be used as a key value";throw new Error(R)}}let p=!d&&(!t||u&&e==null&&!i.inFlow||Ee.isCollection(t)||(Ee.isScalar(t)?t.type===zs.Scalar.BLOCK_FOLDED||t.type===zs.Scalar.BLOCK_LITERAL:typeof t=="object"));i=Object.assign({},i,{allNullValues:!1,implicitKey:!p&&(d||!a),indent:s+c});let v=!1,h=!1,m=Js.stringify(t,i,()=>v=!0,()=>h=!0);if(!p&&!i.inFlow&&m.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");p=!0}if(i.inFlow){if(a||e==null)return v&&r&&r(),m===""?"?":p?`? ${m}`:m}else if(a&&!d||e==null&&p)return m=`? ${m}`,u&&!v?m+=Kt.lineComment(m,i.indent,l(u)):h&&n&&n(),m;v&&(u=null),p?(u&&(m+=Kt.lineComment(m,i.indent,l(u))),m=`? ${m}
|
|
38
|
+
${s}:`):(m=`${m}:`,u&&(m+=Kt.lineComment(m,i.indent,l(u))));let w,y,b;Ee.isNode(e)?(w=!!e.spaceBefore,y=e.commentBefore,b=e.comment):(w=!1,y=null,b=null,e&&typeof e=="object"&&(e=o.createNode(e))),i.implicitKey=!1,!p&&!u&&Ee.isScalar(e)&&(i.indentAtStart=m.length+1),h=!1,!f&&c.length>=2&&!i.inFlow&&!p&&Ee.isSeq(e)&&!e.flow&&!e.tag&&!e.anchor&&(i.indent=i.indent.substring(2));let k=!1,S=Js.stringify(e,i,()=>k=!0,()=>h=!0),E=" ";if(u||w||y){if(E=w?`
|
|
39
39
|
`:"",y){let R=l(y);E+=`
|
|
40
|
-
${
|
|
40
|
+
${Kt.indentComment(R,i.indent)}`}S===""&&!i.inFlow?E===`
|
|
41
41
|
`&&b&&(E=`
|
|
42
42
|
|
|
43
43
|
`):E+=`
|
|
44
44
|
${i.indent}`}else if(!p&&Ee.isCollection(e)){let R=S[0],N=S.indexOf(`
|
|
45
45
|
`),j=N!==-1,_e=i.inFlow??e.flow??e.items.length===0;if(j||!_e){let st=!1;if(j&&(R==="&"||R==="!")){let $=S.indexOf(" ");R==="&"&&$!==-1&&$<N&&S[$+1]==="!"&&($=S.indexOf(" ",$+1)),($===-1||N<$)&&(st=!0)}st||(E=`
|
|
46
46
|
${i.indent}`)}}else(S===""||S[0]===`
|
|
47
|
-
`)&&(E="");return m+=E+S,i.inFlow?k&&r&&r():b&&!k?m+=
|
|
47
|
+
`)&&(E="");return m+=E+S,i.inFlow?k&&r&&r():b&&!k?m+=Kt.lineComment(m,i.indent,l(b)):h&&n&&n(),m}Gs.stringifyPair=sh});var ea=g(Zn=>{"use strict";var Ks=Di("process");function ch(t,...e){t==="debug"&&console.log(...e)}function lh(t,e){(t==="debug"||t==="warn")&&(typeof Ks.emitWarning=="function"?Ks.emitWarning(e):console.warn(e))}Zn.debug=ch;Zn.warn=lh});var sr=g(or=>{"use strict";var ar=P(),Ys=I(),rr="<<",nr={identify:t=>t===rr||typeof t=="symbol"&&t.description===rr,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new Ys.Scalar(Symbol(rr)),{addToJSMap:Xs}),stringify:()=>rr},uh=(t,e)=>(nr.identify(e)||ar.isScalar(e)&&(!e.type||e.type===Ys.Scalar.PLAIN)&&nr.identify(e.value))&&t?.doc.schema.tags.some(i=>i.tag===nr.tag&&i.default);function Xs(t,e,i){let r=Qs(t,i);if(ar.isSeq(r))for(let n of r.items)ta(t,e,n);else if(Array.isArray(r))for(let n of r)ta(t,e,n);else ta(t,e,r)}function ta(t,e,i){let r=Qs(t,i);if(!ar.isMap(r))throw new Error("Merge sources must be maps or map aliases");let n=r.toJSON(null,t,Map);for(let[a,o]of n)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 Qs(t,e){return t&&ar.isAlias(e)?e.resolve(t.doc,t):e}or.addMergeToJSMap=Xs;or.isMergeKey=uh;or.merge=nr});var ra=g(tc=>{"use strict";var dh=ea(),Zs=sr(),fh=Ut(),ec=P(),ia=Ie();function hh(t,e,{key:i,value:r}){if(ec.isNode(i)&&i.addToJSMap)i.addToJSMap(t,e,r);else if(Zs.isMergeKey(t,i))Zs.addMergeToJSMap(t,e,r);else{let n=ia.toJS(i,"",t);if(e instanceof Map)e.set(n,ia.toJS(r,n,t));else if(e instanceof Set)e.add(n);else{let a=ph(i,n,t),o=ia.toJS(r,a,t);a in e?Object.defineProperty(e,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):e[a]=o}}return e}function ph(t,e,i){if(e===null)return"";if(typeof e!="object")return String(e);if(ec.isNode(t)&&i?.doc){let r=fh.createStringifyContext(i.doc,{});r.anchors=new Set;for(let a of i.anchors.keys())r.anchors.add(a.anchor);r.inFlow=!0,r.inStringifyKey=!0;let n=t.toString(r);if(!i.mapKeyWarned){let a=JSON.stringify(n);a.length>40&&(a=a.substring(0,36)+'..."'),dh.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 n}return JSON.stringify(e)}tc.addPairToJSMap=hh});var He=g(na=>{"use strict";var ic=qt(),mh=Us(),vh=ra(),cr=P();function gh(t,e,i){let r=ic.createNode(t,void 0,i),n=ic.createNode(e,void 0,i);return new lr(r,n)}var lr=class t{constructor(e,i=null){Object.defineProperty(this,cr.NODE_TYPE,{value:cr.PAIR}),this.key=e,this.value=i}clone(e){let{key:i,value:r}=this;return cr.isNode(i)&&(i=i.clone(e)),cr.isNode(r)&&(r=r.clone(e)),new t(i,r)}toJSON(e,i){let r=i?.mapAsMap?new Map:{};return vh.addPairToJSMap(i,r,this)}toString(e,i,r){return e?.doc?mh.stringifyPair(this,e,i,r):JSON.stringify(this)}};na.Pair=lr;na.createPair=gh});var aa=g(nc=>{"use strict";var Ue=P(),rc=Ut(),ur=Wt();function wh(t,e,i){return(e.inFlow??t.flow?Nh:yh)(t,e,i)}function yh({comment:t,items:e},i,{blockItemPrefix:r,flowChars:n,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=i,f=Object.assign({},i,{indent:a,type:null}),d=!1,u=[];for(let v=0;v<e.length;++v){let h=e[v],m=null;if(Ue.isNode(h))!d&&h.spaceBefore&&u.push(""),dr(i,u,h.commentBefore,d),h.comment&&(m=h.comment);else if(Ue.isPair(h)){let y=Ue.isNode(h.key)?h.key:null;y&&(!d&&y.spaceBefore&&u.push(""),dr(i,u,y.commentBefore,d))}d=!1;let w=rc.stringify(h,f,()=>m=null,()=>d=!0);m&&(w+=ur.lineComment(w,a,l(m))),d&&m&&(d=!1),u.push(r+w)}let p;if(u.length===0)p=n.start+n.end;else{p=u[0];for(let v=1;v<u.length;++v){let h=u[v];p+=h?`
|
|
48
48
|
${c}${h}`:`
|
|
49
49
|
`}}return t?(p+=`
|
|
50
50
|
`+ur.indentComment(l(t),c),s&&s()):d&&o&&o(),p}function Nh({items:t},e,{flowChars:i,itemIndent:r}){let{indent:n,indentStep:a,flowCollectionPadding:o,options:{commentString:s}}=e;r+=a;let c=Object.assign({},e,{indent:r,inFlow:!0,type:null}),l=!1,f=0,d=[];for(let v=0;v<t.length;++v){let h=t[v],m=null;if(Ue.isNode(h))h.spaceBefore&&d.push(""),dr(e,d,h.commentBefore,!1),h.comment&&(m=h.comment);else if(Ue.isPair(h)){let y=Ue.isNode(h.key)?h.key:null;y&&(y.spaceBefore&&d.push(""),dr(e,d,y.commentBefore,!1),y.comment&&(l=!0));let b=Ue.isNode(h.value)?h.value:null;b?(b.comment&&(m=b.comment),b.commentBefore&&(l=!0)):h.value==null&&y?.comment&&(m=y.comment)}m&&(l=!0);let w=rc.stringify(h,c,()=>m=null);l||(l=d.length>f||w.includes(`
|
|
51
51
|
`)),v<t.length-1?w+=",":e.options.trailingComma&&(e.options.lineWidth>0&&(l||(l=d.reduce((y,b)=>y+b.length+2,2)+(w.length+2)>e.options.lineWidth)),l&&(w+=",")),m&&(w+=ur.lineComment(w,r,s(m))),d.push(w),f=d.length}let{start:u,end:p}=i;if(d.length===0)return u+p;if(!l){let v=d.reduce((h,m)=>h+m.length+2,2);l=e.options.lineWidth>0&&v>e.options.lineWidth}if(l){let v=u;for(let h of d)v+=h?`
|
|
52
52
|
${a}${n}${h}`:`
|
|
53
53
|
`;return`${v}
|
|
54
|
-
${n}${p}`}else return`${u}${o}${d.join(" ")}${o}${p}`}function dr({indent:t,options:{commentString:e}},i,r,n){if(r&&n&&(r=r.replace(/^\n+/,"")),r){let a=ur.indentComment(e(r),t);i.push(a.trimStart())}}nc.stringifyCollection=wh});var Le=g(sa=>{"use strict";var bh=aa(),kh=ra(),Sh=Xi(),De=P(),fr=He(),Eh=I();function
|
|
54
|
+
${n}${p}`}else return`${u}${o}${d.join(" ")}${o}${p}`}function dr({indent:t,options:{commentString:e}},i,r,n){if(r&&n&&(r=r.replace(/^\n+/,"")),r){let a=ur.indentComment(e(r),t);i.push(a.trimStart())}}nc.stringifyCollection=wh});var Le=g(sa=>{"use strict";var bh=aa(),kh=ra(),Sh=Xi(),De=P(),fr=He(),Eh=I();function Yt(t,e){let i=De.isScalar(e)?e.value:e;for(let r of t)if(De.isPair(r)&&(r.key===e||r.key===i||De.isScalar(r.key)&&r.key.value===i))return r}var oa=class extends Sh.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(De.MAP,e),this.items=[]}static from(e,i,r){let{keepUndefined:n,replacer:a}=r,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||n)&&o.items.push(fr.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"&&o.items.sort(e.sortMapEntries),o}add(e,i){let r;De.isPair(e)?r=e:!e||typeof e!="object"||!("key"in e)?r=new fr.Pair(e,e?.value):r=new fr.Pair(e.key,e.value);let n=Yt(this.items,r.key),a=this.schema?.sortMapEntries;if(n){if(!i)throw new Error(`Key ${r.key} already set`);De.isScalar(n.value)&&Eh.isScalarValue(r.value)?n.value.value=r.value:n.value=r.value}else if(a){let o=this.items.findIndex(s=>a(r,s)<0);o===-1?this.items.push(r):this.items.splice(o,0,r)}else this.items.push(r)}delete(e){let i=Yt(this.items,e);return i?this.items.splice(this.items.indexOf(i),1).length>0:!1}get(e,i){let n=Yt(this.items,e)?.value;return(!i&&De.isScalar(n)?n.value:n)??void 0}has(e){return!!Yt(this.items,e)}set(e,i){this.add(new fr.Pair(e,i),!0)}toJSON(e,i,r){let n=r?new r:i?.mapAsMap?new Map:{};i?.onCreate&&i.onCreate(n);for(let a of this.items)kh.addPairToJSMap(i,n,a);return n}toString(e,i,r){if(!e)return JSON.stringify(this);for(let n of this.items)if(!De.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})),bh.stringifyCollection(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:r,onComment:i})}};sa.YAMLMap=oa;sa.findPair=Yt});var ft=g(oc=>{"use strict";var Ph=P(),ac=Le(),xh={collection:"map",default:!0,nodeClass:ac.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(t,e){return Ph.isMap(t)||e("Expected a mapping for this tag"),t},createNode:(t,e,i)=>ac.YAMLMap.from(t,e,i)};oc.map=xh});var Be=g(sc=>{"use strict";var Ch=qt(),Rh=aa(),Ah=Xi(),pr=P(),_h=I(),Th=Ie(),ca=class extends Ah.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(pr.SEQ,e),this.items=[]}add(e){this.items.push(e)}delete(e){let i=hr(e);return typeof i!="number"?!1:this.items.splice(i,1).length>0}get(e,i){let r=hr(e);if(typeof r!="number")return;let n=this.items[r];return!i&&pr.isScalar(n)?n.value:n}has(e){let i=hr(e);return typeof i=="number"&&i<this.items.length}set(e,i){let r=hr(e);if(typeof r!="number")throw new Error(`Expected a valid index, not ${e}.`);let n=this.items[r];pr.isScalar(n)&&_h.isScalarValue(i)?n.value=i:this.items[r]=i}toJSON(e,i){let r=[];i?.onCreate&&i.onCreate(r);let n=0;for(let a of this.items)r.push(Th.toJS(a,String(n++),i));return r}toString(e,i,r){return e?Rh.stringifyCollection(this,e,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(e.indent||"")+" ",onChompKeep:r,onComment:i}):JSON.stringify(this)}static from(e,i,r){let{replacer:n}=r,a=new this(e);if(i&&Symbol.iterator in Object(i)){let o=0;for(let s of i){if(typeof n=="function"){let c=i instanceof Set?s:String(o++);s=n.call(i,c,s)}a.items.push(Ch.createNode(s,void 0,r))}}return a}};function hr(t){let e=pr.isScalar(t)?t.value:t;return e&&typeof e=="string"&&(e=Number(e)),typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}sc.YAMLSeq=ca});var ht=g(lc=>{"use strict";var Ih=P(),cc=Be(),jh={collection:"seq",default:!0,nodeClass:cc.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(t,e){return Ih.isSeq(t)||e("Expected a sequence for this tag"),t},createNode:(t,e,i)=>cc.YAMLSeq.from(t,e,i)};lc.seq=jh});var Xt=g(uc=>{"use strict";var $h=Gt(),Oh={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),$h.stringifyString(t,e,i,r)}};uc.string=Oh});var mr=g(hc=>{"use strict";var dc=I(),fc={identify:t=>t==null,createNode:()=>new dc.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new dc.Scalar(null),stringify:({source:t},e)=>typeof t=="string"&&fc.test.test(t)?t:e.options.nullStr};hc.nullTag=fc});var la=g(mc=>{"use strict";var Hh=I(),pc={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&&pc.test.test(t)){let r=t[0]==="t"||t[0]==="T";if(e===r)return t}return e?i.options.trueStr:i.options.falseStr}};mc.boolTag=pc});var pt=g(vc=>{"use strict";function Dh({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 a=Object.is(r,-0)?"-0":JSON.stringify(r);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}vc.stringifyNumber=Dh});var da=g(vr=>{"use strict";var Lh=I(),ua=pt(),Bh={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:ua.stringifyNumber},Mh={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():ua.stringifyNumber(t)}},Fh={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 Lh.Scalar(parseFloat(t)),i=t.indexOf(".");return i!==-1&&t[t.length-1]==="0"&&(e.minFractionDigits=t.length-i-1),e},stringify:ua.stringifyNumber};vr.float=Fh;vr.floatExp=Mh;vr.floatNaN=Bh});var ha=g(wr=>{"use strict";var gc=pt(),gr=t=>typeof t=="bigint"||Number.isInteger(t),fa=(t,e,i,{intAsBigInt:r})=>r?BigInt(t):parseInt(t.substring(e),i);function wc(t,e,i){let{value:r}=t;return gr(r)&&r>=0?i+r.toString(e):gc.stringifyNumber(t)}var Vh={identify:t=>gr(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(t,e,i)=>fa(t,2,8,i),stringify:t=>wc(t,8,"0o")},qh={identify:gr,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(t,e,i)=>fa(t,0,10,i),stringify:gc.stringifyNumber},Wh={identify:t=>gr(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(t,e,i)=>fa(t,2,16,i),stringify:t=>wc(t,16,"0x")};wr.int=qh;wr.intHex=Wh;wr.intOct=Vh});var Nc=g(yc=>{"use strict";var zh=ft(),Jh=mr(),Gh=ht(),Uh=Xt(),Kh=la(),pa=da(),ma=ha(),Yh=[zh.map,Gh.seq,Uh.string,Jh.nullTag,Kh.boolTag,ma.intOct,ma.int,ma.intHex,pa.floatNaN,pa.floatExp,pa.float];yc.schema=Yh});var Sc=g(kc=>{"use strict";var Xh=I(),Qh=ft(),Zh=ht();function bc(t){return typeof t=="bigint"||Number.isInteger(t)}var yr=({value:t})=>JSON.stringify(t),ep=[{identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify:yr},{identify:t=>t==null,createNode:()=>new Xh.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:yr},{identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:t=>t==="true",stringify:yr},{identify:bc,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})=>bc(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:yr}],tp={default:!0,tag:"",test:/^/,resolve(t,e){return e(`Unresolved plain scalar ${JSON.stringify(t)}`),t}},ip=[Qh.map,Zh.seq].concat(ep,tp);kc.schema=ip});var ga=g(Ec=>{"use strict";var Qt=Di("buffer"),va=I(),rp=Gt(),np={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<i.length;++n)r[n]=i.charCodeAt(n);return r}else return e("This environment does not support reading binary tags; either Buffer or atob is required"),t},stringify({comment:t,type:e,value:i},r,n,a){if(!i)return"";let o=i,s;if(typeof Qt.Buffer=="function")s=o instanceof Qt.Buffer?o.toString("base64"):Qt.Buffer.from(o.buffer).toString("base64");else if(typeof btoa=="function"){let c="";for(let l=0;l<o.length;++l)c+=String.fromCharCode(o[l]);s=btoa(c)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(e??(e=va.Scalar.BLOCK_LITERAL),e!==va.Scalar.QUOTE_DOUBLE){let c=Math.max(r.options.lineWidth-r.indent.length,r.options.minContentWidth),l=Math.ceil(s.length/c),f=new Array(l);for(let d=0,u=0;d<l;++d,u+=c)f[d]=s.substr(u,c);s=f.join(e===va.Scalar.BLOCK_LITERAL?`
|
|
55
55
|
`:" ")}return rp.stringifyString({comment:t,type:e,value:s},r,n,a)}};Ec.binary=np});var kr=g(br=>{"use strict";var Nr=P(),wa=He(),ap=I(),op=Be();function Pc(t,e){if(Nr.isSeq(t))for(let i=0;i<t.items.length;++i){let r=t.items[i];if(!Nr.isPair(r)){if(Nr.isMap(r)){r.items.length>1&&e("Each pair must have its own sequence indicator");let n=r.items[0]||new wa.Pair(new ap.Scalar(null));if(r.commentBefore&&(n.key.commentBefore=n.key.commentBefore?`${r.commentBefore}
|
|
56
56
|
${n.key.commentBefore}`:r.commentBefore),r.comment){let a=n.value??n.key;a.comment=a.comment?`${r.comment}
|
|
57
|
-
${a.comment}`:r.comment}r=n}t.items[i]=Nr.isPair(r)?r:new wa.Pair(r)}}else e("Expected a sequence for this tag");return t}function xc(t,e,i){let{replacer:r}=i,n=new op.YAMLSeq(t);n.tag="tag:yaml.org,2002:pairs";let a=0;if(e&&Symbol.iterator in Object(e))for(let o of e){typeof r=="function"&&(o=r.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;n.items.push(wa.createPair(s,c,i))}return n}var sp={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Pc,createNode:xc};br.createPairs=xc;br.pairs=sp;br.resolvePairs=Pc});var ba=g(Na=>{"use strict";var Cc=P(),ya=Ie(),Qt=Le(),cp=Be(),Rc=kr(),Ke=class t extends cp.YAMLSeq{constructor(){super(),this.add=Qt.YAMLMap.prototype.add.bind(this),this.delete=Qt.YAMLMap.prototype.delete.bind(this),this.get=Qt.YAMLMap.prototype.get.bind(this),this.has=Qt.YAMLMap.prototype.has.bind(this),this.set=Qt.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 a,o;if(Cc.isPair(n)?(a=ya.toJS(n.key,"",i),o=ya.toJS(n.value,a,i)):a=ya.toJS(n,"",i),r.has(a))throw new Error("Ordered maps must not include duplicate keys");r.set(a,o)}return r}static from(e,i,r){let n=Rc.createPairs(e,i,r),a=new this;return a.items=n.items,a}};Ke.tag="tag:yaml.org,2002:omap";var lp={collection:"seq",identify:t=>t instanceof Map,nodeClass:Ke,default:!1,tag:"tag:yaml.org,2002:omap",resolve(t,e){let i=Rc.resolvePairs(t,e),r=[];for(let{key:n}of i.items)Cc.isScalar(n)&&(r.includes(n.value)?e(`Ordered maps must not include duplicate keys: ${n.value}`):r.push(n.value));return Object.assign(new Ke,i)},createNode:(t,e,i)=>Ke.from(t,e,i)};Na.YAMLOMap=Ke;Na.omap=lp});var jc=g(ka=>{"use strict";var Ac=I();function _c({value:t,source:e},i){return e&&(t?Tc:Ic).test.test(e)?e:t?i.options.trueStr:i.options.falseStr}var Tc={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 Ac.Scalar(!0),stringify:_c},Ic={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 Ac.Scalar(!1),stringify:_c};ka.falseTag=Ic;ka.trueTag=Tc});var $c=g(Sr=>{"use strict";var up=I(),Sa=pt(),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:Sa.stringifyNumber},fp={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():Sa.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 up.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:Sa.stringifyNumber};Sr.float=hp;Sr.floatExp=fp;Sr.floatNaN=dp});var Hc=g(ei=>{"use strict";var Oc=pt(),Zt=t=>typeof t=="bigint"||Number.isInteger(t);function Er(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 o=BigInt(t);return n==="-"?BigInt(-1)*o:o}let a=parseInt(t,i);return n==="-"?-1*a:a}function Ea(t,e,i){let{value:r}=t;if(Zt(r)){let n=r.toString(e);return r<0?"-"+i+n.substr(1):i+n}return Oc.stringifyNumber(t)}var pp={identify:Zt,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(t,e,i)=>Er(t,2,2,i),stringify:t=>Ea(t,2,"0b")},mp={identify:Zt,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(t,e,i)=>Er(t,1,8,i),stringify:t=>Ea(t,8,"0")},vp={identify:Zt,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(t,e,i)=>Er(t,0,10,i),stringify:Oc.stringifyNumber},gp={identify:Zt,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(t,e,i)=>Er(t,2,16,i),stringify:t=>Ea(t,16,"0x")};ei.int=vp;ei.intBin=pp;ei.intHex=gp;ei.intOct=mp});var xa=g(Pa=>{"use strict";var Cr=P(),Pr=He(),xr=Le(),Ye=class t extends xr.YAMLMap{constructor(e){super(e),this.tag=t.tag}add(e){let i;Cr.isPair(e)?i=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?i=new Pr.Pair(e.key,null):i=new Pr.Pair(e,null),xr.findPair(this.items,i.key)||this.items.push(i)}get(e,i){let r=xr.findPair(this.items,e);return!i&&Cr.isPair(r)?Cr.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=xr.findPair(this.items,e);r&&!i?this.items.splice(this.items.indexOf(r),1):!r&&i&&this.items.push(new Pr.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,a=new this(e);if(i&&Symbol.iterator in Object(i))for(let o of i)typeof n=="function"&&(o=n.call(i,o,o)),a.items.push(Pr.createPair(o,null,r));return a}};Ye.tag="tag:yaml.org,2002:set";var wp={collection:"map",identify:t=>t instanceof Set,nodeClass:Ye,default:!1,tag:"tag:yaml.org,2002:set",createNode:(t,e,i)=>Ye.from(t,e,i),resolve(t,e){if(Cr.isMap(t)){if(t.hasAllNullValues(!0))return Object.assign(new Ye,t);e("Set items must all have null values")}else e("Expected a mapping for this tag");return t}};Pa.YAMLSet=Ye;Pa.set=wp});var Ra=g(Rr=>{"use strict";var yp=pt();function Ca(t,e){let i=t[0],r=i==="-"||i==="+"?t.substring(1):t,n=o=>e?BigInt(o):Number(o),a=r.replace(/_/g,"").split(":").reduce((o,s)=>o*n(60)+n(s),n(0));return i==="-"?n(-1)*a:a}function Dc(t){let{value:e}=t,i=o=>o;if(typeof e=="bigint")i=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return yp.stringifyNumber(t);let r="";e<0&&(r="-",e*=i(-1));let n=i(60),a=[e%n];return e<60?a.unshift(0):(e=(e-a[0])/n,a.unshift(e%n),e>=60&&(e=(e-a[0])/n,a.unshift(e))),r+a.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:i})=>Ca(t,i),stringify:Dc},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=>Ca(t,!1),stringify:Dc},Lc={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(Lc.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,i,r,n,a,o,s]=e.map(Number),c=e[7]?Number((e[7]+"00").substr(1,3)):0,l=Date.UTC(i,r-1,n,a||0,o||0,s||0,c),f=e[8];if(f&&f!=="Z"){let d=Ca(f,!1);Math.abs(d)<30&&(d*=60),l-=6e4*d}return new Date(l)},stringify:({value:t})=>t?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};Rr.floatTime=bp;Rr.intTime=Np;Rr.timestamp=Lc});var Fc=g(Mc=>{"use strict";var kp=ft(),Sp=mr(),Ep=ht(),Pp=Yt(),xp=ga(),Bc=jc(),Aa=$c(),Ar=Hc(),Cp=sr(),Rp=ba(),Ap=kr(),_p=xa(),_a=Ra(),Tp=[kp.map,Ep.seq,Pp.string,Sp.nullTag,Bc.trueTag,Bc.falseTag,Ar.intBin,Ar.intOct,Ar.int,Ar.intHex,Aa.floatNaN,Aa.floatExp,Aa.float,xp.binary,Cp.merge,Rp.omap,Ap.pairs,_p.set,_a.intTime,_a.floatTime,_a.timestamp];Mc.schema=Tp});var Xc=g(ja=>{"use strict";var zc=ft(),Ip=mr(),Jc=ht(),jp=Yt(),$p=la(),Ta=da(),Ia=ha(),Op=Nc(),Hp=Sc(),Gc=ga(),ti=sr(),Uc=ba(),Kc=kr(),Vc=Fc(),Yc=xa(),_r=Ra(),qc=new Map([["core",Op.schema],["failsafe",[zc.map,Jc.seq,jp.string]],["json",Hp.schema],["yaml11",Vc.schema],["yaml-1.1",Vc.schema]]),Wc={binary:Gc.binary,bool:$p.boolTag,float:Ta.float,floatExp:Ta.floatExp,floatNaN:Ta.floatNaN,floatTime:_r.floatTime,int:Ia.int,intHex:Ia.intHex,intOct:Ia.intOct,intTime:_r.intTime,map:zc.map,merge:ti.merge,null:Ip.nullTag,omap:Uc.omap,pairs:Kc.pairs,seq:Jc.seq,set:Yc.set,timestamp:_r.timestamp},Dp={"tag:yaml.org,2002:binary":Gc.binary,"tag:yaml.org,2002:merge":ti.merge,"tag:yaml.org,2002:omap":Uc.omap,"tag:yaml.org,2002:pairs":Kc.pairs,"tag:yaml.org,2002:set":Yc.set,"tag:yaml.org,2002:timestamp":_r.timestamp};function Lp(t,e,i){let r=qc.get(e);if(r&&!t)return i&&!r.includes(ti.merge)?r.concat(ti.merge):r.slice();let n=r;if(!n)if(Array.isArray(t))n=[];else{let a=Array.from(qc.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)n=n.concat(a);else typeof t=="function"&&(n=t(n.slice()));return i&&(n=n.concat(ti.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?Wc[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(Wc).map(f=>JSON.stringify(f)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return a.includes(s)||a.push(s),a},[])}ja.coreKnownTags=Dp;ja.getTags=Lp});var Ha=g(Qc=>{"use strict";var $a=P(),Bp=ft(),Mp=ht(),Fp=Yt(),Tr=Xc(),Vp=(t,e)=>t.key<e.key?-1:t.key>e.key?1:0,Oa=class t{constructor({compat:e,customTags:i,merge:r,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(e)?Tr.getTags(e,"compat"):e?Tr.getTags(null,e):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?Tr.coreKnownTags:{},this.tags=Tr.getTags(i,this.name,r),this.toStringOptions=s??null,Object.defineProperty(this,$a.MAP,{value:Bp.map}),Object.defineProperty(this,$a.SCALAR,{value:Fp.string}),Object.defineProperty(this,$a.SEQ,{value:Mp.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?Vp:null}clone(){let e=Object.create(t.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};Qc.Schema=Oa});var el=g(Zc=>{"use strict";var qp=P(),Da=Gt(),ii=qt();function Wp(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=Da.createStringifyContext(t,e),{commentString:a}=n.options;if(t.commentBefore){i.length!==1&&i.unshift("");let c=a(t.commentBefore);i.unshift(ii.indentComment(c,""))}let o=!1,s=null;if(t.contents){if(qp.isNode(t.contents)){if(t.contents.spaceBefore&&r&&i.push(""),t.contents.commentBefore){let f=a(t.contents.commentBefore);i.push(ii.indentComment(f,""))}n.forceBlockIndent=!!t.comment,s=t.contents.comment}let c=s?void 0:()=>o=!0,l=Da.stringify(t.contents,n,()=>s=null,c);s&&(l+=ii.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&i[i.length-1]==="---"?i[i.length-1]=`--- ${l}`:i.push(l)}else i.push(Da.stringify(t.contents,n));if(t.directives?.docEnd)if(t.comment){let c=a(t.comment);c.includes(`
|
|
58
|
-
`)?(i.push("..."),i.push(
|
|
57
|
+
${a.comment}`:r.comment}r=n}t.items[i]=Nr.isPair(r)?r:new wa.Pair(r)}}else e("Expected a sequence for this tag");return t}function xc(t,e,i){let{replacer:r}=i,n=new op.YAMLSeq(t);n.tag="tag:yaml.org,2002:pairs";let a=0;if(e&&Symbol.iterator in Object(e))for(let o of e){typeof r=="function"&&(o=r.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;n.items.push(wa.createPair(s,c,i))}return n}var sp={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Pc,createNode:xc};br.createPairs=xc;br.pairs=sp;br.resolvePairs=Pc});var ba=g(Na=>{"use strict";var Cc=P(),ya=Ie(),Zt=Le(),cp=Be(),Rc=kr(),Ke=class t extends cp.YAMLSeq{constructor(){super(),this.add=Zt.YAMLMap.prototype.add.bind(this),this.delete=Zt.YAMLMap.prototype.delete.bind(this),this.get=Zt.YAMLMap.prototype.get.bind(this),this.has=Zt.YAMLMap.prototype.has.bind(this),this.set=Zt.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 a,o;if(Cc.isPair(n)?(a=ya.toJS(n.key,"",i),o=ya.toJS(n.value,a,i)):a=ya.toJS(n,"",i),r.has(a))throw new Error("Ordered maps must not include duplicate keys");r.set(a,o)}return r}static from(e,i,r){let n=Rc.createPairs(e,i,r),a=new this;return a.items=n.items,a}};Ke.tag="tag:yaml.org,2002:omap";var lp={collection:"seq",identify:t=>t instanceof Map,nodeClass:Ke,default:!1,tag:"tag:yaml.org,2002:omap",resolve(t,e){let i=Rc.resolvePairs(t,e),r=[];for(let{key:n}of i.items)Cc.isScalar(n)&&(r.includes(n.value)?e(`Ordered maps must not include duplicate keys: ${n.value}`):r.push(n.value));return Object.assign(new Ke,i)},createNode:(t,e,i)=>Ke.from(t,e,i)};Na.YAMLOMap=Ke;Na.omap=lp});var jc=g(ka=>{"use strict";var Ac=I();function _c({value:t,source:e},i){return e&&(t?Tc:Ic).test.test(e)?e:t?i.options.trueStr:i.options.falseStr}var Tc={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 Ac.Scalar(!0),stringify:_c},Ic={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 Ac.Scalar(!1),stringify:_c};ka.falseTag=Ic;ka.trueTag=Tc});var $c=g(Sr=>{"use strict";var up=I(),Sa=pt(),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:Sa.stringifyNumber},fp={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():Sa.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 up.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:Sa.stringifyNumber};Sr.float=hp;Sr.floatExp=fp;Sr.floatNaN=dp});var Hc=g(ti=>{"use strict";var Oc=pt(),ei=t=>typeof t=="bigint"||Number.isInteger(t);function Er(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 o=BigInt(t);return n==="-"?BigInt(-1)*o:o}let a=parseInt(t,i);return n==="-"?-1*a:a}function Ea(t,e,i){let{value:r}=t;if(ei(r)){let n=r.toString(e);return r<0?"-"+i+n.substr(1):i+n}return Oc.stringifyNumber(t)}var pp={identify:ei,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(t,e,i)=>Er(t,2,2,i),stringify:t=>Ea(t,2,"0b")},mp={identify:ei,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(t,e,i)=>Er(t,1,8,i),stringify:t=>Ea(t,8,"0")},vp={identify:ei,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(t,e,i)=>Er(t,0,10,i),stringify:Oc.stringifyNumber},gp={identify:ei,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(t,e,i)=>Er(t,2,16,i),stringify:t=>Ea(t,16,"0x")};ti.int=vp;ti.intBin=pp;ti.intHex=gp;ti.intOct=mp});var xa=g(Pa=>{"use strict";var Cr=P(),Pr=He(),xr=Le(),Ye=class t extends xr.YAMLMap{constructor(e){super(e),this.tag=t.tag}add(e){let i;Cr.isPair(e)?i=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?i=new Pr.Pair(e.key,null):i=new Pr.Pair(e,null),xr.findPair(this.items,i.key)||this.items.push(i)}get(e,i){let r=xr.findPair(this.items,e);return!i&&Cr.isPair(r)?Cr.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=xr.findPair(this.items,e);r&&!i?this.items.splice(this.items.indexOf(r),1):!r&&i&&this.items.push(new Pr.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,a=new this(e);if(i&&Symbol.iterator in Object(i))for(let o of i)typeof n=="function"&&(o=n.call(i,o,o)),a.items.push(Pr.createPair(o,null,r));return a}};Ye.tag="tag:yaml.org,2002:set";var wp={collection:"map",identify:t=>t instanceof Set,nodeClass:Ye,default:!1,tag:"tag:yaml.org,2002:set",createNode:(t,e,i)=>Ye.from(t,e,i),resolve(t,e){if(Cr.isMap(t)){if(t.hasAllNullValues(!0))return Object.assign(new Ye,t);e("Set items must all have null values")}else e("Expected a mapping for this tag");return t}};Pa.YAMLSet=Ye;Pa.set=wp});var Ra=g(Rr=>{"use strict";var yp=pt();function Ca(t,e){let i=t[0],r=i==="-"||i==="+"?t.substring(1):t,n=o=>e?BigInt(o):Number(o),a=r.replace(/_/g,"").split(":").reduce((o,s)=>o*n(60)+n(s),n(0));return i==="-"?n(-1)*a:a}function Dc(t){let{value:e}=t,i=o=>o;if(typeof e=="bigint")i=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return yp.stringifyNumber(t);let r="";e<0&&(r="-",e*=i(-1));let n=i(60),a=[e%n];return e<60?a.unshift(0):(e=(e-a[0])/n,a.unshift(e%n),e>=60&&(e=(e-a[0])/n,a.unshift(e))),r+a.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:i})=>Ca(t,i),stringify:Dc},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=>Ca(t,!1),stringify:Dc},Lc={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(Lc.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,i,r,n,a,o,s]=e.map(Number),c=e[7]?Number((e[7]+"00").substr(1,3)):0,l=Date.UTC(i,r-1,n,a||0,o||0,s||0,c),f=e[8];if(f&&f!=="Z"){let d=Ca(f,!1);Math.abs(d)<30&&(d*=60),l-=6e4*d}return new Date(l)},stringify:({value:t})=>t?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};Rr.floatTime=bp;Rr.intTime=Np;Rr.timestamp=Lc});var Fc=g(Mc=>{"use strict";var kp=ft(),Sp=mr(),Ep=ht(),Pp=Xt(),xp=ga(),Bc=jc(),Aa=$c(),Ar=Hc(),Cp=sr(),Rp=ba(),Ap=kr(),_p=xa(),_a=Ra(),Tp=[kp.map,Ep.seq,Pp.string,Sp.nullTag,Bc.trueTag,Bc.falseTag,Ar.intBin,Ar.intOct,Ar.int,Ar.intHex,Aa.floatNaN,Aa.floatExp,Aa.float,xp.binary,Cp.merge,Rp.omap,Ap.pairs,_p.set,_a.intTime,_a.floatTime,_a.timestamp];Mc.schema=Tp});var Xc=g(ja=>{"use strict";var zc=ft(),Ip=mr(),Jc=ht(),jp=Xt(),$p=la(),Ta=da(),Ia=ha(),Op=Nc(),Hp=Sc(),Gc=ga(),ii=sr(),Uc=ba(),Kc=kr(),Vc=Fc(),Yc=xa(),_r=Ra(),qc=new Map([["core",Op.schema],["failsafe",[zc.map,Jc.seq,jp.string]],["json",Hp.schema],["yaml11",Vc.schema],["yaml-1.1",Vc.schema]]),Wc={binary:Gc.binary,bool:$p.boolTag,float:Ta.float,floatExp:Ta.floatExp,floatNaN:Ta.floatNaN,floatTime:_r.floatTime,int:Ia.int,intHex:Ia.intHex,intOct:Ia.intOct,intTime:_r.intTime,map:zc.map,merge:ii.merge,null:Ip.nullTag,omap:Uc.omap,pairs:Kc.pairs,seq:Jc.seq,set:Yc.set,timestamp:_r.timestamp},Dp={"tag:yaml.org,2002:binary":Gc.binary,"tag:yaml.org,2002:merge":ii.merge,"tag:yaml.org,2002:omap":Uc.omap,"tag:yaml.org,2002:pairs":Kc.pairs,"tag:yaml.org,2002:set":Yc.set,"tag:yaml.org,2002:timestamp":_r.timestamp};function Lp(t,e,i){let r=qc.get(e);if(r&&!t)return i&&!r.includes(ii.merge)?r.concat(ii.merge):r.slice();let n=r;if(!n)if(Array.isArray(t))n=[];else{let a=Array.from(qc.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)n=n.concat(a);else typeof t=="function"&&(n=t(n.slice()));return i&&(n=n.concat(ii.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?Wc[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(Wc).map(f=>JSON.stringify(f)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return a.includes(s)||a.push(s),a},[])}ja.coreKnownTags=Dp;ja.getTags=Lp});var Ha=g(Qc=>{"use strict";var $a=P(),Bp=ft(),Mp=ht(),Fp=Xt(),Tr=Xc(),Vp=(t,e)=>t.key<e.key?-1:t.key>e.key?1:0,Oa=class t{constructor({compat:e,customTags:i,merge:r,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(e)?Tr.getTags(e,"compat"):e?Tr.getTags(null,e):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?Tr.coreKnownTags:{},this.tags=Tr.getTags(i,this.name,r),this.toStringOptions=s??null,Object.defineProperty(this,$a.MAP,{value:Bp.map}),Object.defineProperty(this,$a.SCALAR,{value:Fp.string}),Object.defineProperty(this,$a.SEQ,{value:Mp.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?Vp:null}clone(){let e=Object.create(t.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};Qc.Schema=Oa});var el=g(Zc=>{"use strict";var qp=P(),Da=Ut(),ri=Wt();function Wp(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=Da.createStringifyContext(t,e),{commentString:a}=n.options;if(t.commentBefore){i.length!==1&&i.unshift("");let c=a(t.commentBefore);i.unshift(ri.indentComment(c,""))}let o=!1,s=null;if(t.contents){if(qp.isNode(t.contents)){if(t.contents.spaceBefore&&r&&i.push(""),t.contents.commentBefore){let f=a(t.contents.commentBefore);i.push(ri.indentComment(f,""))}n.forceBlockIndent=!!t.comment,s=t.contents.comment}let c=s?void 0:()=>o=!0,l=Da.stringify(t.contents,n,()=>s=null,c);s&&(l+=ri.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&i[i.length-1]==="---"?i[i.length-1]=`--- ${l}`:i.push(l)}else i.push(Da.stringify(t.contents,n));if(t.directives?.docEnd)if(t.comment){let c=a(t.comment);c.includes(`
|
|
58
|
+
`)?(i.push("..."),i.push(ri.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(ri.indentComment(a(c),"")))}return i.join(`
|
|
59
59
|
`)+`
|
|
60
|
-
`}Zc.stringifyDocument=Wp});var
|
|
60
|
+
`}Zc.stringifyDocument=Wp});var ni=g(tl=>{"use strict";var zp=Vt(),mt=Xi(),X=P(),Jp=He(),Gp=Ie(),Up=Ha(),Kp=el(),La=Gi(),Yp=Vn(),Xp=qt(),Ba=Fn(),Ma=class t{constructor(e,i,r){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,X.NODE_TYPE,{value:X.DOC});let n=null;typeof i=="function"||Array.isArray(i)?n=i:r===void 0&&i&&(r=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"},r);this.options=a;let{version:o}=a;r?._directives?(this.directives=r._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new Ba.Directives({version:o}),this.setSchema(o,r),this.contents=e===void 0?null:this.createNode(e,n,r)}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){vt(this.contents)&&this.contents.add(e)}addIn(e,i){vt(this.contents)&&this.contents.addIn(e,i)}createAlias(e,i){if(!e.anchor){let r=La.anchorNames(this);e.anchor=!i||r.has(i)?La.findNewAnchor(i||"a",r):i}return new zp.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 m=y=>typeof y=="number"||y instanceof String||y instanceof Number,w=i.filter(m).map(String);w.length>0&&(i=i.concat(w)),n=i}else r===void 0&&i&&(r=i,i=void 0);let{aliasDuplicateObjects:a,anchorPrefix:o,flow:s,keepUndefined:c,onTagObj:l,tag:f}=r??{},{onAnchor:d,setAnchors:u,sourceObjects:p}=La.createNodeAnchors(this,o||"a"),v={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:d,onTagObj:l,replacer:n,schema:this.schema,sourceObjects:p},h=Xp.createNode(e,f,v);return s&&X.isCollection(h)&&(h.flow=!0),u(),h}createPair(e,i,r={}){let n=this.createNode(e,null,r),a=this.createNode(i,null,r);return new Jp.Pair(n,a)}delete(e){return vt(this.contents)?this.contents.delete(e):!1}deleteIn(e){return mt.isEmptyPath(e)?this.contents==null?!1:(this.contents=null,!0):vt(this.contents)?this.contents.deleteIn(e):!1}get(e,i){return X.isCollection(this.contents)?this.contents.get(e,i):void 0}getIn(e,i){return mt.isEmptyPath(e)?!i&&X.isScalar(this.contents)?this.contents.value:this.contents:X.isCollection(this.contents)?this.contents.getIn(e,i):void 0}has(e){return X.isCollection(this.contents)?this.contents.has(e):!1}hasIn(e){return mt.isEmptyPath(e)?this.contents!==void 0:X.isCollection(this.contents)?this.contents.hasIn(e):!1}set(e,i){this.contents==null?this.contents=mt.collectionFromPath(this.schema,[e],i):vt(this.contents)&&this.contents.set(e,i)}setIn(e,i){mt.isEmptyPath(e)?this.contents=i:this.contents==null?this.contents=mt.collectionFromPath(this.schema,Array.from(e),i):vt(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 Ba.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 Ba.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 Up.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:a,reviver:o}={}){let s={anchors:new Map,doc:this,keep:!e,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},c=Gp.toJS(this.contents,i??"",s);if(typeof a=="function")for(let{count:l,res:f}of s.anchors.values())a(f,l);return typeof o=="function"?Yp.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 Kp.stringifyDocument(this,e)}};function vt(t){if(X.isCollection(t))return!0;throw new Error("Expected a YAML collection as document contents")}tl.Document=Ma});var si=g(oi=>{"use strict";var ai=class extends Error{constructor(e,i,r,n){super(),this.name=e,this.code=r,this.message=n,this.pos=i}},Fa=class extends ai{constructor(e,i,r){super("YAMLParseError",e,i,r)}},Va=class extends ai{constructor(e,i,r){super("YAMLWarning",e,i,r)}},Qp=(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 a=n-1,o=t.substring(e.lineStarts[r-1],e.lineStarts[r]).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)+"…"),r>1&&/^ *$/.test(o.substring(0,a))){let s=t.substring(e.lineStarts[r-2],e.lineStarts[r-1]);s.length>80&&(s=s.substring(0,79)+`…
|
|
61
61
|
`),o=s+o}if(/[^ ]/.test(o)){let s=1,c=i.linePos[1];c?.line===r&&c.col>n&&(s=Math.max(1,Math.min(c.col-n,80-a)));let l=" ".repeat(a)+"^".repeat(s);i.message+=`:
|
|
62
62
|
|
|
63
63
|
${o}
|
|
64
64
|
${l}
|
|
65
|
-
`}};
|
|
66
|
-
`))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(qa(e.key)||qa(e.value))return!0}return!1;default:return!0}}rl.containsNewline=qa});var Wa=g(nl=>{"use strict";var em=Ir();function tm(t,e,i){if(e?.type==="flow-collection"){let r=e.end[0];r.indent===t&&(r.source==="]"||r.source==="}")&&em.containsNewline(e)&&i(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}nl.flowIndentCheck=tm});var za=g(ol=>{"use strict";var al=P();function im(t,e,i){let{uniqueKeys:r}=t.options;if(r===!1)return!1;let n=typeof r=="function"?r:(a,o)=>a===o||al.isScalar(a)&&al.isScalar(o)&&a.value===o.value;return e.some(a=>n(a.key,i))}ol.mapIncludes=im});var fl=g(dl=>{"use strict";var sl=He(),rm=Le(),cl=
|
|
65
|
+
`}};oi.YAMLError=ai;oi.YAMLParseError=Fa;oi.YAMLWarning=Va;oi.prettifyError=Qp});var ci=g(il=>{"use strict";function Zp(t,{flow:e,indicator:i,next:r,offset:n,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,f=s,d="",u="",p=!1,v=!1,h=null,m=null,w=null,y=null,b=null,k=null,S=null;for(let N of t)switch(v&&(N.type!=="space"&&N.type!=="newline"&&N.type!=="comma"&&a(N.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),v=!1),h&&(l&&N.type!=="comment"&&N.type!=="newline"&&a(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||a(N,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let j=N.source.substring(1)||" ";d?d+=u+j:d=j,u="",l=!1;break}case"newline":l?d?d+=N.source:(!k||i!=="seq-item-ind")&&(c=!0):u+=N.source,l=!0,p=!0,(m||w)&&(y=N),f=!0;break;case"anchor":m&&a(N,"MULTIPLE_ANCHORS","A node can have at most one anchor"),N.source.endsWith(":")&&a(N.offset+N.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),m=N,S??(S=N.offset),l=!1,f=!1,v=!0;break;case"tag":{w&&a(N,"MULTIPLE_TAGS","A node can have at most one tag"),w=N,S??(S=N.offset),l=!1,f=!1,v=!0;break}case i:(m||w)&&a(N,"BAD_PROP_ORDER",`Anchors and tags must be after the ${N.source} indicator`),k&&a(N,"UNEXPECTED_TOKEN",`Unexpected ${N.source} in ${e??"collection"}`),k=N,l=i==="seq-item-ind"||i==="explicit-key-ind",f=!1;break;case"comma":if(e){b&&a(N,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),b=N,l=!1,f=!1;break}default:a(N,"UNEXPECTED_TOKEN",`Unexpected ${N.type} token`),l=!1,f=!1}let E=t[t.length-1],R=E?E.offset+E.source.length:n;return v&&r&&r.type!=="space"&&r.type!=="newline"&&r.type!=="comma"&&(r.type!=="scalar"||r.source!=="")&&a(r.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),h&&(l&&h.indent<=o||r?.type==="block-map"||r?.type==="block-seq")&&a(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:b,found:k,spaceBefore:c,comment:d,hasNewline:p,anchor:m,tag:w,newlineAfterProp:y,end:R,start:S??R}}il.resolveProps=Zp});var Ir=g(rl=>{"use strict";function qa(t){if(!t)return null;switch(t.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(t.source.includes(`
|
|
66
|
+
`))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(qa(e.key)||qa(e.value))return!0}return!1;default:return!0}}rl.containsNewline=qa});var Wa=g(nl=>{"use strict";var em=Ir();function tm(t,e,i){if(e?.type==="flow-collection"){let r=e.end[0];r.indent===t&&(r.source==="]"||r.source==="}")&&em.containsNewline(e)&&i(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}nl.flowIndentCheck=tm});var za=g(ol=>{"use strict";var al=P();function im(t,e,i){let{uniqueKeys:r}=t.options;if(r===!1)return!1;let n=typeof r=="function"?r:(a,o)=>a===o||al.isScalar(a)&&al.isScalar(o)&&a.value===o.value;return e.some(a=>n(a.key,i))}ol.mapIncludes=im});var fl=g(dl=>{"use strict";var sl=He(),rm=Le(),cl=ci(),nm=Ir(),ll=Wa(),am=za(),ul="All mapping items must start at the same column";function om({composeNode:t,composeEmptyNode:e},i,r,n,a){let o=a?.nodeClass??rm.YAMLMap,s=new o(i.schema);i.atRoot&&(i.atRoot=!1);let c=r.offset,l=null;for(let f of r.items){let{start:d,key:u,sep:p,value:v}=f,h=cl.resolveProps(d,{indicator:"explicit-key-ind",next:u??p?.[0],offset:c,onError:n,parentIndent:r.indent,startOnNewline:!0}),m=!h.found;if(m){if(u&&(u.type==="block-seq"?n(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in u&&u.indent!==r.indent&&n(c,"BAD_INDENT",ul)),!h.anchor&&!h.tag&&!p){l=h.end,h.comment&&(s.comment?s.comment+=`
|
|
67
67
|
`+h.comment:s.comment=h.comment);continue}(h.newlineAfterProp||nm.containsNewline(u))&&n(u??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else h.found?.indent!==r.indent&&n(c,"BAD_INDENT",ul);i.atKey=!0;let w=h.end,y=u?t(i,u,h,n):e(i,w,d,null,h,n);i.schema.compat&&ll.flowIndentCheck(r.indent,u,n),i.atKey=!1,am.mapIncludes(i,s.items,y)&&n(w,"DUPLICATE_KEY","Map keys must be unique");let b=cl.resolveProps(p??[],{indicator:"map-value-ind",next:v,offset:y.range[2],onError:n,parentIndent:r.indent,startOnNewline:!u||u.type==="block-scalar"});if(c=b.end,b.found){m&&(v?.type==="block-map"&&!b.hasNewline&&n(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),i.options.strict&&h.start<b.found.offset-1024&&n(y.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let k=v?t(i,v,b,n):e(i,c,p,null,b,n);i.schema.compat&&ll.flowIndentCheck(r.indent,v,n),c=k.range[2];let S=new sl.Pair(y,k);i.options.keepSourceTokens&&(S.srcToken=f),s.items.push(S)}else{m&&n(y.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),b.comment&&(y.comment?y.comment+=`
|
|
68
|
-
`+b.comment:y.comment=b.comment);let k=new sl.Pair(y);i.options.keepSourceTokens&&(k.srcToken=f),s.items.push(k)}}return l&&l<c&&n(l,"IMPOSSIBLE","Map comment with trailing content"),s.range=[r.offset,c,l??c],s}dl.resolveBlockMap=om});var pl=g(hl=>{"use strict";var sm=Be(),cm=
|
|
68
|
+
`+b.comment:y.comment=b.comment);let k=new sl.Pair(y);i.options.keepSourceTokens&&(k.srcToken=f),s.items.push(k)}}return l&&l<c&&n(l,"IMPOSSIBLE","Map comment with trailing content"),s.range=[r.offset,c,l??c],s}dl.resolveBlockMap=om});var pl=g(hl=>{"use strict";var sm=Be(),cm=ci(),lm=Wa();function um({composeNode:t,composeEmptyNode:e},i,r,n,a){let o=a?.nodeClass??sm.YAMLSeq,s=new o(i.schema);i.atRoot&&(i.atRoot=!1),i.atKey&&(i.atKey=!1);let c=r.offset,l=null;for(let{start:f,value:d}of r.items){let u=cm.resolveProps(f,{indicator:"seq-item-ind",next:d,offset:c,onError:n,parentIndent:r.indent,startOnNewline:!0});if(!u.found)if(u.anchor||u.tag||d)d?.type==="block-seq"?n(u.end,"BAD_INDENT","All sequence items must start at the same column"):n(c,"MISSING_CHAR","Sequence item without - indicator");else{l=u.end,u.comment&&(s.comment=u.comment);continue}let p=d?t(i,d,u,n):e(i,u.end,f,null,u,n);i.schema.compat&&lm.flowIndentCheck(r.indent,d,n),c=p.range[2],s.items.push(p)}return s.range=[r.offset,c,l??c],s}hl.resolveBlockSeq=um});var gt=g(ml=>{"use strict";function dm(t,e,i,r){let n="";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&&r(s,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let f=c.substring(1)||" ";n?n+=o+f:n=f,o="";break}case"newline":n&&(o+=c),a=!0;break;default:r(s,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}e+=c.length}}return{comment:n,offset:e}}ml.resolveEnd=dm});var yl=g(wl=>{"use strict";var fm=P(),hm=He(),vl=Le(),pm=Be(),mm=gt(),gl=ci(),vm=Ir(),gm=za(),Ja="Block collections are not allowed within flow collections",Ga=t=>t&&(t.type==="block-map"||t.type==="block-seq");function wm({composeNode:t,composeEmptyNode:e},i,r,n,a){let o=r.start.source==="{",s=o?"flow map":"flow sequence",c=a?.nodeClass??(o?vl.YAMLMap:pm.YAMLSeq),l=new c(i.schema);l.flow=!0;let f=i.atRoot;f&&(i.atRoot=!1),i.atKey&&(i.atKey=!1);let d=r.offset+r.start.source.length;for(let m=0;m<r.items.length;++m){let w=r.items[m],{start:y,key:b,sep:k,value:S}=w,E=gl.resolveProps(y,{flow:s,indicator:"explicit-key-ind",next:b??k?.[0],offset:d,onError:n,parentIndent:r.indent,startOnNewline:!1});if(!E.found){if(!E.anchor&&!E.tag&&!k&&!S){m===0&&E.comma?n(E.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`):m<r.items.length-1&&n(E.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${s}`),E.comment&&(l.comment?l.comment+=`
|
|
69
69
|
`+E.comment:l.comment=E.comment),d=E.end;continue}!o&&i.options.strict&&vm.containsNewline(b)&&n(b,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(m===0)E.comma&&n(E.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`);else if(E.comma||n(E.start,"MISSING_CHAR",`Missing , between ${s} items`),E.comment){let R="";e:for(let N of y)switch(N.type){case"comma":case"space":break;case"comment":R=N.source.substring(1);break e;default:break e}if(R){let N=l.items[l.items.length-1];fm.isPair(N)&&(N=N.value??N.key),N.comment?N.comment+=`
|
|
70
70
|
`+R:N.comment=R,E.comment=E.comment.substring(R.length+1)}}if(!o&&!k&&!E.found){let R=S?t(i,S,E,n):e(i,E.end,k,null,E,n);l.items.push(R),d=R.range[2],Ga(S)&&n(R.range,"BLOCK_IN_FLOW",Ja)}else{i.atKey=!0;let R=E.end,N=b?t(i,b,E,n):e(i,R,y,null,E,n);Ga(b)&&n(N.range,"BLOCK_IN_FLOW",Ja),i.atKey=!1;let j=gl.resolveProps(k??[],{flow:s,indicator:"map-value-ind",next:S,offset:N.range[2],onError:n,parentIndent:r.indent,startOnNewline:!1});if(j.found){if(!o&&!E.found&&i.options.strict){if(k)for(let $ of k){if($===j.found)break;if($.type==="newline"){n($,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}E.start<j.found.offset-1024&&n(j.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else S&&("source"in S&&S.source?.[0]===":"?n(S,"MISSING_CHAR",`Missing space after : in ${s}`):n(j.start,"MISSING_CHAR",`Missing , or : between ${s} items`));let _e=S?t(i,S,j,n):j.found?e(i,j.end,k,null,j,n):null;_e?Ga(S)&&n(_e.range,"BLOCK_IN_FLOW",Ja):j.comment&&(N.comment?N.comment+=`
|
|
71
71
|
`+j.comment:N.comment=j.comment);let st=new hm.Pair(N,_e);if(i.options.keepSourceTokens&&(st.srcToken=w),o){let $=l;gm.mapIncludes(i,$.items,N)&&n(R,"DUPLICATE_KEY","Map keys must be unique"),$.items.push(st)}else{let $=new vl.YAMLMap(i.schema);$.flow=!0,$.items.push(st);let ps=(_e??N).range;$.range=[N.range[0],ps[1],ps[2]],l.items.push($)}d=_e?_e.range[2]:j.end}}let u=o?"}":"]",[p,...v]=r.end,h=d;if(p?.source===u)h=p.offset+p.source.length;else{let m=s[0].toUpperCase()+s.substring(1),w=f?`${m} must end with a ${u}`:`${m} in block collection must be sufficiently indented and end with a ${u}`;n(d,f?"MISSING_CHAR":"BAD_INDENT",w),p&&p.source.length!==1&&v.unshift(p)}if(v.length>0){let m=mm.resolveEnd(v,h,i.options.strict,n);m.comment&&(l.comment?l.comment+=`
|
|
@@ -99,14 +99,14 @@ ${l}
|
|
|
99
99
|
`);)r===`
|
|
100
100
|
`&&(i+=`
|
|
101
101
|
`),e+=1,r=t[e+1];return i||(i=" "),{fold:i,offset:e}}var Hm={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
|
|
102
|
-
`,r:"\r",t:" ",v:"\v",N:"
",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function Dm(t,e,i,r){let n=t.substr(e,i),o=n.length===i&&/^[0-9a-fA-F]+$/.test(n)?parseInt(n,16):NaN;try{return String.fromCodePoint(o)}catch{let s=t.substr(e-2,i+2);return r(e-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),s}}El.resolveFlowScalar=Tm});var Cl=g(xl=>{"use strict";var Xe=P(),Pl=I(),Lm=Ya(),Bm=Qa();function Mm(t,e,i,r){let{value:n,type:a,comment:o,range:s}=e.type==="block-scalar"?Lm.resolveBlockScalar(t,e,r):Bm.resolveFlowScalar(e,t.options.strict,r),c=i?t.directives.tagName(i.source,d=>r(i,"TAG_RESOLVE_FAILED",d)):null,l;t.options.stringKeys&&t.atKey?l=t.schema[Xe.SCALAR]:c?l=Fm(t.schema,n,c,i,r):e.type==="scalar"?l=Vm(t,n,e,r):l=t.schema[Xe.SCALAR];let f;try{let d=l.resolve(n,u=>r(i??e,"TAG_RESOLVE_FAILED",u),t.options);f=Xe.isScalar(d)?d:new Pl.Scalar(d)}catch(d){let u=d instanceof Error?d.message:String(d);r(i??e,"TAG_RESOLVE_FAILED",u),f=new Pl.Scalar(n)}return f.range=s,f.source=n,a&&(f.type=a),c&&(f.tag=c),l.format&&(f.format=l.format),o&&(f.comment=o),f}function Fm(t,e,i,r,n){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):(n(r,"TAG_RESOLVE_FAILED",`Unresolved tag: ${i}`,i!=="tag:yaml.org,2002:str"),t[Xe.SCALAR])}function Vm({atKey:t,directives:e,schema:i},r,n,a){let o=i.tags.find(s=>(s.default===!0||t&&s.default==="key")&&s.test?.test(r))||i[Xe.SCALAR];if(i.compat){let s=i.compat.find(c=>c.default&&c.test?.test(r))??i[Xe.SCALAR];if(o.tag!==s.tag){let c=e.tagString(o.tag),l=e.tagString(s.tag),f=`Value may be parsed as either ${c} or ${l}`;a(n,"TAG_RESOLVE_FAILED",f,!0)}}return o}xl.composeScalar=Mm});var Al=g(Rl=>{"use strict";function qm(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}Rl.emptyScalarPosition=qm});var Il=g(eo=>{"use strict";var Wm=
|
|
102
|
+
`,r:"\r",t:" ",v:"\v",N:"
",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function Dm(t,e,i,r){let n=t.substr(e,i),o=n.length===i&&/^[0-9a-fA-F]+$/.test(n)?parseInt(n,16):NaN;try{return String.fromCodePoint(o)}catch{let s=t.substr(e-2,i+2);return r(e-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),s}}El.resolveFlowScalar=Tm});var Cl=g(xl=>{"use strict";var Xe=P(),Pl=I(),Lm=Ya(),Bm=Qa();function Mm(t,e,i,r){let{value:n,type:a,comment:o,range:s}=e.type==="block-scalar"?Lm.resolveBlockScalar(t,e,r):Bm.resolveFlowScalar(e,t.options.strict,r),c=i?t.directives.tagName(i.source,d=>r(i,"TAG_RESOLVE_FAILED",d)):null,l;t.options.stringKeys&&t.atKey?l=t.schema[Xe.SCALAR]:c?l=Fm(t.schema,n,c,i,r):e.type==="scalar"?l=Vm(t,n,e,r):l=t.schema[Xe.SCALAR];let f;try{let d=l.resolve(n,u=>r(i??e,"TAG_RESOLVE_FAILED",u),t.options);f=Xe.isScalar(d)?d:new Pl.Scalar(d)}catch(d){let u=d instanceof Error?d.message:String(d);r(i??e,"TAG_RESOLVE_FAILED",u),f=new Pl.Scalar(n)}return f.range=s,f.source=n,a&&(f.type=a),c&&(f.tag=c),l.format&&(f.format=l.format),o&&(f.comment=o),f}function Fm(t,e,i,r,n){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):(n(r,"TAG_RESOLVE_FAILED",`Unresolved tag: ${i}`,i!=="tag:yaml.org,2002:str"),t[Xe.SCALAR])}function Vm({atKey:t,directives:e,schema:i},r,n,a){let o=i.tags.find(s=>(s.default===!0||t&&s.default==="key")&&s.test?.test(r))||i[Xe.SCALAR];if(i.compat){let s=i.compat.find(c=>c.default&&c.test?.test(r))??i[Xe.SCALAR];if(o.tag!==s.tag){let c=e.tagString(o.tag),l=e.tagString(s.tag),f=`Value may be parsed as either ${c} or ${l}`;a(n,"TAG_RESOLVE_FAILED",f,!0)}}return o}xl.composeScalar=Mm});var Al=g(Rl=>{"use strict";function qm(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}Rl.emptyScalarPosition=qm});var Il=g(eo=>{"use strict";var Wm=Vt(),zm=P(),Jm=bl(),_l=Cl(),Gm=gt(),Um=Al(),Km={composeNode:Tl,composeEmptyNode:Za};function Tl(t,e,i,r){let n=t.atKey,{spaceBefore:a,comment:o,anchor:s,tag:c}=i,l,f=!0;switch(e.type){case"alias":l=Ym(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=_l.composeScalar(t,e,c,r),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=Jm.composeCollection(Km,t,e,i,r),s&&(l.anchor=s.source.substring(1))}catch(d){let u=d instanceof Error?d.message:String(d);r(e,"RESOURCE_EXHAUSTION",u)}break;default:{let d=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;r(e,"UNEXPECTED_TOKEN",d),f=!1}}return l??(l=Za(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&&(!zm.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"),a&&(l.spaceBefore=!0),o&&(e.type==="scalar"&&e.source===""?l.comment=o:l.commentBefore=o),t.options.keepSourceTokens&&f&&(l.srcToken=e),l}function Za(t,e,i,r,{spaceBefore:n,comment:a,anchor:o,tag:s,end:c},l){let f={type:"scalar",offset:Um.emptyScalarPosition(e,i,r),indent:-1,source:""},d=_l.composeScalar(t,f,s,l);return o&&(d.anchor=o.source.substring(1),d.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),n&&(d.spaceBefore=!0),a&&(d.comment=a,d.range[2]=c),d}function Ym({options:t},{offset:e,source:i,end:r},n){let a=new Wm.Alias(i.substring(1));a.source===""&&n(e,"BAD_ALIAS","Alias cannot be an empty string"),a.source.endsWith(":")&&n(e+i.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=e+i.length,s=Gm.resolveEnd(r,o,t.strict,n);return a.range=[e,o,s.offset],s.comment&&(a.comment=s.comment),a}eo.composeEmptyNode=Za;eo.composeNode=Tl});var Ol=g($l=>{"use strict";var Xm=ni(),jl=Il(),Qm=gt(),Zm=ci();function ev(t,e,{offset:i,start:r,value:n,end:a},o){let s=Object.assign({_directives:e},t),c=new Xm.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},f=Zm.resolveProps(r,{indicator:"doc-start",next:n??a?.[0],offset:i,onError:o,parentIndent:0,startOnNewline:!0});f.found&&(c.directives.docStart=!0,n&&(n.type==="block-map"||n.type==="block-seq")&&!f.hasNewline&&o(f.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=n?jl.composeNode(l,n,f,o):jl.composeEmptyNode(l,f.end,r,null,f,o);let d=c.contents.range[2],u=Qm.resolveEnd(a,d,!1,o);return u.comment&&(c.comment=u.comment),c.range=[i,d,u.offset],c}$l.composeDoc=ev});var io=g(Ll=>{"use strict";var tv=Di("process"),iv=Fn(),rv=ni(),li=si(),Hl=P(),nv=Ol(),av=gt();function ui(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 Dl(t){let e="",i=!1,r=!1;for(let n=0;n<t.length;++n){let a=t[n];switch(a[0]){case"#":e+=(e===""?"":r?`
|
|
103
103
|
|
|
104
104
|
`:`
|
|
105
|
-
`)+(a.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 to=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(i,r,n,a)=>{let o=
|
|
105
|
+
`)+(a.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 to=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(i,r,n,a)=>{let o=ui(i);a?this.warnings.push(new li.YAMLWarning(o,r,n)):this.errors.push(new li.YAMLParseError(o,r,n))},this.directives=new iv.Directives({version:e.version||"1.2"}),this.options=e}decorate(e,i){let{comment:r,afterEmptyLine:n}=Dl(this.prelude);if(r){let a=e.contents;if(i)e.comment=e.comment?`${e.comment}
|
|
106
106
|
${r}`:r;else if(n||e.directives.docStart||!a)e.commentBefore=r;else if(Hl.isCollection(a)&&!a.flow&&a.items.length>0){let o=a.items[0];Hl.isPair(o)&&(o=o.key);let s=o.commentBefore;o.commentBefore=s?`${r}
|
|
107
107
|
${s}`:r}else{let o=a.commentBefore;a.commentBefore=o?`${r}
|
|
108
|
-
${o}`:r}}if(i){for(let a=0;a<this.errors.length;++a)e.errors.push(this.errors[a]);for(let a=0;a<this.warnings.length;++a)e.warnings.push(this.warnings[a])}else e.errors=this.errors,e.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:Dl(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(e,i=!1,r=-1){for(let n of e)yield*this.next(n);yield*this.end(i,r)}*next(e){switch(tv.env.LOG_STREAM&&console.dir(e,{depth:null}),e.type){case"directive":this.directives.add(e.source,(i,r,n)=>{let a=
|
|
109
|
-
${i.comment}`:i.comment}this.doc.range[2]=i.offset;break}default:this.errors.push(new
|
|
108
|
+
${o}`:r}}if(i){for(let a=0;a<this.errors.length;++a)e.errors.push(this.errors[a]);for(let a=0;a<this.warnings.length;++a)e.warnings.push(this.warnings[a])}else e.errors=this.errors,e.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:Dl(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(e,i=!1,r=-1){for(let n of e)yield*this.next(n);yield*this.end(i,r)}*next(e){switch(tv.env.LOG_STREAM&&console.dir(e,{depth:null}),e.type){case"directive":this.directives.add(e.source,(i,r,n)=>{let a=ui(e);a[0]+=i,this.onError(a,"BAD_DIRECTIVE",r,n)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let i=nv.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 li.YAMLParseError(ui(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 li.YAMLParseError(ui(e),"UNEXPECTED_TOKEN",r));break}this.doc.directives.docEnd=!0;let i=av.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}
|
|
109
|
+
${i.comment}`:i.comment}this.doc.range[2]=i.offset;break}default:this.errors.push(new li.YAMLParseError(ui(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 rv.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}}};Ll.Composer=to});var Fl=g(jr=>{"use strict";var ov=Ya(),sv=Qa(),cv=si(),Bl=Gt();function lv(t,e=!0,i){if(t){let r=(n,a,o)=>{let s=typeof n=="number"?n:Array.isArray(n)?n[0]:n.offset;if(i)i(s,a,o);else throw new cv.YAMLParseError([s,s+1],a,o)};switch(t.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return sv.resolveFlowScalar(t,e,r);case"block-scalar":return ov.resolveBlockScalar({options:{strict:e}},t,r)}}return null}function uv(t,e){let{implicitKey:i=!1,indent:r,inFlow:n=!1,offset:a=-1,type:o="PLAIN"}=e,s=Bl.stringifyString({type:o,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:`
|
|
110
110
|
`}];switch(s[0]){case"|":case">":{let l=s.indexOf(`
|
|
111
111
|
`),f=s.substring(0,l),d=s.substring(l+1)+`
|
|
112
112
|
`,u=[{type:"block-scalar-header",offset:a,indent:r,source:f}];return Ml(u,c)||u.push({type:"newline",offset:-1,indent:r,source:`
|
|
@@ -116,48 +116,48 @@ ${i.comment}`:i.comment}this.doc.range[2]=i.offset;break}default:this.errors.pus
|
|
|
116
116
|
`});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: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 ro(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 a of r)a.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:`
|
|
117
117
|
`};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(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:r,source:e,end:n})}}}jr.createScalarToken=uv;jr.resolveAsScalar=lv;jr.setScalarValue=dv});var ql=g(Vl=>{"use strict";var hv=t=>"type"in t?Or(t):$r(t);function Or(t){switch(t.type){case"block-scalar":{let e="";for(let i of t.props)e+=Or(i);return e+t.source}case"block-map":case"block-seq":{let e="";for(let i of t.items)e+=$r(i);return e}case"flow-collection":{let e=t.start.source;for(let i of t.items)e+=$r(i);for(let i of t.end)e+=i.source;return e}case"document":{let e=$r(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 $r({start:t,key:e,sep:i,value:r}){let n="";for(let a of t)n+=a.source;if(e&&(n+=Or(e)),i)for(let a of i)n+=a.source;return r&&(n+=Or(r)),n}Vl.stringify=hv});var Gl=g(Jl=>{"use strict";var no=Symbol("break visit"),pv=Symbol("skip children"),Wl=Symbol("remove item");function Qe(t,e){"type"in t&&t.type==="document"&&(t={start:t.start,value:t.value}),zl(Object.freeze([]),t,e)}Qe.BREAK=no;Qe.SKIP=pv;Qe.REMOVE=Wl;Qe.itemAtPath=(t,e)=>{let i=t;for(let[r,n]of e){let a=i?.[r];if(a&&"items"in a)i=a.items[n];else return}return i};Qe.parentCollection=(t,e)=>{let i=Qe.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 zl(t,e,i){let r=i(e,t);if(typeof r=="symbol")return r;for(let n of["key","value"]){let a=e[n];if(a&&"items"in a){for(let o=0;o<a.items.length;++o){let s=zl(Object.freeze(t.concat([[n,o]])),a.items[o],i);if(typeof s=="number")o=s-1;else{if(s===no)return no;s===Wl&&(a.items.splice(o,1),o-=1)}}typeof r=="function"&&n==="key"&&(r=r(e,t))}}return typeof r=="function"?r(e,t):r}Jl.visit=Qe});var Hr=g(W=>{"use strict";var ao=Fl(),mv=ql(),vv=Gl(),oo="\uFEFF",so="",co="",lo="",gv=t=>!!t&&"items"in t,wv=t=>!!t&&(t.type==="scalar"||t.type==="single-quoted-scalar"||t.type==="double-quoted-scalar"||t.type==="block-scalar");function yv(t){switch(t){case oo:return"<BOM>";case so:return"<DOC>";case co:return"<FLOW_END>";case lo:return"<SCALAR>";default:return JSON.stringify(t)}}function Nv(t){switch(t){case oo:return"byte-order-mark";case so:return"doc-mode";case co:return"flow-error-end";case lo:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
|
|
118
118
|
`:case`\r
|
|
119
|
-
`: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=ao.createScalarToken;W.resolveAsScalar=ao.resolveAsScalar;W.setScalarValue=ao.setScalarValue;W.stringify=mv.stringify;W.visit=vv.visit;W.BOM=oo;W.DOCUMENT=so;W.FLOW_END=co;W.SCALAR=lo;W.isCollection=gv;W.isScalar=wv;W.prettyToken=yv;W.tokenType=Nv});var ho=g(Kl=>{"use strict";var
|
|
119
|
+
`: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=ao.createScalarToken;W.resolveAsScalar=ao.resolveAsScalar;W.setScalarValue=ao.setScalarValue;W.stringify=mv.stringify;W.visit=vv.visit;W.BOM=oo;W.DOCUMENT=so;W.FLOW_END=co;W.SCALAR=lo;W.isCollection=gv;W.isScalar=wv;W.prettyToken=yv;W.tokenType=Nv});var ho=g(Kl=>{"use strict";var di=Hr();function ne(t){switch(t){case void 0:case" ":case`
|
|
120
120
|
`:case"\r":case" ":return!0;default:return!1}}var Ul=new Set("0123456789ABCDEFabcdef"),bv=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Dr=new Set(",[]{}"),kv=new Set(` ,[]{}
|
|
121
121
|
\r `),uo=t=>!t||kv.has(t),fo=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===`
|
|
122
122
|
`?!0:i==="\r"?this.buffer[e+1]===`
|
|
123
123
|
`:!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===`
|
|
124
124
|
`||!n&&!this.atEnd)return e+r+1}return i===`
|
|
125
125
|
`||r>=this.indentNext||!i&&!this.atEnd?e+r:-1}if(i==="-"||i==="."){let r=this.buffer.substr(e,3);if((r==="---"||r==="...")&&ne(this.buffer[e+3]))return-1}return e}getLine(){let e=this.lineEndPos;return(typeof e!="number"||e!==-1&&e<this.pos)&&(e=this.buffer.indexOf(`
|
|
126
|
-
`,this.pos),this.lineEndPos=e),e===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[e-1]==="\r"&&(e-=1),this.buffer.substring(this.pos,e))}hasChars(e){return this.pos+e<=this.buffer.length}setNext(e){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=e,null}peek(e){return this.buffer.substr(this.pos,e)}*parseNext(e){switch(e){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let e=this.getLine();if(e===null)return this.setNext("stream");if(e[0]===
|
|
126
|
+
`,this.pos),this.lineEndPos=e),e===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[e-1]==="\r"&&(e-=1),this.buffer.substring(this.pos,e))}hasChars(e){return this.pos+e<=this.buffer.length}setNext(e){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=e,null}peek(e){return this.buffer.substr(this.pos,e)}*parseNext(e){switch(e){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let e=this.getLine();if(e===null)return this.setNext("stream");if(e[0]===di.BOM&&(yield*this.pushCount(1),e=e.substring(1)),e[0]==="%"){let i=e.length,r=e.indexOf("#");for(;r!==-1;){let a=e[r-1];if(a===" "||a===" "){i=r-1;break}else r=e.indexOf("#",r+1)}for(;;){let a=e[i-1];if(a===" "||a===" ")i-=1;else break}let n=(yield*this.pushCount(i))+(yield*this.pushSpaces(!0));return yield*this.pushCount(e.length-n),this.pushNewline(),"stream"}if(this.atLineEnd()){let i=yield*this.pushSpaces(!0);return yield*this.pushCount(e.length-i),yield*this.pushNewline(),"stream"}return yield di.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let e=this.charAt(0);if(!e&&!this.atEnd)return this.setNext("line-start");if(e==="-"||e==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let i=this.peek(3);if((i==="---"||i==="...")&&ne(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,i==="---"?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!ne(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===":")&&ne(i)){let r=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=r,"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(uo),"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,r=-1;do e=yield*this.pushNewline(),e>0?(i=yield*this.pushSpaces(!1),this.indentValue=r=i):i=0,i+=yield*this.pushSpaces(!0);while(e+i>0);let n=this.getLine();if(n===null)return this.setNext("flow");if((r!==-1&&r<this.indentNext&&n[0]!=="#"||r===0&&(n.startsWith("---")||n.startsWith("..."))&&ne(n[3]))&&!(r===this.indentNext-1&&this.flowLevel===1&&(n[0]==="]"||n[0]==="}")))return this.flowLevel=0,yield di.FLOW_END,yield*this.parseLineStart();let a=0;for(;n[a]===",";)a+=yield*this.pushCount(1),a+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(a+=yield*this.pushIndicators(),n[a]){case void 0:return"flow";case"#":return yield*this.pushCount(n.length-a),"flow";case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,"flow";case"}":case"]":return yield*this.pushCount(1),this.flowKey=!0,this.flowLevel-=1,this.flowLevel?"flow":"doc";case"*":return yield*this.pushUntil(uo),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||ne(o)||o===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let e=this.charAt(0),i=this.buffer.indexOf(e,this.pos+1);if(e==="'")for(;i!==-1&&this.buffer[i+1]==="'";)i=this.buffer.indexOf("'",i+2);else for(;i!==-1;){let a=0;for(;this.buffer[i-1-a]==="\\";)a+=1;if(a%2===0)break;i=this.buffer.indexOf('"',i+1)}let r=this.buffer.substring(0,i),n=r.indexOf(`
|
|
127
127
|
`,this.pos);if(n!==-1){for(;n!==-1;){let a=this.continueScalar(n+1);if(a===-1)break;n=r.indexOf(`
|
|
128
128
|
`,a)}n!==-1&&(i=n-(r[n-1]==="\r"?2:1))}if(i===-1){if(!this.atEnd)return this.setNext("quoted-scalar");i=this.buffer.length}return yield*this.pushToIndex(i+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let e=this.pos;for(;;){let i=this.buffer[++e];if(i==="+")this.blockScalarKeep=!0;else if(i>"0"&&i<="9")this.blockScalarIndent=Number(i)-1;else if(i!=="-")break}return yield*this.pushUntil(i=>ne(i)||i==="#")}*parseBlockScalar(){let e=this.pos-1,i=0,r;e:for(let a=this.pos;r=this.buffer[a];++a)switch(r){case" ":i+=1;break;case`
|
|
129
129
|
`:e=a,i=0;break;case"\r":{let o=this.buffer[a+1];if(!o&&!this.atEnd)return this.setNext("block-scalar");if(o===`
|
|
130
130
|
`)break}default:break e}if(!r&&!this.atEnd)return this.setNext("block-scalar");if(i>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=i:this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let a=this.continueScalar(e+1);if(a===-1)break;e=this.buffer.indexOf(`
|
|
131
131
|
`,a)}while(e!==-1);if(e===-1){if(!this.atEnd)return this.setNext("block-scalar");e=this.buffer.length}}let n=e+1;for(r=this.buffer[n];r===" ";)r=this.buffer[++n];if(r===" "){for(;r===" "||r===" "||r==="\r"||r===`
|
|
132
132
|
`;)r=this.buffer[++n];e=n-1}else if(!this.blockScalarKeep)do{let a=e-1,o=this.buffer[a];o==="\r"&&(o=this.buffer[--a]);let s=a;for(;o===" ";)o=this.buffer[--a];if(o===`
|
|
133
|
-
`&&a>=this.pos&&a+1+i>s)e=a;else break}while(!0);return yield
|
|
133
|
+
`&&a>=this.pos&&a+1+i>s)e=a;else break}while(!0);return yield di.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 a=this.buffer[r+1];if(ne(a)||e&&Dr.has(a))break;i=r}else if(ne(n)){let a=this.buffer[r+1];if(n==="\r"&&(a===`
|
|
134
134
|
`?(r+=1,n=`
|
|
135
135
|
`,a=this.buffer[r+1]):i=r),a==="#"||e&&Dr.has(a))break;if(n===`
|
|
136
|
-
`){let o=this.continueScalar(r+1);if(o===-1)break;r=Math.max(r,o-2)}}else{if(e&&Dr.has(n))break;i=r}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield
|
|
136
|
+
`){let o=this.continueScalar(r+1);if(o===-1)break;r=Math.max(r,o-2)}}else{if(e&&Dr.has(n))break;i=r}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield di.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(uo),e+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let i=this.flowLevel>0,r=this.charAt(1);if(ne(r)||i&&Dr.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(;!ne(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(bv.has(i))i=this.buffer[++e];else if(i==="%"&&Ul.has(this.buffer[e+1])&&Ul.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===`
|
|
137
137
|
`?yield*this.pushCount(1):e==="\r"&&this.charAt(1)===`
|
|
138
|
-
`?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)}};Kl.Lexer=fo});var mo=g(Yl=>{"use strict";var po=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let i=0,r=this.lineStarts.length;for(;i<r;){let a=i+r>>1;this.lineStarts[a]<e?i=a+1:r=a}if(this.lineStarts[i]===e)return{line:i+1,col:1};if(i===0)return{line:0,col:e};let n=this.lineStarts[i-1];return{line:i,col:e-n+1}}}};Yl.LineCounter=po});var go=g(tu=>{"use strict";var Sv=
|
|
138
|
+
`?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)}};Kl.Lexer=fo});var mo=g(Yl=>{"use strict";var po=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let i=0,r=this.lineStarts.length;for(;i<r;){let a=i+r>>1;this.lineStarts[a]<e?i=a+1:r=a}if(this.lineStarts[i]===e)return{line:i+1,col:1};if(i===0)return{line:0,col:e};let n=this.lineStarts[i-1];return{line:i,col:e-n+1}}}};Yl.LineCounter=po});var go=g(tu=>{"use strict";var Sv=Di("process"),Xl=Hr(),Ev=ho();function Me(t,e){for(let i=0;i<t.length;++i)if(t[i].type===e)return!0;return!1}function Ql(t){for(let e=0;e<t.length;++e)switch(t[e].type){case"space":case"comment":case"newline":break;default:return e}return-1}function eu(t){switch(t?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function Lr(t){switch(t.type){case"document":return t.start;case"block-map":{let e=t.items[t.items.length-1];return e.sep??e.start}case"block-seq":return t.items[t.items.length-1].start;default:return[]}}function wt(t){if(t.length===0)return[];let e=t.length;e:for(;--e>=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 Br(t,e){if(e.length<1e5)Array.prototype.push.apply(t,e);else for(let i=0;i<e.length;++i)t.push(e[i])}function Zl(t){if(t.start.type==="flow-seq-start")for(let e of t.items)e.sep&&!e.value&&!Me(e.start,"explicit-key-ind")&&!Me(e.sep,"map-value-ind")&&(e.key&&(e.value=e.key),delete e.key,eu(e.value)?e.value.end?Br(e.value.end,e.sep):e.value.end=e.sep:Br(e.start,e.sep),delete e.sep)}var vo=class{constructor(e){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new Ev.Lexer,this.onNewLine=e}*parse(e,i=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let r of this.lexer.lex(e,i))yield*this.next(r);i||(yield*this.end())}*next(e){if(this.source=e,Sv.env.LOG_TOKENS&&console.log("|",Xl.prettyToken(e)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=e.length;return}let i=Xl.tokenType(e);if(i)if(i==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=i,yield*this.step(),i){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+e.length);break;case"space":this.atNewLine&&e[0]===" "&&(this.indent+=e.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=e.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=e.length}else{let r=`Not a YAML token: ${e}`;yield*this.pop({type:"error",offset:this.offset,message:r,source:e}),this.offset+=e.length}}*end(){for(;this.stack.length>0;)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"&&Zl(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&&Ql(n.start)===-1&&(i.indent===0||n.start.every(a=>a.type!=="comment"||a.indent<i.indent))&&(r.type==="document"?r.end=n.start:r.items.push({start:n.start}),i.items.splice(-1,1))}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{let e={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&e.start.push(this.sourceToken),this.stack.push(e);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(e){if(e.value)return yield*this.lineEnd(e);switch(this.type){case"doc-start":{Ql(e.start)!==-1?(yield*this.pop(),yield*this.step()):e.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":e.start.push(this.sourceToken);return}let i=this.startBlockValue(e);i?this.stack.push(i):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(e){if(this.type==="map-value-ind"){let i=Lr(this.peek(2)),r=wt(i),n;e.end?(n=e.end,n.push(this.sourceToken),delete e.end):n=[this.sourceToken];let a={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:r,key:e,sep:n}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(e)}*blockScalar(e){switch(this.type){case"space":case"comment":case"newline":e.props.push(this.sourceToken);return;case"scalar":if(e.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let i=this.source.indexOf(`
|
|
139
139
|
`)+1;for(;i!==0;)this.onNewLine(this.offset+i),i=this.source.indexOf(`
|
|
140
140
|
`,i)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let i=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,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.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"space":case"comment":if(i.value)e.items.push({start:[this.sourceToken]});else if(i.sep)i.sep.push(this.sourceToken);else{if(this.atIndentedComment(i.start,e.indent)){let n=e.items[e.items.length-2]?.value?.end;if(Array.isArray(n)){Br(n,i.start),n.push(this.sourceToken),e.items.pop();return}}i.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let r=!this.onKeyLine&&this.indent===e.indent,n=r&&(i.sep||i.explicitKey)&&this.type!=="seq-item-ind",a=[];if(n&&i.sep&&!i.value){let o=[];for(let s=0;s<i.sep.length;++s){let c=i.sep[s];switch(c.type){case"newline":o.push(s);break;case"space":break;case"comment":c.indent>e.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":n||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):n||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(Me(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(eu(i.key)&&!Me(i.sep,"newline")){let o=wt(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(Me(i.start,"newline"))Object.assign(i,{key:null,sep:[this.sourceToken]});else{let o=wt(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||n?e.items.push({start:a,key:null,sep:[this.sourceToken]}):Me(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);n||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&&!Me(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: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 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)){Br(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||Me(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=Lr(r),a=wt(n);Zl(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(`
|
|
141
141
|
`)+1;for(;i!==0;)this.onNewLine(this.offset+i),i=this.source.indexOf(`
|
|
142
|
-
`,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=Lr(e),r=wt(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=Lr(e),r=wt(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())}}};tu.Parser=vo});var ou=g(fi=>{"use strict";var iu=io(),Pv=ri(),di=oi(),xv=ea(),Cv=P(),Rv=mo(),ru=go();function nu(t){let e=t.prettyErrors!==!1;return{lineCounter:t.lineCounter||e&&new Rv.LineCounter||null,prettyErrors:e}}function Av(t,e={}){let{lineCounter:i,prettyErrors:r}=nu(e),n=new ru.Parser(i?.addNewLine),a=new iu.Composer(e),o=Array.from(a.compose(n.parse(t)));if(r&&i)for(let s of o)s.errors.forEach(di.prettifyError(t,i)),s.warnings.forEach(di.prettifyError(t,i));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function au(t,e={}){let{lineCounter:i,prettyErrors:r}=nu(e),n=new ru.Parser(i?.addNewLine),a=new iu.Composer(e),o=null;for(let s of a.compose(n.parse(t),!0,t.length))if(!o)o=s;else if(o.options.logLevel!=="silent"){o.errors.push(new di.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return r&&i&&(o.errors.forEach(di.prettifyError(t,i)),o.warnings.forEach(di.prettifyError(t,i))),o}function _v(t,e,i){let r;typeof e=="function"?r=e:i===void 0&&e&&typeof e=="object"&&(i=e);let n=au(t,i);if(!n)return null;if(n.warnings.forEach(a=>xv.warn(n.options.logLevel,a)),n.errors.length>0){if(n.options.logLevel!=="silent")throw n.errors[0];n.errors=[]}return n.toJS(Object.assign({reviver:r},i))}function Tv(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 Cv.isDocument(t)&&!r?t.toString(i):new Pv.Document(t,r,i).toString(i)}fi.parse=_v;fi.parseAllDocuments=Av;fi.parseDocument=au;fi.stringify=Tv});var yt=g(x=>{"use strict";var Iv=io(),jv=ri(),$v=Ha(),wo=oi(),Ov=Ft(),Fe=P(),Hv=He(),Dv=I(),Lv=Le(),Bv=Be(),Mv=Hr(),Fv=ho(),Vv=mo(),qv=go(),Mr=ou(),su=Dt();x.Composer=Iv.Composer;x.Document=jv.Document;x.Schema=$v.Schema;x.YAMLError=wo.YAMLError;x.YAMLParseError=wo.YAMLParseError;x.YAMLWarning=wo.YAMLWarning;x.Alias=Ov.Alias;x.isAlias=Fe.isAlias;x.isCollection=Fe.isCollection;x.isDocument=Fe.isDocument;x.isMap=Fe.isMap;x.isNode=Fe.isNode;x.isPair=Fe.isPair;x.isScalar=Fe.isScalar;x.isSeq=Fe.isSeq;x.Pair=Hv.Pair;x.Scalar=Dv.Scalar;x.YAMLMap=Lv.YAMLMap;x.YAMLSeq=Bv.YAMLSeq;x.CST=Mv;x.Lexer=Fv.Lexer;x.LineCounter=Vv.LineCounter;x.Parser=qv.Parser;x.parse=Mr.parse;x.parseAllDocuments=Mr.parseAllDocuments;x.parseDocument=Mr.parseDocument;x.stringify=Mr.stringify;x.visit=su.visit;x.visitAsync=su.visitAsync});function Di(t){return["comet","native","next",t.change,"--summary","<summary>",t.flag,"--expected-state-version",String(t.stateVersion),"--expected-action",t.action]}function Li(t,e){return{name:t,flag:e,valueKind:"text",required:!0,template:null}}function Qd(t,e){return{name:t,flag:e,valueKind:"confirmation",required:!0,template:null}}function Bi(t){return{name:t.name,stateVersion:t.stateVersion,expectedAction:t.expectedAction,commandArgs:Di({change:t.change,stateVersion:t.stateVersion,action:t.expectedAction,flag:t.flag}),requiredInputs:["summary",t.confirmationInput],inputOptions:[Li("summary","--summary"),Qd(t.name,t.flag)]}}function jn(t){return[Bi({name:"revise-implementation",change:t.change,stateVersion:t.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),Bi({name:"revise-requirements",change:t.change,stateVersion:t.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function vs(t,e){let i={schema:"comet.native.continuation.v2",skill:"comet-native",change:t.name,phase:t.phase,status:t.status,stateVersion:t.state_version,inputOptions:[]},r=n=>({kind:n,candidateId:t.builder_handoff?.candidate_id??null,iteration:t.loop.iteration,attempt:t.loop.attempt});if(t.status==="done")return{...i,disposition:"done",action:"none",commandArgs:null,requiredInputs:[],runnerAction:r("none")};if(t.status==="await-user")return t.phase==="verify"&&t.verification_result==="pass"&&t.loop.next_action==="confirm-skill-coordinated-pass"?{...i,disposition:"await-user",action:"confirm-skill-coordinated-pass",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Li("summary","--summary")],commandAlternatives:[Bi({name:"accept-result",change:t.name,stateVersion:t.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...jn({change:t.name,stateVersion:t.state_version})],runnerAction:r("none")}:t.phase==="verify"&&t.verification?.assurance==="semantic-verification-unavailable"&&t.loop.next_action==="confirm-verifier-unavailable"?{...i,disposition:"await-user",action:"confirm-verifier-unavailable",commandArgs:Di({change:t.name,stateVersion:t.state_version,action:"confirm-verifier-unavailable",flag:"--confirmed"}),requiredInputs:["summary","user-confirmation"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},{name:"confirmed",flag:"--confirmed",valueKind:"confirmation",required:!0,template:null}],runnerAction:r("none")}:t.phase==="verify"&&t.loop.next_action==="resolve-verifier-blocker"?{...i,disposition:"await-user",action:"resolve-verifier-blocker",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Li("summary","--summary")],commandAlternatives:[Bi({name:"resolve-verifier-blocker",change:t.name,stateVersion:t.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...jn({change:t.name,stateVersion:t.state_version})],runnerAction:r("none")}:t.phase==="verify"&&t.loop.next_action==="await-user"?{...i,disposition:"await-user",action:"resolve-loop-stop",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Li("summary","--summary")],commandAlternatives:jn({change:t.name,stateVersion:t.state_version}),runnerAction:r("none")}:{...i,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["resolve-blocker"],runnerAction:r("none")};if(t.status==="blocked"){let n=t.blockers.some(({resolution_action:a})=>a==="retry-verifier");return{...i,disposition:"blocked",action:n?"retry-verifier":"none",commandArgs:n?Di({change:t.name,stateVersion:t.state_version,action:"retry-verifier",flag:"--retry-verifier"}):null,requiredInputs:n?["summary"]:["repair-runtime"],inputOptions:n?[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}]:[],runnerAction:r(n?"retry-verifier":"none")}}if(t.phase==="shape")return{...i,disposition:"continue",action:"confirm-shape",commandArgs:Di({change:t.name,stateVersion:t.state_version,action:"confirm-shape",flag:"--confirmed"}),requiredInputs:["summary","shared-understanding-confirmation"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},{name:"confirmed",flag:"--confirmed",valueKind:"confirmation",required:!0,template:null}],runnerAction:r("none")};if(t.phase==="build"){if(e){if(!e.confirmed)return{...i,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",t.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:r("none")};if(t.loop.stage==="repairing"&&t.verification_result==="fail")return{...i,disposition:"continue",action:"repair",commandArgs:null,requiredInputs:["repair-child"],inputOptions:[],runnerAction:r("none")};if(e.allDone)return{...i,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",t.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:r("none")};let n=e.children.some(({status:o})=>o==="blocked"),a=e.children.some(({status:o})=>o==="ready"||o==="active");return{...i,disposition:n&&!a?"blocked":"continue",action:"advance-children",commandArgs:null,requiredInputs:n&&!a?["resolve-child-blocker"]:["ready-children"],inputOptions:[],runnerAction:r("none")}}return{...i,disposition:"continue",action:t.loop.stage==="repairing"?"repair":"builder-handoff",commandArgs:["comet","native","next",t.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:["<acceptance-id>"],checks:[{name:"<check-name>",result:"not-run",note:null}],known_limits:[]}}],runnerAction:r("builder-handoff")}}if(t.phase==="verify"){let n=t.loop.next_action==="await-verifier-result";return{...i,disposition:"continue",action:n?"await-verifier":"dispatch-verifier",commandArgs:["comet","native","next",t.name,"--runner-input","<temporary-json-file>"],requiredInputs:[n?"verifier-response-or-error-json-file":"resolved-check-plan-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:n?[{kind:"verifier-response",response:{kind:"request-checks",iteration:t.loop.iteration,attempt:t.loop.attempt,checks:[{id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}]}},{kind:"verifier-response",response:{kind:"final-result",result:{iteration:t.loop.iteration,attempt:t.loop.attempt,verdict:"<pass|fail|blocked>",acceptance:[{id:"<acceptance-id>",result:"<passed|failed|blocked>",reason:"<reason>"}],risks:[],summary:"<summary>"}}},{kind:"verifier-execution-error",summary:"<summary>",stateVersion:t.state_version,iteration:t.loop.iteration,attempt:t.loop.attempt,verifierExecutionRef:"<from verifierDispatch>"},{kind:"verifier-unavailable",summary:"<why no independent semantic execution is available>",stateVersion:t.state_version,iteration:t.loop.iteration,attempt:t.loop.attempt,verifierExecutionRef:"<from verifierDispatch>"}]:{kind:"dispatch-verifier",checks:[]}}],runnerAction:r(n?"await-verifier":"dispatch-verifier")}}return{...i,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",t.name,"--confirmed"],requiredInputs:[],runnerAction:r("none")}}import{randomUUID as Yy}from"node:crypto";import{promises as ji}from"node:fs";import Xy from"node:path";import{execFileSync as Zd}from"child_process";import Mi from"path";function $n(t,e){return Zd("git",["-C",t,...e],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function ef(t,e){let i=Mi.normalize(t),r=Mi.normalize(e);return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function ke(t){try{let e=Mi.resolve($n(t,["rev-parse","--show-toplevel"])),r=$n(t,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=r?Mi.resolve(r.slice(9)):e,a=null;try{a=$n(t,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!ef(e,n),currentWorktreeRoot:e,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}import{randomUUID as tf}from"crypto";import{promises as B}from"fs";import te from"path";function Te(t){return t!==0&&t!==0n&&t!=="0"}function ue(t,e){return Te(t.dev)&&Te(e.dev)&&Te(t.ino)&&Te(e.ino)}function A(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}function On(t,e){let i=te.relative(t,e);return i===""||!te.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${te.sep}`)}function rf(t,e){return A({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function Hn(t,e){return A({dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs},{dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs})}function nf(t,e){return Hn(t,e)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.mtimeMs===e.mtimeMs&&t.size===e.size}async function gs(t){let e=await B.lstat(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Native atomic write parent must be a real directory: ${t}`);return{path:t,realPath:await B.realpath(t),dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}async function Ot(t){for(let e of t){let i=await B.lstat(e.path);if(!i.isDirectory()||i.isSymbolicLink()||!rf(e,i)||await B.realpath(e.path)!==e.realPath)throw new Error(`Native atomic write parent changed before commit: ${e.path}`)}}async function af(t,e){let i=te.resolve(t),r=te.resolve(e);if(!On(i,r))throw new Error(`Native atomic write parent is outside its managed root: ${e}`);let n=[await gs(i)],a=te.relative(i,r).split(te.sep).filter(Boolean),o=i;for(let s of a){await Ot(n),o=te.join(o,s);try{await B.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await gs(o);if(!On(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await Ot(n),n}async function of(t){let e;try{e=await B.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 sf(t,e,i={}){let r=te.dirname(t),n=i.containedRoot?await af(i.containedRoot,r):null;n||await B.mkdir(r,{recursive:!0});let a=te.join(r,`.${te.basename(t)}.${tf()}.tmp`),o,s,c;try{if(await i.beforeTemporaryOpen?.(),o=await B.open(a,"wx"),s=await o.stat(),n){let[l,f]=await Promise.all([B.lstat(a),B.realpath(a)]);if(await Ot(n),!l.isFile()||l.isSymbolicLink()||!Hn(s,l)||!On(n[0].realPath,f))throw new Error("Native 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(),c=await o.stat(),!Hn(s,c))throw new Error("Native atomic write temporary file changed while writing");if(await o.close(),o=void 0,await i.beforeCommit?.(),n){await Ot(n);let l=await B.lstat(a);if(!l.isFile()||l.isSymbolicLink()||!c||!nf(l,c))throw new Error("Native atomic write temporary file changed before commit")}i.exclusive?(await B.link(a,t),await B.unlink(a)):await B.rename(a,t),await of(r)}catch(l){if(await o?.close(),!n)await B.rm(a,{force:!0});else try{await Ot(n),await B.rm(a,{force:!0})}catch{}throw l}}async function de(t,e,i={}){await sf(t,e,i)}async function K(t,e,i={}){await de(t,JSON.stringify(e,null,2)+`
|
|
143
|
-
`,i)}import{createHash as df}from"node:crypto";import{promises as ie}from"node:fs";import Y from"node:path";import{TextDecoder as ff}from"node:util";var cf=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),lf=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function uf(t){return t.toLowerCase().startsWith(".env")}function Ht(t){let i=t.replaceAll("\\","/").split("/").filter(Boolean).map(r=>r.toLowerCase());return i.some(r=>uf(r))?"environment-file":i.some(r=>lf.has(r))?"credential-config":i.includes(".git")?"git-metadata":i.some(r=>cf.has(r))?"dependency-or-cache":i.join("/")===".comet/config.yaml"?"comet-config":i.join("/")===".comet/current-change.json"?"comet-selection":null}var Vi=1024*1024;function Dn(t,e){let i=Y.relative(t,e);return i===""||!Y.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Y.sep}`)}function hf(t){let e=Y.posix.normalize(t);if(t.length===0||t!==t.trim()||t.includes("\\")||Array.from(t).some(n=>{let a=n.codePointAt(0)??0;return a<=31||a===127})||Y.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=Ht(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 pf(t){if(!Number.isSafeInteger(t)||t<1)throw new Error("Native artifact byte limit must be a positive integer");return t}function mf(t,e){return A({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function Fi(t,e){let i={...t,birthtime:t.birthtimeMs},r={...e,birthtime:e.birthtimeMs};return ue(i,r)?A(i,r):A(i,r)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.size===e.size}async function ws(t){let e=await ie.lstat(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${t}`);return{path:t,realPath:await ie.realpath(t),dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}async function vf(t,e){let i=Y.resolve(t),r=Y.resolve(e);if(!Dn(i,r))throw new Error("Native artifact path is outside its root");let n=[await ws(i)],a=i;for(let o of Y.relative(i,r).split(Y.sep).filter(Boolean)){a=Y.join(a,o);let s=await ws(a);if(!Dn(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function ys(t){for(let e of t){let i=await ie.lstat(e.path);if(!i.isDirectory()||i.isSymbolicLink()||!mf(e,i)||await ie.realpath(e.path)!==e.realPath)throw new Error(`Native artifact parent changed while reading: ${e.path}`)}}async function M(t){let e=hf(t.ref),i=t.maxBytes===null?null:pf(t.maxBytes??Vi),r=Y.resolve(t.root,...e.split("/")),n=await vf(t.root,Y.dirname(r));await t.hooks?.afterParentChainCaptured?.();let a=await ie.lstat(r);if(!a.isFile()||a.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${e}`);if(i!==null&&a.size>i)throw new Error(`Native artifact exceeds ${i} bytes: ${e}`);let o=await ie.realpath(r);if(!Dn(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${e}`);let s=await ie.open(r,"r");try{let[c,l,f]=await Promise.all([s.stat(),ie.lstat(r),ie.realpath(r)]);if(await ys(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||f!==o||!Fi(a,c)||!Fi(c,l))throw new Error(`Native artifact changed while opening: ${e}`);await t.hooks?.afterOpen?.();let d=[],u=0,p=Buffer.allocUnsafe(i===null?64*1024:Math.min(64*1024,i+1));for(;;){let b=i===null?p.length:i+1-u,k=await s.read(p,0,Math.min(p.length,b),null);if(k.bytesRead===0)break;if(u+=k.bytesRead,i!==null&&u>i)throw new Error(`Native artifact exceeds ${i} bytes: ${e}`);d.push(Buffer.from(p.subarray(0,k.bytesRead)))}await t.hooks?.beforeFinalCheck?.();let[v,h,m]=await Promise.all([s.stat(),ie.lstat(r),ie.realpath(r)]);if(await ys(n),!h.isFile()||h.isSymbolicLink()||m!==o||!Fi(c,v)||!Fi(c,h))throw new Error(`Native artifact changed while reading: ${e}`);let w=Buffer.concat(d,u),y;try{y=new ff("utf-8",{fatal:!0}).decode(w)}catch(b){throw new Error(`Native artifact is not valid UTF-8: ${e}`,{cause:b})}return{ref:e,size:u,hash:t.includeHash===!1?null:df("sha256").update(w).digest("hex"),text:y}}finally{await s.close()}}var as=$t(yt(),1);import Tt from"path";var No=$t(yt(),1);import Nt from"path";var hi=64*1024,Fr=1024,Vr=64,bo=5,Wv=12e4,cu=6e5,zv=[".agents/skills/**",".amazonq/skills/**",".augment/skills/**",".bob/skills/**",".claude/skills/**",".cline/skills/**",".codebuddy/skills/**",".workbuddy/skills/**",".continue/skills/**",".cospec/skills/**",".crush/skills/**",".cursor/skills/**",".factory/skills/**",".forge/skills/**",".gemini/skills/**",".github/skills/**",".grok/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/**"],Jv=["**/.idea/**","**/.vscode/**",".codex/skills/**","**/node_modules/**","**/.next/**","**/.nuxt/**","**/.output/**","**/.svelte-kit/**","**/.vite/**","**/.parcel-cache/**","**/.turbo/**","**/.nx/cache/**","**/dist/**","**/build/**","**/out/**","**/coverage/**","**/.nyc_output/**","**/target/**","**/.gradle/**","**/.cxx/**","**/.externalNativeBuild/**","**/captures/**","**/__pycache__/**","**/.pytest_cache/**","**/.mypy_cache/**","**/.ruff_cache/**","**/.tox/**","**/.nox/**","**/.venv/**","**/venv/**","**/obj/**","**/CMakeFiles/**","**/cmake-build-*/**","**/.cache/**","**/tmp/**","**/temp/**","**/logs/**","**/*.tsbuildinfo","**/*.log","**/.DS_Store","**/Thumbs.db"],Gv=[...zv,...Jv].sort((t,e)=>t.localeCompare(e,"en"));var G={include:["**/*"],exclude:[...Gv],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4};function Uv(t,e){if(typeof t!="string")throw new Error(`${e} must be a string`);let i=t.trim();if(i.length===0||Nt.posix.isAbsolute(i)||Nt.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 Ze(t){let e=Uv(t,"native.artifact_root");return e.length===0?".":e.join("/")}function uu(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 qr(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||Nt.posix.isAbsolute(r)||Nt.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(a=>a===".."))throw new Error(`${e} must stay inside its declared path base`);if(n.some(a=>a===""||a==="."))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 Ve(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function du(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 ko(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>Fr)throw new Error(`${e} exceeds ${Fr} characters`);let i=0;for(let r=0;r<t.length;r+=1)t[r]==="?"?i+=1:t[r]==="*"&&(i+=1,t[r+1]==="*"&&(r+=1));if(i>Vr)throw new Error(`${e} contains more than ${Vr} wildcard tokens`);return t}function lu(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=>ko(r,e)))].sort((r,n)=>r.localeCompare(n,"en"))}function yo(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 Kv(t){if(t===void 0)return{...G,include:[...G.include],exclude:[...G.exclude]};let e=Ve(t,"native.snapshot");return{include:lu(e.include,"native.snapshot.include",G.include),exclude:lu(e.exclude,"native.snapshot.exclude",G.exclude),max_files:yo(e.max_files,G.max_files,"native.snapshot.max_files"),max_total_bytes:yo(e.max_total_bytes,G.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:yo(e.max_duration_ms,G.max_duration_ms,"native.snapshot.max_duration_ms")}}function Yv(t){if(t===void 0)return;let e=Ve(t,"native.pending_root_move"),i=e.id,r=e.from_artifact_root,n=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 r!="string"||typeof n!="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=Ve(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");o={kind:c,state:l,manifestHash:f}}return{id:i,fromArtifactRoot:Ze(r),toArtifactRoot:Ze(n),stage:a,...o?{cleanup:o}:{}}}function Xv(t){if(t===void 0)return;let e=Ve(t,"native.finish");if(e.pull_request===void 0)return{};let i=Ve(e.pull_request,"native.finish.pull_request");if(i.provider!=="repository-command")throw new Error("native.finish.pull_request.provider must be repository-command");if(!Array.isArray(i.command)||i.command.length===0)throw new Error("native.finish.pull_request.command must be a non-empty array");if(i.command.length>64)throw new Error("native.finish.pull_request.command must contain at most 64 arguments");let r=i.command.map((a,o)=>{if(typeof a!="string"||a.trim().length===0||a.length>4096||/[\0\r\n]/u.test(a))throw new Error(`native.finish.pull_request.command[${o}] must be a non-empty single-line string of at most 4096 characters`);return a});if(Nt.posix.isAbsolute(r[0])||Nt.win32.isAbsolute(r[0]))throw new Error("native.finish.pull_request.command[0] must be a bare executable name or a project-relative path");let n=i.timeout_ms??Wv;if(!Number.isSafeInteger(n)||n<1||n>cu)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${cu}`);return{pull_request:{provider:"repository-command",command:r,timeout_ms:n}}}function Qv(t,e={}){let i=Ve(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??"batch";if(n!=="sequential"&&n!=="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??bo;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=Yv(i.pending_root_move),c=Xv(i.finish);return{artifact_root:Ze(r),language:du(i.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,snapshot:Kv(i.snapshot),...c?{finish:c}:{},...s?{pending_root_move:s}:{}}}function Zv(t){let e=Ve(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:uu(e.artifact_layout),language:du(e.language,"zh-CN","classic.language"),context_compression:i,review_mode:r,auto_transition:n}}function eg(t){let i=Ve(t,"hook").allow_paths??[];if(!Array.isArray(i))throw new Error("hook.allow_paths must be an array");return{allow_paths:[...new Set(i.map((r,n)=>qr(r,`hook.allow_paths[${n}]`)))]}}function tg(t){let e=t??!0;if(typeof e!="boolean")throw new Error("ambient_resume must be true or false");return e}function ig(t,e,i,r,n,a){let o=t.schema!==void 0;if(!(o||t.default_workflow!==void 0||t.workflows!==void 0||!a.allowPartialProject&&t.native!==void 0)||a.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 c=t.workflows??[t.default_workflow];if(!Array.isArray(c)||c.length===0||c.some(f=>f!=="native"&&f!=="classic"))throw new Error("workflows must contain native and/or classic");let l=[...new Set(c)];if(!l.includes(t.default_workflow))throw new Error("workflows must include default_workflow");if(l.includes("native")&&!i)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:t.default_workflow,workflows:l,ambient_resume:n,...e?{hook:e}:{},...i?{native:i}:{},...r?{classic:r}:{}}}function pi(t,e={}){let i=(0,No.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,a=tg(n.ambient_resume),o=n.hook===void 0?void 0:eg(n.hook),s=n.native===void 0?void 0:Qv(n.native,{allowMissingArtifactRoot:e.allowMissingNativeFields}),c=n.classic===void 0?void 0:Zv(n.classic),l=ig(n,o,s,c,a,{allowPartialProject:e.allowPartialProject??!1});return{value:n,config:l,ambient_resume:a,...o?{hook:o}:{},...s?{native:s}:{},...c?{classic:c}:{}}}function Wr(t="docs",e="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,native:{artifact_root:Ze(t),language:e,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:bo,snapshot:{...G,include:[...G.include],exclude:[...G.exclude]}}}}import{createHash as ng}from"crypto";import{promises as Gr}from"fs";import qe from"path";import{constants as zr,promises as et}from"fs";var ae=class extends Error{reason;constructor(e,i,r){super(i,r),this.name="RaceSafeReadError",this.reason=e}};function So(t){return"birthtimeNs"in t&&typeof t.birthtimeNs=="bigint"?t.birthtimeNs:t.birthtimeMs}function fu(t){return"ctimeNs"in t&&typeof t.ctimeNs=="bigint"?t.ctimeNs:t.ctimeMs}function mi(t){return{dev:t.dev,ino:t.ino,birthtime:So(t)}}function Jr(t,e){let i=mi(t),r=mi(e);return ue(i,r)?A(i,r):A(i,r)&&So(t)===So(e)&&fu(t)===fu(e)&&t.size===e.size}async function bt(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,a=await et.lstat(t,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new ae("not-regular-file",`${r} must be a regular file`);if(BigInt(a.size)>BigInt(e))throw new ae("too-large",`${r} exceeds ${e} bytes`);let o=await et.realpath(t);await i.verify?.("pre-open",{realPath:o,identity:mi(a)});let s=process.platform==="win32"?zr.O_RDONLY:zr.O_RDONLY|zr.O_NOFOLLOW|zr.O_NONBLOCK,c;try{c=await et.open(t,s)}catch(l){throw l.code==="ELOOP"?new ae("not-regular-file",`${r} must be a regular file`,{cause:l}):l}try{let[l,f,d]=await Promise.all([c.stat({bigint:n}),et.lstat(t,{bigint:n}),et.realpath(t)]);if(!l.isFile()||!f.isFile()||f.isSymbolicLink()||d!==o||!Jr(a,l)||!Jr(a,f))throw new ae("changed",`${r} changed while opening`);await i.verify?.("post-open",{realPath:d,identity:mi(l)}),await i.hooks?.afterOpen?.();let u=[],p=0,v=Buffer.allocUnsafe(Math.min(64*1024,e+1));for(;;){let y=e+1-p,{bytesRead:b}=await c.read(v,0,Math.min(v.length,y),null);if(b===0)break;if(p+=b,p>e)throw new ae("too-large",`${r} exceeds ${e} bytes`);u.push(Buffer.from(v.subarray(0,b)))}await i.hooks?.beforeFinalCheck?.();let[h,m,w]=await Promise.all([c.stat({bigint:n}),et.lstat(t,{bigint:n}),et.realpath(t)]);if(!m.isFile()||m.isSymbolicLink()||w!==o||!Jr(a,h)||!Jr(a,m))throw new ae("changed",`${r} changed while reading`);return await i.verify?.("post-read",{realPath:w,identity:mi(h)}),{bytes:Buffer.concat(u,p),stat:h,realPath:w}}finally{await c.close()}}function rg(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}function Eo(t,e){let i=qe.relative(t,e);return i===""||!qe.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${qe.sep}`)}async function hu(t,e){let i=qe.resolve(t),r=await Gr.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${e} project root must be a real directory`);return Gr.realpath(i)}async function pu(t,e,i,r){let n=t;for(let a=0;a<i.length;a++){n=qe.join(n,i[a]);let o;try{o=await Gr.lstat(n)}catch(f){if(rg(f))return{exists:!1,kind:"missing"};throw f}let s=qe.relative(t,n).replaceAll("\\","/");if(o.isSymbolicLink())throw new Error(`${r.label} crosses a symbolic link or junction at ${s}`);let c=a===i.length-1;if(!c&&!o.isDirectory())throw new Error(`${r.label} ancestor ${s} must be a real directory`);if(c&&(r.expected==="file"&&!o.isFile()||r.expected==="directory"&&!o.isDirectory()||r.expected==="any"&&!o.isFile()&&!o.isDirectory()))throw new Error(`${r.label} must be a real ${r.expected}`);let l=await Gr.realpath(n);if(!Eo(e,l))throw new Error(`${r.label} resolves outside the project root`);if(c)return{exists:!0,kind:o.isFile()?"file":o.isDirectory()?"directory":"missing"}}return{exists:!0,kind:"directory"}}async function kt(t,e,i){let r=qr(e,i.label),n=qe.resolve(t),a=await hu(n,i.label),o=r.split("/"),s=qe.resolve(n,...o);if(!Eo(n,s))throw new Error(`${i.label} must stay inside the project root`);let c=await pu(n,a,o,i);return{projectRoot:n,target:s,relative:r,exists:c.exists,kind:c.kind}}async function We(t,e,i,r){let n=await kt(t,e,{label:r.label,expected:"file"});if(!n.exists){let o=new Error(`${r.label} does not exist`);throw o.code="ENOENT",o}let a=await hu(n.projectRoot,r.label);return bt(n.target,i,{...r,verify:async(o,s)=>{if(!Eo(a,s.realPath))throw new Error(`${r.label} resolves outside the project root`);await pu(n.projectRoot,a,n.relative.split("/"),{label:r.label,expected:"file"})}})}var vi=".comet/config.yaml";function ag(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function Ur(t,e={}){return(await Kr(t,e)).document}async function og(t){try{return(await We(t,vi,hi,{label:vi})).bytes}catch(e){if(ag(e))return null;throw e}}function sg(t){return t?{exists:!0,sha256:ng("sha256").update(t).digest("hex")}:{exists:!1,sha256:null}}async function Kr(t,e={}){let i=await og(t);return{document:i?pi(i.toString("utf8"),e):null,identity:sg(i)}}async function Po(t){return(await Ur(t))?.config??null}var Jk=16*1024;import{existsSync as vu,promises as tt}from"fs";import C from"path";import fg from"os";var Yr=".comet/config.yaml",hg=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;async function Ro(t){try{return await tt.lstat(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function pg(t){try{let e=await tt.readFile(t,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(e)}catch(e){if(e.code==="ENOENT")return!1;throw e}}function Et(t,e){let i=C.relative(t,e);return i===""||!C.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${C.sep}`)}async function St(t){let e=[],i=t;for(;!await Ro(i);){let n=C.dirname(i);if(n===i)break;e.push(C.basename(i)),i=n}let r=await tt.realpath(i);return C.resolve(r,...e.reverse())}async function Ao(t){try{return(await tt.lstat(t)).isSymbolicLink()}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function Xr(t){let e=C.resolve(t);try{(await tt.stat(e)).isDirectory()||(e=C.dirname(e))}catch(n){if(n.code!=="ENOENT")throw n}let i=e,r=C.resolve(fg.homedir());for(;;){if(!(e===r&&i!==r)){let o=C.join(e,...Yr.split("/")),s=e===i||await pg(o);if(await Ro(o)&&s)return e}if(await Ro(C.join(e,".git")))return e;let a=C.dirname(e);if(a===e)return i;e=a}}function Qr(t){return Ze(t)}async function mg(t,e){let i=Qr(e),r=C.resolve(t,...i.split("/")),n=await tt.realpath(t),a=await St(r);if(!Et(n,a))throw new Error("native.artifact_root resolves outside the project root");return r}async function Pt(t,e){let i=Qr(e),r=await mg(t,i),n=C.join(r,"comet");if(await Ao(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([St(r),St(n)]);if(!Et(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=C.resolve(t),c=C.join(s,".comet","runtime","native");if(await Ao(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,f]=await Promise.all([tt.realpath(s),St(c)]);if(!Et(l,f))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:C.join(t,...Yr.split("/")),artifactRoot:r,artifactRootRef:i,nativeRoot:n,specsDir:C.join(n,"specs"),changesDir:C.join(n,"changes"),archiveDir:C.join(n,"archive"),runtimeDir:c,changesRuntimeDir:C.join(c,"changes"),locksDir:C.join(c,"locks"),transactionsDir:C.join(c,"transactions")}}function gu(t){if(!hg.test(t))throw new Error(`Invalid Native change name: ${t}`)}function it(t,e){gu(e);let i=C.join(t.changesRuntimeDir,e);if(!F(t.changesRuntimeDir,i))throw new Error("Native change Runtime path escaped");return i}function _o(t,e){gu(e);let i=C.join(t.changesDir,e,"runtime");if(!F(t.changesDir,i))throw new Error("Legacy Native change Runtime path escaped");return i}function pe(t,e){let i=it(t,e);if(vu(i))return i;let r=_o(t,e);return vu(r)?r:i}function me(t,e){let i=C.resolve(e);if(F(t.runtimeDir,i))return t.runtimeDir;if(F(t.nativeRoot,i))return t.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${e}`)}function F(t,e){return Et(C.resolve(t),C.resolve(e))}async function T(t,e){let i=C.resolve(t),r=C.resolve(e);if(!Et(i,r))throw new Error(`Path is outside the Native root: ${e}`);if(await Ao(i))throw new Error(`Native root must not be a symbolic link: ${t}`);let[n,a]=await Promise.all([St(i),St(r)]);if(!Et(n,a))throw new Error(`Path resolves outside the Native root: ${e}`);return r}function gg(t="docs",e="en"){return Wr(t,e)}async function Pe(t){let e=(await Ur(t))?.config??null;return e?.native?e:null}async function Zr(t){let e=await Pe(t);if(e?.native.pending_root_move)throw new Error(`Native root move ${e.native.pending_root_move.id} is incomplete; use comet native doctor --repair`)}async function wu(t){let e=await Xr(t.startPath),i=await Pe(e);if(!i&&t.allowMissingConfig===!1)throw new Error(`${Yr} 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 r=t.explicitArtifactRoot?Qr(t.explicitArtifactRoot):void 0;if(i&&r&&r!==i.native.artifact_root)throw new Error(`Configured Native artifact root is ${i.native.artifact_root}; refusing conflicting root ${r}`);let n=i??gg(r??"docs"),a=await Pt(e,n.native.artifact_root);return{config:n,paths:a,configured:i!==null}}import{promises as Uw}from"fs";import Kw from"path";import{AsyncLocalStorage as wg}from"async_hooks";import{randomUUID as bu}from"crypto";import{promises as Q}from"fs";import ku from"os";import V from"path";var yu=16*1024,Su=".coordinator",yg=5e3,Nu=new wg,en=new Map;function Ng(t){if(!/^[a-z][a-z0-9-]*$/u.test(t))throw new Error(`Invalid Native lock name: ${t}`);return`${t}.lock`}function bg(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`Invalid Native lock metadata: ${e}`);let i=t;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: ${e}`);return i}function Eu(t){return{device:t.dev.toString(),inode:t.ino.toString(),size:t.size.toString(),birthtimeNs:t.birthtimeNs.toString(),ctimeNs:t.ctimeNs.toString(),mtimeNs:t.mtimeNs.toString()}}function To(t,e){let i={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs},r={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs};return ue(i,r)?A(i,r):A(i,r)&&t.size===e.size}function Io(t,e){return To(t,e)&&t.size===e.size&&t.birthtimeNs===e.birthtimeNs&&t.ctimeNs===e.ctimeNs&&t.mtimeNs===e.mtimeNs}async function xe(t){let e,i;try{let r=await bt(t,yu,{bigint:!0,label:"Native lock"});e=r.bytes,i=r.stat}catch(r){if(r.code==="ENOENT")return null;throw r instanceof ae?r.reason==="too-large"?new Error(`Native lock metadata exceeds ${yu} bytes: ${t}`,{cause:r}):r.reason==="not-regular-file"?new Error(`Native lock must be a regular file: ${t}`,{cause:r}):new Error(`Native lock changed while reading: ${t}`,{cause:r}):r}return{file:t,owner:bg(JSON.parse(e.toString("utf8")),t),identity:Eu(i)}}async function kg(t){return(await xe(t))?.owner??null}function Pu(t){if(!t)return{status:"missing",owner:null,identity:null};if(t.owner.hostname!==ku.hostname())return{status:"unknown",owner:t.owner,identity:t.identity};let e=Rg(t.owner.pid);return{status:e===!0?"active":e===!1?"stale":"unknown",owner:t.owner,identity:t.identity}}async function Sg(t,e){try{await Q.lstat(e);return}catch(i){if(i.code!=="ENOENT")throw i}try{await Q.rename(t,e)}catch(i){if(i.code!=="ENOENT")throw i}}async function jo(t,e){let i=await xe(t.file);if(!i)return"missing";if(i.owner.id!==t.owner.id)throw new Error(`Native lock ownership changed: ${t.file}`);if(!Io(i.identity,t.identity))throw new Error(`Native lock identity changed: ${t.file}`);await Q.mkdir(e,{recursive:!0});let r=V.join(e,`${V.basename(t.file)}.${t.owner.id}.${bu()}.removed`);try{await Q.rename(t.file,r)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await xe(r);if(!n||n.owner.id!==t.owner.id||!To(n.identity,t.identity))throw await Sg(r,t.file),new Error(`Native lock changed before quarantine: ${t.file}`);return await Q.rm(r,{force:!0}),"removed"}function xu(t){return{id:bu(),pid:process.pid,hostname:ku.hostname(),createdAt:new Date().toISOString(),operation:t}}async function Cu(t,e){let i;try{i=await Q.open(t,"wx")}catch(r){if(r.code==="EEXIST"){let n=await kg(t);throw new Error(`Native lock is already held: ${t}${n?` by pid ${n.pid} for ${n.operation}`:""}`,{cause:r})}throw r}try{return await i.writeFile(JSON.stringify(e,null,2)+`
|
|
142
|
+
`,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=Lr(e),r=wt(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=Lr(e),r=wt(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())}}};tu.Parser=vo});var ou=g(hi=>{"use strict";var iu=io(),Pv=ni(),fi=si(),xv=ea(),Cv=P(),Rv=mo(),ru=go();function nu(t){let e=t.prettyErrors!==!1;return{lineCounter:t.lineCounter||e&&new Rv.LineCounter||null,prettyErrors:e}}function Av(t,e={}){let{lineCounter:i,prettyErrors:r}=nu(e),n=new ru.Parser(i?.addNewLine),a=new iu.Composer(e),o=Array.from(a.compose(n.parse(t)));if(r&&i)for(let s of o)s.errors.forEach(fi.prettifyError(t,i)),s.warnings.forEach(fi.prettifyError(t,i));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function au(t,e={}){let{lineCounter:i,prettyErrors:r}=nu(e),n=new ru.Parser(i?.addNewLine),a=new iu.Composer(e),o=null;for(let s of a.compose(n.parse(t),!0,t.length))if(!o)o=s;else if(o.options.logLevel!=="silent"){o.errors.push(new fi.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return r&&i&&(o.errors.forEach(fi.prettifyError(t,i)),o.warnings.forEach(fi.prettifyError(t,i))),o}function _v(t,e,i){let r;typeof e=="function"?r=e:i===void 0&&e&&typeof e=="object"&&(i=e);let n=au(t,i);if(!n)return null;if(n.warnings.forEach(a=>xv.warn(n.options.logLevel,a)),n.errors.length>0){if(n.options.logLevel!=="silent")throw n.errors[0];n.errors=[]}return n.toJS(Object.assign({reviver:r},i))}function Tv(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 Cv.isDocument(t)&&!r?t.toString(i):new Pv.Document(t,r,i).toString(i)}hi.parse=_v;hi.parseAllDocuments=Av;hi.parseDocument=au;hi.stringify=Tv});var yt=g(x=>{"use strict";var Iv=io(),jv=ni(),$v=Ha(),wo=si(),Ov=Vt(),Fe=P(),Hv=He(),Dv=I(),Lv=Le(),Bv=Be(),Mv=Hr(),Fv=ho(),Vv=mo(),qv=go(),Mr=ou(),su=Lt();x.Composer=Iv.Composer;x.Document=jv.Document;x.Schema=$v.Schema;x.YAMLError=wo.YAMLError;x.YAMLParseError=wo.YAMLParseError;x.YAMLWarning=wo.YAMLWarning;x.Alias=Ov.Alias;x.isAlias=Fe.isAlias;x.isCollection=Fe.isCollection;x.isDocument=Fe.isDocument;x.isMap=Fe.isMap;x.isNode=Fe.isNode;x.isPair=Fe.isPair;x.isScalar=Fe.isScalar;x.isSeq=Fe.isSeq;x.Pair=Hv.Pair;x.Scalar=Dv.Scalar;x.YAMLMap=Lv.YAMLMap;x.YAMLSeq=Bv.YAMLSeq;x.CST=Mv;x.Lexer=Fv.Lexer;x.LineCounter=Vv.LineCounter;x.Parser=qv.Parser;x.parse=Mr.parse;x.parseAllDocuments=Mr.parseAllDocuments;x.parseDocument=Mr.parseDocument;x.stringify=Mr.stringify;x.visit=su.visit;x.visitAsync=su.visitAsync});function Li(t){return["comet","native","next",t.change,"--summary","<summary>",t.flag,"--expected-state-version",String(t.stateVersion),"--expected-action",t.action]}function Bi(t,e){return{name:t,flag:e,valueKind:"text",required:!0,template:null}}function Qd(t,e){return{name:t,flag:e,valueKind:"confirmation",required:!0,template:null}}function Ot(t){return{name:t.name,stateVersion:t.stateVersion,expectedAction:t.expectedAction,commandArgs:Li({change:t.change,stateVersion:t.stateVersion,action:t.expectedAction,flag:t.flag}),requiredInputs:["summary",t.confirmationInput],inputOptions:[Bi("summary","--summary"),Qd(t.name,t.flag)]}}function jn(t){return[Ot({name:"revise-implementation",change:t.change,stateVersion:t.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),Ot({name:"revise-requirements",change:t.change,stateVersion:t.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function vs(t,e){let i={schema:"comet.native.continuation.v2",skill:"comet-native",change:t.name,phase:t.phase,status:t.status,stateVersion:t.state_version,inputOptions:[]},r=n=>({kind:n,candidateId:t.builder_handoff?.candidate_id??null,iteration:t.loop.iteration,attempt:t.loop.attempt});if(t.status==="done")return{...i,disposition:"done",action:"none",commandArgs:null,requiredInputs:[],runnerAction:r("none")};if(t.status==="await-user")return t.phase==="verify"&&t.verification_result==="pass"&&t.loop.next_action==="confirm-skill-coordinated-pass"?{...i,disposition:"await-user",action:"confirm-skill-coordinated-pass",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Bi("summary","--summary")],commandAlternatives:[Ot({name:"accept-result",change:t.name,stateVersion:t.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...jn({change:t.name,stateVersion:t.state_version})],runnerAction:r("none")}:t.phase==="verify"&&t.verification?.assurance==="semantic-verification-unavailable"&&t.loop.next_action==="confirm-verifier-unavailable"?{...i,disposition:"await-user",action:"confirm-verifier-unavailable",commandArgs:Li({change:t.name,stateVersion:t.state_version,action:"confirm-verifier-unavailable",flag:"--confirmed"}),requiredInputs:["summary","user-confirmation"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},{name:"confirmed",flag:"--confirmed",valueKind:"confirmation",required:!0,template:null}],runnerAction:r("none")}:t.phase==="verify"&&t.loop.next_action==="resolve-verifier-blocker"?{...i,disposition:"await-user",action:"resolve-verifier-blocker",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Bi("summary","--summary")],commandAlternatives:[Ot({name:"resolve-verifier-blocker",change:t.name,stateVersion:t.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...jn({change:t.name,stateVersion:t.state_version})],runnerAction:r("none")}:t.phase==="verify"&&t.loop.next_action==="await-user"?{...i,disposition:"await-user",action:"resolve-loop-stop",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Bi("summary","--summary")],commandAlternatives:jn({change:t.name,stateVersion:t.state_version}),runnerAction:r("none")}:{...i,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["resolve-blocker"],runnerAction:r("none")};if(t.status==="blocked"){let n=t.blockers.some(({resolution_action:a})=>a==="retry-verifier");return{...i,disposition:"blocked",action:n?"retry-verifier":"none",commandArgs:n?Li({change:t.name,stateVersion:t.state_version,action:"retry-verifier",flag:"--retry-verifier"}):null,requiredInputs:n?["summary"]:["repair-runtime"],inputOptions:n?[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}]:[],runnerAction:r(n?"retry-verifier":"none")}}if(t.phase==="shape")return{...i,disposition:"continue",action:"confirm-shape",commandArgs:Li({change:t.name,stateVersion:t.state_version,action:"confirm-shape",flag:"--confirmed"}),requiredInputs:["summary","shared-understanding-confirmation"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},{name:"confirmed",flag:"--confirmed",valueKind:"confirmation",required:!0,template:null}],runnerAction:r("none")};if(t.phase==="build"){if(e){if(!e.confirmed)return{...i,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",t.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:r("none")};if(t.loop.stage==="repairing"&&t.verification_result==="fail")return{...i,disposition:"continue",action:"repair",commandArgs:null,requiredInputs:["repair-child"],inputOptions:[],runnerAction:r("none")};if(e.allDone)return{...i,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",t.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:r("none")};let n=e.children.some(({status:o})=>o==="blocked"),a=e.children.some(({status:o})=>o==="ready"||o==="active");return{...i,disposition:n&&!a?"blocked":"continue",action:"advance-children",commandArgs:null,requiredInputs:n&&!a?["resolve-child-blocker"]:["ready-children"],inputOptions:[],runnerAction:r("none")}}return{...i,disposition:"continue",action:t.loop.stage==="repairing"?"repair":"builder-handoff",commandArgs:["comet","native","next",t.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:["<acceptance-id>"],checks:[{name:"<check-name>",result:"not-run",note:null}],known_limits:[]}}],runnerAction:r("builder-handoff")}}if(t.phase==="verify"){let n=t.loop.next_action==="await-verifier-result";return{...i,disposition:"continue",action:n?"await-verifier":"dispatch-verifier",commandArgs:["comet","native","next",t.name,"--runner-input","<temporary-json-file>"],requiredInputs:[n?"verifier-response-or-error-json-file":"resolved-check-plan-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:n?[{kind:"verifier-response",response:{kind:"request-checks",iteration:t.loop.iteration,attempt:t.loop.attempt,checks:[{id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}]}},{kind:"verifier-response",response:{kind:"final-result",result:{iteration:t.loop.iteration,attempt:t.loop.attempt,verdict:"<pass|fail|blocked>",acceptance:[{id:"<acceptance-id>",result:"<passed|failed|blocked>",reason:"<reason>"}],risks:[],summary:"<summary>"}}},{kind:"verifier-execution-error",summary:"<summary>",stateVersion:t.state_version,iteration:t.loop.iteration,attempt:t.loop.attempt,verifierExecutionRef:"<from verifierDispatch>"},{kind:"verifier-unavailable",summary:"<why no independent semantic execution is available>",stateVersion:t.state_version,iteration:t.loop.iteration,attempt:t.loop.attempt,verifierExecutionRef:"<from verifierDispatch>"}]:{kind:"dispatch-verifier",checks:[]}}],runnerAction:r(n?"await-verifier":"dispatch-verifier")}}return t.phase==="archive"&&t.status==="active"&&t.loop.stage==="archive-ready"&&!t.archived?{...i,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",t.name,"--confirmed"],requiredInputs:[],commandAlternatives:[Ot({name:"revise-requirements",change:t.name,stateVersion:t.state_version,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})],runnerAction:r("none")}:{...i,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",t.name,"--confirmed"],requiredInputs:[],runnerAction:r("none")}}import{randomUUID as Ky}from"node:crypto";import{promises as $i}from"node:fs";import Yy from"node:path";import{execFileSync as Zd}from"child_process";import Mi from"path";function $n(t,e){return Zd("git",["-C",t,...e],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function ef(t,e){let i=Mi.normalize(t),r=Mi.normalize(e);return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function ke(t){try{let e=Mi.resolve($n(t,["rev-parse","--show-toplevel"])),r=$n(t,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=r?Mi.resolve(r.slice(9)):e,a=null;try{a=$n(t,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!ef(e,n),currentWorktreeRoot:e,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}import{randomUUID as tf}from"crypto";import{promises as B}from"fs";import te from"path";function Te(t){return t!==0&&t!==0n&&t!=="0"}function ue(t,e){return Te(t.dev)&&Te(e.dev)&&Te(t.ino)&&Te(e.ino)}function A(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}function On(t,e){let i=te.relative(t,e);return i===""||!te.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${te.sep}`)}function rf(t,e){return A({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function Hn(t,e){return A({dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs},{dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs})}function nf(t,e){return Hn(t,e)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.mtimeMs===e.mtimeMs&&t.size===e.size}async function gs(t){let e=await B.lstat(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Native atomic write parent must be a real directory: ${t}`);return{path:t,realPath:await B.realpath(t),dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}async function Ht(t){for(let e of t){let i=await B.lstat(e.path);if(!i.isDirectory()||i.isSymbolicLink()||!rf(e,i)||await B.realpath(e.path)!==e.realPath)throw new Error(`Native atomic write parent changed before commit: ${e.path}`)}}async function af(t,e){let i=te.resolve(t),r=te.resolve(e);if(!On(i,r))throw new Error(`Native atomic write parent is outside its managed root: ${e}`);let n=[await gs(i)],a=te.relative(i,r).split(te.sep).filter(Boolean),o=i;for(let s of a){await Ht(n),o=te.join(o,s);try{await B.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await gs(o);if(!On(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await Ht(n),n}async function of(t){let e;try{e=await B.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 sf(t,e,i={}){let r=te.dirname(t),n=i.containedRoot?await af(i.containedRoot,r):null;n||await B.mkdir(r,{recursive:!0});let a=te.join(r,`.${te.basename(t)}.${tf()}.tmp`),o,s,c;try{if(await i.beforeTemporaryOpen?.(),o=await B.open(a,"wx"),s=await o.stat(),n){let[l,f]=await Promise.all([B.lstat(a),B.realpath(a)]);if(await Ht(n),!l.isFile()||l.isSymbolicLink()||!Hn(s,l)||!On(n[0].realPath,f))throw new Error("Native 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(),c=await o.stat(),!Hn(s,c))throw new Error("Native atomic write temporary file changed while writing");if(await o.close(),o=void 0,await i.beforeCommit?.(),n){await Ht(n);let l=await B.lstat(a);if(!l.isFile()||l.isSymbolicLink()||!c||!nf(l,c))throw new Error("Native atomic write temporary file changed before commit")}i.exclusive?(await B.link(a,t),await B.unlink(a)):await B.rename(a,t),await of(r)}catch(l){if(await o?.close(),!n)await B.rm(a,{force:!0});else try{await Ht(n),await B.rm(a,{force:!0})}catch{}throw l}}async function de(t,e,i={}){await sf(t,e,i)}async function K(t,e,i={}){await de(t,JSON.stringify(e,null,2)+`
|
|
143
|
+
`,i)}import{createHash as df}from"node:crypto";import{promises as ie}from"node:fs";import Y from"node:path";import{TextDecoder as ff}from"node:util";var cf=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),lf=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function uf(t){return t.toLowerCase().startsWith(".env")}function Dt(t){let i=t.replaceAll("\\","/").split("/").filter(Boolean).map(r=>r.toLowerCase());return i.some(r=>uf(r))?"environment-file":i.some(r=>lf.has(r))?"credential-config":i.includes(".git")?"git-metadata":i.some(r=>cf.has(r))?"dependency-or-cache":i.join("/")===".comet/config.yaml"?"comet-config":i.join("/")===".comet/current-change.json"?"comet-selection":null}var Vi=1024*1024;function Dn(t,e){let i=Y.relative(t,e);return i===""||!Y.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Y.sep}`)}function hf(t){let e=Y.posix.normalize(t);if(t.length===0||t!==t.trim()||t.includes("\\")||Array.from(t).some(n=>{let a=n.codePointAt(0)??0;return a<=31||a===127})||Y.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=Dt(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 pf(t){if(!Number.isSafeInteger(t)||t<1)throw new Error("Native artifact byte limit must be a positive integer");return t}function mf(t,e){return A({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function Fi(t,e){let i={...t,birthtime:t.birthtimeMs},r={...e,birthtime:e.birthtimeMs};return ue(i,r)?A(i,r):A(i,r)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.size===e.size}async function ws(t){let e=await ie.lstat(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${t}`);return{path:t,realPath:await ie.realpath(t),dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}async function vf(t,e){let i=Y.resolve(t),r=Y.resolve(e);if(!Dn(i,r))throw new Error("Native artifact path is outside its root");let n=[await ws(i)],a=i;for(let o of Y.relative(i,r).split(Y.sep).filter(Boolean)){a=Y.join(a,o);let s=await ws(a);if(!Dn(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function ys(t){for(let e of t){let i=await ie.lstat(e.path);if(!i.isDirectory()||i.isSymbolicLink()||!mf(e,i)||await ie.realpath(e.path)!==e.realPath)throw new Error(`Native artifact parent changed while reading: ${e.path}`)}}async function M(t){let e=hf(t.ref),i=t.maxBytes===null?null:pf(t.maxBytes??Vi),r=Y.resolve(t.root,...e.split("/")),n=await vf(t.root,Y.dirname(r));await t.hooks?.afterParentChainCaptured?.();let a=await ie.lstat(r);if(!a.isFile()||a.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${e}`);if(i!==null&&a.size>i)throw new Error(`Native artifact exceeds ${i} bytes: ${e}`);let o=await ie.realpath(r);if(!Dn(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${e}`);let s=await ie.open(r,"r");try{let[c,l,f]=await Promise.all([s.stat(),ie.lstat(r),ie.realpath(r)]);if(await ys(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||f!==o||!Fi(a,c)||!Fi(c,l))throw new Error(`Native artifact changed while opening: ${e}`);await t.hooks?.afterOpen?.();let d=[],u=0,p=Buffer.allocUnsafe(i===null?64*1024:Math.min(64*1024,i+1));for(;;){let b=i===null?p.length:i+1-u,k=await s.read(p,0,Math.min(p.length,b),null);if(k.bytesRead===0)break;if(u+=k.bytesRead,i!==null&&u>i)throw new Error(`Native artifact exceeds ${i} bytes: ${e}`);d.push(Buffer.from(p.subarray(0,k.bytesRead)))}await t.hooks?.beforeFinalCheck?.();let[v,h,m]=await Promise.all([s.stat(),ie.lstat(r),ie.realpath(r)]);if(await ys(n),!h.isFile()||h.isSymbolicLink()||m!==o||!Fi(c,v)||!Fi(c,h))throw new Error(`Native artifact changed while reading: ${e}`);let w=Buffer.concat(d,u),y;try{y=new ff("utf-8",{fatal:!0}).decode(w)}catch(b){throw new Error(`Native artifact is not valid UTF-8: ${e}`,{cause:b})}return{ref:e,size:u,hash:t.includeHash===!1?null:df("sha256").update(w).digest("hex"),text:y}}finally{await s.close()}}var as=$t(yt(),1);import Tt from"path";var No=$t(yt(),1);import Nt from"path";var pi=64*1024,Fr=1024,Vr=64,bo=5,Wv=12e4,cu=6e5,zv=[".agents/skills/**",".amazonq/skills/**",".augment/skills/**",".bob/skills/**",".claude/skills/**",".cline/skills/**",".codebuddy/skills/**",".workbuddy/skills/**",".continue/skills/**",".cospec/skills/**",".crush/skills/**",".cursor/skills/**",".factory/skills/**",".forge/skills/**",".gemini/skills/**",".github/skills/**",".grok/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/**"],Jv=["**/.idea/**","**/.vscode/**",".codex/skills/**","**/node_modules/**","**/.next/**","**/.nuxt/**","**/.output/**","**/.svelte-kit/**","**/.vite/**","**/.parcel-cache/**","**/.turbo/**","**/.nx/cache/**","**/dist/**","**/build/**","**/out/**","**/coverage/**","**/.nyc_output/**","**/target/**","**/.gradle/**","**/.cxx/**","**/.externalNativeBuild/**","**/captures/**","**/__pycache__/**","**/.pytest_cache/**","**/.mypy_cache/**","**/.ruff_cache/**","**/.tox/**","**/.nox/**","**/.venv/**","**/venv/**","**/obj/**","**/CMakeFiles/**","**/cmake-build-*/**","**/.cache/**","**/tmp/**","**/temp/**","**/logs/**","**/*.tsbuildinfo","**/*.log","**/.DS_Store","**/Thumbs.db"],Gv=[...zv,...Jv].sort((t,e)=>t.localeCompare(e,"en"));var G={include:["**/*"],exclude:[...Gv],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4};function Uv(t,e){if(typeof t!="string")throw new Error(`${e} must be a string`);let i=t.trim();if(i.length===0||Nt.posix.isAbsolute(i)||Nt.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 Ze(t){let e=Uv(t,"native.artifact_root");return e.length===0?".":e.join("/")}function uu(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 qr(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||Nt.posix.isAbsolute(r)||Nt.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(a=>a===".."))throw new Error(`${e} must stay inside its declared path base`);if(n.some(a=>a===""||a==="."))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 Ve(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function du(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 ko(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>Fr)throw new Error(`${e} exceeds ${Fr} characters`);let i=0;for(let r=0;r<t.length;r+=1)t[r]==="?"?i+=1:t[r]==="*"&&(i+=1,t[r+1]==="*"&&(r+=1));if(i>Vr)throw new Error(`${e} contains more than ${Vr} wildcard tokens`);return t}function lu(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=>ko(r,e)))].sort((r,n)=>r.localeCompare(n,"en"))}function yo(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 Kv(t){if(t===void 0)return{...G,include:[...G.include],exclude:[...G.exclude]};let e=Ve(t,"native.snapshot");return{include:lu(e.include,"native.snapshot.include",G.include),exclude:lu(e.exclude,"native.snapshot.exclude",G.exclude),max_files:yo(e.max_files,G.max_files,"native.snapshot.max_files"),max_total_bytes:yo(e.max_total_bytes,G.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:yo(e.max_duration_ms,G.max_duration_ms,"native.snapshot.max_duration_ms")}}function Yv(t){if(t===void 0)return;let e=Ve(t,"native.pending_root_move"),i=e.id,r=e.from_artifact_root,n=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 r!="string"||typeof n!="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=Ve(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");o={kind:c,state:l,manifestHash:f}}return{id:i,fromArtifactRoot:Ze(r),toArtifactRoot:Ze(n),stage:a,...o?{cleanup:o}:{}}}function Xv(t){if(t===void 0)return;let e=Ve(t,"native.finish");if(e.pull_request===void 0)return{};let i=Ve(e.pull_request,"native.finish.pull_request");if(i.provider!=="repository-command")throw new Error("native.finish.pull_request.provider must be repository-command");if(!Array.isArray(i.command)||i.command.length===0)throw new Error("native.finish.pull_request.command must be a non-empty array");if(i.command.length>64)throw new Error("native.finish.pull_request.command must contain at most 64 arguments");let r=i.command.map((a,o)=>{if(typeof a!="string"||a.trim().length===0||a.length>4096||/[\0\r\n]/u.test(a))throw new Error(`native.finish.pull_request.command[${o}] must be a non-empty single-line string of at most 4096 characters`);return a});if(Nt.posix.isAbsolute(r[0])||Nt.win32.isAbsolute(r[0]))throw new Error("native.finish.pull_request.command[0] must be a bare executable name or a project-relative path");let n=i.timeout_ms??Wv;if(!Number.isSafeInteger(n)||n<1||n>cu)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${cu}`);return{pull_request:{provider:"repository-command",command:r,timeout_ms:n}}}function Qv(t,e={}){let i=Ve(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??"batch";if(n!=="sequential"&&n!=="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??bo;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=Yv(i.pending_root_move),c=Xv(i.finish);return{artifact_root:Ze(r),language:du(i.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,snapshot:Kv(i.snapshot),...c?{finish:c}:{},...s?{pending_root_move:s}:{}}}function Zv(t){let e=Ve(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:uu(e.artifact_layout),language:du(e.language,"zh-CN","classic.language"),context_compression:i,review_mode:r,auto_transition:n}}function eg(t){let i=Ve(t,"hook").allow_paths??[];if(!Array.isArray(i))throw new Error("hook.allow_paths must be an array");return{allow_paths:[...new Set(i.map((r,n)=>qr(r,`hook.allow_paths[${n}]`)))]}}function tg(t){let e=t??!0;if(typeof e!="boolean")throw new Error("ambient_resume must be true or false");return e}function ig(t,e,i,r,n,a){let o=t.schema!==void 0;if(!(o||t.default_workflow!==void 0||t.workflows!==void 0||!a.allowPartialProject&&t.native!==void 0)||a.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 c=t.workflows??[t.default_workflow];if(!Array.isArray(c)||c.length===0||c.some(f=>f!=="native"&&f!=="classic"))throw new Error("workflows must contain native and/or classic");let l=[...new Set(c)];if(!l.includes(t.default_workflow))throw new Error("workflows must include default_workflow");if(l.includes("native")&&!i)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:t.default_workflow,workflows:l,ambient_resume:n,...e?{hook:e}:{},...i?{native:i}:{},...r?{classic:r}:{}}}function mi(t,e={}){let i=(0,No.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,a=tg(n.ambient_resume),o=n.hook===void 0?void 0:eg(n.hook),s=n.native===void 0?void 0:Qv(n.native,{allowMissingArtifactRoot:e.allowMissingNativeFields}),c=n.classic===void 0?void 0:Zv(n.classic),l=ig(n,o,s,c,a,{allowPartialProject:e.allowPartialProject??!1});return{value:n,config:l,ambient_resume:a,...o?{hook:o}:{},...s?{native:s}:{},...c?{classic:c}:{}}}function Wr(t="docs",e="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,native:{artifact_root:Ze(t),language:e,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:bo,snapshot:{...G,include:[...G.include],exclude:[...G.exclude]}}}}import{createHash as ng}from"crypto";import{promises as Gr}from"fs";import qe from"path";import{constants as zr,promises as et}from"fs";var ae=class extends Error{reason;constructor(e,i,r){super(i,r),this.name="RaceSafeReadError",this.reason=e}};function So(t){return"birthtimeNs"in t&&typeof t.birthtimeNs=="bigint"?t.birthtimeNs:t.birthtimeMs}function fu(t){return"ctimeNs"in t&&typeof t.ctimeNs=="bigint"?t.ctimeNs:t.ctimeMs}function vi(t){return{dev:t.dev,ino:t.ino,birthtime:So(t)}}function Jr(t,e){let i=vi(t),r=vi(e);return ue(i,r)?A(i,r):A(i,r)&&So(t)===So(e)&&fu(t)===fu(e)&&t.size===e.size}async function bt(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,a=await et.lstat(t,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new ae("not-regular-file",`${r} must be a regular file`);if(BigInt(a.size)>BigInt(e))throw new ae("too-large",`${r} exceeds ${e} bytes`);let o=await et.realpath(t);await i.verify?.("pre-open",{realPath:o,identity:vi(a)});let s=process.platform==="win32"?zr.O_RDONLY:zr.O_RDONLY|zr.O_NOFOLLOW|zr.O_NONBLOCK,c;try{c=await et.open(t,s)}catch(l){throw l.code==="ELOOP"?new ae("not-regular-file",`${r} must be a regular file`,{cause:l}):l}try{let[l,f,d]=await Promise.all([c.stat({bigint:n}),et.lstat(t,{bigint:n}),et.realpath(t)]);if(!l.isFile()||!f.isFile()||f.isSymbolicLink()||d!==o||!Jr(a,l)||!Jr(a,f))throw new ae("changed",`${r} changed while opening`);await i.verify?.("post-open",{realPath:d,identity:vi(l)}),await i.hooks?.afterOpen?.();let u=[],p=0,v=Buffer.allocUnsafe(Math.min(64*1024,e+1));for(;;){let y=e+1-p,{bytesRead:b}=await c.read(v,0,Math.min(v.length,y),null);if(b===0)break;if(p+=b,p>e)throw new ae("too-large",`${r} exceeds ${e} bytes`);u.push(Buffer.from(v.subarray(0,b)))}await i.hooks?.beforeFinalCheck?.();let[h,m,w]=await Promise.all([c.stat({bigint:n}),et.lstat(t,{bigint:n}),et.realpath(t)]);if(!m.isFile()||m.isSymbolicLink()||w!==o||!Jr(a,h)||!Jr(a,m))throw new ae("changed",`${r} changed while reading`);return await i.verify?.("post-read",{realPath:w,identity:vi(h)}),{bytes:Buffer.concat(u,p),stat:h,realPath:w}}finally{await c.close()}}function rg(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}function Eo(t,e){let i=qe.relative(t,e);return i===""||!qe.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${qe.sep}`)}async function hu(t,e){let i=qe.resolve(t),r=await Gr.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${e} project root must be a real directory`);return Gr.realpath(i)}async function pu(t,e,i,r){let n=t;for(let a=0;a<i.length;a++){n=qe.join(n,i[a]);let o;try{o=await Gr.lstat(n)}catch(f){if(rg(f))return{exists:!1,kind:"missing"};throw f}let s=qe.relative(t,n).replaceAll("\\","/");if(o.isSymbolicLink())throw new Error(`${r.label} crosses a symbolic link or junction at ${s}`);let c=a===i.length-1;if(!c&&!o.isDirectory())throw new Error(`${r.label} ancestor ${s} must be a real directory`);if(c&&(r.expected==="file"&&!o.isFile()||r.expected==="directory"&&!o.isDirectory()||r.expected==="any"&&!o.isFile()&&!o.isDirectory()))throw new Error(`${r.label} must be a real ${r.expected}`);let l=await Gr.realpath(n);if(!Eo(e,l))throw new Error(`${r.label} resolves outside the project root`);if(c)return{exists:!0,kind:o.isFile()?"file":o.isDirectory()?"directory":"missing"}}return{exists:!0,kind:"directory"}}async function kt(t,e,i){let r=qr(e,i.label),n=qe.resolve(t),a=await hu(n,i.label),o=r.split("/"),s=qe.resolve(n,...o);if(!Eo(n,s))throw new Error(`${i.label} must stay inside the project root`);let c=await pu(n,a,o,i);return{projectRoot:n,target:s,relative:r,exists:c.exists,kind:c.kind}}async function We(t,e,i,r){let n=await kt(t,e,{label:r.label,expected:"file"});if(!n.exists){let o=new Error(`${r.label} does not exist`);throw o.code="ENOENT",o}let a=await hu(n.projectRoot,r.label);return bt(n.target,i,{...r,verify:async(o,s)=>{if(!Eo(a,s.realPath))throw new Error(`${r.label} resolves outside the project root`);await pu(n.projectRoot,a,n.relative.split("/"),{label:r.label,expected:"file"})}})}var gi=".comet/config.yaml";function ag(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function Ur(t,e={}){return(await Kr(t,e)).document}async function og(t){try{return(await We(t,gi,pi,{label:gi})).bytes}catch(e){if(ag(e))return null;throw e}}function sg(t){return t?{exists:!0,sha256:ng("sha256").update(t).digest("hex")}:{exists:!1,sha256:null}}async function Kr(t,e={}){let i=await og(t);return{document:i?mi(i.toString("utf8"),e):null,identity:sg(i)}}async function Po(t){return(await Ur(t))?.config??null}var zk=16*1024;import{existsSync as vu,promises as tt}from"fs";import C from"path";import fg from"os";var Yr=".comet/config.yaml",hg=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;async function Ro(t){try{return await tt.lstat(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function pg(t){try{let e=await tt.readFile(t,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(e)}catch(e){if(e.code==="ENOENT")return!1;throw e}}function Et(t,e){let i=C.relative(t,e);return i===""||!C.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${C.sep}`)}async function St(t){let e=[],i=t;for(;!await Ro(i);){let n=C.dirname(i);if(n===i)break;e.push(C.basename(i)),i=n}let r=await tt.realpath(i);return C.resolve(r,...e.reverse())}async function Ao(t){try{return(await tt.lstat(t)).isSymbolicLink()}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function Xr(t){let e=C.resolve(t);try{(await tt.stat(e)).isDirectory()||(e=C.dirname(e))}catch(n){if(n.code!=="ENOENT")throw n}let i=e,r=C.resolve(fg.homedir());for(;;){if(!(e===r&&i!==r)){let o=C.join(e,...Yr.split("/")),s=e===i||await pg(o);if(await Ro(o)&&s)return e}if(await Ro(C.join(e,".git")))return e;let a=C.dirname(e);if(a===e)return i;e=a}}function Qr(t){return Ze(t)}async function mg(t,e){let i=Qr(e),r=C.resolve(t,...i.split("/")),n=await tt.realpath(t),a=await St(r);if(!Et(n,a))throw new Error("native.artifact_root resolves outside the project root");return r}async function Pt(t,e){let i=Qr(e),r=await mg(t,i),n=C.join(r,"comet");if(await Ao(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([St(r),St(n)]);if(!Et(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=C.resolve(t),c=C.join(s,".comet","runtime","native");if(await Ao(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,f]=await Promise.all([tt.realpath(s),St(c)]);if(!Et(l,f))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:C.join(t,...Yr.split("/")),artifactRoot:r,artifactRootRef:i,nativeRoot:n,specsDir:C.join(n,"specs"),changesDir:C.join(n,"changes"),archiveDir:C.join(n,"archive"),runtimeDir:c,changesRuntimeDir:C.join(c,"changes"),locksDir:C.join(c,"locks"),transactionsDir:C.join(c,"transactions")}}function gu(t){if(!hg.test(t))throw new Error(`Invalid Native change name: ${t}`)}function it(t,e){gu(e);let i=C.join(t.changesRuntimeDir,e);if(!F(t.changesRuntimeDir,i))throw new Error("Native change Runtime path escaped");return i}function _o(t,e){gu(e);let i=C.join(t.changesDir,e,"runtime");if(!F(t.changesDir,i))throw new Error("Legacy Native change Runtime path escaped");return i}function pe(t,e){let i=it(t,e);if(vu(i))return i;let r=_o(t,e);return vu(r)?r:i}function me(t,e){let i=C.resolve(e);if(F(t.runtimeDir,i))return t.runtimeDir;if(F(t.nativeRoot,i))return t.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${e}`)}function F(t,e){return Et(C.resolve(t),C.resolve(e))}async function T(t,e){let i=C.resolve(t),r=C.resolve(e);if(!Et(i,r))throw new Error(`Path is outside the Native root: ${e}`);if(await Ao(i))throw new Error(`Native root must not be a symbolic link: ${t}`);let[n,a]=await Promise.all([St(i),St(r)]);if(!Et(n,a))throw new Error(`Path resolves outside the Native root: ${e}`);return r}function gg(t="docs",e="en"){return Wr(t,e)}async function Pe(t){let e=(await Ur(t))?.config??null;return e?.native?e:null}async function Zr(t){let e=await Pe(t);if(e?.native.pending_root_move)throw new Error(`Native root move ${e.native.pending_root_move.id} is incomplete; use comet native doctor --repair`)}async function wu(t){let e=await Xr(t.startPath),i=await Pe(e);if(!i&&t.allowMissingConfig===!1)throw new Error(`${Yr} 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 r=t.explicitArtifactRoot?Qr(t.explicitArtifactRoot):void 0;if(i&&r&&r!==i.native.artifact_root)throw new Error(`Configured Native artifact root is ${i.native.artifact_root}; refusing conflicting root ${r}`);let n=i??gg(r??"docs"),a=await Pt(e,n.native.artifact_root);return{config:n,paths:a,configured:i!==null}}import{promises as Uw}from"fs";import Kw from"path";import{AsyncLocalStorage as wg}from"async_hooks";import{randomUUID as bu}from"crypto";import{promises as Q}from"fs";import ku from"os";import V from"path";var yu=16*1024,Su=".coordinator",yg=5e3,Nu=new wg,en=new Map;function Ng(t){if(!/^[a-z][a-z0-9-]*$/u.test(t))throw new Error(`Invalid Native lock name: ${t}`);return`${t}.lock`}function bg(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`Invalid Native lock metadata: ${e}`);let i=t;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: ${e}`);return i}function Eu(t){return{device:t.dev.toString(),inode:t.ino.toString(),size:t.size.toString(),birthtimeNs:t.birthtimeNs.toString(),ctimeNs:t.ctimeNs.toString(),mtimeNs:t.mtimeNs.toString()}}function To(t,e){let i={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs},r={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs};return ue(i,r)?A(i,r):A(i,r)&&t.size===e.size}function Io(t,e){return To(t,e)&&t.size===e.size&&t.birthtimeNs===e.birthtimeNs&&t.ctimeNs===e.ctimeNs&&t.mtimeNs===e.mtimeNs}async function xe(t){let e,i;try{let r=await bt(t,yu,{bigint:!0,label:"Native lock"});e=r.bytes,i=r.stat}catch(r){if(r.code==="ENOENT")return null;throw r instanceof ae?r.reason==="too-large"?new Error(`Native lock metadata exceeds ${yu} bytes: ${t}`,{cause:r}):r.reason==="not-regular-file"?new Error(`Native lock must be a regular file: ${t}`,{cause:r}):new Error(`Native lock changed while reading: ${t}`,{cause:r}):r}return{file:t,owner:bg(JSON.parse(e.toString("utf8")),t),identity:Eu(i)}}async function kg(t){return(await xe(t))?.owner??null}function Pu(t){if(!t)return{status:"missing",owner:null,identity:null};if(t.owner.hostname!==ku.hostname())return{status:"unknown",owner:t.owner,identity:t.identity};let e=Rg(t.owner.pid);return{status:e===!0?"active":e===!1?"stale":"unknown",owner:t.owner,identity:t.identity}}async function Sg(t,e){try{await Q.lstat(e);return}catch(i){if(i.code!=="ENOENT")throw i}try{await Q.rename(t,e)}catch(i){if(i.code!=="ENOENT")throw i}}async function jo(t,e){let i=await xe(t.file);if(!i)return"missing";if(i.owner.id!==t.owner.id)throw new Error(`Native lock ownership changed: ${t.file}`);if(!Io(i.identity,t.identity))throw new Error(`Native lock identity changed: ${t.file}`);await Q.mkdir(e,{recursive:!0});let r=V.join(e,`${V.basename(t.file)}.${t.owner.id}.${bu()}.removed`);try{await Q.rename(t.file,r)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await xe(r);if(!n||n.owner.id!==t.owner.id||!To(n.identity,t.identity))throw await Sg(r,t.file),new Error(`Native lock changed before quarantine: ${t.file}`);return await Q.rm(r,{force:!0}),"removed"}function xu(t){return{id:bu(),pid:process.pid,hostname:ku.hostname(),createdAt:new Date().toISOString(),operation:t}}async function Cu(t,e){let i;try{i=await Q.open(t,"wx")}catch(r){if(r.code==="EEXIST"){let n=await kg(t);throw new Error(`Native lock is already held: ${t}${n?` by pid ${n.pid} for ${n.operation}`:""}`,{cause:r})}throw r}try{return await i.writeFile(JSON.stringify(e,null,2)+`
|
|
144
144
|
`,"utf8"),await i.sync(),Eu(await i.stat({bigint:!0}))}finally{await i.close()}}async function Eg(t,e){let i=await T(t.runtimeDir,t.locksDir);await Q.mkdir(i,{recursive:!0});let r=await T(t.runtimeDir,V.join(i,Su));await Q.mkdir(r,{recursive:!0});let n=xu(e),a=V.join(r,`.${n.id}.tmp`),o=V.join(r,`${n.id}.claim`);try{let s=await Cu(a,n);await Q.rename(a,o);let c=await xe(o);if(!c||!To(s,c.identity))throw new Error(`Native lock coordinator claim changed while publishing: ${o}`);return{file:o,nativeRoot:t.runtimeDir,locksDir:i,owner:n,identity:c.identity}}finally{await Q.rm(a,{force:!0})}}async function Pg(t){let e=V.dirname(t.file),i=!1,r=V.basename(t.file);for(let n of await Q.readdir(e,{withFileTypes:!0})){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".claim"))continue;let a=V.join(e,n.name);if(V.resolve(a)!==V.resolve(t.file))try{let o=await xe(a),s=Pu(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await jo(o,e);continue}n.name<r&&(i=!0)}catch{n.name<r&&(i=!0)}}return i}async function Ru(t){let e=await xe(t.file);if(e){if(e.owner.id!==t.owner.id||!Io(e.identity,t.identity))throw new Error(`Native lock coordinator ownership changed: ${t.file}`);await jo(e,V.dirname(t.file))}}async function xg(t,e){let i=Date.now()+yg;for(;;){let r=await Eg(t,e);if(!await Pg(r))return r;if(await Ru(r),Date.now()>=i)throw new Error(`Native lock coordinator is busy: ${t.locksDir}`);await new Promise(n=>setTimeout(n,2+Math.floor(Math.random()*7)))}}async function Cg(t){let e=en.get(t)??Promise.resolve(),i,r=new Promise(a=>{i=a}),n=e.then(()=>r);return en.set(t,n),await e,()=>{i(),en.get(t)===n&&en.delete(t)}}async function Au(t,e,i){let r=V.resolve(t.locksDir),n=Nu.getStore();if(n?.has(r))return i();let a=await Cg(r);try{let o=await xg(t,e),s=new Map(n??[]);return s.set(r,o),await Nu.run(s,async()=>{try{return await i()}finally{await Ru(o)}})}finally{a()}}async function tn(t,e,i){return Au(t,`acquire ${e}`,async()=>{let r=await T(t.runtimeDir,t.locksDir);await Q.mkdir(r,{recursive:!0});let n=await T(t.runtimeDir,V.join(r,Ng(e))),a=xu(i),o=await Cu(n,a);return{file:n,nativeRoot:t.runtimeDir,locksDir:r,owner:a,identity:o}})}async function rn(t){await xe(t.file)&&await Au({runtimeDir:t.nativeRoot,locksDir:t.locksDir},`release ${V.basename(t.file)}`,async()=>{let e=await xe(t.file);if(!e)return;if(e.owner.id!==t.owner.id)throw new Error(`Native lock ownership changed: ${t.file}`);if(!Io(e.identity,t.identity))throw new Error(`Native lock identity changed: ${t.file}`);let i=V.join(t.locksDir,Su);await jo(e,i)})}function Rg(t){try{return process.kill(t,0),!0}catch(e){let i=e.code;return i==="ESRCH"?!1:i==="EPERM"?!0:null}}async function _u(t){return Pu(await xe(t))}import Uo from"node:path";import sw from"node:path";import Iu from"node:path";import{createHash as Ag}from"crypto";function oe(t){throw new TypeError(`Value is not valid canonical JSON: ${t}`)}function _g(t,e){e.has(t)&&oe("cyclic structures are not supported"),e.add(t);try{let i=Object.keys(t);for(let r=0;r<t.length;r+=1)Object.prototype.hasOwnProperty.call(t,r)||oe("sparse arrays are not supported");return(i.length!==t.length||i.some((r,n)=>r!==String(n)))&&oe("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(t).length>0&&oe("symbol properties are not supported"),`[${t.map(r=>$o(r,e)).join(",")}]`}finally{e.delete(t)}}function Tg(t,e){let i=Object.getPrototypeOf(t);i!==Object.prototype&&i!==null&&oe("only plain objects are supported"),e.has(t)&&oe("cyclic structures are not supported"),Object.getOwnPropertySymbols(t).length>0&&oe("symbol properties are not supported"),e.add(t);try{let r=Object.getOwnPropertyDescriptors(t);return`{${Object.keys(t).sort().map(o=>{let s=r[o];return(!s||!("value"in s))&&oe("accessor properties are not supported"),`${JSON.stringify(o)}:${$o(s.value,e)}`}).join(",")}}`}finally{e.delete(t)}}function $o(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)||oe("numbers must be finite"),JSON.stringify(Object.is(t,-0)?0:t);case"object":return Array.isArray(t)?_g(t,e):Tg(t,e);case"bigint":case"function":case"symbol":case"undefined":return oe(`${typeof t} values are not supported`)}return oe("unsupported value type")}function Oo(t){return $o(t,new Set)}function U(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 Ag("sha256").update(`${t}
|
|
145
|
-
${Oo(e)}`).digest("hex")}var Ig="comet.native.acceptance.v1";var
|
|
145
|
+
${Oo(e)}`).digest("hex")}var Ig="comet.native.acceptance.v1";var ES=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),bi=Object.freeze({maxCriteria:1024});function Do(t){let e=/^ {0,3}(#{1,6})[ \t]+(.+?)[ \t]*$/u.exec(t);return e?{level:e[1].length,text:e[2].replace(/[ \t]+#+[ \t]*$/u,"").trim()}:null}function Ho(t,e){let i=/^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(t);if(!i)return e;let r=i[1][0];return e===null?{marker:r,length:i[1].length}:r===e.marker&&i[1].length>=e.length&&i[2].trim().length===0?null:e}function Tu(t){return t.includes("-->")||t.includes("--!>")}function*yi(t){let e=null,i=!1,r=null,n=new Set(["code","pre","script","style","svg","template"]),a=t.replace(/\r\n?/gu,`
|
|
146
146
|
`),o=0,s=0;for(;o<=a.length;){let c=a.indexOf(`
|
|
147
|
-
`,o),l=c===-1?a.slice(o):a.slice(o,c);if(yield{line:l,body:e===null&&!i&&r===null,index:s},s+=1,e!==null)e=Ho(l,e);else if(i)Tu(l)&&(i=!1);else if(r!==null)new RegExp(`</${r}\\s*>`,"iu").test(l)&&(r=null);else{let d=Ho(l,null);if(d!==null)e=d;else{let u=l.trimStart();if(u.startsWith("<!--")&&!Tu(u))i=!0;else{let p=/^<([A-Za-z][A-Za-z0-9-]*)\b[^>]*>/u.exec(u);p&&n.has(p[1].toLowerCase())&&!u.startsWith("</")&&!u.endsWith("/>")&&!new RegExp(`</${p[1]}\\s*>`,"iu").test(u)&&(r=p[1])}}}if(c===-1)break;o=c+1}}function
|
|
148
|
-
`),[],r)),"Brief",r)}function Fo(t,e="spec.md",i=
|
|
149
|
-
`),o.context,r)),o=null}};for(let{line:c,body:l}of wi(t)){let f=l?Do(c):null,d=f?/^Scenario\s*:\s*(.*)$/iu.exec(f.text):null;if(d){for(s();a.at(-1)&&a.at(-1).level>=f.level;)a.pop();let u=yi(d[1]);if(u.length===0)throw new Error("Scenario title must not be empty");o={level:f.level,title:u,body:[],context:a.map(p=>p.text)}}else if(f){for(o!==null&&f.level<=o.level?s():o!==null&&o.body.push(c);a.at(-1)&&a.at(-1).level>=f.level;)a.pop();a.push(f)}else o!==null&&l&&o.body.push(c)}return s(),Bo(n,"Specification",r)}function Vo(t,e="spec.md",i=Ni.maxCriteria,r="content-hash"){if(!Number.isSafeInteger(i)||i<0)throw new Error("Native specification acceptance budget is invalid");let n=[],a=[],o=null,s=null,c=()=>{if(s!==null){if(n.length>=i)throw new Error(`Native acceptance exceeds its ${i}-criterion acceptance budget`);n.push(Lo("spec-must",e,s.parts.join(" "),s.context,r)),s=null}},l=()=>a.some(f=>/^(?:non-?goals?|非目标)$/iu.test(f.text.trim()));for(let{line:f,body:d}of wi(t)){let u=d?Do(f):null;if(u){for(c(),o!==null&&u.level<=o&&(o=null);a.at(-1)&&a.at(-1).level>=u.level;)a.pop();a.push(u),/^Scenario\s*:/iu.test(u.text)&&(o=u.level);continue}let p=f.trim();if(!d||o!==null||l()){c();continue}if(p.length===0||Ho(f,null)!==null||p.startsWith("<!--")||p==="-->"||p==="--!>"||/^<\/?[A-Za-z][^>]*>$/u.test(p)||/^<[A-Za-z][^>]*>.*<\/[A-Za-z][^>]*>$/u.test(p)||/^(?:[-*_]\s*){3,}$/u.test(p)||/^\|?(?:\s*:?-{3,}:?\s*\|)+\s*$/u.test(p)){c();continue}let v=/^\s*(?:[-*+]|\d+[.)])[ \t]+(.+)$/u.exec(f);if(v){c(),s={parts:[v[1]],context:a.map(h=>h.text)};continue}if(/^\|.*\|$/u.test(p)){c(),s={parts:[p],context:a.map(h=>h.text)},c();continue}s===null?s={parts:[p],context:a.map(h=>h.text)}:s.parts.push(p)}return c(),Bo(n,"Specification mandatory requirements",r)}var $g=/^A[1-9]\d*$/u;function ju(t,e){if(t.length===0||t!==t.trim()||t.includes("\\")||Iu.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes("..")||Iu.posix.normalize(t)!==t||t==="."||t.endsWith("/"))throw new Error(`${e} must be a normalized change-relative ref`);return t}function Og(t,e){return t.localeCompare(e,"en")}function qo(t){let e=ju(t.briefSource??"brief.md","Native brief source"),i=[...t.specs??[]].sort((a,o)=>Og(a.capability,o.capability));if(new Set(i.map(a=>a.capability)).size!==i.length)throw new Error("Native acceptance sources contain duplicate capabilities");let r=Mo(t.briefMarkdown,e,Number.MAX_SAFE_INTEGER,"none").map(({source:a,text:o})=>({source:a,text:o}));for(let a of i){let o=ju(a.source,`Native spec source for ${a.capability}`);r.push(...Fo(a.markdown,o,Number.MAX_SAFE_INTEGER,"none").map(({text:s})=>({source:o,text:s})),...Vo(a.markdown,o,Number.MAX_SAFE_INTEGER,"none").map(({text:s})=>({source:o,text:s})))}let n=new Set;for(let a of r){a.text=yi(a.text);let o=`${a.source}\0${a.text}`;if(n.has(o))throw new Error(`Native acceptance contains a duplicate criterion: ${a.text}`);n.add(o)}if(r.length===0)throw new Error("Native change must define at least one acceptance criterion");return r.map((a,o)=>({id:`A${o+1}`,source:a.source,text:a.text}))}function $u(t){let e=t.map(({id:i})=>i);if(new Set(e).size!==e.length)throw new Error("Native acceptance IDs must be unique");for(let i=0;i<e.length;i+=1)if(!$g.test(e[i])||e[i]!==`A${i+1}`)throw new Error("Native acceptance IDs must be the contiguous sequence A1..An")}var on=$t(yt(),1);import{promises as Hg}from"node:fs";var xt="comet.native.v4",bi="comet.native.local-execution.v4";function Wo(){return{dropped_entries:0,first_dropped_at:null,last_dropped_at:null,outcome_counts:{pass:0,fail:0,blocked:0,"execution-error":0,recovery:0}}}var Dg=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Lg=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Bg=/^A[1-9][0-9]*$/u,Mg=/^[a-f0-9]{64}$/u,Fg=new Set(["schema","name","language","phase","status","state_version","brief","children_contract_hash","spec_changes","workspace","loop","acceptance","builder_handoff","blockers","verification","history","history_overflow","verification_result","verification_report","archived","created_at"]),an=class extends Error{constructor(i,r){super(`Native state version conflict: expected ${i}, got ${r}`);this.expectedStateVersion=i;this.actualStateVersion=r;this.name="NativePortableStateVersionConflictError"}expectedStateVersion;actualStateVersion;code="native-state-version-conflict"};function z(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function J(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 L(t,e,i){if(typeof t!="string"||!i?.empty&&t.length===0)throw new Error(`${e} must be ${i?.empty?"a string":"a non-empty string"}`);return t}function zo(t,e){return t===null?null:L(t,e)}function Vg(t,e){let i=L(t,e);if(!Mg.test(i))throw new Error(`${e} must be a SHA-256 hash`);return i}function Ct(t,e){if(typeof t!="boolean")throw new Error(`${e} must be a boolean`);return t}function _(t,e,i=0){if(!Number.isSafeInteger(t)||t<i)throw new Error(`${e} must be a safe integer greater than or equal to ${i}`);return t}function qg(t,e){return t===null?null:_(t,e,Number.MIN_SAFE_INTEGER)}function D(t,e,i){if(typeof t!="string"||!e.includes(t))throw new Error(`${i} must be one of: ${e.join(", ")}`);return t}function ve(t,e,i){if(!Array.isArray(t))throw new Error(`${e} must be an array`);return t.map((r,n)=>i(r,n))}function sn(t,e){return ve(t,e,(i,r)=>L(i,`${e}[${r}]`))}function rt(t,e){if(new Set(t).size!==t.length)throw new Error(`${e} must be unique`)}function Rt(t,e){let i=L(t,e);if(Number.isNaN(Date.parse(i)))throw new Error(`${e} must be an ISO date or timestamp`);return i}function Jo(t,e,i=!1){let r=L(t,e);if(r.includes("\\")||r.startsWith("/")||/^[A-Za-z]:/u.test(r)||r.split("/").includes("..")||!i&&(r==="."||r.split("/").includes(".")))throw new Error(`${e} must be a portable relative path`);return r}function se(t,e){let i=z(t,e);return J(i,new Set(["text","truncated"]),e),{text:L(i.text,`${e}.text`,{empty:!0}),truncated:Ct(i.truncated,`${e}.truncated`)}}function Wg(t,e){let i=`Native spec_changes[${e}]`,r=z(t,i);J(r,new Set(["capability","operation","source"]),i);let n=L(r.capability,`${i}.capability`);if(!Lg.test(n))throw new Error(`${i}.capability is invalid`);let a=D(r.operation,["create","modify","remove"],`${i}.operation`),o=r.source===null?null:Jo(r.source,`${i}.source`);if(a==="remove"&&o!==null)throw new Error(`${i} remove requires source null`);if(a!=="remove"&&o===null)throw new Error(`${i} ${a} requires a source`);return{capability:n,operation:a,source:o}}function zg(t){let e="Native workspace",i=z(t,e);J(i,new Set(["isolation","change_branch","target_branch","finish"]),e);let r=D(i.isolation,["current","branch","worktree"],`${e}.isolation`),n=zo(i.change_branch,`${e}.change_branch`),a=zo(i.target_branch,`${e}.target_branch`),o=i.finish===null?null:D(i.finish,["merge","push","pull-request","keep"],`${e}.finish`);if(r==="current"&&o!==null)throw new Error("Native current workspace cannot contain a finish action");if(r==="current"&&n===null!=(a===null))throw new Error("Native workspace branch bindings must both be present or both be null");if(r!=="current"&&(n===null||a===null))throw new Error("Native isolated workspace requires change_branch and target_branch");return{isolation:r,change_branch:n,target_branch:a,finish:o}}function Jg(t){let e="Native loop",i=z(t,e);J(i,new Set(["stage","goal_cycle","iteration","attempt","retry_epoch","failed_iteration_count","no_progress_count","execution_failure_count","previous_unresolved_ids","next_action"]),e);let r=sn(i.previous_unresolved_ids,`${e}.previous_unresolved_ids`);return rt(r,`${e}.previous_unresolved_ids`),{stage:D(i.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${e}.stage`),goal_cycle:_(i.goal_cycle,`${e}.goal_cycle`,1),iteration:_(i.iteration,`${e}.iteration`),attempt:_(i.attempt,`${e}.attempt`),retry_epoch:_(i.retry_epoch,`${e}.retry_epoch`),failed_iteration_count:_(i.failed_iteration_count,`${e}.failed_iteration_count`),no_progress_count:_(i.no_progress_count,`${e}.no_progress_count`),execution_failure_count:_(i.execution_failure_count,`${e}.execution_failure_count`),previous_unresolved_ids:r,next_action:zo(i.next_action,`${e}.next_action`)}}function Gg(t,e){let i=`Native acceptance[${e}]`,r=z(t,i);J(r,new Set(["id","source","text","result","reason"]),i);let n=L(r.id,`${i}.id`);if(!Bg.test(n))throw new Error(`${i}.id must use A1, A2, ...`);return{id:n,source:Jo(r.source,`${i}.source`),text:L(r.text,`${i}.text`),result:D(r.result,["pending","passed","failed","blocked"],`${i}.result`),reason:r.reason===null?null:se(r.reason,`${i}.reason`)}}function Ug(t,e){let i=`Native builder_handoff.checks[${e}]`,r=z(t,i);return J(r,new Set(["name","result","note"]),i),{name:se(r.name,`${i}.name`),result:D(r.result,["passed","failed","not-run"],`${i}.result`),note:r.note===null?null:se(r.note,`${i}.note`)}}function Kg(t){let e="Native builder_handoff",i=z(t,e);J(i,new Set(["candidate_id","identity_provider","builder_execution_ref","iteration","summary","addressed_acceptance_ids","checks","checks_truncated","known_limits","known_limits_truncated","submitted_at"]),e);let r=sn(i.addressed_acceptance_ids,`${e}.addressed_acceptance_ids`);return rt(r,`${e}.addressed_acceptance_ids`),{candidate_id:L(i.candidate_id,`${e}.candidate_id`),identity_provider:L(i.identity_provider,`${e}.identity_provider`),builder_execution_ref:L(i.builder_execution_ref,`${e}.builder_execution_ref`),iteration:_(i.iteration,`${e}.iteration`,1),summary:se(i.summary,`${e}.summary`),addressed_acceptance_ids:r,checks:ve(i.checks,`${e}.checks`,Ug),checks_truncated:Ct(i.checks_truncated,`${e}.checks_truncated`),known_limits:ve(i.known_limits,`${e}.known_limits`,(n,a)=>se(n,`${e}.known_limits[${a}]`)),known_limits_truncated:Ct(i.known_limits_truncated,`${e}.known_limits_truncated`),submitted_at:Rt(i.submitted_at,`${e}.submitted_at`)}}function Yg(t,e){let i=`Native blockers[${e}]`,r=z(t,i);J(r,new Set(["owner","reason","acceptance_ids","resolution_action"]),i);let n=sn(r.acceptance_ids,`${i}.acceptance_ids`);return rt(n,`${i}.acceptance_ids`),{owner:D(r.owner,["builder","runtime","verifier","user","external"],`${i}.owner`),reason:se(r.reason,`${i}.reason`),acceptance_ids:n,resolution_action:D(r.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${i}.resolution_action`)}}function Xg(t,e){let i=`Native verification.checks[${e}]`,r=z(t,i);return J(r,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),i),{id:L(r.id,`${i}.id`),name:se(r.name,`${i}.name`),argv_display:ve(r.argv_display,`${i}.argv_display`,(n,a)=>se(n,`${i}.argv_display[${a}]`)),argv_truncated:Ct(r.argv_truncated,`${i}.argv_truncated`),cwd_ref:Jo(r.cwd_ref,`${i}.cwd_ref`,!0),status:D(r.status,["passed","failed","interrupted"],`${i}.status`),exit_code:qg(r.exit_code,`${i}.exit_code`),duration_ms:_(r.duration_ms,`${i}.duration_ms`)}}function Qg(t){let e="Native verification",i=z(t,e);J(i,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),e);let r=ve(i.checks,`${e}.checks`,Xg);rt(r.map(a=>a.id),`${e}.checks IDs`);let n=L(i.identity_provider,`${e}.identity_provider`);return{candidate_id:L(i.candidate_id,`${e}.candidate_id`),identity_provider:n,verifier_execution_ref:L(i.verifier_execution_ref,`${e}.verifier_execution_ref`),iteration:_(i.iteration,`${e}.iteration`,1),attempt:_(i.attempt,`${e}.attempt`,1),assurance:i.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":D(i.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${e}.assurance`),verdict:D(i.verdict,["pass","fail","blocked"],`${e}.verdict`),checks:r,summary:se(i.summary,`${e}.summary`),risks:ve(i.risks,`${e}.risks`,(a,o)=>se(a,`${e}.risks[${o}]`)),risks_truncated:Ct(i.risks_truncated,`${e}.risks_truncated`),completed_at:Rt(i.completed_at,`${e}.completed_at`)}}function Zg(t,e){let i=`Native history[${e}]`,r=z(t,i);J(r,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),i);let n=sn(r.unresolved_ids,`${i}.unresolved_ids`);return rt(n,`${i}.unresolved_ids`),{goal_cycle:_(r.goal_cycle,`${i}.goal_cycle`,1),iteration:_(r.iteration,`${i}.iteration`),attempt:_(r.attempt,`${i}.attempt`),outcome:D(r.outcome,["pass","fail","blocked","execution-error","recovery"],`${i}.outcome`),unresolved_ids:n,summary:se(r.summary,`${i}.summary`),completed_at:Rt(r.completed_at,`${i}.completed_at`)}}function ew(t){let e="Native history_overflow.outcome_counts",i=z(t,e),r=["pass","fail","blocked","execution-error","recovery"];return J(i,new Set(r),e),{pass:_(i.pass,`${e}.pass`),fail:_(i.fail,`${e}.fail`),blocked:_(i.blocked,`${e}.blocked`),"execution-error":_(i["execution-error"],`${e}.execution-error`),recovery:_(i.recovery,`${e}.recovery`)}}function tw(t){let e="Native history_overflow",i=z(t,e);J(i,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),e);let r=_(i.dropped_entries,`${e}.dropped_entries`),n=i.first_dropped_at===null?null:Rt(i.first_dropped_at,`${e}.first_dropped_at`),a=i.last_dropped_at===null?null:Rt(i.last_dropped_at,`${e}.last_dropped_at`);if(r===0&&(n!==null||a!==null))throw new Error("Native empty history overflow cannot contain dropped timestamps");if(r>0&&(n===null||a===null))throw new Error("Native non-empty history overflow requires dropped timestamps");let o=ew(i.outcome_counts);if(Object.values(o).reduce((c,l)=>c+l,0)!==r)throw new Error("Native history overflow outcome count must equal dropped_entries");return{dropped_entries:r,first_dropped_at:n,last_dropped_at:a,outcome_counts:o}}function iw(t){let e=new Set(t.acceptance.map(i=>i.id));for(let i of t.loop.previous_unresolved_ids)if(!e.has(i))throw new Error(`Native loop references unknown acceptance ID ${i}`);for(let i of t.builder_handoff?.addressed_acceptance_ids??[])if(!e.has(i))throw new Error(`Native builder handoff references unknown ID ${i}`);for(let i of t.blockers)for(let r of i.acceptance_ids)if(!e.has(r))throw new Error(`Native blocker references unknown ID ${r}`);if(t.builder_handoff&&!(t.builder_handoff.iteration===t.loop.iteration||t.phase==="build"&&t.loop.stage==="repairing"&&t.builder_handoff.iteration===t.loop.iteration-1))throw new Error("Native builder handoff iteration is not current or the prior repair result");if(t.verification){if(!t.builder_handoff)throw new Error("Native verification requires a builder handoff");if(t.verification.candidate_id!==t.builder_handoff.candidate_id)throw new Error("Native verification candidate must match the builder handoff");if(t.verification.identity_provider!==t.builder_handoff.identity_provider)throw new Error("Native Builder and Verifier identity providers must match");if(["skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"].includes(t.verification.assurance)!==(t.verification.identity_provider==="skill-coordinated"))throw new Error("Native verification assurance does not match its identity provider");if(t.verification.assurance==="semantic-verification-unavailable"&&t.verification.verdict!=="blocked")throw new Error("Native unavailable semantic verification must remain blocked");if(t.verification.assurance==="user-confirmed-degraded"&&t.verification.verdict!=="pass")throw new Error("Native user-confirmed degraded verification must be passing");if(t.verification.verifier_execution_ref===t.builder_handoff.builder_execution_ref)throw new Error("Native Builder and Verifier execution refs must differ");let r=t.verification.iteration===t.loop.iteration&&t.verification.attempt===t.loop.attempt,n=t.phase==="build"&&t.loop.stage==="repairing"&&t.verification.iteration===t.loop.iteration-1&&t.verification.iteration===t.builder_handoff.iteration;if(!r&&!n)throw new Error("Native verification iteration and attempt do not match a stable loop result")}}function rw(t){if(!{shape:new Set(["shape","await-user","blocked"]),build:new Set(["building","repairing","await-user","blocked"]),verify:new Set(["verify-ready","await-user","blocked"]),archive:new Set(["archive-ready","await-user","blocked","done"])}[t.phase].has(t.loop.stage))throw new Error(`Native loop stage ${t.loop.stage} is invalid for phase ${t.phase}`);let i=t.status==="await-user"?"await-user":t.status==="blocked"?"blocked":t.status==="done"?"done":null;if(i!==null&&t.loop.stage!==i)throw new Error(`Native status ${t.status} requires loop stage ${i}`);if(t.status==="active"&&["await-user","blocked","done"].includes(t.loop.stage))throw new Error(`Native active status cannot use loop stage ${t.loop.stage}`);if(t.archived!==(t.status==="done"))throw new Error("Native archived must be true exactly when status is done");if(t.archived&&t.phase!=="archive")throw new Error("Native archived state must be in Archive");if(t.verification_result==="pass"){if(t.verification?.verdict!=="pass")throw new Error("Native pass requires a persisted passing verification");if(t.acceptance.some(r=>r.result!=="passed"))throw new Error("Native pass requires every acceptance item to pass");if(t.verification.checks.some(r=>r.status!=="passed"))throw new Error("Native pass requires every persisted check to pass")}if(t.verification?.assurance==="semantic-verification-unavailable"&&(t.phase!=="verify"||t.status!=="await-user"||t.verification_result!=="blocked"||t.loop.next_action!=="confirm-verifier-unavailable"))throw new Error("Native unavailable semantic verification must await explicit user confirmation");if(t.verification_report!==null&&t.verification===null)throw new Error("Native verification report requires persisted verification")}function nt(t){let e=z(t,"Native portable state");if(J(e,Fg,"Native portable state"),e.schema!==xt)throw new Error(`Native portable state schema must be ${xt}`);let i=L(e.name,"Native state name");if(!Dg.test(i))throw new Error("Native state name is invalid");if(e.brief!=="brief.md")throw new Error("Native state brief must be brief.md");let r=ve(e.spec_changes,"Native spec_changes",Wg);rt(r.map(s=>s.capability),"Native spec change capabilities");let n=ve(e.acceptance,"Native acceptance",Gg);rt(n.map(s=>s.id),"Native acceptance IDs");let a=ve(e.history,"Native history",Zg);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:xt,name:i,language:D(e.language,["en","zh-CN"],"Native state language"),phase:D(e.phase,["shape","build","verify","archive"],"Native state phase"),status:D(e.status,["active","await-user","blocked","done"],"Native state status"),state_version:_(e.state_version,"Native state_version",1),brief:"brief.md",...e.children_contract_hash===void 0?{}:{children_contract_hash:Vg(e.children_contract_hash,"Native children contract hash")},spec_changes:r,workspace:zg(e.workspace),loop:Jg(e.loop),acceptance:n,builder_handoff:e.builder_handoff===null?null:Kg(e.builder_handoff),blockers:ve(e.blockers,"Native blockers",Yg),verification:e.verification===null?null:Qg(e.verification),history:a,history_overflow:tw(e.history_overflow),verification_result:D(e.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:e.verification_report===null?null:D(e.verification_report,["verification.md"],"Native verification_report"),archived:Ct(e.archived,"Native archived"),created_at:Rt(e.created_at,"Native created_at")};return iw(o),rw(o),o}function nw(t,e){let i=(0,on.parseDocument)(t,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`${e} is invalid YAML: ${i.errors[0].message}`);return i.toJS({mapAsMap:!1})}async function Ce(t){let e=await Hg.readFile(t,"utf8");return nt(nw(e,"Native portable state"))}async function cn(t,e,i={}){let r=nt(e);await de(t,(0,on.stringify)(r),i)}var nn=new Map;async function aw(t,e){let i=nn.get(t)??Promise.resolve(),r,n=new Promise(o=>{r=o}),a=i.then(()=>n);nn.set(t,a),await i;try{return await e()}finally{r(),nn.get(t)===a&&nn.delete(t)}}async function Hu(t){return aw(t.file,async()=>{let e=_(t.expectedStateVersion,"Native expected state version",1),i=nt(t.next);if(i.state_version!==e+1)throw new Error("Native CAS next state_version must increment exactly once");let r=await Ce(t.file);if(r.state_version===i.state_version&&JSON.stringify(r)===JSON.stringify(i))return r;if(r.state_version!==e)throw new an(e,r.state_version);return await cn(t.file,i,{...t.containedRoot?{containedRoot:t.containedRoot}:{},beforeCommit:async()=>{let n=await Ce(t.file);if(n.state_version!==e)throw new an(e,n.state_version)}}),i})}function ow(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("Native portable text byte budget must be a non-negative safe integer")}function ln(t,e=16384){if(typeof t!="string")throw new Error("Native portable text must be a string");if(ow(e),Buffer.byteLength(t,"utf8")<=e)return{text:t,truncated:!1};let i="",r=0;for(let n of t){let a=Buffer.byteLength(n,"utf8");if(r+a>e)break;i+=n,r+=a}return{text:i,truncated:!0}}var Re="comet.native.v3",ge="comet.native.v2",we="comet.native.v1";var un="comet.native.portable-migration.v1",cw=new Set(["schema","id","change","fromSchema","status","createdAt"]),lw=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,uw=/^[a-z0-9][a-z0-9-]{7,127}$/u,dw=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),fw=new Set([we,ge,Re]);function hw(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function pw(t,e){let i=t instanceof Date?new Date(t.valueOf()):new Date(t);if(Number.isNaN(i.valueOf()))throw new Error(`${e} must be a valid timestamp`);return i.toISOString()}function mw(t,e){if(typeof t!="string")throw new Error(`${e} must be an ISO timestamp`);let i=new Date(t);if(Number.isNaN(i.valueOf())||i.toISOString()!==t)throw new Error(`${e} must be a canonical ISO timestamp`);return t}function vw(t){return t.schema===we?ki(t):t.schema===ge?Si(t):Ei(t)}function gw(t){return sw.posix.normalize(t.replaceAll("\\","/"))}function ww(t){return t.spec_changes.map(e=>e.operation==="remove"?{capability:e.capability,operation:"remove",source:null}:{capability:e.capability,operation:e.operation==="replace"?"modify":"create",source:gw(e.source)})}function yw(t){return t==="shape"?"shape":"build"}function Nw(t,e){return t==="zh-CN"?e==="shape"?"继续澄清并确认验收项":"重新提交候选实现":e==="shape"?"Continue clarification and confirm acceptance":"Submit a fresh implementation candidate"}function bw(t,e,i){return t==="zh-CN"?`从旧版 ${e} ${i} 状态恢复;旧版 Loop、验证结论和运行记录未继承。`:`Recovered from legacy ${e} ${i} state; prior Loop, verification results, and execution records were not inherited.`}function Du(t){let e=vw(t.state);$u(t.acceptance);let i=yw(e.phase),r=i==="shape"?0:1,n=pw(t.migratedAt??`${e.created_at}T00:00:00.000Z`,"Native portable migration time"),a=t.acceptance.map(o=>({id:o.id,source:o.source,text:o.text,result:"pending",reason:null}));return nt({schema:xt,name:e.name,language:e.language,phase:i,status:"active",state_version:1,brief:"brief.md",spec_changes:ww(e),workspace:t.workspace,loop:{stage:i==="shape"?"shape":"building",goal_cycle:1,iteration:r,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:Nw(e.language,i)},acceptance:a,builder_handoff:null,blockers:[],verification:null,history:[{goal_cycle:1,iteration:r,attempt:0,outcome:"recovery",unresolved_ids:a.map(({id:o})=>o),summary:ln(bw(e.language,e.schema,e.phase)),completed_at:n}],history_overflow:Wo(),verification_result:"pending",verification_report:null,archived:!1,created_at:`${e.created_at}T00:00:00.000Z`})}function Go(t){let e=hw(t,"Native portable migration transaction"),i=Object.keys(e).filter(r=>!cw.has(r));if(i.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${i.join(", ")}`);if(e.schema!==un)throw new Error("Unsupported Native portable migration transaction schema");if(typeof e.id!="string"||!uw.test(e.id))throw new Error("Native portable migration transaction id is invalid");if(typeof e.change!="string"||!lw.test(e.change))throw new Error("Native portable migration transaction change is invalid");if(typeof e.fromSchema!="string"||!fw.has(e.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof e.status!="string"||!dw.has(e.status))throw new Error("Native portable migration transaction status is invalid");return{schema:un,id:e.id,change:e.change,fromSchema:e.fromSchema,status:e.status,createdAt:mw(e.createdAt,"Native portable migration transaction createdAt")}}function Lu(t){switch(Go(t).status){case"prepared":return{action:"commit-portable-yaml",fromStatus:"prepared",nextStatus:"yaml-committed"};case"yaml-committed":return{action:"cleanup-legacy-runtime",fromStatus:"yaml-committed",nextStatus:"legacy-cleanup"};case"legacy-cleanup":return{action:"commit-transaction",fromStatus:"legacy-cleanup",nextStatus:"committed"};case"committed":return{action:"done",fromStatus:"committed",nextStatus:null}}}var Bu="comet.native.archive-transaction.v4",Mu="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",kw=new RegExp(`^portable-archive-(${Mu})\\.json$`,"u"),Sw=new RegExp(`^portable-migration-(${Mu})\\.json$`,"u"),Ew=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Pw=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,xw=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),Cw=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),Rw=new Set(["capability","operation","source","content"]),Fu=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function Vu(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function qu(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(", ")}`);if(Object.keys(t).length!==e.size)throw new Error(`${i} fields are invalid`)}function Aw(t,e){let i=`Native portable Archive spec_changes[${e}]`,r=Vu(t,i);if(qu(r,Rw,i),typeof r.capability!="string"||!Fu.test(r.capability))throw new Error(`${i}.capability is invalid`);if(!["create","modify","remove"].includes(String(r.operation)))throw new Error(`${i}.operation is invalid`);let n=r.operation;if(n==="remove"){if(r.source!==null||r.content!==null)throw new Error(`${i} remove requires source and content null`);return{capability:r.capability,operation:n,source:null,content:null}}if(typeof r.source!="string"||r.source.length===0||r.source.includes("\\")||r.source.startsWith("/")||/^[A-Za-z]:/u.test(r.source)||r.source.split("/").some(a=>a==="."||a===".."))throw new Error(`${i}.${n} source is invalid`);if(typeof r.content!="string")throw new Error(`${i}.${n} content is invalid`);return{capability:r.capability,operation:n,source:r.source,content:r.content}}function _w(t){let e=Vu(t,"Native portable Archive transaction");if(qu(e,Cw,"Native portable Archive transaction"),e.schema!==Bu)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof e.id!="string"||!Ew.test(e.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof e.change!="string"||!Fu.test(e.change))throw new Error("Native portable Archive transaction change is invalid");if(!Number.isSafeInteger(e.start_state_version)||Number(e.start_state_version)<0)throw new Error("Native portable Archive transaction state version is invalid");if(typeof e.archive_ref!="string"||!Pw.test(e.archive_ref)||!e.archive_ref.endsWith(`-${e.change}`))throw new Error("Native portable Archive transaction ref is invalid");if(typeof e.status!="string"||!xw.has(e.status))throw new Error("Native portable Archive transaction status is invalid");if(!Array.isArray(e.spec_changes))throw new Error("Native portable Archive transaction spec changes are invalid");let i=e.spec_changes.map(Aw);if(new Set(i.map(({capability:n})=>n)).size!==i.length)throw new Error("Native portable Archive transaction capabilities must be unique");if(!Number.isSafeInteger(e.next_spec_index)||Number(e.next_spec_index)<0||Number(e.next_spec_index)>i.length)throw new Error("Native portable Archive transaction spec cursor is invalid");if(typeof e.created_at!="string")throw new Error("Native portable Archive transaction timestamp is invalid");let r=new Date(e.created_at);if(Number.isNaN(r.valueOf())||r.toISOString()!==e.created_at)throw new Error("Native portable Archive transaction timestamp is invalid");return{schema:Bu,id:e.id,change:e.change,start_state_version:Number(e.start_state_version),archive_ref:e.archive_ref,status:e.status,next_spec_index:Number(e.next_spec_index),spec_changes:i,created_at:e.created_at}}function dn(t){let e=kw.exec(t);if(e)return{kind:"archive",change:e[1]};let i=Sw.exec(t);return i?{kind:"migration",change:i[1]}:null}function fn(t,e){let i=`${e.kind==="archive"?"portable-archive":"portable-migration"}-${e.change}.json`,r=dn(i);if(!r||r.kind!==e.kind||r.change!==e.change)throw new Error(`Invalid Native portable transaction change: ${e.change}`);return Uo.join(t.transactionsDir,i)}async function Ko(t,e){let i=dn(e);if(!i)return null;let r=await M({root:t.transactionsDir,ref:e,maxBytes:null,includeHash:!1}),n=JSON.parse(r.text),a=Uo.join(t.transactionsDir,e);if(i.kind==="archive"){let s=_w(n);if(s.change!==i.change)throw new Error(`Native portable transaction filename does not match ${s.change}`);return{kind:"archive",change:i.change,file:a,journal:s}}let o=Go(n);if(o.change!==i.change)throw new Error(`Native portable transaction filename does not match ${o.change}`);return{kind:"migration",change:i.change,file:a,journal:o}}async function Wu(t,e){let i=fn(t,e);try{return await Ko(t,Uo.basename(i))}catch(r){if(r.code==="ENOENT")return null;throw r}}function zu(t){return t.kind==="archive"||t.journal.status!=="committed"}import Ae from"path";import{TextDecoder as Lw}from"util";import{createHash as Tw}from"node:crypto";import{constants as hn,promises as ce}from"node:fs";import le from"node:path";function mn(t,e){let i=le.relative(t,e);return i===""||!le.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${le.sep}`)}function Iw(t){if(!Number.isSafeInteger(t)||t<1)throw new Error("Native protected file byte limit must be a positive integer");return t}function jw(t,e){return A({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function $w(t){return{dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs,ctimeMs:t.ctimeMs,mtimeMs:t.mtimeMs,size:t.size}}function pn(t,e){return A({...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 Yo(t,e){let i=await ce.lstat(t);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${e} parent must be a real directory: ${t}`);return{path:t,realPath:await ce.realpath(t),dev:i.dev,ino:i.ino,birthtimeMs:i.birthtimeMs}}async function Ow(t,e,i){let r=le.resolve(t),n=le.resolve(e);if(!mn(r,n))throw new Error(`${i} is outside its managed root`);let a=[await Yo(r,i)],o=r;for(let s of le.relative(r,n).split(le.sep).filter(Boolean)){await at(a,i),o=le.join(o,s);let c=await Yo(o,i);if(!mn(a[0].realPath,c.realPath))throw new Error(`${i} parent resolves outside its managed root: ${o}`);a.push(c)}return await at(a,i),a}async function at(t,e){for(let i of t){let r=await ce.lstat(i.path);if(!r.isDirectory()||r.isSymbolicLink()||!jw(i,r)||await ce.realpath(i.path)!==i.realPath)throw new Error(`${e} parent changed during I/O: ${i.path}`)}}async function Hw(t,e,i){let r=[],n=0,a=Buffer.allocUnsafe(Math.min(64*1024,e+1));for(;;){let o=e+1-n,{bytesRead:s}=await t.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,n>e)throw new Error(`${i} exceeds ${e} bytes`);r.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(r,n)}async function At(t){let e=Iw(t.maxBytes),i=le.resolve(t.file),r=await Ow(t.root,le.dirname(i),t.label),n=await Promise.all((t.forbiddenRoots??[]).map(f=>Yo(le.resolve(f),t.label)));await t.hooks?.afterParentChainCaptured?.(),await at(r,t.label);let a=await ce.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=$w(a),s=await ce.realpath(i);if(!mn(r[0].realPath,s))throw new Error(`${t.label} resolves outside its managed root`);if(n.some(f=>mn(f.realPath,s)))throw new Error(`${t.label} resolves inside an excluded root`);let c=process.platform==="win32"?hn.O_RDONLY:hn.O_RDONLY|hn.O_NOFOLLOW|hn.O_NONBLOCK,l=await ce.open(i,c);try{let f=await l.stat();await t.hooks?.afterOpen?.();let[d,u]=await Promise.all([ce.lstat(i),ce.realpath(i)]);if(await at(r,t.label),await at(n,t.label),!f.isFile()||!d.isFile()||d.isSymbolicLink()||u!==s||!pn(o,f)||!pn(o,d))throw new Error(`${t.label} changed while opening`);await t.hooks?.beforeRead?.();let p=await Hw(l,e,t.label);await t.hooks?.beforeFinalCheck?.();let[v,h,m]=await Promise.all([l.stat(),ce.lstat(i),ce.realpath(i)]);if(await at(r,t.label),await at(n,t.label),!h.isFile()||h.isSymbolicLink()||m!==s||!pn(o,v)||!pn(o,h))throw new Error(`${t.label} changed while reading`);return{bytes:p,hash:Tw("sha256").update(p).digest("hex"),size:p.length}}finally{await l.close()}}var Bw=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),Mw=new Set(["id","type","source","target","staged","backup"]),Fw=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),Vw=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]);var Uu=new Set(["prepared","applying","committed","rolling-back","rolled-back"]);var qw=256*1024,lE=1024*1024,uE=16*1024;var dE=64*1024*1024;var Ww=new Lw("utf-8",{fatal:!0});function gn(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function wn(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 Ku(t){if(typeof t!="string")return!1;let e=new Date(t);return!Number.isNaN(e.valueOf())&&e.toISOString()===t}function Xo(t,e){if(typeof t!="string"||t.length===0||Ae.isAbsolute(t)||/^(?:[A-Za-z]:|~|[\\/])/u.test(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`${e} must stay inside the Native root`)}function vn(t,e){if(typeof t!="string"||!/^[a-f0-9]{64}$/u.test(t))throw new Error(`${e} must be a SHA-256 hash`)}function Ju(t,e){if(Xo(t,e),t.includes("\\")||t!==Ae.posix.normalize(t)||t.split("/").includes(".")||t.endsWith("/")||Buffer.byteLength(t,"utf8")>1024)throw new Error(`${e} must be a normalized Native-relative ref`)}function zw(t,e){let i=gn(t,`transaction operations[${e}]`);if(wn(i,Mw,`transaction operations[${e}]`),typeof i.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(i.id))throw new Error(`transaction operations[${e}].id is invalid`);if(i.type!=="write"&&i.type!=="remove"&&i.type!=="move")throw new Error(`transaction operation ${i.id} has an invalid type`);Xo(i.target,`transaction operation ${i.id} target`);for(let r of["source","staged","backup"])i[r]!==void 0&&Xo(i[r],`transaction operation ${i.id} ${r}`);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 Yu(t){let e=gn(t,"Native Archive transaction journal");if(wn(e,Fw,"Native Archive transaction journal"),e.schema!=="comet.native.transaction.v2")throw new Error("Unsupported Native Archive transaction schema");if(typeof e.id!="string"||!/^[a-f0-9-]{8,}$/u.test(e.id))throw new Error("Native Archive transaction id is invalid");if(e.kind!=="archive")throw new Error("Native v2 transaction kind must be archive");if(typeof e.status!="string"||!Uu.has(e.status))throw new Error("Native Archive transaction status is invalid");if(typeof e.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.change))throw new Error("Native Archive transaction change name is invalid");if(!Ku(e.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(vn(e.preflightHash,"Native Archive transaction preflightHash"),!Array.isArray(e.operations)||e.operations.length>65)throw new Error("Native Archive transaction operations must be an array");let i=e.operations.map((s,c)=>{let l=gn(s,`Archive transaction operations[${c}]`);if(wn(l,Vw,`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`);Ju(l.target,`Archive transaction operation ${l.id} target`);for(let f of["source","staged","backup"])l[f]!==void 0&&Ju(l[f],`Archive transaction operation ${l.id} ${f}`);if(l.expectedTargetHash!==null&&vn(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(vn(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`);vn(l.expectedSourceHash,`Archive move operation ${l.id} expectedSourceHash`)}return l}),r=i.map(s=>s.id);if(new Set(r).size!==r.length)throw new Error("Native Archive transaction operation ids must be unique");let n=`runtime/transactions/${e.id}`,a=i.filter(s=>s.type==="move");if(a.length!==1||a[0].id!=="archive-change"||a[0].source!==`changes/${e.change}`||!new RegExp(`^archive/\\d{4}-\\d{2}-\\d{2}-${e.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(`${n}/staged/specs/`))throw new Error(`Native Archive transaction staged ref is invalid: ${s.staged}`);if(s.backup!==void 0&&!s.backup.startsWith(`${n}/backups/specs/`))throw new Error(`Native Archive transaction backup ref is invalid: ${s.backup}`)}return{schema:"comet.native.transaction.v2",id:e.id,kind:"archive",status:e.status,change:e.change,createdAt:e.createdAt,preflightHash:e.preflightHash,operations:i}}function Jw(t){let e=gn(t,"Native transaction journal");if(e.schema==="comet.native.transaction.v2")return Yu(e);if(wn(e,Bw,"Native transaction journal"),e.schema!=="comet.native.transaction.v1")throw new Error("Unsupported Native transaction schema");if(typeof e.id!="string"||!/^[a-f0-9-]{8,}$/u.test(e.id))throw new Error("Native transaction id is invalid");if(e.kind!=="archive"&&e.kind!=="root-move")throw new Error("Native transaction kind is invalid");if(typeof e.status!="string"||!Uu.has(e.status))throw new Error("Native transaction status is invalid");if(typeof e.projectRoot!="string"||!Ae.isAbsolute(e.projectRoot)||typeof e.nativeRoot!="string"||!Ae.isAbsolute(e.nativeRoot))throw new Error("Native transaction roots must be absolute paths");if(e.change!==void 0&&(typeof e.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.change)))throw new Error("Native transaction change name is invalid");if(!Ku(e.createdAt))throw new Error("Native transaction createdAt is invalid");if(!Array.isArray(e.operations))throw new Error("Native transaction operations must be an array");let i=e.operations.map(zw),r=i.map(n=>n.id);if(new Set(r).size!==r.length)throw new Error("Native transaction operation ids must be unique");return{schema:"comet.native.transaction.v1",id:e.id,kind:e.kind,status:e.status,projectRoot:e.projectRoot,nativeRoot:e.nativeRoot,...typeof e.change=="string"?{change:e.change}:{},createdAt:e.createdAt,operations:i}}function Gw(t,e){if(!/^[a-f0-9-]{8,}$/u.test(e))throw new Error(`Invalid Native transaction id: ${e}`);return Ae.join(t.transactionsDir,e)}function Xu(t,e){let i=Gw(t,e);return{directory:i,journal:Ae.join(i,"transaction.json"),events:Ae.join(i,"events.jsonl"),staged:Ae.join(i,"staged"),backups:Ae.join(i,"backups")}}async function Zo(t,e){let i=Xu(t,e);return await Promise.all(Object.values(i).map(r=>T(t.runtimeDir,r))),i}async function es(t,e,i={}){let r=await Zo(t,e),n=await At({root:t.runtimeDir,file:r.journal,maxBytes:qw,label:`Native transaction journal ${e}`,hooks:i.hooks}),a=JSON.parse(Ww.decode(n.bytes)),o=Jw(a);if(o.id!==e)throw new Error(`Invalid Native transaction journal: ${e}`);return o}async function Yw(t,e,i){let r;try{r=await Uw.readdir(t.transactionsDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return!1;throw n}for(let n of r)if(!(!n.isDirectory()||n.isSymbolicLink()))try{let a=await es(t,n.name);if(a.id!==e&&a.status!=="committed"&&a.status!=="rolled-back")return!0}catch{return!0}for(let n of r)if(dn(n.name))try{let a=await Ko(t,n.name);if(!a||i?.kind===a.kind&&i.change===a.change)continue;if(zu(a))return!0}catch{return!0}return!1}async function Xw(t,e){let i=Date.now()+5e3,r=Kw.join(t.locksDir,"root-move.lock");for(;;)try{return await tn(t,"root-move",e)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await _u(r);if(o.status==="missing")continue;if(o.status!=="active"||Date.now()>=i)throw n;await new Promise(s=>setTimeout(s,5+Math.floor(Math.random()*11)))}}async function Z(t,e,i,r){let n=await Xw(t,e);try{if(await Zr(t.projectRoot),await Yw(t,r?.allowedTransactionId,r?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await i()}finally{await rn(n)}}import{createHash as Qw}from"crypto";function ee(t){return Qw("sha256").update(t).digest("hex")}var IE={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024};var jE=8*1024*1024;var $E=64*1024,OE=64*1024;var HE={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},DE={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};var LE=(1n<<256n)-1n;var ay=$t(yt(),1);var eP=4*1024*1024;var oy=null;function sy(t,e){let i=t;for(let r of e)i+="\0"+(typeof r=="string"?r:JSON.stringify(r));return i}function Qu(t,e){return(...i)=>{let r=oy;if(r===null)return e(...i);let n=sy(`async:${t}`,i),a=r.entries.get(n);if(a)return a.value;let o=e(...i).catch(s=>{throw r.entries.delete(n),s});return r.entries.set(n,{value:o}),o}}var aP=Qu("hookWritePolicy",async t=>(await Po(t))?.hook??{allow_paths:[]});var ex=256*1024;var hx={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 _t from"node:path";var Pi=/^[a-f0-9]{64}$/u,ed=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,uy=16*1024,Ax=process.platform;function dy(t,e){let i=_t.relative(t,e);return _t.isAbsolute(i)||i===".."||i.startsWith(`..${_t.sep}`)?null:i.replaceAll("\\","/")||"."}function td(t){return Array.from(t).some(e=>{let i=e.codePointAt(0)??0;return i<=31||i===127})}function id(t,e){if(t.length===0||td(t)||t.includes("\\")||_t.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=_t.posix.normalize(t);if(i!==t||i===".."||i.startsWith("../"))throw new Error(`${e} must be a normalized project-relative path`);return i}function fy(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 ts(t,e){if(t===null)return null;if(typeof t!="string"||t.length===0||t.trim()!==t||td(t))throw new Error(`${e} must be a non-empty branch name or null`);return t}function hy(t){if(!new Set(["current","branch","worktree"]).has(t.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(ts(t.changeBranch,"Native workspace change branch"),ts(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 py(t){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Native workspace Git provenance must be an object");let e=t,i=new Set(["provider","baseCommit","targetBranch","targetCommit"]),r=Object.keys(e).filter(n=>!i.has(n));if(r.length>0)throw new Error(`Native workspace Git provenance has unknown field(s): ${r.join(", ")}`);if(e.provider!=="git"||typeof e.baseCommit!="string"||!ed.test(e.baseCommit)||typeof e.targetCommit!="string"||!ed.test(e.targetCommit))throw new Error("Native workspace Git provenance is invalid");ts(e.targetBranch,"Native workspace Git target branch")}function my(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","git","isolation","changeBranch","targetBranch","finish"]),r=Object.keys(e).filter(o=>!i.has(o));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"||!Pi.test(String(e.projectRootId))||!Pi.test(String(e.nativeRootId)))throw new Error("Native workspace identity is invalid");fy(e.capturedAt),id(e.nativeRootRef,"Native workspace root ref");let n=e.projectRootPathId!==void 0,a=e.nativeRootPathId!==void 0;if(n!==a)throw new Error("Native workspace path identities must be provided together");if(n&&!Pi.test(String(e.projectRootPathId))||a&&!Pi.test(String(e.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(e.sessionHash!==void 0&&!Pi.test(String(e.sessionHash)))throw new Error("Native workspace session hash is invalid");if(e.git!==void 0&&py(e.git),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(hy(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 vy(t,e){return _t.join(pe(t,e),"workspace.json")}function gy(t,e){let i=vy(t,e),r=me(t,i),n=dy(r,i);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:r,ref:id(n,"Native workspace file ref")}}async function wy(t,e){try{let i=gy(t,e),r=await M({root:i.root,ref:i.ref,maxBytes:uy});return JSON.parse(r.text)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function xi(t,e){let i=await wy(t,e);return i===null||i&&typeof i=="object"&&!Array.isArray(i)&&i.schema==="comet.native.workspace.v1"?null:(my(i),i)}var ad=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],Ny=new Set(ad),od=new Set([...ad,"minimum_runtime_version","revision"]),by=new Set([...od,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),ky=new Set(["capability","operation","source","base_hash"]),Sy=new Set(["shape","build","verify","archive"]),Ey=new Set(["implicit","confirmed"]),Py=new Set(["pending","pass","fail"]),ot="comet-state.yaml",rs=/^[a-f0-9]{64}$/u,sd=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,xy=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,ns=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"},It=class extends Error{constructor(i,r){super(i!==Re||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"},yn=class extends Error{constructor(i,r,n){super(`Native change ${i} revision conflict: expected ${r}, actual ${n}`);this.change=i;this.expectedRevision=r;this.actualRevision=n;this.name="NativeChangeRevisionConflictError"}change;expectedRevision;actualRevision;code="native-change-revision-conflict"},Ci=class extends Error{constructor(i,r){super(`Native working directory already contains active change${r.length===1?"":"s"} ${r.join(", ")}; create the new change in a separate worktree`);this.requestedIsolation=i;this.activeChanges=r;this.name="NativeWorkspaceIsolationRequiredError"}requestedIsolation;activeChanges;code="native-workspace-isolation-required"},Nn=class extends Error{constructor(i,r,n,a,o,s=null,c=null){super(`Native change ${i} baseline is incomplete (${r} omitted entr${r===1?"y":"ies"}). Adjust native.snapshot scope or resource budgets in .comet/config.yaml, then retry.`);this.change=i;this.omittedCount=r;this.omittedByReason=n;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"},eC=["# Outcome","","# Scope","","# Non-goals","","# Acceptance examples","","# Constraints and invariants","","# Decisions","","# Open questions","","# Verification expectations",""].join(`
|
|
150
|
-
`);function Ai(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function cd(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 os(t){if(!sd.test(t))throw new Error(`Invalid Native change name: ${t}`)}function Cy(t){if(!sd.test(t))throw new Error(`Invalid Native capability id: ${t}`)}function ld(t,e){if(t.length===0||Tt.isAbsolute(t)||/^(?:[A-Za-z]:|~|[\\/])/u.test(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`${e} must stay inside the Native change`)}function Ry(t,e){let i=Ai(t,`spec_changes[${e}]`);if(cd(i,ky,`spec_changes[${e}]`),typeof i.capability!="string")throw new Error("spec change capability is required");if(Cy(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"&&ld(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"||!rs.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"||!rs.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 Ay(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 ss(t,e){if(cd(t,e,ot),typeof t.name!="string")throw new Error("Native change name is required");if(os(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"||!Sy.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&&!Ey.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(Ry),r=i.map(n=>n.capability).filter((n,a,o)=>o.indexOf(n)!==a);if(r.length>0)throw new Error(`Duplicate Native capability operation: ${[...new Set(r)].join(", ")}`);if(typeof t.verification_result!="string"||!Py.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"&&ld(t.verification_report,"Native verification_report"),typeof t.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof t.created_at!="string"||!Ay(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 ki(t){let e=Ai(t,ot);if(e.schema!==we)throw new Error(`Expected ${we}`);return{schema:we,...ss(e,Ny)}}function Ri(t,e){if(!Number.isSafeInteger(t)||t<1)throw new Error(`${e} must be a positive integer`);return t}function is(t,e,i){if(t===null)return null;let r=typeof t=="string"?xy.exec(t):null;if(!r||r[1]!==i)throw new Error(`${e} must be null or runtime/evidence/${i}/<sha256>.json relative to the Native change`);return t}function _y(t){if(t==null)return null;if(typeof t!="string"||!rs.test(t))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return t}function Ty(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 Si(t){let e=Ai(t,ot);if(e.schema!==ge)throw new Error(`Expected ${ge}`);if(Ri(e.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${ge} minimum_runtime_version must be 2`);return{schema:ge,minimum_runtime_version:2,revision:Ri(e.revision,"Native v2 revision"),...ss(e,od)}}function Ei(t){let e=Ai(t,ot);if(e.schema!==Re){if(e.schema===we||e.schema===ge){let o=e.schema===we?ki(e):Si(e);throw new ns(o.name,o.schema)}throw new It(typeof e.schema=="string"?e.schema:"(missing)",typeof e.minimum_runtime_version=="number"?e.minimum_runtime_version:null)}let i=Ri(e.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)throw new It(e.schema,i);if(i!==3)throw new Error(`Native ${e.schema} minimum_runtime_version must be ${3}`);let r=Ri(e.revision,"Native revision"),n=ss(e,by),a=_y(e.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:Re,minimum_runtime_version:3,revision:r,verification_protocol:Ty(e.verification_protocol),...n,approved_contract_hash:a,implementation_scope:is(e.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:is(e.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:is(e.partial_allowance,"Native partial_allowance","allowances")}}function Iy(t){let e=Ai(t,ot);if(e.schema===we){let n=ki(e);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${Re}`}}if(e.schema===ge){let n=Si(e);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${Re}`}}if(e.schema!==Re){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 It(typeof e.schema=="string"?e.schema:"(missing)",n).message}}let i=Ri(e.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)return{status:"runtime-incompatible",schema:e.schema,minimumRuntimeVersion:i,state:null,message:new It(e.schema,i).message};let r=Ei(e);return{status:"current",schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,state:r}}function ye(t,e){os(e);let i=Tt.join(t.changesDir,e);if(!F(t.changesDir,i))throw new Error("Native change path escaped");return i}var jy=256*1024;async function $y(t,e=Tt.dirname(t)){let i=Tt.relative(e,t).split(Tt.sep).join("/"),r=await M({root:e,ref:i,maxBytes:jy}),n=(0,as.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 ud(t,e){let i=Tt.join(ye(t,e),ot);await T(t.nativeRoot,i);let r=Iy(await $y(i,t.nativeRoot));if(r.state&&r.state.name!==e)throw new Error(`Native change directory/name mismatch: ${e}`);return r}import{promises as hd}from"node:fs";import Cn from"node:path";var Hy=$t(yt(),1);var iC=8*1024*1024;var fC=["$ProgressPreference = 'SilentlyContinue'","$encoded = $env:COMET_COMMAND_PAYLOAD","Remove-Item Env:COMET_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("; ");import{promises as Vy}from"node:fs";import Ti from"node:path";function bn(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function kn(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 Ne(t,e,i=!1){if(typeof t!="string"||!i&&t.length===0)throw new Error(`${e} must be ${i?"a string":"a non-empty string"}`);return t}function dd(t,e){return t===null?null:Ne(t,e)}function En(t,e,i=0){if(!Number.isSafeInteger(t)||t<i)throw new Error(`${e} must be a safe integer greater than or equal to ${i}`);return t}function qy(t,e){if(t===null)return null;if(!Number.isSafeInteger(t))throw new Error(`${e} must be null or a safe integer`);return t}function Wy(t,e){if(typeof t!="boolean")throw new Error(`${e} must be a boolean`);return t}function Sn(t,e,i){if(typeof t!="string"||!e.includes(t))throw new Error(`${i} must be one of: ${e.join(", ")}`);return t}function cs(t,e){if(t===null)return null;let i=Ne(t,e);if(Number.isNaN(Date.parse(i)))throw new Error(`${e} must be an ISO timestamp`);return i}function ls(t,e){let i=Ne(t,e);if(!Ti.isAbsolute(i))throw new Error(`${e} must be absolute`);return Ti.resolve(i)}function zy(t,e){let i=`Native local checks[${e}]`,r=bn(t,i);if(kn(r,new Set(["id","name","operationId","status","repeatable","timeoutMs","executionCount","argv","cwd","exitCode","startedAt","completedAt","log"]),i),!Array.isArray(r.argv)||r.argv.length===0)throw new Error(`${i}.argv must be a non-empty array`);let n=r.argv.map((l,f)=>Ne(l,`${i}.argv[${f}]`,!0)),a=Sn(r.status,["planned","running","passed","failed","interrupted"],`${i}.status`),o=cs(r.startedAt,`${i}.startedAt`),s=cs(r.completedAt,`${i}.completedAt`);if(a==="planned"&&(o!==null||s!==null))throw new Error(`${i} planned check cannot contain execution timestamps`);if(a==="running"&&(o===null||s!==null))throw new Error(`${i} running check requires only startedAt`);if((a==="passed"||a==="failed")&&(o===null||s===null))throw new Error(`${i} completed check requires startedAt and completedAt`);let c=En(r.timeoutMs,`${i}.timeoutMs`);if(c<1)throw new Error(`${i}.timeoutMs must be positive`);return{id:Ne(r.id,`${i}.id`),name:Ne(r.name,`${i}.name`),operationId:Ne(r.operationId,`${i}.operationId`),status:a,repeatable:Wy(r.repeatable,`${i}.repeatable`),timeoutMs:c,executionCount:En(r.executionCount,`${i}.executionCount`),argv:n,cwd:ls(r.cwd,`${i}.cwd`),exitCode:qy(r.exitCode,`${i}.exitCode`),startedAt:o,completedAt:s,log:Ne(r.log,`${i}.log`)}}function fd(t){let e="Native local execution state",i=bn(t,e);if(kn(i,new Set(["schema","change","basedOnStateVersion","workspace","execution","checks"]),e),i.schema!==bi)throw new Error(`Native local execution schema must be ${bi}`);let r=bn(i.workspace,"Native local workspace");kn(r,new Set(["projectRoot","worktreeRoot","branch"]),"Native local workspace");let n=null;if(i.execution!==null){let o=bn(i.execution,"Native local execution");kn(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds"]),"Native local execution");let s=cs(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:Ne(o.operationId,"Native local execution.operationId"),stage:Sn(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:Sn(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:dd(o.executionId,"Native local execution.executionId"),status:Sn(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:En(o.requestCheckRounds,"Native local execution.requestCheckRounds")}}if(!Array.isArray(i.checks))throw new Error("Native local checks must be an array");let a=i.checks.map(zy);if(new Set(a.map(o=>o.id)).size!==a.length)throw new Error("Native local check IDs must be unique");if(n&&a.some(o=>o.operationId!==n.operationId))throw new Error("Native local checks must belong to the current operation");return{schema:bi,change:Ne(i.change,"Native local change"),basedOnStateVersion:En(i.basedOnStateVersion,"Native local basedOnStateVersion",1),workspace:{projectRoot:ls(r.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:ls(r.worktreeRoot,"Native local workspace.worktreeRoot"),branch:dd(r.branch,"Native local workspace.branch")},execution:n,checks:a}}function Pn(t){return fd({schema:bi,change:t.portableState.name,basedOnStateVersion:t.portableState.state_version,workspace:{projectRoot:Ti.resolve(t.projectRoot),worktreeRoot:Ti.resolve(t.worktreeRoot??t.projectRoot),branch:t.branch??null},execution:null,checks:[]})}async function xn(t,e,i={}){let r=fd(e);await Vy.mkdir(Ti.dirname(t),{recursive:!0}),await K(t,r,i)}var pd=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Jy="comet-state.yaml",Gy="state.json";function md(t,e){if(!pd.test(e))throw new Error(`Invalid Native change name: ${e}`);let i=Cn.join(t.changesDir,e);if(!F(t.changesDir,i))throw new Error("Native change path escaped");return i}function Je(t,e){return Cn.join(md(t,e),Jy)}function us(t,e){return Cn.join(it(t,e),Gy)}async function Ii(t,e){try{let i=await hd.readFile(Je(t,e),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(i)}catch(i){if(i.code==="ENOENT")return!1;throw i}}function Uy(t){return ke(t).currentBranch}async function vd(t,e){return Ce(Je(t,e))}async function Ky(t){let e=await Hu({file:Je(t.paths,t.previous.name),expectedStateVersion:t.previous.state_version,next:t.next,containedRoot:t.paths.nativeRoot});if(e.verification===null&&e.verification_report===null){let i=Cn.join(md(t.paths,e.name),"verification.md");await T(t.paths.nativeRoot,i),await hd.rm(i,{force:!0})}return e}async function gd(t){if(!pd.test(t.capability))throw new Error(`Invalid Native capability: ${t.capability}`);return Z(t.paths,`remove portable spec ${t.capability}`,async()=>{let e=await vd(t.paths,t.name);if(e.archived)throw new Error(`Native change ${e.name} is already archived`);let i=e.spec_changes.filter(({capability:a})=>a!==t.capability),r={...e,phase:"shape",status:"active",state_version:e.state_version+1,spec_changes:[...i,{capability:t.capability,operation:"remove",source:null}].sort((a,o)=>a.capability.localeCompare(o.capability,"en")),acceptance:[],builder_handoff:null,blockers:[],verification:null,verification_result:"pending",verification_report:null,history:[],history_overflow:{dropped_entries:0,first_dropped_at:null,last_dropped_at:null,outcome_counts:{pass:0,fail:0,blocked:0,"execution-error":0,recovery:0}},loop:{stage:"shape",goal_cycle:e.loop.goal_cycle+(e.phase==="shape"?0:1),iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:"confirm-shape"}};delete r.children_contract_hash;let n=await Ky({paths:t.paths,previous:e,next:r});return await xn(us(t.paths,e.name),Pn({portableState:n,projectRoot:t.paths.projectRoot,branch:Uy(t.paths.projectRoot)}),{containedRoot:t.paths.runtimeDir}),n})}var wd=["evidence.md","repair.md","archive.md","checkpoint.md"],Qy="verification.md";async function Zy(t,e){let i=await Wu(t,{kind:"migration",change:e});return i?.kind==="migration"?i.journal:null}async function yd(t,e){await ji.mkdir(t.transactionsDir,{recursive:!0}),await K(fn(t,{kind:"migration",change:e.change}),e,{containedRoot:t.runtimeDir})}async function Nd(t,e,i={}){let r=i.removeVerificationReport===!1?wd:[...wd,Qy];await Promise.all([ji.rm(it(t,e),{recursive:!0,force:!0}),ji.rm(_o(t,e),{recursive:!0,force:!0}),...r.map(n=>ji.rm(Xy.join(ye(t,e),n),{force:!0}))])}async function bd(t,e){await xn(us(t,e.name),Pn({portableState:e,projectRoot:t.projectRoot}),{containedRoot:t.runtimeDir})}async function kd(t,e){try{let i=await xi(t,e);if(i?.schema==="comet.native.workspace.v3")return{isolation:i.isolation,change_branch:i.changeBranch,target_branch:i.targetBranch,finish:i.finish}}catch{}return{isolation:"current",change_branch:null,target_branch:null,finish:null}}function Sd(t,e){if(e.isolation==="current"&&e.change_branch===null)return;let i=ke(t.projectRoot);if(!i.isGitWorktree)throw new Error("Native legacy migration requires its bound Git branch or worktree");if(i.currentBranch!==e.change_branch)throw new Error(`Native legacy migration expected branch ${e.change_branch??"(missing)"}, current branch is ${i.currentBranch??"(detached)"}`);if(e.isolation==="worktree"&&!i.isSecondaryWorktree)throw new Error("Native legacy migration requires its bound linked worktree")}async function eN(t){let e=ye(t.paths,t.state.name),i=await M({root:e,ref:t.state.brief,maxBytes:null,includeHash:!1}),r=[];for(let n of t.state.spec_changes){if(n.operation==="remove"||!n.source)continue;let a=await M({root:e,ref:n.source,maxBytes:null,includeHash:!1});r.push({capability:n.capability,source:a.ref,markdown:a.text})}try{return qo({briefMarkdown:i.text,specs:r})}catch(n){if(t.state.phase==="shape"&&n.message.includes("at least one acceptance"))return[];throw n}}async function Ed(t,e){let i=await ud(t,e);if(!i.state)throw new Error(`Native legacy change ${e} is unreadable`);return i.state}async function Pd(t){return Z(t.paths,`migrate ${t.name} to portable Native`,async()=>{let e=await Zy(t.paths,t.name),i=await Ii(t.paths,t.name)?await Ce(Je(t.paths,t.name)):null;if(!e&&i)return await Nd(t.paths,t.name,{removeVerificationReport:!1}),await bd(t.paths,i),i;let r=null,n=null;for(e||(r=await Ed(t.paths,t.name),n=await kd(t.paths,t.name),Sd(t.paths,n),e={schema:un,id:Yy(),change:r.name,fromSchema:r.schema,status:"prepared",createdAt:(t.now??new Date).toISOString()},await yd(t.paths,e));;){let a=Lu(e);if(a.action==="done")break;a.action==="commit-portable-yaml"?i||(r??=await Ed(t.paths,t.name),n??=await kd(t.paths,t.name),Sd(t.paths,n),i=Du({state:r,acceptance:await eN({paths:t.paths,state:r}),workspace:n,migratedAt:t.now}),await cn(Je(t.paths,t.name),i,{containedRoot:t.paths.nativeRoot})):a.action==="cleanup-legacy-runtime"?await Nd(t.paths,t.name):a.action==="commit-transaction"&&(i??=await Ce(Je(t.paths,t.name)),await bd(t.paths,i)),e={...e,status:a.nextStatus},await yd(t.paths,e)}return await ji.rm(fn(t.paths,{kind:"migration",change:t.name}),{force:!0}),i??Ce(Je(t.paths,t.name))},{allowedPortableTransaction:{kind:"migration",change:t.name}})}import Oi from"path";import{realpathSync as BN}from"fs";var iN=["Outcome","Scope","Non-goals","Acceptance examples"],fA=[...iN,"Constraints and invariants","Decisions","Open questions","Verification expectations"];var rN=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 xd=1024*1024;var Rd="scoped-text-safety",nN=1,aN=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128});var oN="comet.native.checker-policy.v1";var RA=U(oN,{policy:Rd,version:nN,limits:aN,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"});var sN=["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"],AA=new Set(sN);var uN=xd,JA=3*uN;var Ad={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:[]},fN=ee("comet-native-runtime:v3:scope-reopen"),y_=[{skillVersion:"3",skillHash:ee("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:ee("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:ee("comet-native-runtime:v1")}];var Td=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],Z_=new Set(Td),yN=new Set([...Td,"minimum_runtime_version","revision"]),eT=new Set([...yN,"operation"]),tT=512*1024,NN=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),iT=new Set([...NN,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]);var oT={maxAcceptanceCriteria:Ni.maxCriteria};var dT={maxSpecs:64,maxFileBytes:Vi,maxTotalBytes:4*1024*1024};import{execFile as AN}from"node:child_process";import{promisify as _N}from"node:util";var bT={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024};var VT=512*1024;var $i=class extends Error{recovery;constructor(e,i){super(e),this.name="NativeReceiptScopeStaleError",this.recovery=i}};var dI=64*1024;var fI=3600*1e3;var hI=_N(AN);var Rn=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(r=>`${r.ref}${r.acceptanceId?`[${r.acceptanceId}]`:""} -> ${r.mismatches.join("; ")}`).join(" | ")}`;super(i),this.name="NativeVerificationReceiptBindingError",this.details=e}};var QI={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};var cj=16*1024*1024,lj=256*1024,uj=16*1024;var mj=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});var wj=16*1024;var _j=16*1024;var N$=16*1024*1024,An=class extends Error{constructor(i,r,n,a){super(`Canonical spec conflict for ${i}: expected ${r??"(missing)"}, actual ${n??"(missing)"}`);this.capability=i;this.expectedHash=r;this.actualHash=n;this.canonicalPath=a;this.name="NativeSpecConflictError"}capability;expectedHash;actualHash;canonicalPath;code="native-spec-conflict"},_n=class extends Error{constructor(i,r=i.ready?"Native Archive preflight no longer matches the expected hash":`Native Archive preflight is blocked: ${i.findingCodes.join(", ")}`){super(r);this.preflight=i;this.name="NativeArchivePreflightError"}preflight;code="native-archive-preflight"};var Tn=class extends Error{constructor(i,r,n){super(i,n);this.preparation=r;this.name="NativeWorkspacePreparationError"}preparation};var $d=["--project-root <path> Resolve the Native project from this working directory.","--json Emit the stable JSON command envelope.","--help Show help without requiring an initialized project."],fs=Object.freeze({"":{usage:"comet native <command> [options]",purpose:"Create, inspect, recover, and archive portable Native changes through Runtime-enforced, skill-coordinated steps.",subcommands:["init Initialize Native project configuration.","root show Inspect the configured artifact root.","root move <artifact-root> Move the configured artifact root.","new <change-name> Create a change and prepare its workspace.","spec remove Record a complete capability removal intent.","show <change-name> Read formal artifacts and portable state.","status [<change-name>] Discover stable boundaries and Runner actions.","select <change-name> Select a change in its bound workspace.","next <change-name> Confirm or recover a stable workflow boundary.","archive <change-name> Preview and execute Archive plus workspace finish.","doctor [<change-name>] Diagnose, migrate, or rebuild local execution state."],options:$d,output:"Human-readable text by default; use --json for a structured command envelope.",examples:["comet native status --json","comet native status my-change --details --json","comet native next --help"]},init:{usage:"comet native init [--root <artifact-root>] [--language en|zh-CN]",purpose:"Create or normalize .comet/config.yaml and the configured Native directories.",options:["--root <artifact-root> Project-relative artifact root; defaults to docs.","--language en|zh-CN Language for newly generated Native artifacts."],output:"The resolved project configuration and Native paths.",examples:["comet native init --root docs --language zh-CN"]},root:{usage:"comet native root <show|move> [arguments]",purpose:"Inspect or transactionally move the configured Native artifact root.",subcommands:["show Print the configured artifact root and resolved paths.","move <artifact-root> Move Native artifacts and update project configuration."],output:"The current root projection or the completed move result.",examples:["comet native root show","comet native root move artifacts/native"]},"root show":{usage:"comet native root show",purpose:"Print the configured Native artifact root and resolved paths.",output:"The configured artifact root and resolved Native paths."},"root move":{usage:"comet native root move <artifact-root>",purpose:"Transactionally move Native artifacts and update project configuration.",output:"The source, destination, and committed root-move transaction result.",examples:["comet native root move artifacts/native"]},new:{usage:"comet native new <change-name> [--language en|zh-CN] [--isolation current|branch|worktree] [--change-branch <branch>] [--target-branch <branch>] [--worktree-path <path>]",purpose:"Create a portable Native change and prepare the requested branch or linked worktree.",options:["--language en|zh-CN Artifact language; defaults to project configuration.","--isolation <kind> current, branch, or worktree; defaults to current.","--change-branch <branch> Change branch; defaults to comet/<change-name>.","--target-branch <branch> Local base branch; defaults to the current branch.","--worktree-path <path> Worktree directory; defaults to .worktrees/<change-name>."],output:"The portable state, workspace preparation result, and continuation with the next Runner action.",examples:["comet native new session-timeout --language zh-CN","comet native new session-timeout --isolation branch --target-branch main","comet native new session-timeout --isolation worktree --target-branch main"]},spec:{usage:"comet native spec remove <change-name> <capability>",purpose:"Record a capability removal; create and modify intents use complete proposed Spec files.",subcommands:["remove <change-name> <capability> Record a capability removal."],output:"The updated portable state and continuation."},"spec remove":{usage:"comet native spec remove <change-name> <capability>",purpose:"Record removal of a capability in the complete target specification.",output:"The updated portable state and continuation with the next Runner action."},show:{usage:"comet native show <change-name>",purpose:"Read formal artifacts and portable state for one Native change.",output:"The portable state, brief, complete proposed Specs, and continuation; legacy state is reported as migration-required."},status:{usage:"comet native status [<change-name>] [--cursor <token>] [--details]",purpose:"Discover portable stable boundaries, parent child readiness, or the exact next Runner action.",options:["--cursor <token> Continue a status-list page.","--details Include acceptance, Spec, workspace, and report details."],output:"A v2 status page or one portable Loop projection with local execution availability and continuation.runnerAction; parent changes also expose children and readyChildren.",examples:["comet native status --json","comet native status session-timeout --details --json"]},select:{usage:"comet native select <change-name>",purpose:"Select one Native change after validating its workspace binding.",output:"The selected change record."},next:{usage:`comet native next <change-name> --summary <text> [--confirmed|--accept-result|--revise-implementation|--revise-requirements|--retry-verifier|--resolve-verifier-blocker]
|
|
151
|
-
comet native next <change-name> --runner-input <json-file>`,purpose:"Confirm or recover an Agent boundary, advance parent child changes, or use one skill-coordinated JSON bridge for Builder handoff, check-plan dispatch, and Verifier response/error.",options:["--summary <text> Required transition or recovery summary.","--confirmed Confirm Shape or an explicitly degraded verifier-unavailable fallback before Archive.","--accept-result Accept the current skill-coordinated Verify result and make it archive-ready.","--revise-implementation Keep confirmed requirements unchanged and return Verify to Build for implementation revision.","--revise-requirements Return Verify to Shape when user-visible goals or acceptance criteria must change.","--retry-verifier Retry a blocked Verifier execution when the continuation allows it.","--resolve-verifier-blocker Resolve a semantic Verifier blocker without changing the candidate, then dispatch a new attempt.","--expected-state-version <n> Continuation-issued guard that rejects stale public transition decisions.","--expected-action <action> Continuation-issued guard that binds the public transition decision to its intended action.","--runner-input <file> Skill-coordinated JSON: builder-handoff, dispatch-verifier, verifier-response, verifier-execution-error, or verifier-unavailable. Identity/provider/execution/candidate fields are rejected."," builder-handoff fields: kind, summary, addressed_acceptance_ids, checks, known_limits."," dispatch-verifier fields: kind, checks (an explicitly resolved plan; [] is allowed)."," verifier-response fields: kind, response (request-checks or final-result)."," verifier-execution-error fields: kind, summary, stateVersion, iteration, attempt, verifierExecutionRef copied from verifierDispatch."," verifier-unavailable fields: kind, summary, stateVersion, iteration, attempt, verifierExecutionRef copied from verifierDispatch; accepted only after the explicit Runtime check plan completed and passed."],output:"The portable state, explicit skill-coordinated label, Runtime-owned check results, complete verifierDispatch, bounded request-check response, continuation.runnerAction, and machine-readable continuation.inputOptions. This generic bridge is not trusted identity attestation: a passing result waits for explicit user confirmation before Archive.",examples:['comet native next session-timeout --summary "Shape confirmed" --confirmed','comet native next session-timeout --summary "Current result accepted" --accept-result','comet native next session-timeout --summary "Implementation needs revision" --revise-implementation','comet native next session-timeout --summary "Acceptance criteria changed" --revise-requirements','comet native next session-timeout --summary "Retry verifier infrastructure" --retry-verifier','comet native next session-timeout --summary "Retry semantic verification" --resolve-verifier-blocker',"comet native next session-timeout --runner-input <temporary-json-file>"]},archive:{usage:`comet native archive <change-name> --dry-run [--finish merge|push|pull-request|keep]
|
|
147
|
+
`,o),l=c===-1?a.slice(o):a.slice(o,c);if(yield{line:l,body:e===null&&!i&&r===null,index:s},s+=1,e!==null)e=Ho(l,e);else if(i)Tu(l)&&(i=!1);else if(r!==null)new RegExp(`</${r}\\s*>`,"iu").test(l)&&(r=null);else{let d=Ho(l,null);if(d!==null)e=d;else{let u=l.trimStart();if(u.startsWith("<!--")&&!Tu(u))i=!0;else{let p=/^<([A-Za-z][A-Za-z0-9-]*)\b[^>]*>/u.exec(u);p&&n.has(p[1].toLowerCase())&&!u.startsWith("</")&&!u.endsWith("/>")&&!new RegExp(`</${p[1]}\\s*>`,"iu").test(u)&&(r=p[1])}}}if(c===-1)break;o=c+1}}function Ni(t){return t.normalize("NFC").replace(/\s+/gu," ").trim()}function Lo(t,e,i,r=[],n="content-hash"){let a=Ni(i),o=e.replaceAll("\\","/").trim(),s=r.map(Ni);if(a.length===0)throw new Error(`${t} acceptance criterion must not be empty`);if(o.length===0)throw new Error(`${t} acceptance criterion source must not be empty`);return{id:n==="content-hash"?`acceptance-${U(Ig,{kind:t,source:o,context:s,text:a})}`:"",kind:t,source:o,context:s,text:a}}function Bo(t,e,i="content-hash"){let r=new Set;for(let n of t){let a=i==="content-hash"?n.id:JSON.stringify([n.kind,n.source,n.context,n.text]);if(r.has(a))throw new Error(`${e} contains duplicate acceptance criteria`);r.add(a)}return t}function jg(t){let e=null,i=null,r=0,n=0;for(let{line:a,body:o,index:s}of yi(t)){n=s+1;let c=o?Do(a):null;c?.level===1&&(c.text.toLocaleLowerCase("en-US")==="acceptance examples"?(r+=1,r===1&&(e=s+1)):e!==null&&i===null&&(i=s))}if(r===0||e===null)return null;if(r!==1)throw new Error("Brief must contain exactly one Acceptance examples section");return{start:e,end:i??n}}function Mo(t,e="brief.md",i=bi.maxCriteria,r="content-hash"){if(!Number.isSafeInteger(i)||i<0)throw new Error("Native brief acceptance budget is invalid");let n=jg(t);if(n===null)return[];let a=null;for(let{line:l,body:f,index:d}of yi(t)){if(d<n.start||d>=n.end)continue;let u=f?/^( {0,3})[-*+][ \t]+/u.exec(l):null;if(u===null)continue;let p=u[1].length;a=a===null?p:Math.min(a,p)}let o=[],s=null,c=()=>{if(s!==null){if(o.length>=i)throw new Error(`Native acceptance exceeds its ${i}-criterion acceptance budget`);o.push(s)}};for(let{line:l,body:f,index:d}of yi(t)){if(d<n.start||d>=n.end)continue;let u=f?/^( {0,3})[-*+][ \t]+(.*)$/u.exec(l):null;u&&u[1].length===a?(c(),s=[u[2]]):s!==null&&s.push(l)}return c(),Bo(o.map(l=>Lo("brief-example",e,l.join(`
|
|
148
|
+
`),[],r)),"Brief",r)}function Fo(t,e="spec.md",i=bi.maxCriteria,r="content-hash"){if(!Number.isSafeInteger(i)||i<0)throw new Error("Native specification acceptance budget is invalid");let n=[],a=[],o=null,s=()=>{if(o!==null){if(n.length>=i)throw new Error(`Native acceptance exceeds its ${i}-criterion acceptance budget`);n.push(Lo("spec-scenario",e,[o.title,...o.body].join(`
|
|
149
|
+
`),o.context,r)),o=null}};for(let{line:c,body:l}of yi(t)){let f=l?Do(c):null,d=f?/^Scenario\s*:\s*(.*)$/iu.exec(f.text):null;if(d){for(s();a.at(-1)&&a.at(-1).level>=f.level;)a.pop();let u=Ni(d[1]);if(u.length===0)throw new Error("Scenario title must not be empty");o={level:f.level,title:u,body:[],context:a.map(p=>p.text)}}else if(f){for(o!==null&&f.level<=o.level?s():o!==null&&o.body.push(c);a.at(-1)&&a.at(-1).level>=f.level;)a.pop();a.push(f)}else o!==null&&l&&o.body.push(c)}return s(),Bo(n,"Specification",r)}function Vo(t,e="spec.md",i=bi.maxCriteria,r="content-hash"){if(!Number.isSafeInteger(i)||i<0)throw new Error("Native specification acceptance budget is invalid");let n=[],a=[],o=null,s=null,c=()=>{if(s!==null){if(n.length>=i)throw new Error(`Native acceptance exceeds its ${i}-criterion acceptance budget`);n.push(Lo("spec-must",e,s.parts.join(" "),s.context,r)),s=null}},l=()=>a.some(f=>/^(?:non-?goals?|非目标)$/iu.test(f.text.trim()));for(let{line:f,body:d}of yi(t)){let u=d?Do(f):null;if(u){for(c(),o!==null&&u.level<=o&&(o=null);a.at(-1)&&a.at(-1).level>=u.level;)a.pop();a.push(u),/^Scenario\s*:/iu.test(u.text)&&(o=u.level);continue}let p=f.trim();if(!d||o!==null||l()){c();continue}if(p.length===0||Ho(f,null)!==null||p.startsWith("<!--")||p==="-->"||p==="--!>"||/^<\/?[A-Za-z][^>]*>$/u.test(p)||/^<[A-Za-z][^>]*>.*<\/[A-Za-z][^>]*>$/u.test(p)||/^(?:[-*_]\s*){3,}$/u.test(p)||/^\|?(?:\s*:?-{3,}:?\s*\|)+\s*$/u.test(p)){c();continue}let v=/^\s*(?:[-*+]|\d+[.)])[ \t]+(.+)$/u.exec(f);if(v){c(),s={parts:[v[1]],context:a.map(h=>h.text)};continue}if(/^\|.*\|$/u.test(p)){c(),s={parts:[p],context:a.map(h=>h.text)},c();continue}s===null?s={parts:[p],context:a.map(h=>h.text)}:s.parts.push(p)}return c(),Bo(n,"Specification mandatory requirements",r)}var $g=/^A[1-9]\d*$/u;function ju(t,e){if(t.length===0||t!==t.trim()||t.includes("\\")||Iu.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes("..")||Iu.posix.normalize(t)!==t||t==="."||t.endsWith("/"))throw new Error(`${e} must be a normalized change-relative ref`);return t}function Og(t,e){return t.localeCompare(e,"en")}function qo(t){let e=ju(t.briefSource??"brief.md","Native brief source"),i=[...t.specs??[]].sort((a,o)=>Og(a.capability,o.capability));if(new Set(i.map(a=>a.capability)).size!==i.length)throw new Error("Native acceptance sources contain duplicate capabilities");let r=Mo(t.briefMarkdown,e,Number.MAX_SAFE_INTEGER,"none").map(({source:a,text:o})=>({source:a,text:o}));for(let a of i){let o=ju(a.source,`Native spec source for ${a.capability}`);r.push(...Fo(a.markdown,o,Number.MAX_SAFE_INTEGER,"none").map(({text:s})=>({source:o,text:s})),...Vo(a.markdown,o,Number.MAX_SAFE_INTEGER,"none").map(({text:s})=>({source:o,text:s})))}let n=new Set;for(let a of r){a.text=Ni(a.text);let o=`${a.source}\0${a.text}`;if(n.has(o))throw new Error(`Native acceptance contains a duplicate criterion: ${a.text}`);n.add(o)}if(r.length===0)throw new Error("Native change must define at least one acceptance criterion");return r.map((a,o)=>({id:`A${o+1}`,source:a.source,text:a.text}))}function $u(t){let e=t.map(({id:i})=>i);if(new Set(e).size!==e.length)throw new Error("Native acceptance IDs must be unique");for(let i=0;i<e.length;i+=1)if(!$g.test(e[i])||e[i]!==`A${i+1}`)throw new Error("Native acceptance IDs must be the contiguous sequence A1..An")}var on=$t(yt(),1);import{promises as Hg}from"node:fs";var xt="comet.native.v4",ki="comet.native.local-execution.v4";function Wo(){return{dropped_entries:0,first_dropped_at:null,last_dropped_at:null,outcome_counts:{pass:0,fail:0,blocked:0,"execution-error":0,recovery:0}}}var Dg=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Lg=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Bg=/^A[1-9][0-9]*$/u,Mg=/^[a-f0-9]{64}$/u,Fg=new Set(["schema","name","language","phase","status","state_version","brief","children_contract_hash","spec_changes","workspace","loop","acceptance","builder_handoff","blockers","verification","history","history_overflow","verification_result","verification_report","archived","created_at"]),an=class extends Error{constructor(i,r){super(`Native state version conflict: expected ${i}, got ${r}`);this.expectedStateVersion=i;this.actualStateVersion=r;this.name="NativePortableStateVersionConflictError"}expectedStateVersion;actualStateVersion;code="native-state-version-conflict"};function z(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function J(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 L(t,e,i){if(typeof t!="string"||!i?.empty&&t.length===0)throw new Error(`${e} must be ${i?.empty?"a string":"a non-empty string"}`);return t}function zo(t,e){return t===null?null:L(t,e)}function Vg(t,e){let i=L(t,e);if(!Mg.test(i))throw new Error(`${e} must be a SHA-256 hash`);return i}function Ct(t,e){if(typeof t!="boolean")throw new Error(`${e} must be a boolean`);return t}function _(t,e,i=0){if(!Number.isSafeInteger(t)||t<i)throw new Error(`${e} must be a safe integer greater than or equal to ${i}`);return t}function qg(t,e){return t===null?null:_(t,e,Number.MIN_SAFE_INTEGER)}function D(t,e,i){if(typeof t!="string"||!e.includes(t))throw new Error(`${i} must be one of: ${e.join(", ")}`);return t}function ve(t,e,i){if(!Array.isArray(t))throw new Error(`${e} must be an array`);return t.map((r,n)=>i(r,n))}function sn(t,e){return ve(t,e,(i,r)=>L(i,`${e}[${r}]`))}function rt(t,e){if(new Set(t).size!==t.length)throw new Error(`${e} must be unique`)}function Rt(t,e){let i=L(t,e);if(Number.isNaN(Date.parse(i)))throw new Error(`${e} must be an ISO date or timestamp`);return i}function Jo(t,e,i=!1){let r=L(t,e);if(r.includes("\\")||r.startsWith("/")||/^[A-Za-z]:/u.test(r)||r.split("/").includes("..")||!i&&(r==="."||r.split("/").includes(".")))throw new Error(`${e} must be a portable relative path`);return r}function se(t,e){let i=z(t,e);return J(i,new Set(["text","truncated"]),e),{text:L(i.text,`${e}.text`,{empty:!0}),truncated:Ct(i.truncated,`${e}.truncated`)}}function Wg(t,e){let i=`Native spec_changes[${e}]`,r=z(t,i);J(r,new Set(["capability","operation","source"]),i);let n=L(r.capability,`${i}.capability`);if(!Lg.test(n))throw new Error(`${i}.capability is invalid`);let a=D(r.operation,["create","modify","remove"],`${i}.operation`),o=r.source===null?null:Jo(r.source,`${i}.source`);if(a==="remove"&&o!==null)throw new Error(`${i} remove requires source null`);if(a!=="remove"&&o===null)throw new Error(`${i} ${a} requires a source`);return{capability:n,operation:a,source:o}}function zg(t){let e="Native workspace",i=z(t,e);J(i,new Set(["isolation","change_branch","target_branch","finish"]),e);let r=D(i.isolation,["current","branch","worktree"],`${e}.isolation`),n=zo(i.change_branch,`${e}.change_branch`),a=zo(i.target_branch,`${e}.target_branch`),o=i.finish===null?null:D(i.finish,["merge","push","pull-request","keep"],`${e}.finish`);if(r==="current"&&o!==null)throw new Error("Native current workspace cannot contain a finish action");if(r==="current"&&n===null!=(a===null))throw new Error("Native workspace branch bindings must both be present or both be null");if(r!=="current"&&(n===null||a===null))throw new Error("Native isolated workspace requires change_branch and target_branch");return{isolation:r,change_branch:n,target_branch:a,finish:o}}function Jg(t){let e="Native loop",i=z(t,e);J(i,new Set(["stage","goal_cycle","iteration","attempt","retry_epoch","failed_iteration_count","no_progress_count","execution_failure_count","previous_unresolved_ids","next_action"]),e);let r=sn(i.previous_unresolved_ids,`${e}.previous_unresolved_ids`);return rt(r,`${e}.previous_unresolved_ids`),{stage:D(i.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${e}.stage`),goal_cycle:_(i.goal_cycle,`${e}.goal_cycle`,1),iteration:_(i.iteration,`${e}.iteration`),attempt:_(i.attempt,`${e}.attempt`),retry_epoch:_(i.retry_epoch,`${e}.retry_epoch`),failed_iteration_count:_(i.failed_iteration_count,`${e}.failed_iteration_count`),no_progress_count:_(i.no_progress_count,`${e}.no_progress_count`),execution_failure_count:_(i.execution_failure_count,`${e}.execution_failure_count`),previous_unresolved_ids:r,next_action:zo(i.next_action,`${e}.next_action`)}}function Gg(t,e){let i=`Native acceptance[${e}]`,r=z(t,i);J(r,new Set(["id","source","text","result","reason"]),i);let n=L(r.id,`${i}.id`);if(!Bg.test(n))throw new Error(`${i}.id must use A1, A2, ...`);return{id:n,source:Jo(r.source,`${i}.source`),text:L(r.text,`${i}.text`),result:D(r.result,["pending","passed","failed","blocked"],`${i}.result`),reason:r.reason===null?null:se(r.reason,`${i}.reason`)}}function Ug(t,e){let i=`Native builder_handoff.checks[${e}]`,r=z(t,i);return J(r,new Set(["name","result","note"]),i),{name:se(r.name,`${i}.name`),result:D(r.result,["passed","failed","not-run"],`${i}.result`),note:r.note===null?null:se(r.note,`${i}.note`)}}function Kg(t){let e="Native builder_handoff",i=z(t,e);J(i,new Set(["candidate_id","identity_provider","builder_execution_ref","iteration","summary","addressed_acceptance_ids","checks","checks_truncated","known_limits","known_limits_truncated","submitted_at"]),e);let r=sn(i.addressed_acceptance_ids,`${e}.addressed_acceptance_ids`);return rt(r,`${e}.addressed_acceptance_ids`),{candidate_id:L(i.candidate_id,`${e}.candidate_id`),identity_provider:L(i.identity_provider,`${e}.identity_provider`),builder_execution_ref:L(i.builder_execution_ref,`${e}.builder_execution_ref`),iteration:_(i.iteration,`${e}.iteration`,1),summary:se(i.summary,`${e}.summary`),addressed_acceptance_ids:r,checks:ve(i.checks,`${e}.checks`,Ug),checks_truncated:Ct(i.checks_truncated,`${e}.checks_truncated`),known_limits:ve(i.known_limits,`${e}.known_limits`,(n,a)=>se(n,`${e}.known_limits[${a}]`)),known_limits_truncated:Ct(i.known_limits_truncated,`${e}.known_limits_truncated`),submitted_at:Rt(i.submitted_at,`${e}.submitted_at`)}}function Yg(t,e){let i=`Native blockers[${e}]`,r=z(t,i);J(r,new Set(["owner","reason","acceptance_ids","resolution_action"]),i);let n=sn(r.acceptance_ids,`${i}.acceptance_ids`);return rt(n,`${i}.acceptance_ids`),{owner:D(r.owner,["builder","runtime","verifier","user","external"],`${i}.owner`),reason:se(r.reason,`${i}.reason`),acceptance_ids:n,resolution_action:D(r.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${i}.resolution_action`)}}function Xg(t,e){let i=`Native verification.checks[${e}]`,r=z(t,i);return J(r,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),i),{id:L(r.id,`${i}.id`),name:se(r.name,`${i}.name`),argv_display:ve(r.argv_display,`${i}.argv_display`,(n,a)=>se(n,`${i}.argv_display[${a}]`)),argv_truncated:Ct(r.argv_truncated,`${i}.argv_truncated`),cwd_ref:Jo(r.cwd_ref,`${i}.cwd_ref`,!0),status:D(r.status,["passed","failed","interrupted"],`${i}.status`),exit_code:qg(r.exit_code,`${i}.exit_code`),duration_ms:_(r.duration_ms,`${i}.duration_ms`)}}function Qg(t){let e="Native verification",i=z(t,e);J(i,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),e);let r=ve(i.checks,`${e}.checks`,Xg);rt(r.map(a=>a.id),`${e}.checks IDs`);let n=L(i.identity_provider,`${e}.identity_provider`);return{candidate_id:L(i.candidate_id,`${e}.candidate_id`),identity_provider:n,verifier_execution_ref:L(i.verifier_execution_ref,`${e}.verifier_execution_ref`),iteration:_(i.iteration,`${e}.iteration`,1),attempt:_(i.attempt,`${e}.attempt`,1),assurance:i.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":D(i.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${e}.assurance`),verdict:D(i.verdict,["pass","fail","blocked"],`${e}.verdict`),checks:r,summary:se(i.summary,`${e}.summary`),risks:ve(i.risks,`${e}.risks`,(a,o)=>se(a,`${e}.risks[${o}]`)),risks_truncated:Ct(i.risks_truncated,`${e}.risks_truncated`),completed_at:Rt(i.completed_at,`${e}.completed_at`)}}function Zg(t,e){let i=`Native history[${e}]`,r=z(t,i);J(r,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),i);let n=sn(r.unresolved_ids,`${i}.unresolved_ids`);return rt(n,`${i}.unresolved_ids`),{goal_cycle:_(r.goal_cycle,`${i}.goal_cycle`,1),iteration:_(r.iteration,`${i}.iteration`),attempt:_(r.attempt,`${i}.attempt`),outcome:D(r.outcome,["pass","fail","blocked","execution-error","recovery"],`${i}.outcome`),unresolved_ids:n,summary:se(r.summary,`${i}.summary`),completed_at:Rt(r.completed_at,`${i}.completed_at`)}}function ew(t){let e="Native history_overflow.outcome_counts",i=z(t,e),r=["pass","fail","blocked","execution-error","recovery"];return J(i,new Set(r),e),{pass:_(i.pass,`${e}.pass`),fail:_(i.fail,`${e}.fail`),blocked:_(i.blocked,`${e}.blocked`),"execution-error":_(i["execution-error"],`${e}.execution-error`),recovery:_(i.recovery,`${e}.recovery`)}}function tw(t){let e="Native history_overflow",i=z(t,e);J(i,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),e);let r=_(i.dropped_entries,`${e}.dropped_entries`),n=i.first_dropped_at===null?null:Rt(i.first_dropped_at,`${e}.first_dropped_at`),a=i.last_dropped_at===null?null:Rt(i.last_dropped_at,`${e}.last_dropped_at`);if(r===0&&(n!==null||a!==null))throw new Error("Native empty history overflow cannot contain dropped timestamps");if(r>0&&(n===null||a===null))throw new Error("Native non-empty history overflow requires dropped timestamps");let o=ew(i.outcome_counts);if(Object.values(o).reduce((c,l)=>c+l,0)!==r)throw new Error("Native history overflow outcome count must equal dropped_entries");return{dropped_entries:r,first_dropped_at:n,last_dropped_at:a,outcome_counts:o}}function iw(t){let e=new Set(t.acceptance.map(i=>i.id));for(let i of t.loop.previous_unresolved_ids)if(!e.has(i))throw new Error(`Native loop references unknown acceptance ID ${i}`);for(let i of t.builder_handoff?.addressed_acceptance_ids??[])if(!e.has(i))throw new Error(`Native builder handoff references unknown ID ${i}`);for(let i of t.blockers)for(let r of i.acceptance_ids)if(!e.has(r))throw new Error(`Native blocker references unknown ID ${r}`);if(t.builder_handoff&&!(t.builder_handoff.iteration===t.loop.iteration||t.phase==="build"&&t.loop.stage==="repairing"&&t.builder_handoff.iteration===t.loop.iteration-1))throw new Error("Native builder handoff iteration is not current or the prior repair result");if(t.verification){if(!t.builder_handoff)throw new Error("Native verification requires a builder handoff");if(t.verification.candidate_id!==t.builder_handoff.candidate_id)throw new Error("Native verification candidate must match the builder handoff");if(t.verification.identity_provider!==t.builder_handoff.identity_provider)throw new Error("Native Builder and Verifier identity providers must match");if(["skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"].includes(t.verification.assurance)!==(t.verification.identity_provider==="skill-coordinated"))throw new Error("Native verification assurance does not match its identity provider");if(t.verification.assurance==="semantic-verification-unavailable"&&t.verification.verdict!=="blocked")throw new Error("Native unavailable semantic verification must remain blocked");if(t.verification.assurance==="user-confirmed-degraded"&&t.verification.verdict!=="pass")throw new Error("Native user-confirmed degraded verification must be passing");if(t.verification.verifier_execution_ref===t.builder_handoff.builder_execution_ref)throw new Error("Native Builder and Verifier execution refs must differ");let r=t.verification.iteration===t.loop.iteration&&t.verification.attempt===t.loop.attempt,n=t.phase==="build"&&t.loop.stage==="repairing"&&t.verification.iteration===t.loop.iteration-1&&t.verification.iteration===t.builder_handoff.iteration;if(!r&&!n)throw new Error("Native verification iteration and attempt do not match a stable loop result")}}function rw(t){if(!{shape:new Set(["shape","await-user","blocked"]),build:new Set(["building","repairing","await-user","blocked"]),verify:new Set(["verify-ready","await-user","blocked"]),archive:new Set(["archive-ready","await-user","blocked","done"])}[t.phase].has(t.loop.stage))throw new Error(`Native loop stage ${t.loop.stage} is invalid for phase ${t.phase}`);let i=t.status==="await-user"?"await-user":t.status==="blocked"?"blocked":t.status==="done"?"done":null;if(i!==null&&t.loop.stage!==i)throw new Error(`Native status ${t.status} requires loop stage ${i}`);if(t.status==="active"&&["await-user","blocked","done"].includes(t.loop.stage))throw new Error(`Native active status cannot use loop stage ${t.loop.stage}`);if(t.archived!==(t.status==="done"))throw new Error("Native archived must be true exactly when status is done");if(t.archived&&t.phase!=="archive")throw new Error("Native archived state must be in Archive");if(t.verification_result==="pass"){if(t.verification?.verdict!=="pass")throw new Error("Native pass requires a persisted passing verification");if(t.acceptance.some(r=>r.result!=="passed"))throw new Error("Native pass requires every acceptance item to pass");if(t.verification.checks.some(r=>r.status!=="passed"))throw new Error("Native pass requires every persisted check to pass")}if(t.verification?.assurance==="semantic-verification-unavailable"&&(t.phase!=="verify"||t.status!=="await-user"||t.verification_result!=="blocked"||t.loop.next_action!=="confirm-verifier-unavailable"))throw new Error("Native unavailable semantic verification must await explicit user confirmation");if(t.verification_report!==null&&t.verification===null)throw new Error("Native verification report requires persisted verification")}function nt(t){let e=z(t,"Native portable state");if(J(e,Fg,"Native portable state"),e.schema!==xt)throw new Error(`Native portable state schema must be ${xt}`);let i=L(e.name,"Native state name");if(!Dg.test(i))throw new Error("Native state name is invalid");if(e.brief!=="brief.md")throw new Error("Native state brief must be brief.md");let r=ve(e.spec_changes,"Native spec_changes",Wg);rt(r.map(s=>s.capability),"Native spec change capabilities");let n=ve(e.acceptance,"Native acceptance",Gg);rt(n.map(s=>s.id),"Native acceptance IDs");let a=ve(e.history,"Native history",Zg);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:xt,name:i,language:D(e.language,["en","zh-CN"],"Native state language"),phase:D(e.phase,["shape","build","verify","archive"],"Native state phase"),status:D(e.status,["active","await-user","blocked","done"],"Native state status"),state_version:_(e.state_version,"Native state_version",1),brief:"brief.md",...e.children_contract_hash===void 0?{}:{children_contract_hash:Vg(e.children_contract_hash,"Native children contract hash")},spec_changes:r,workspace:zg(e.workspace),loop:Jg(e.loop),acceptance:n,builder_handoff:e.builder_handoff===null?null:Kg(e.builder_handoff),blockers:ve(e.blockers,"Native blockers",Yg),verification:e.verification===null?null:Qg(e.verification),history:a,history_overflow:tw(e.history_overflow),verification_result:D(e.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:e.verification_report===null?null:D(e.verification_report,["verification.md"],"Native verification_report"),archived:Ct(e.archived,"Native archived"),created_at:Rt(e.created_at,"Native created_at")};return iw(o),rw(o),o}function nw(t,e){let i=(0,on.parseDocument)(t,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`${e} is invalid YAML: ${i.errors[0].message}`);return i.toJS({mapAsMap:!1})}async function Ce(t){let e=await Hg.readFile(t,"utf8");return nt(nw(e,"Native portable state"))}async function cn(t,e,i={}){let r=nt(e);await de(t,(0,on.stringify)(r),i)}var nn=new Map;async function aw(t,e){let i=nn.get(t)??Promise.resolve(),r,n=new Promise(o=>{r=o}),a=i.then(()=>n);nn.set(t,a),await i;try{return await e()}finally{r(),nn.get(t)===a&&nn.delete(t)}}async function Hu(t){return aw(t.file,async()=>{let e=_(t.expectedStateVersion,"Native expected state version",1),i=nt(t.next);if(i.state_version!==e+1)throw new Error("Native CAS next state_version must increment exactly once");let r=await Ce(t.file);if(r.state_version===i.state_version&&JSON.stringify(r)===JSON.stringify(i))return r;if(r.state_version!==e)throw new an(e,r.state_version);return await cn(t.file,i,{...t.containedRoot?{containedRoot:t.containedRoot}:{},beforeCommit:async()=>{let n=await Ce(t.file);if(n.state_version!==e)throw new an(e,n.state_version)}}),i})}function ow(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("Native portable text byte budget must be a non-negative safe integer")}function ln(t,e=16384){if(typeof t!="string")throw new Error("Native portable text must be a string");if(ow(e),Buffer.byteLength(t,"utf8")<=e)return{text:t,truncated:!1};let i="",r=0;for(let n of t){let a=Buffer.byteLength(n,"utf8");if(r+a>e)break;i+=n,r+=a}return{text:i,truncated:!0}}var Re="comet.native.v3",ge="comet.native.v2",we="comet.native.v1";var un="comet.native.portable-migration.v1",cw=new Set(["schema","id","change","fromSchema","status","createdAt"]),lw=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,uw=/^[a-z0-9][a-z0-9-]{7,127}$/u,dw=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),fw=new Set([we,ge,Re]);function hw(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function pw(t,e){let i=t instanceof Date?new Date(t.valueOf()):new Date(t);if(Number.isNaN(i.valueOf()))throw new Error(`${e} must be a valid timestamp`);return i.toISOString()}function mw(t,e){if(typeof t!="string")throw new Error(`${e} must be an ISO timestamp`);let i=new Date(t);if(Number.isNaN(i.valueOf())||i.toISOString()!==t)throw new Error(`${e} must be a canonical ISO timestamp`);return t}function vw(t){return t.schema===we?Si(t):t.schema===ge?Ei(t):Pi(t)}function gw(t){return sw.posix.normalize(t.replaceAll("\\","/"))}function ww(t){return t.spec_changes.map(e=>e.operation==="remove"?{capability:e.capability,operation:"remove",source:null}:{capability:e.capability,operation:e.operation==="replace"?"modify":"create",source:gw(e.source)})}function yw(t){return t==="shape"?"shape":"build"}function Nw(t,e){return t==="zh-CN"?e==="shape"?"继续澄清并确认验收项":"重新提交候选实现":e==="shape"?"Continue clarification and confirm acceptance":"Submit a fresh implementation candidate"}function bw(t,e,i){return t==="zh-CN"?`从旧版 ${e} ${i} 状态恢复;旧版 Loop、验证结论和运行记录未继承。`:`Recovered from legacy ${e} ${i} state; prior Loop, verification results, and execution records were not inherited.`}function Du(t){let e=vw(t.state);$u(t.acceptance);let i=yw(e.phase),r=i==="shape"?0:1,n=pw(t.migratedAt??`${e.created_at}T00:00:00.000Z`,"Native portable migration time"),a=t.acceptance.map(o=>({id:o.id,source:o.source,text:o.text,result:"pending",reason:null}));return nt({schema:xt,name:e.name,language:e.language,phase:i,status:"active",state_version:1,brief:"brief.md",spec_changes:ww(e),workspace:t.workspace,loop:{stage:i==="shape"?"shape":"building",goal_cycle:1,iteration:r,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:Nw(e.language,i)},acceptance:a,builder_handoff:null,blockers:[],verification:null,history:[{goal_cycle:1,iteration:r,attempt:0,outcome:"recovery",unresolved_ids:a.map(({id:o})=>o),summary:ln(bw(e.language,e.schema,e.phase)),completed_at:n}],history_overflow:Wo(),verification_result:"pending",verification_report:null,archived:!1,created_at:`${e.created_at}T00:00:00.000Z`})}function Go(t){let e=hw(t,"Native portable migration transaction"),i=Object.keys(e).filter(r=>!cw.has(r));if(i.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${i.join(", ")}`);if(e.schema!==un)throw new Error("Unsupported Native portable migration transaction schema");if(typeof e.id!="string"||!uw.test(e.id))throw new Error("Native portable migration transaction id is invalid");if(typeof e.change!="string"||!lw.test(e.change))throw new Error("Native portable migration transaction change is invalid");if(typeof e.fromSchema!="string"||!fw.has(e.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof e.status!="string"||!dw.has(e.status))throw new Error("Native portable migration transaction status is invalid");return{schema:un,id:e.id,change:e.change,fromSchema:e.fromSchema,status:e.status,createdAt:mw(e.createdAt,"Native portable migration transaction createdAt")}}function Lu(t){switch(Go(t).status){case"prepared":return{action:"commit-portable-yaml",fromStatus:"prepared",nextStatus:"yaml-committed"};case"yaml-committed":return{action:"cleanup-legacy-runtime",fromStatus:"yaml-committed",nextStatus:"legacy-cleanup"};case"legacy-cleanup":return{action:"commit-transaction",fromStatus:"legacy-cleanup",nextStatus:"committed"};case"committed":return{action:"done",fromStatus:"committed",nextStatus:null}}}var Bu="comet.native.archive-transaction.v4",Mu="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",kw=new RegExp(`^portable-archive-(${Mu})\\.json$`,"u"),Sw=new RegExp(`^portable-migration-(${Mu})\\.json$`,"u"),Ew=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Pw=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,xw=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),Cw=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),Rw=new Set(["capability","operation","source","content"]),Fu=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function Vu(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function qu(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(", ")}`);if(Object.keys(t).length!==e.size)throw new Error(`${i} fields are invalid`)}function Aw(t,e){let i=`Native portable Archive spec_changes[${e}]`,r=Vu(t,i);if(qu(r,Rw,i),typeof r.capability!="string"||!Fu.test(r.capability))throw new Error(`${i}.capability is invalid`);if(!["create","modify","remove"].includes(String(r.operation)))throw new Error(`${i}.operation is invalid`);let n=r.operation;if(n==="remove"){if(r.source!==null||r.content!==null)throw new Error(`${i} remove requires source and content null`);return{capability:r.capability,operation:n,source:null,content:null}}if(typeof r.source!="string"||r.source.length===0||r.source.includes("\\")||r.source.startsWith("/")||/^[A-Za-z]:/u.test(r.source)||r.source.split("/").some(a=>a==="."||a===".."))throw new Error(`${i}.${n} source is invalid`);if(typeof r.content!="string")throw new Error(`${i}.${n} content is invalid`);return{capability:r.capability,operation:n,source:r.source,content:r.content}}function _w(t){let e=Vu(t,"Native portable Archive transaction");if(qu(e,Cw,"Native portable Archive transaction"),e.schema!==Bu)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof e.id!="string"||!Ew.test(e.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof e.change!="string"||!Fu.test(e.change))throw new Error("Native portable Archive transaction change is invalid");if(!Number.isSafeInteger(e.start_state_version)||Number(e.start_state_version)<0)throw new Error("Native portable Archive transaction state version is invalid");if(typeof e.archive_ref!="string"||!Pw.test(e.archive_ref)||!e.archive_ref.endsWith(`-${e.change}`))throw new Error("Native portable Archive transaction ref is invalid");if(typeof e.status!="string"||!xw.has(e.status))throw new Error("Native portable Archive transaction status is invalid");if(!Array.isArray(e.spec_changes))throw new Error("Native portable Archive transaction spec changes are invalid");let i=e.spec_changes.map(Aw);if(new Set(i.map(({capability:n})=>n)).size!==i.length)throw new Error("Native portable Archive transaction capabilities must be unique");if(!Number.isSafeInteger(e.next_spec_index)||Number(e.next_spec_index)<0||Number(e.next_spec_index)>i.length)throw new Error("Native portable Archive transaction spec cursor is invalid");if(typeof e.created_at!="string")throw new Error("Native portable Archive transaction timestamp is invalid");let r=new Date(e.created_at);if(Number.isNaN(r.valueOf())||r.toISOString()!==e.created_at)throw new Error("Native portable Archive transaction timestamp is invalid");return{schema:Bu,id:e.id,change:e.change,start_state_version:Number(e.start_state_version),archive_ref:e.archive_ref,status:e.status,next_spec_index:Number(e.next_spec_index),spec_changes:i,created_at:e.created_at}}function dn(t){let e=kw.exec(t);if(e)return{kind:"archive",change:e[1]};let i=Sw.exec(t);return i?{kind:"migration",change:i[1]}:null}function fn(t,e){let i=`${e.kind==="archive"?"portable-archive":"portable-migration"}-${e.change}.json`,r=dn(i);if(!r||r.kind!==e.kind||r.change!==e.change)throw new Error(`Invalid Native portable transaction change: ${e.change}`);return Uo.join(t.transactionsDir,i)}async function Ko(t,e){let i=dn(e);if(!i)return null;let r=await M({root:t.transactionsDir,ref:e,maxBytes:null,includeHash:!1}),n=JSON.parse(r.text),a=Uo.join(t.transactionsDir,e);if(i.kind==="archive"){let s=_w(n);if(s.change!==i.change)throw new Error(`Native portable transaction filename does not match ${s.change}`);return{kind:"archive",change:i.change,file:a,journal:s}}let o=Go(n);if(o.change!==i.change)throw new Error(`Native portable transaction filename does not match ${o.change}`);return{kind:"migration",change:i.change,file:a,journal:o}}async function Wu(t,e){let i=fn(t,e);try{return await Ko(t,Uo.basename(i))}catch(r){if(r.code==="ENOENT")return null;throw r}}function zu(t){return t.kind==="archive"||t.journal.status!=="committed"}import Ae from"path";import{TextDecoder as Lw}from"util";import{createHash as Tw}from"node:crypto";import{constants as hn,promises as ce}from"node:fs";import le from"node:path";function mn(t,e){let i=le.relative(t,e);return i===""||!le.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${le.sep}`)}function Iw(t){if(!Number.isSafeInteger(t)||t<1)throw new Error("Native protected file byte limit must be a positive integer");return t}function jw(t,e){return A({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function $w(t){return{dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs,ctimeMs:t.ctimeMs,mtimeMs:t.mtimeMs,size:t.size}}function pn(t,e){return A({...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 Yo(t,e){let i=await ce.lstat(t);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${e} parent must be a real directory: ${t}`);return{path:t,realPath:await ce.realpath(t),dev:i.dev,ino:i.ino,birthtimeMs:i.birthtimeMs}}async function Ow(t,e,i){let r=le.resolve(t),n=le.resolve(e);if(!mn(r,n))throw new Error(`${i} is outside its managed root`);let a=[await Yo(r,i)],o=r;for(let s of le.relative(r,n).split(le.sep).filter(Boolean)){await at(a,i),o=le.join(o,s);let c=await Yo(o,i);if(!mn(a[0].realPath,c.realPath))throw new Error(`${i} parent resolves outside its managed root: ${o}`);a.push(c)}return await at(a,i),a}async function at(t,e){for(let i of t){let r=await ce.lstat(i.path);if(!r.isDirectory()||r.isSymbolicLink()||!jw(i,r)||await ce.realpath(i.path)!==i.realPath)throw new Error(`${e} parent changed during I/O: ${i.path}`)}}async function Hw(t,e,i){let r=[],n=0,a=Buffer.allocUnsafe(Math.min(64*1024,e+1));for(;;){let o=e+1-n,{bytesRead:s}=await t.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,n>e)throw new Error(`${i} exceeds ${e} bytes`);r.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(r,n)}async function At(t){let e=Iw(t.maxBytes),i=le.resolve(t.file),r=await Ow(t.root,le.dirname(i),t.label),n=await Promise.all((t.forbiddenRoots??[]).map(f=>Yo(le.resolve(f),t.label)));await t.hooks?.afterParentChainCaptured?.(),await at(r,t.label);let a=await ce.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=$w(a),s=await ce.realpath(i);if(!mn(r[0].realPath,s))throw new Error(`${t.label} resolves outside its managed root`);if(n.some(f=>mn(f.realPath,s)))throw new Error(`${t.label} resolves inside an excluded root`);let c=process.platform==="win32"?hn.O_RDONLY:hn.O_RDONLY|hn.O_NOFOLLOW|hn.O_NONBLOCK,l=await ce.open(i,c);try{let f=await l.stat();await t.hooks?.afterOpen?.();let[d,u]=await Promise.all([ce.lstat(i),ce.realpath(i)]);if(await at(r,t.label),await at(n,t.label),!f.isFile()||!d.isFile()||d.isSymbolicLink()||u!==s||!pn(o,f)||!pn(o,d))throw new Error(`${t.label} changed while opening`);await t.hooks?.beforeRead?.();let p=await Hw(l,e,t.label);await t.hooks?.beforeFinalCheck?.();let[v,h,m]=await Promise.all([l.stat(),ce.lstat(i),ce.realpath(i)]);if(await at(r,t.label),await at(n,t.label),!h.isFile()||h.isSymbolicLink()||m!==s||!pn(o,v)||!pn(o,h))throw new Error(`${t.label} changed while reading`);return{bytes:p,hash:Tw("sha256").update(p).digest("hex"),size:p.length}}finally{await l.close()}}var Bw=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),Mw=new Set(["id","type","source","target","staged","backup"]),Fw=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),Vw=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]);var Uu=new Set(["prepared","applying","committed","rolling-back","rolled-back"]);var qw=256*1024,cE=1024*1024,lE=16*1024;var uE=64*1024*1024;var Ww=new Lw("utf-8",{fatal:!0});function gn(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function wn(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 Ku(t){if(typeof t!="string")return!1;let e=new Date(t);return!Number.isNaN(e.valueOf())&&e.toISOString()===t}function Xo(t,e){if(typeof t!="string"||t.length===0||Ae.isAbsolute(t)||/^(?:[A-Za-z]:|~|[\\/])/u.test(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`${e} must stay inside the Native root`)}function vn(t,e){if(typeof t!="string"||!/^[a-f0-9]{64}$/u.test(t))throw new Error(`${e} must be a SHA-256 hash`)}function Ju(t,e){if(Xo(t,e),t.includes("\\")||t!==Ae.posix.normalize(t)||t.split("/").includes(".")||t.endsWith("/")||Buffer.byteLength(t,"utf8")>1024)throw new Error(`${e} must be a normalized Native-relative ref`)}function zw(t,e){let i=gn(t,`transaction operations[${e}]`);if(wn(i,Mw,`transaction operations[${e}]`),typeof i.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(i.id))throw new Error(`transaction operations[${e}].id is invalid`);if(i.type!=="write"&&i.type!=="remove"&&i.type!=="move")throw new Error(`transaction operation ${i.id} has an invalid type`);Xo(i.target,`transaction operation ${i.id} target`);for(let r of["source","staged","backup"])i[r]!==void 0&&Xo(i[r],`transaction operation ${i.id} ${r}`);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 Yu(t){let e=gn(t,"Native Archive transaction journal");if(wn(e,Fw,"Native Archive transaction journal"),e.schema!=="comet.native.transaction.v2")throw new Error("Unsupported Native Archive transaction schema");if(typeof e.id!="string"||!/^[a-f0-9-]{8,}$/u.test(e.id))throw new Error("Native Archive transaction id is invalid");if(e.kind!=="archive")throw new Error("Native v2 transaction kind must be archive");if(typeof e.status!="string"||!Uu.has(e.status))throw new Error("Native Archive transaction status is invalid");if(typeof e.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.change))throw new Error("Native Archive transaction change name is invalid");if(!Ku(e.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(vn(e.preflightHash,"Native Archive transaction preflightHash"),!Array.isArray(e.operations)||e.operations.length>65)throw new Error("Native Archive transaction operations must be an array");let i=e.operations.map((s,c)=>{let l=gn(s,`Archive transaction operations[${c}]`);if(wn(l,Vw,`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`);Ju(l.target,`Archive transaction operation ${l.id} target`);for(let f of["source","staged","backup"])l[f]!==void 0&&Ju(l[f],`Archive transaction operation ${l.id} ${f}`);if(l.expectedTargetHash!==null&&vn(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(vn(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`);vn(l.expectedSourceHash,`Archive move operation ${l.id} expectedSourceHash`)}return l}),r=i.map(s=>s.id);if(new Set(r).size!==r.length)throw new Error("Native Archive transaction operation ids must be unique");let n=`runtime/transactions/${e.id}`,a=i.filter(s=>s.type==="move");if(a.length!==1||a[0].id!=="archive-change"||a[0].source!==`changes/${e.change}`||!new RegExp(`^archive/\\d{4}-\\d{2}-\\d{2}-${e.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(`${n}/staged/specs/`))throw new Error(`Native Archive transaction staged ref is invalid: ${s.staged}`);if(s.backup!==void 0&&!s.backup.startsWith(`${n}/backups/specs/`))throw new Error(`Native Archive transaction backup ref is invalid: ${s.backup}`)}return{schema:"comet.native.transaction.v2",id:e.id,kind:"archive",status:e.status,change:e.change,createdAt:e.createdAt,preflightHash:e.preflightHash,operations:i}}function Jw(t){let e=gn(t,"Native transaction journal");if(e.schema==="comet.native.transaction.v2")return Yu(e);if(wn(e,Bw,"Native transaction journal"),e.schema!=="comet.native.transaction.v1")throw new Error("Unsupported Native transaction schema");if(typeof e.id!="string"||!/^[a-f0-9-]{8,}$/u.test(e.id))throw new Error("Native transaction id is invalid");if(e.kind!=="archive"&&e.kind!=="root-move")throw new Error("Native transaction kind is invalid");if(typeof e.status!="string"||!Uu.has(e.status))throw new Error("Native transaction status is invalid");if(typeof e.projectRoot!="string"||!Ae.isAbsolute(e.projectRoot)||typeof e.nativeRoot!="string"||!Ae.isAbsolute(e.nativeRoot))throw new Error("Native transaction roots must be absolute paths");if(e.change!==void 0&&(typeof e.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.change)))throw new Error("Native transaction change name is invalid");if(!Ku(e.createdAt))throw new Error("Native transaction createdAt is invalid");if(!Array.isArray(e.operations))throw new Error("Native transaction operations must be an array");let i=e.operations.map(zw),r=i.map(n=>n.id);if(new Set(r).size!==r.length)throw new Error("Native transaction operation ids must be unique");return{schema:"comet.native.transaction.v1",id:e.id,kind:e.kind,status:e.status,projectRoot:e.projectRoot,nativeRoot:e.nativeRoot,...typeof e.change=="string"?{change:e.change}:{},createdAt:e.createdAt,operations:i}}function Gw(t,e){if(!/^[a-f0-9-]{8,}$/u.test(e))throw new Error(`Invalid Native transaction id: ${e}`);return Ae.join(t.transactionsDir,e)}function Xu(t,e){let i=Gw(t,e);return{directory:i,journal:Ae.join(i,"transaction.json"),events:Ae.join(i,"events.jsonl"),staged:Ae.join(i,"staged"),backups:Ae.join(i,"backups")}}async function Zo(t,e){let i=Xu(t,e);return await Promise.all(Object.values(i).map(r=>T(t.runtimeDir,r))),i}async function es(t,e,i={}){let r=await Zo(t,e),n=await At({root:t.runtimeDir,file:r.journal,maxBytes:qw,label:`Native transaction journal ${e}`,hooks:i.hooks}),a=JSON.parse(Ww.decode(n.bytes)),o=Jw(a);if(o.id!==e)throw new Error(`Invalid Native transaction journal: ${e}`);return o}async function Yw(t,e,i){let r;try{r=await Uw.readdir(t.transactionsDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return!1;throw n}for(let n of r)if(!(!n.isDirectory()||n.isSymbolicLink()))try{let a=await es(t,n.name);if(a.id!==e&&a.status!=="committed"&&a.status!=="rolled-back")return!0}catch{return!0}for(let n of r)if(dn(n.name))try{let a=await Ko(t,n.name);if(!a||i?.kind===a.kind&&i.change===a.change)continue;if(zu(a))return!0}catch{return!0}return!1}async function Xw(t,e){let i=Date.now()+5e3,r=Kw.join(t.locksDir,"root-move.lock");for(;;)try{return await tn(t,"root-move",e)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await _u(r);if(o.status==="missing")continue;if(o.status!=="active"||Date.now()>=i)throw n;await new Promise(s=>setTimeout(s,5+Math.floor(Math.random()*11)))}}async function Z(t,e,i,r){let n=await Xw(t,e);try{if(await Zr(t.projectRoot),await Yw(t,r?.allowedTransactionId,r?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await i()}finally{await rn(n)}}import{createHash as Qw}from"crypto";function ee(t){return Qw("sha256").update(t).digest("hex")}var TE={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024};var IE=8*1024*1024;var jE=64*1024,$E=64*1024;var OE={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},HE={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};var DE=(1n<<256n)-1n;var ay=$t(yt(),1);var ZE=4*1024*1024;var oy=null;function sy(t,e){let i=t;for(let r of e)i+="\0"+(typeof r=="string"?r:JSON.stringify(r));return i}function Qu(t,e){return(...i)=>{let r=oy;if(r===null)return e(...i);let n=sy(`async:${t}`,i),a=r.entries.get(n);if(a)return a.value;let o=e(...i).catch(s=>{throw r.entries.delete(n),s});return r.entries.set(n,{value:o}),o}}var nP=Qu("hookWritePolicy",async t=>(await Po(t))?.hook??{allow_paths:[]});var ZP=256*1024;var fx={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 _t from"node:path";var xi=/^[a-f0-9]{64}$/u,ed=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,uy=16*1024,Rx=process.platform;function dy(t,e){let i=_t.relative(t,e);return _t.isAbsolute(i)||i===".."||i.startsWith(`..${_t.sep}`)?null:i.replaceAll("\\","/")||"."}function td(t){return Array.from(t).some(e=>{let i=e.codePointAt(0)??0;return i<=31||i===127})}function id(t,e){if(t.length===0||td(t)||t.includes("\\")||_t.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=_t.posix.normalize(t);if(i!==t||i===".."||i.startsWith("../"))throw new Error(`${e} must be a normalized project-relative path`);return i}function fy(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 ts(t,e){if(t===null)return null;if(typeof t!="string"||t.length===0||t.trim()!==t||td(t))throw new Error(`${e} must be a non-empty branch name or null`);return t}function hy(t){if(!new Set(["current","branch","worktree"]).has(t.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(ts(t.changeBranch,"Native workspace change branch"),ts(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 py(t){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Native workspace Git provenance must be an object");let e=t,i=new Set(["provider","baseCommit","targetBranch","targetCommit"]),r=Object.keys(e).filter(n=>!i.has(n));if(r.length>0)throw new Error(`Native workspace Git provenance has unknown field(s): ${r.join(", ")}`);if(e.provider!=="git"||typeof e.baseCommit!="string"||!ed.test(e.baseCommit)||typeof e.targetCommit!="string"||!ed.test(e.targetCommit))throw new Error("Native workspace Git provenance is invalid");ts(e.targetBranch,"Native workspace Git target branch")}function my(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","git","isolation","changeBranch","targetBranch","finish"]),r=Object.keys(e).filter(o=>!i.has(o));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"||!xi.test(String(e.projectRootId))||!xi.test(String(e.nativeRootId)))throw new Error("Native workspace identity is invalid");fy(e.capturedAt),id(e.nativeRootRef,"Native workspace root ref");let n=e.projectRootPathId!==void 0,a=e.nativeRootPathId!==void 0;if(n!==a)throw new Error("Native workspace path identities must be provided together");if(n&&!xi.test(String(e.projectRootPathId))||a&&!xi.test(String(e.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(e.sessionHash!==void 0&&!xi.test(String(e.sessionHash)))throw new Error("Native workspace session hash is invalid");if(e.git!==void 0&&py(e.git),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(hy(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 vy(t,e){return _t.join(pe(t,e),"workspace.json")}function gy(t,e){let i=vy(t,e),r=me(t,i),n=dy(r,i);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:r,ref:id(n,"Native workspace file ref")}}async function wy(t,e){try{let i=gy(t,e),r=await M({root:i.root,ref:i.ref,maxBytes:uy});return JSON.parse(r.text)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function Ci(t,e){let i=await wy(t,e);return i===null||i&&typeof i=="object"&&!Array.isArray(i)&&i.schema==="comet.native.workspace.v1"?null:(my(i),i)}var ad=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],Ny=new Set(ad),od=new Set([...ad,"minimum_runtime_version","revision"]),by=new Set([...od,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),ky=new Set(["capability","operation","source","base_hash"]),Sy=new Set(["shape","build","verify","archive"]),Ey=new Set(["implicit","confirmed"]),Py=new Set(["pending","pass","fail"]),ot="comet-state.yaml",rs=/^[a-f0-9]{64}$/u,sd=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,xy=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,ns=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"},It=class extends Error{constructor(i,r){super(i!==Re||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"},yn=class extends Error{constructor(i,r,n){super(`Native change ${i} revision conflict: expected ${r}, actual ${n}`);this.change=i;this.expectedRevision=r;this.actualRevision=n;this.name="NativeChangeRevisionConflictError"}change;expectedRevision;actualRevision;code="native-change-revision-conflict"},Ri=class extends Error{constructor(i,r){super(`Native working directory already contains active change${r.length===1?"":"s"} ${r.join(", ")}; create the new change in a separate worktree`);this.requestedIsolation=i;this.activeChanges=r;this.name="NativeWorkspaceIsolationRequiredError"}requestedIsolation;activeChanges;code="native-workspace-isolation-required"},Nn=class extends Error{constructor(i,r,n,a,o,s=null,c=null){super(`Native change ${i} baseline is incomplete (${r} omitted entr${r===1?"y":"ies"}). Adjust native.snapshot scope or resource budgets in .comet/config.yaml, then retry.`);this.change=i;this.omittedCount=r;this.omittedByReason=n;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"},Zx=["# Outcome","","# Scope","","# Non-goals","","# Acceptance examples","","# Constraints and invariants","","# Decisions","","# Open questions","","# Verification expectations",""].join(`
|
|
150
|
+
`);function _i(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function cd(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 os(t){if(!sd.test(t))throw new Error(`Invalid Native change name: ${t}`)}function Cy(t){if(!sd.test(t))throw new Error(`Invalid Native capability id: ${t}`)}function ld(t,e){if(t.length===0||Tt.isAbsolute(t)||/^(?:[A-Za-z]:|~|[\\/])/u.test(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`${e} must stay inside the Native change`)}function Ry(t,e){let i=_i(t,`spec_changes[${e}]`);if(cd(i,ky,`spec_changes[${e}]`),typeof i.capability!="string")throw new Error("spec change capability is required");if(Cy(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"&&ld(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"||!rs.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"||!rs.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 Ay(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 ss(t,e){if(cd(t,e,ot),typeof t.name!="string")throw new Error("Native change name is required");if(os(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"||!Sy.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&&!Ey.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(Ry),r=i.map(n=>n.capability).filter((n,a,o)=>o.indexOf(n)!==a);if(r.length>0)throw new Error(`Duplicate Native capability operation: ${[...new Set(r)].join(", ")}`);if(typeof t.verification_result!="string"||!Py.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"&&ld(t.verification_report,"Native verification_report"),typeof t.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof t.created_at!="string"||!Ay(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 Si(t){let e=_i(t,ot);if(e.schema!==we)throw new Error(`Expected ${we}`);return{schema:we,...ss(e,Ny)}}function Ai(t,e){if(!Number.isSafeInteger(t)||t<1)throw new Error(`${e} must be a positive integer`);return t}function is(t,e,i){if(t===null)return null;let r=typeof t=="string"?xy.exec(t):null;if(!r||r[1]!==i)throw new Error(`${e} must be null or runtime/evidence/${i}/<sha256>.json relative to the Native change`);return t}function _y(t){if(t==null)return null;if(typeof t!="string"||!rs.test(t))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return t}function Ty(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 Ei(t){let e=_i(t,ot);if(e.schema!==ge)throw new Error(`Expected ${ge}`);if(Ai(e.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${ge} minimum_runtime_version must be 2`);return{schema:ge,minimum_runtime_version:2,revision:Ai(e.revision,"Native v2 revision"),...ss(e,od)}}function Pi(t){let e=_i(t,ot);if(e.schema!==Re){if(e.schema===we||e.schema===ge){let o=e.schema===we?Si(e):Ei(e);throw new ns(o.name,o.schema)}throw new It(typeof e.schema=="string"?e.schema:"(missing)",typeof e.minimum_runtime_version=="number"?e.minimum_runtime_version:null)}let i=Ai(e.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)throw new It(e.schema,i);if(i!==3)throw new Error(`Native ${e.schema} minimum_runtime_version must be ${3}`);let r=Ai(e.revision,"Native revision"),n=ss(e,by),a=_y(e.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:Re,minimum_runtime_version:3,revision:r,verification_protocol:Ty(e.verification_protocol),...n,approved_contract_hash:a,implementation_scope:is(e.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:is(e.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:is(e.partial_allowance,"Native partial_allowance","allowances")}}function Iy(t){let e=_i(t,ot);if(e.schema===we){let n=Si(e);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${Re}`}}if(e.schema===ge){let n=Ei(e);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${Re}`}}if(e.schema!==Re){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 It(typeof e.schema=="string"?e.schema:"(missing)",n).message}}let i=Ai(e.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)return{status:"runtime-incompatible",schema:e.schema,minimumRuntimeVersion:i,state:null,message:new It(e.schema,i).message};let r=Pi(e);return{status:"current",schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,state:r}}function ye(t,e){os(e);let i=Tt.join(t.changesDir,e);if(!F(t.changesDir,i))throw new Error("Native change path escaped");return i}async function jy(t,e=Tt.dirname(t)){let i=Tt.relative(e,t).split(Tt.sep).join("/"),r=await M({root:e,ref:i,maxBytes:null,includeHash:!1}),n=(0,as.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 ud(t,e){let i=Tt.join(ye(t,e),ot);await T(t.nativeRoot,i);let r=Iy(await jy(i,t.nativeRoot));if(r.state&&r.state.name!==e)throw new Error(`Native change directory/name mismatch: ${e}`);return r}import{promises as hd}from"node:fs";import Cn from"node:path";var Oy=$t(yt(),1);var tC=8*1024*1024;var dC=["$ProgressPreference = 'SilentlyContinue'","$encoded = $env:COMET_COMMAND_PAYLOAD","Remove-Item Env:COMET_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("; ");import{promises as Fy}from"node:fs";import Ii from"node:path";function bn(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function kn(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 Ne(t,e,i=!1){if(typeof t!="string"||!i&&t.length===0)throw new Error(`${e} must be ${i?"a string":"a non-empty string"}`);return t}function dd(t,e){return t===null?null:Ne(t,e)}function En(t,e,i=0){if(!Number.isSafeInteger(t)||t<i)throw new Error(`${e} must be a safe integer greater than or equal to ${i}`);return t}function Vy(t,e){if(t===null)return null;if(!Number.isSafeInteger(t))throw new Error(`${e} must be null or a safe integer`);return t}function qy(t,e){if(typeof t!="boolean")throw new Error(`${e} must be a boolean`);return t}function Sn(t,e,i){if(typeof t!="string"||!e.includes(t))throw new Error(`${i} must be one of: ${e.join(", ")}`);return t}function cs(t,e){if(t===null)return null;let i=Ne(t,e);if(Number.isNaN(Date.parse(i)))throw new Error(`${e} must be an ISO timestamp`);return i}function ls(t,e){let i=Ne(t,e);if(!Ii.isAbsolute(i))throw new Error(`${e} must be absolute`);return Ii.resolve(i)}function Wy(t,e){let i=`Native local checks[${e}]`,r=bn(t,i);if(kn(r,new Set(["id","name","operationId","status","repeatable","timeoutMs","executionCount","argv","cwd","exitCode","startedAt","completedAt","log"]),i),!Array.isArray(r.argv)||r.argv.length===0)throw new Error(`${i}.argv must be a non-empty array`);let n=r.argv.map((l,f)=>Ne(l,`${i}.argv[${f}]`,!0)),a=Sn(r.status,["planned","running","passed","failed","interrupted"],`${i}.status`),o=cs(r.startedAt,`${i}.startedAt`),s=cs(r.completedAt,`${i}.completedAt`);if(a==="planned"&&(o!==null||s!==null))throw new Error(`${i} planned check cannot contain execution timestamps`);if(a==="running"&&(o===null||s!==null))throw new Error(`${i} running check requires only startedAt`);if((a==="passed"||a==="failed")&&(o===null||s===null))throw new Error(`${i} completed check requires startedAt and completedAt`);let c=En(r.timeoutMs,`${i}.timeoutMs`);if(c<1)throw new Error(`${i}.timeoutMs must be positive`);return{id:Ne(r.id,`${i}.id`),name:Ne(r.name,`${i}.name`),operationId:Ne(r.operationId,`${i}.operationId`),status:a,repeatable:qy(r.repeatable,`${i}.repeatable`),timeoutMs:c,executionCount:En(r.executionCount,`${i}.executionCount`),argv:n,cwd:ls(r.cwd,`${i}.cwd`),exitCode:Vy(r.exitCode,`${i}.exitCode`),startedAt:o,completedAt:s,log:Ne(r.log,`${i}.log`)}}function fd(t){let e="Native local execution state",i=bn(t,e);if(kn(i,new Set(["schema","change","basedOnStateVersion","workspace","execution","checks"]),e),i.schema!==ki)throw new Error(`Native local execution schema must be ${ki}`);let r=bn(i.workspace,"Native local workspace");kn(r,new Set(["projectRoot","worktreeRoot","branch"]),"Native local workspace");let n=null;if(i.execution!==null){let o=bn(i.execution,"Native local execution");kn(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds"]),"Native local execution");let s=cs(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:Ne(o.operationId,"Native local execution.operationId"),stage:Sn(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:Sn(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:dd(o.executionId,"Native local execution.executionId"),status:Sn(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:En(o.requestCheckRounds,"Native local execution.requestCheckRounds")}}if(!Array.isArray(i.checks))throw new Error("Native local checks must be an array");let a=i.checks.map(Wy);if(new Set(a.map(o=>o.id)).size!==a.length)throw new Error("Native local check IDs must be unique");if(n&&a.some(o=>o.operationId!==n.operationId))throw new Error("Native local checks must belong to the current operation");return{schema:ki,change:Ne(i.change,"Native local change"),basedOnStateVersion:En(i.basedOnStateVersion,"Native local basedOnStateVersion",1),workspace:{projectRoot:ls(r.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:ls(r.worktreeRoot,"Native local workspace.worktreeRoot"),branch:dd(r.branch,"Native local workspace.branch")},execution:n,checks:a}}function Pn(t){return fd({schema:ki,change:t.portableState.name,basedOnStateVersion:t.portableState.state_version,workspace:{projectRoot:Ii.resolve(t.projectRoot),worktreeRoot:Ii.resolve(t.worktreeRoot??t.projectRoot),branch:t.branch??null},execution:null,checks:[]})}async function xn(t,e,i={}){let r=fd(e);await Fy.mkdir(Ii.dirname(t),{recursive:!0}),await K(t,r,i)}var pd=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,zy="comet-state.yaml",Jy="state.json";function md(t,e){if(!pd.test(e))throw new Error(`Invalid Native change name: ${e}`);let i=Cn.join(t.changesDir,e);if(!F(t.changesDir,i))throw new Error("Native change path escaped");return i}function Je(t,e){return Cn.join(md(t,e),zy)}function us(t,e){return Cn.join(it(t,e),Jy)}async function ji(t,e){try{let i=await hd.readFile(Je(t,e),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(i)}catch(i){if(i.code==="ENOENT")return!1;throw i}}function Gy(t){return ke(t).currentBranch}async function vd(t,e){return Ce(Je(t,e))}async function Uy(t){let e=await Hu({file:Je(t.paths,t.previous.name),expectedStateVersion:t.previous.state_version,next:t.next,containedRoot:t.paths.nativeRoot});if(e.verification===null&&e.verification_report===null){let i=Cn.join(md(t.paths,e.name),"verification.md");await T(t.paths.nativeRoot,i),await hd.rm(i,{force:!0})}return e}async function gd(t){if(!pd.test(t.capability))throw new Error(`Invalid Native capability: ${t.capability}`);return Z(t.paths,`remove portable spec ${t.capability}`,async()=>{let e=await vd(t.paths,t.name);if(e.archived)throw new Error(`Native change ${e.name} is already archived`);let i=e.spec_changes.filter(({capability:a})=>a!==t.capability),r={...e,phase:"shape",status:"active",state_version:e.state_version+1,spec_changes:[...i,{capability:t.capability,operation:"remove",source:null}].sort((a,o)=>a.capability.localeCompare(o.capability,"en")),acceptance:[],builder_handoff:null,blockers:[],verification:null,verification_result:"pending",verification_report:null,history:[],history_overflow:{dropped_entries:0,first_dropped_at:null,last_dropped_at:null,outcome_counts:{pass:0,fail:0,blocked:0,"execution-error":0,recovery:0}},loop:{stage:"shape",goal_cycle:e.loop.goal_cycle+(e.phase==="shape"?0:1),iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:"confirm-shape"}};delete r.children_contract_hash;let n=await Uy({paths:t.paths,previous:e,next:r});return await xn(us(t.paths,e.name),Pn({portableState:n,projectRoot:t.paths.projectRoot,branch:Gy(t.paths.projectRoot)}),{containedRoot:t.paths.runtimeDir}),n})}var wd=["evidence.md","repair.md","archive.md","checkpoint.md"],Xy="verification.md";async function Qy(t,e){let i=await Wu(t,{kind:"migration",change:e});return i?.kind==="migration"?i.journal:null}async function yd(t,e){await $i.mkdir(t.transactionsDir,{recursive:!0}),await K(fn(t,{kind:"migration",change:e.change}),e,{containedRoot:t.runtimeDir})}async function Nd(t,e,i={}){let r=i.removeVerificationReport===!1?wd:[...wd,Xy];await Promise.all([$i.rm(it(t,e),{recursive:!0,force:!0}),$i.rm(_o(t,e),{recursive:!0,force:!0}),...r.map(n=>$i.rm(Yy.join(ye(t,e),n),{force:!0}))])}async function bd(t,e){await xn(us(t,e.name),Pn({portableState:e,projectRoot:t.projectRoot}),{containedRoot:t.runtimeDir})}async function kd(t,e){try{let i=await Ci(t,e);if(i?.schema==="comet.native.workspace.v3")return{isolation:i.isolation,change_branch:i.changeBranch,target_branch:i.targetBranch,finish:i.finish}}catch{}return{isolation:"current",change_branch:null,target_branch:null,finish:null}}function Sd(t,e){if(e.isolation==="current"&&e.change_branch===null)return;let i=ke(t.projectRoot);if(!i.isGitWorktree)throw new Error("Native legacy migration requires its bound Git branch or worktree");if(i.currentBranch!==e.change_branch)throw new Error(`Native legacy migration expected branch ${e.change_branch??"(missing)"}, current branch is ${i.currentBranch??"(detached)"}`);if(e.isolation==="worktree"&&!i.isSecondaryWorktree)throw new Error("Native legacy migration requires its bound linked worktree")}async function Zy(t){let e=ye(t.paths,t.state.name),i=await M({root:e,ref:t.state.brief,maxBytes:null,includeHash:!1}),r=[];for(let n of t.state.spec_changes){if(n.operation==="remove"||!n.source)continue;let a=await M({root:e,ref:n.source,maxBytes:null,includeHash:!1});r.push({capability:n.capability,source:a.ref,markdown:a.text})}try{return qo({briefMarkdown:i.text,specs:r})}catch(n){if(t.state.phase==="shape"&&n.message.includes("at least one acceptance"))return[];throw n}}async function Ed(t,e){let i=await ud(t,e);if(!i.state)throw new Error(`Native legacy change ${e} is unreadable`);return i.state}async function Pd(t){return Z(t.paths,`migrate ${t.name} to portable Native`,async()=>{let e=await Qy(t.paths,t.name),i=await ji(t.paths,t.name)?await Ce(Je(t.paths,t.name)):null;if(!e&&i)return await Nd(t.paths,t.name,{removeVerificationReport:!1}),await bd(t.paths,i),i;let r=null,n=null;for(e||(r=await Ed(t.paths,t.name),n=await kd(t.paths,t.name),Sd(t.paths,n),e={schema:un,id:Ky(),change:r.name,fromSchema:r.schema,status:"prepared",createdAt:(t.now??new Date).toISOString()},await yd(t.paths,e));;){let a=Lu(e);if(a.action==="done")break;a.action==="commit-portable-yaml"?i||(r??=await Ed(t.paths,t.name),n??=await kd(t.paths,t.name),Sd(t.paths,n),i=Du({state:r,acceptance:await Zy({paths:t.paths,state:r}),workspace:n,migratedAt:t.now}),await cn(Je(t.paths,t.name),i,{containedRoot:t.paths.nativeRoot})):a.action==="cleanup-legacy-runtime"?await Nd(t.paths,t.name):a.action==="commit-transaction"&&(i??=await Ce(Je(t.paths,t.name)),await bd(t.paths,i)),e={...e,status:a.nextStatus},await yd(t.paths,e)}return await $i.rm(fn(t.paths,{kind:"migration",change:t.name}),{force:!0}),i??Ce(Je(t.paths,t.name))},{allowedPortableTransaction:{kind:"migration",change:t.name}})}import Hi from"path";import{realpathSync as LN}from"fs";var tN=["Outcome","Scope","Non-goals","Acceptance examples"],dA=[...tN,"Constraints and invariants","Decisions","Open questions","Verification expectations"];var iN=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 xd=1024*1024;var Rd="scoped-text-safety",rN=1,nN=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128});var aN="comet.native.checker-policy.v1";var CA=U(aN,{policy:Rd,version:rN,limits:nN,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"});var oN=["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"],RA=new Set(oN);var lN=xd,zA=3*lN;var Ad={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:[]},dN=ee("comet-native-runtime:v3:scope-reopen"),w_=[{skillVersion:"3",skillHash:ee("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:ee("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:ee("comet-native-runtime:v1")}];var Td=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],Q_=new Set(Td),wN=new Set([...Td,"minimum_runtime_version","revision"]),Z_=new Set([...wN,"operation"]),eT=512*1024,yN=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),tT=new Set([...yN,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]);var aT={maxAcceptanceCriteria:bi.maxCriteria};var uT={maxSpecs:64,maxFileBytes:Vi,maxTotalBytes:4*1024*1024};import{execFile as RN}from"node:child_process";import{promisify as AN}from"node:util";var NT={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024};var FT=512*1024;var Oi=class extends Error{recovery;constructor(e,i){super(e),this.name="NativeReceiptScopeStaleError",this.recovery=i}};var uI=64*1024;var dI=3600*1e3;var fI=AN(RN);var Rn=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(r=>`${r.ref}${r.acceptanceId?`[${r.acceptanceId}]`:""} -> ${r.mismatches.join("; ")}`).join(" | ")}`;super(i),this.name="NativeVerificationReceiptBindingError",this.details=e}};var XI={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};var sj=16*1024*1024,cj=256*1024,lj=16*1024;var pj=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});var gj=16*1024;var Aj=16*1024;var y$=16*1024*1024,An=class extends Error{constructor(i,r,n,a){super(`Canonical spec conflict for ${i}: expected ${r??"(missing)"}, actual ${n??"(missing)"}`);this.capability=i;this.expectedHash=r;this.actualHash=n;this.canonicalPath=a;this.name="NativeSpecConflictError"}capability;expectedHash;actualHash;canonicalPath;code="native-spec-conflict"},_n=class extends Error{constructor(i,r=i.ready?"Native Archive preflight no longer matches the expected hash":`Native Archive preflight is blocked: ${i.findingCodes.join(", ")}`){super(r);this.preflight=i;this.name="NativeArchivePreflightError"}preflight;code="native-archive-preflight"};var Tn=class extends Error{constructor(i,r,n){super(i,n);this.preparation=r;this.name="NativeWorkspacePreparationError"}preparation};var $d=["--project-root <path> Resolve the Native project from this working directory.","--json Emit the stable JSON command envelope.","--help Show help without requiring an initialized project."],fs=Object.freeze({"":{usage:"comet native <command> [options]",purpose:"Create, inspect, recover, and archive portable Native changes through Runtime-enforced, skill-coordinated steps.",subcommands:["init Initialize Native project configuration.","root show Inspect the configured artifact root.","root move <artifact-root> Move the configured artifact root.","new <change-name> Create a change and prepare its workspace.","spec remove Record a complete capability removal intent.","show <change-name> Read formal artifacts and portable state.","status [<change-name>] Discover stable boundaries and Runner actions.","select <change-name> Select a change in its bound workspace.","next <change-name> Confirm or recover a stable workflow boundary.","archive <change-name> Preview and execute Archive plus workspace finish.","doctor [<change-name>] Diagnose, migrate, or rebuild local execution state."],options:$d,output:"Human-readable text by default; use --json for a structured command envelope.",examples:["comet native status --json","comet native status my-change --details --json","comet native next --help"]},init:{usage:"comet native init [--root <artifact-root>] [--language en|zh-CN]",purpose:"Create or normalize .comet/config.yaml and the configured Native directories.",options:["--root <artifact-root> Project-relative artifact root; defaults to docs.","--language en|zh-CN Language for newly generated Native artifacts."],output:"The resolved project configuration and Native paths.",examples:["comet native init --root docs --language zh-CN"]},root:{usage:"comet native root <show|move> [arguments]",purpose:"Inspect or transactionally move the configured Native artifact root.",subcommands:["show Print the configured artifact root and resolved paths.","move <artifact-root> Move Native artifacts and update project configuration."],output:"The current root projection or the completed move result.",examples:["comet native root show","comet native root move artifacts/native"]},"root show":{usage:"comet native root show",purpose:"Print the configured Native artifact root and resolved paths.",output:"The configured artifact root and resolved Native paths."},"root move":{usage:"comet native root move <artifact-root>",purpose:"Transactionally move Native artifacts and update project configuration.",output:"The source, destination, and committed root-move transaction result.",examples:["comet native root move artifacts/native"]},new:{usage:"comet native new <change-name> [--language en|zh-CN] [--isolation current|branch|worktree] [--change-branch <branch>] [--target-branch <branch>] [--worktree-path <path>]",purpose:"Create a portable Native change and prepare the requested branch or linked worktree.",options:["--language en|zh-CN Artifact language; defaults to project configuration.","--isolation <kind> current, branch, or worktree; defaults to current.","--change-branch <branch> Change branch; defaults to comet/<change-name>.","--target-branch <branch> Local base branch; defaults to the current branch.","--worktree-path <path> Worktree directory; defaults to .worktrees/<change-name>."],output:"The portable state, workspace preparation result, and continuation with the next Runner action.",examples:["comet native new session-timeout --language zh-CN","comet native new session-timeout --isolation branch --target-branch main","comet native new session-timeout --isolation worktree --target-branch main"]},spec:{usage:"comet native spec remove <change-name> <capability>",purpose:"Record a capability removal; create and modify intents use complete proposed Spec files.",subcommands:["remove <change-name> <capability> Record a capability removal."],output:"The updated portable state and continuation."},"spec remove":{usage:"comet native spec remove <change-name> <capability>",purpose:"Record removal of a capability in the complete target specification.",output:"The updated portable state and continuation with the next Runner action."},show:{usage:"comet native show <change-name>",purpose:"Read formal artifacts and portable state for one Native change.",output:"The portable state, brief, complete proposed Specs, and continuation; legacy state is reported as migration-required."},status:{usage:"comet native status [<change-name>] [--cursor <token>] [--details]",purpose:"Discover portable stable boundaries, parent child readiness, or the exact next Runner action.",options:["--cursor <token> Continue a status-list page.","--details Include acceptance, Spec, workspace, and report details."],output:"A v2 status page or one portable Loop projection with local execution availability and continuation.runnerAction; parent changes also expose children and readyChildren.",examples:["comet native status --json","comet native status session-timeout --details --json"]},select:{usage:"comet native select <change-name>",purpose:"Select one Native change after validating its workspace binding.",output:"The selected change record."},next:{usage:`comet native next <change-name> --summary <text> [--confirmed|--accept-result|--revise-implementation|--revise-requirements|--retry-verifier|--resolve-verifier-blocker]
|
|
151
|
+
comet native next <change-name> --runner-input <json-file>`,purpose:"Confirm or recover an Agent boundary, advance parent child changes, or use one skill-coordinated JSON bridge for Builder handoff, check-plan dispatch, and Verifier response/error.",options:["--summary <text> Required transition or recovery summary.","--confirmed Confirm Shape or an explicitly degraded verifier-unavailable fallback before Archive.","--accept-result Accept the current skill-coordinated Verify result and make it archive-ready.","--revise-implementation Keep confirmed requirements unchanged and return Verify to Build for implementation revision.","--revise-requirements Return Verify or Archive to Shape when user-visible goals or acceptance criteria must change.","--retry-verifier Retry a blocked Verifier execution when the continuation allows it.","--resolve-verifier-blocker Resolve a semantic Verifier blocker without changing the candidate, then dispatch a new attempt.","--expected-state-version <n> Continuation-issued guard that rejects stale public transition decisions.","--expected-action <action> Continuation-issued guard that binds the public transition decision to its intended action.","--runner-input <file> Skill-coordinated JSON: builder-handoff, dispatch-verifier, verifier-response, verifier-execution-error, or verifier-unavailable. Identity/provider/execution/candidate fields are rejected."," builder-handoff fields: kind, summary, addressed_acceptance_ids, checks, known_limits."," dispatch-verifier fields: kind, checks (an explicitly resolved plan; [] is allowed)."," verifier-response fields: kind, response (request-checks or final-result)."," verifier-execution-error fields: kind, summary, stateVersion, iteration, attempt, verifierExecutionRef copied from verifierDispatch."," verifier-unavailable fields: kind, summary, stateVersion, iteration, attempt, verifierExecutionRef copied from verifierDispatch; accepted only after the explicit Runtime check plan completed and passed."],output:"The portable state, explicit skill-coordinated label, Runtime-owned check results, complete verifierDispatch, bounded request-check response, continuation.runnerAction, and machine-readable continuation.inputOptions. This generic bridge is not trusted identity attestation: a passing result waits for explicit user confirmation before Archive.",examples:['comet native next session-timeout --summary "Shape confirmed" --confirmed','comet native next session-timeout --summary "Current result accepted" --accept-result','comet native next session-timeout --summary "Implementation needs revision" --revise-implementation','comet native next session-timeout --summary "Acceptance criteria changed" --revise-requirements','comet native next session-timeout --summary "Retry verifier infrastructure" --retry-verifier','comet native next session-timeout --summary "Retry semantic verification" --resolve-verifier-blocker',"comet native next session-timeout --runner-input <temporary-json-file>"]},archive:{usage:`comet native archive <change-name> --dry-run [--finish merge|push|pull-request|keep]
|
|
152
152
|
comet native archive <change-name> [--confirmed] [--serial-first <current-change>]`,purpose:"Preview or execute deterministic Archive after the portable state reaches archive-ready.",options:["--dry-run Inspect readiness without rerunning verification.","--finish <action> Persist merge, push, pull-request, or keep for an isolated workspace.","--serial-first <current-change> During execution only, confirm that this change archives before detected capability peers; the value must equal <change-name>.","--confirmed Confirm Archive when project policy requires it."],output:"Readiness plus continuation, or the completed Archive transaction and workspace finish result; Archive does not repeat verification."},doctor:{usage:"comet native doctor [<change-name>] [--repair]",purpose:"Inspect portable state, migrate a legacy active change, or rebuild its local execution overlay.",options:["--repair Apply deterministic migration or rebuild from the portable stable boundary."],output:"Health, migration or recovery details, and the continuation with the next Runner action."}});function ds(t,e){return`${t}:
|
|
153
153
|
${e.map(i=>` ${i}`).join(`
|
|
154
|
-
`)}`}function
|
|
154
|
+
`)}`}function ON(t){let e=t.filter(r=>r!=="--help");if(e.length===0)return"";let i=e.slice(0,2).join(" ");return fs[i]||e.length>1&&fs[e[0]]?.subcommands?i:e[0]}function HN(t=[]){let e=ON(t),i=fs[e];if(!i)throw new Error(`Unknown Native help topic: ${e}`);let r=[`Usage: ${i.usage}`,"",i.purpose];i.subcommands&&r.push("",ds("Commands",i.subcommands));let n=e===""?i.options:[...i.options??[],...$d];return n&&n.length>0&&r.push("",ds("Options",n)),r.push("",`Output:
|
|
155
155
|
${i.output}`),i.examples&&r.push("",ds("Examples",i.examples)),e===""&&r.push("","Run `comet native <command> --help` for command-specific details."),{topic:e,usage:`${r.join(`
|
|
156
156
|
`)}
|
|
157
|
-
`}}var
|
|
158
|
-
`}}function Vd(t,e){if(e instanceof be)return{command:t,exitCode:64,error:{code:"usage",message:e.message}};if(e instanceof An)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 _n)return{command:t,exitCode:73,data:e.preflight,error:{code:"conflict",message:e.message}};if(e instanceof yn)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
|
|
159
|
-
`}:t.error?{exitCode:t.exitCode,stderr:t.error.message}:{exitCode:t.exitCode,stdout:t.text}}async function Wd(t,e){let i=In(t,"spec subcommand");if(i!=="remove")throw new be(`Unknown spec command: ${i}`);let r=In(t,"change name"),n=In(t,"capability");Ld(t);let{paths:a}=await Md(e);await
|
|
160
|
-
`)}function
|
|
161
|
-
`}}async function zd(t,e,i=process.argv.slice(2)){let r=i.indexOf("--"),n=r<0?[...i]:i.slice(0,r),a=r<0?[]:i.slice(r),o=n.includes("--json"),s,c;try{Hd(n,"--json"),s=Dd(n,"--project-root");let f=[...n,...a],d=await Bd(s);c=await e(f,d)}catch(f){c=Vd(t,f)}let l=o?
|
|
157
|
+
`}}var DN=HN().usage;var z$=10*1024*1024,be=class extends Error{};function Hd(t,e){let i=t.flatMap((r,n)=>r===e?[n]:[]);if(i.length>1)throw new be(`${e} may only be provided once`);return i.length===0?!1:(t.splice(i[0],1),!0)}function Dd(t,e){let i=t.flatMap((a,o)=>a===e?[o]:[]);if(i.length>1)throw new be(`${e} may only be provided once`);if(i.length===0)return;let r=i[0],n=t[r+1];if(n===void 0||n.startsWith("--"))throw new be(`${e} requires a value`);return t.splice(r,2),n}function Ld(t){if(t.length>0)throw new be(`Unexpected argument: ${t[0]}`)}function In(t,e){let i=t.shift();if(!i||i.startsWith("--"))throw new be(`${e} is required`);return i}function hs(t,e){let i=Hi.normalize(Od(t)),r=Hi.normalize(Od(e));return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function Od(t){let e=Hi.resolve(t);try{return LN.native(e)}catch{return e}}function BN(t){let e=Hi.resolve(t),i=ke(process.cwd());if(!i.isSecondaryWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null)return e;let r=ke(e);return!r.isGitWorktree||r.currentWorktreeRoot===null||r.primaryWorktreeRoot===null||!hs(i.primaryWorktreeRoot,r.primaryWorktreeRoot)||hs(i.currentWorktreeRoot,r.currentWorktreeRoot)?e:hs(process.cwd(),i.currentWorktreeRoot)?Hi.resolve(process.cwd()):i.currentWorktreeRoot}async function Bd(t){return t?BN(t):Xr(process.cwd())}async function Md(t){let e=await wu({startPath:t,allowMissingConfig:!1});return{config:e.config,paths:e.paths}}function Fd(t,e,i){return{command:t,exitCode:0,data:e,text:i??JSON.stringify(e,null,2)+`
|
|
158
|
+
`}}function Vd(t,e){if(e instanceof be)return{command:t,exitCode:64,error:{code:"usage",message:e.message}};if(e instanceof An)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 _n)return{command:t,exitCode:73,data:e.preflight,error:{code:"conflict",message:e.message}};if(e instanceof yn)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 Ri)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 Tn)return{command:t,exitCode:73,data:{preparation:e.preparation},error:{code:"workspace-preparation-incomplete",message:e.message}};if(e instanceof Nn)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 Rn)return{command:t,exitCode:65,data:{receiptBindingFailures:e.details},error:{code:"invalid-data",message:e.message}};if(e instanceof Oi)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 r=/\b(lock|transaction|conflict|occupied|incomplete|recovery)\b/iu.test(e.message);return{command:t,exitCode:r?73:65,error:{code:r?"conflict":"invalid-data",message:e.message}}}return{command:t,exitCode:70,error:{code:"internal",message:String(e)}}}function qd(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}})+`
|
|
159
|
+
`}:t.error?{exitCode:t.exitCode,stderr:t.error.message}:{exitCode:t.exitCode,stdout:t.text}}async function Wd(t,e){let i=In(t,"spec subcommand");if(i!=="remove")throw new be(`Unknown spec command: ${i}`);let r=In(t,"change name"),n=In(t,"capability");Ld(t);let{paths:a}=await Md(e);await ji(a,r)||await Pd({paths:a,name:r});let o=await gd({paths:a,name:r,capability:n});return Fd("spec remove",{...o,continuation:vs(o)},`Marked Native capability ${n} for removal in ${r}
|
|
160
|
+
`)}function MN(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}})+`
|
|
161
|
+
`}}async function zd(t,e,i=process.argv.slice(2)){let r=i.indexOf("--"),n=r<0?[...i]:i.slice(0,r),a=r<0?[]:i.slice(r),o=n.includes("--json"),s,c;try{Hd(n,"--json"),s=Dd(n,"--project-root");let f=[...n,...a],d=await Bd(s);c=await e(f,d)}catch(f){c=Vd(t,f)}let l=o?MN(c):qd(c,!1);return l.stdout&&process.stdout.write(l.stdout),l.stderr&&process.stderr.write(l.stderr+(l.stderr.endsWith(`
|
|
162
162
|
`)?"":`
|
|
163
163
|
`)),l.exitCode}process.exitCode=await zd("spec",Wd);
|