@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,39 +1,39 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __cometCreateRequire } from 'module';
|
|
3
3
|
const require = __cometCreateRequire(import.meta.url);
|
|
4
|
-
var Sh=Object.create;var kc=Object.defineProperty;var Eh=Object.getOwnPropertyDescriptor;var Ph=Object.getOwnPropertyNames;var xh=Object.getPrototypeOf,Rh=Object.prototype.hasOwnProperty;var
|
|
5
|
-
`)}};di.defaultYaml={explicit:!1,version:"1.2"};di.defaultTags={"!!":"tag:yaml.org,2002:"};Hc.Directives=di});var
|
|
4
|
+
var Sh=Object.create;var kc=Object.defineProperty;var Eh=Object.getOwnPropertyDescriptor;var Ph=Object.getOwnPropertyNames;var xh=Object.getPrototypeOf,Rh=Object.prototype.hasOwnProperty;var yr=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,i)=>(typeof require<"u"?require:t)[i]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var y=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(i){throw t=0,i}};var Ch=(e,t,i,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Ph(t))!Rh.call(e,n)&&n!==i&&kc(e,n,{get:()=>t[n],enumerable:!(r=Eh(t,n))||r.enumerable});return e};var ai=(e,t,i)=>(i=e!=null?Sh(xh(e)):{},Ch(t||!e||!e.__esModule?kc(i,"default",{value:e,enumerable:!0}):i,e));var P=y(M=>{"use strict";var Ea=Symbol.for("yaml.alias"),Rc=Symbol.for("yaml.document"),kr=Symbol.for("yaml.map"),Cc=Symbol.for("yaml.pair"),Pa=Symbol.for("yaml.scalar"),Sr=Symbol.for("yaml.seq"),je=Symbol.for("yaml.node.type"),Jh=e=>!!e&&typeof e=="object"&&e[je]===Ea,Gh=e=>!!e&&typeof e=="object"&&e[je]===Rc,Uh=e=>!!e&&typeof e=="object"&&e[je]===kr,Kh=e=>!!e&&typeof e=="object"&&e[je]===Cc,Ac=e=>!!e&&typeof e=="object"&&e[je]===Pa,Yh=e=>!!e&&typeof e=="object"&&e[je]===Sr;function _c(e){if(e&&typeof e=="object")switch(e[je]){case kr:case Sr:return!0}return!1}function Xh(e){if(e&&typeof e=="object")switch(e[je]){case Ea:case kr:case Pa:case Sr:return!0}return!1}var Qh=e=>(Ac(e)||_c(e))&&!!e.anchor;M.ALIAS=Ea;M.DOC=Rc;M.MAP=kr;M.NODE_TYPE=je;M.PAIR=Cc;M.SCALAR=Pa;M.SEQ=Sr;M.hasAnchor=Qh;M.isAlias=Jh;M.isCollection=_c;M.isDocument=Gh;M.isMap=Uh;M.isNode=Xh;M.isPair=Kh;M.isScalar=Ac;M.isSeq=Yh});var ui=y(xa=>{"use strict";var B=P(),Q=Symbol("break visit"),Tc=Symbol("skip children"),Ee=Symbol("remove node");function Er(e,t){let i=Ic(t);B.isDocument(e)?_t(null,e.contents,i,Object.freeze([e]))===Ee&&(e.contents=null):_t(null,e,i,Object.freeze([]))}Er.BREAK=Q;Er.SKIP=Tc;Er.REMOVE=Ee;function _t(e,t,i,r){let n=jc(e,t,i,r);if(B.isNode(n)||B.isPair(n))return $c(e,r,n),_t(e,n,i,r);if(typeof n!="symbol"){if(B.isCollection(t)){r=Object.freeze(r.concat(t));for(let a=0;a<t.items.length;++a){let o=_t(a,t.items[a],i,r);if(typeof o=="number")a=o-1;else{if(o===Q)return Q;o===Ee&&(t.items.splice(a,1),a-=1)}}}else if(B.isPair(t)){r=Object.freeze(r.concat(t));let a=_t("key",t.key,i,r);if(a===Q)return Q;a===Ee&&(t.key=null);let o=_t("value",t.value,i,r);if(o===Q)return Q;o===Ee&&(t.value=null)}}return n}async function Pr(e,t){let i=Ic(t);B.isDocument(e)?await Tt(null,e.contents,i,Object.freeze([e]))===Ee&&(e.contents=null):await Tt(null,e,i,Object.freeze([]))}Pr.BREAK=Q;Pr.SKIP=Tc;Pr.REMOVE=Ee;async function Tt(e,t,i,r){let n=await jc(e,t,i,r);if(B.isNode(n)||B.isPair(n))return $c(e,r,n),Tt(e,n,i,r);if(typeof n!="symbol"){if(B.isCollection(t)){r=Object.freeze(r.concat(t));for(let a=0;a<t.items.length;++a){let o=await Tt(a,t.items[a],i,r);if(typeof o=="number")a=o-1;else{if(o===Q)return Q;o===Ee&&(t.items.splice(a,1),a-=1)}}}else if(B.isPair(t)){r=Object.freeze(r.concat(t));let a=await Tt("key",t.key,i,r);if(a===Q)return Q;a===Ee&&(t.key=null);let o=await Tt("value",t.value,i,r);if(o===Q)return Q;o===Ee&&(t.value=null)}}return n}function Ic(e){return typeof e=="object"&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function jc(e,t,i,r){if(typeof i=="function")return i(e,t,r);if(B.isMap(t))return i.Map?.(e,t,r);if(B.isSeq(t))return i.Seq?.(e,t,r);if(B.isPair(t))return i.Pair?.(e,t,r);if(B.isScalar(t))return i.Scalar?.(e,t,r);if(B.isAlias(t))return i.Alias?.(e,t,r)}function $c(e,t,i){let r=t[t.length-1];if(B.isCollection(r))r.items[e]=i;else if(B.isPair(r))e==="key"?r.key=i:r.value=i;else if(B.isDocument(r))r.contents=i;else{let n=B.isAlias(r)?"alias":"scalar";throw new Error(`Cannot replace node with ${n} parent`)}}xa.visit=Er;xa.visitAsync=Pr});var Ra=y(Hc=>{"use strict";var Oc=P(),Zh=ui(),ep={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},tp=e=>e.replace(/[!,[\]{}]/g,t=>ep[t]),di=class e{constructor(t,i){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,i)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},e.defaultTags);break}return t}add(t,i){this.atNextDocument&&(this.yaml={explicit:e.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},e.defaultTags),this.atNextDocument=!1);let r=t.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(t,i){if(t==="!")return"!";if(t[0]!=="!")return i(`Not a valid tag: ${t}`),null;if(t[1]==="<"){let o=t.slice(2,-1);return o==="!"||o==="!!"?(i(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&i("Verbatim tags must end with a >"),o)}let[,r,n]=t.match(/^(.*!)([^!]*)$/s);n||i(`The ${t} 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==="!"?t:(i(`Could not resolve tag: ${t}`),null)}tagString(t){for(let[i,r]of Object.entries(this.tags))if(t.startsWith(r))return i+tp(t.substring(r.length));return t[0]==="!"?t:`!<${t}>`}toString(t){let i=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],r=Object.entries(this.tags),n;if(t&&r.length>0&&Oc.isNode(t.contents)){let a={};Zh.visit(t.contents,(o,s)=>{Oc.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:"||(!t||n.some(s=>s.startsWith(o)))&&i.push(`%TAG ${a} ${o}`);return i.join(`
|
|
5
|
+
`)}};di.defaultYaml={explicit:!1,version:"1.2"};di.defaultTags={"!!":"tag:yaml.org,2002:"};Hc.Directives=di});var xr=y(fi=>{"use strict";var Dc=P(),ip=ui();function rp(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let i=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw new Error(i)}return!0}function Bc(e){let t=new Set;return ip.visit(e,{Value(i,r){r.anchor&&t.add(r.anchor)}}),t}function Lc(e,t){for(let i=1;;++i){let r=`${e}${i}`;if(!t.has(r))return r}}function np(e,t){let i=[],r=new Map,n=null;return{onAnchor:a=>{i.push(a),n??(n=Bc(e));let o=Lc(t,n);return n.add(o),o},setAnchors:()=>{for(let a of i){let o=r.get(a);if(typeof o=="object"&&o.anchor&&(Dc.isScalar(o.node)||Dc.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}}fi.anchorIsValid=rp;fi.anchorNames=Bc;fi.createNodeAnchors=np;fi.findNewAnchor=Lc});var Ca=y(qc=>{"use strict";function hi(e,t,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=hi(e,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=hi(e,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=hi(e,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=hi(e,r,n,a);o===void 0?delete r[n]:o!==a&&(r[n]=o)}return e.call(t,i,r)}qc.applyReviver=hi});var ze=y(Mc=>{"use strict";var ap=P();function Fc(e,t,i){if(Array.isArray(e))return e.map((r,n)=>Fc(r,String(n),i));if(e&&typeof e.toJSON=="function"){if(!i||!ap.hasAnchor(e))return e.toJSON(t,i);let r={aliasCount:0,count:1,res:void 0};i.anchors.set(e,r),i.onCreate=a=>{r.res=a,delete i.onCreate};let n=e.toJSON(t,i);return i.onCreate&&i.onCreate(n),n}return typeof e=="bigint"&&!i?.keep?Number(e):e}Mc.toJS=Fc});var Rr=y(Wc=>{"use strict";var op=Ca(),Vc=P(),sp=ze(),Aa=class{constructor(t){Object.defineProperty(this,Vc.NODE_TYPE,{value:t})}clone(){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(t.range=this.range.slice()),t}toJS(t,{mapAsMap:i,maxAliasCount:r,onAnchor:n,reviver:a}={}){if(!Vc.isDocument(t))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:t,keep:!0,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},s=sp.toJS(this,"",o);if(typeof n=="function")for(let{count:c,res:l}of o.anchors.values())n(l,c);return typeof a=="function"?op.applyReviver(a,{"":s},"",s):s}};Wc.NodeBase=Aa});var pi=y(zc=>{"use strict";var cp=xr(),lp=ui(),It=P(),up=Rr(),dp=ze(),_a=class extends up.NodeBase{constructor(t){super(It.ALIAS),this.source=t,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(t,i){if(i?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let r;i?.aliasResolveCache?r=i.aliasResolveCache:(r=[],lp.visit(t,{Node:(a,o)=>{(It.isAlias(o)||It.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(t,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||(dp.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=Cr(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(t,i,r){let n=`*${this.source}`;if(t){if(cp.anchorIsValid(this.source),t.options.verifyAliasOrder&&!t.anchors.has(this.source)){let a=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(a)}if(t.implicitKey)return`${n} `}return n}};function Cr(e,t,i){if(It.isAlias(t)){let r=t.resolve(e),n=i&&r&&i.get(r);return n?n.count*n.aliasCount:0}else if(It.isCollection(t)){let r=0;for(let n of t.items){let a=Cr(e,n,i);a>r&&(r=a)}return r}else if(It.isPair(t)){let r=Cr(e,t.key,i),n=Cr(e,t.value,i);return Math.max(r,n)}return 1}zc.Alias=_a});var $=y(Ta=>{"use strict";var fp=P(),hp=Rr(),pp=ze(),mp=e=>!e||typeof e!="function"&&typeof e!="object",Je=class extends hp.NodeBase{constructor(t){super(fp.SCALAR),this.value=t}toJSON(t,i){return i?.keep?this.value:pp.toJS(this.value,t,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";Ta.Scalar=Je;Ta.isScalarValue=mp});var mi=y(Gc=>{"use strict";var vp=pi(),ut=P(),Jc=$(),gp="tag:yaml.org,2002:";function wp(e,t,i){if(t){let r=i.filter(a=>a.tag===t),n=r.find(a=>!a.format)??r[0];if(!n)throw new Error(`Tag ${t} not found`);return n}return i.find(r=>r.identify?.(e)&&!r.format)}function yp(e,t,i){if(ut.isDocument(e)&&(e=e.contents),ut.isNode(e))return e;if(ut.isPair(e)){let f=i.schema[ut.MAP].createNode?.(i.schema,null,i);return f.items.push(e),f}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:r,onAnchor:n,onTagObj:a,schema:o,sourceObjects:s}=i,c;if(r&&e&&typeof e=="object"){if(c=s.get(e),c)return c.anchor??(c.anchor=n(e)),new vp.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=gp+t.slice(2));let l=wp(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let f=new Jc.Scalar(e);return c&&(c.node=f),f}l=e instanceof Map?o[ut.MAP]:Symbol.iterator in Object(e)?o[ut.SEQ]:o[ut.MAP]}a&&(a(l),delete i.onTagObj);let u=l?.createNode?l.createNode(i.schema,e,i):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(i.schema,e,i):new Jc.Scalar(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}Gc.createNode=yp});var _r=y(Ar=>{"use strict";var Np=mi(),Pe=P(),bp=Rr();function Ia(e,t,i){let r=i;for(let n=t.length-1;n>=0;--n){let a=t[n];if(typeof a=="number"&&Number.isInteger(a)&&a>=0){let o=[];o[a]=r,r=o}else r=new Map([[a,r]])}return Np.createNode(r,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}var Uc=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,ja=class extends bp.NodeBase{constructor(t,i){super(t),Object.defineProperty(this,"schema",{value:i,configurable:!0,enumerable:!1,writable:!0})}clone(t){let i=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return t&&(i.schema=t),i.items=i.items.map(r=>Pe.isNode(r)||Pe.isPair(r)?r.clone(t):r),this.range&&(i.range=this.range.slice()),i}addIn(t,i){if(Uc(t))this.add(i);else{let[r,...n]=t,a=this.get(r,!0);if(Pe.isCollection(a))a.addIn(n,i);else if(a===void 0&&this.schema)this.set(r,Ia(this.schema,n,i));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}}deleteIn(t){let[i,...r]=t;if(r.length===0)return this.delete(i);let n=this.get(i,!0);if(Pe.isCollection(n))return n.deleteIn(r);throw new Error(`Expected YAML collection at ${i}. Remaining path: ${r}`)}getIn(t,i){let[r,...n]=t,a=this.get(r,!0);return n.length===0?!i&&Pe.isScalar(a)?a.value:a:Pe.isCollection(a)?a.getIn(n,i):void 0}hasAllNullValues(t){return this.items.every(i=>{if(!Pe.isPair(i))return!1;let r=i.value;return r==null||t&&Pe.isScalar(r)&&r.value==null&&!r.commentBefore&&!r.comment&&!r.tag})}hasIn(t){let[i,...r]=t;if(r.length===0)return this.has(i);let n=this.get(i,!0);return Pe.isCollection(n)?n.hasIn(r):!1}setIn(t,i){let[r,...n]=t;if(n.length===0)this.set(r,i);else{let a=this.get(r,!0);if(Pe.isCollection(a))a.setIn(n,i);else if(a===void 0&&this.schema)this.set(r,Ia(this.schema,n,i));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}}};Ar.Collection=ja;Ar.collectionFromPath=Ia;Ar.isEmptyPath=Uc});var vi=y(Tr=>{"use strict";var kp=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function $a(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var Sp=(e,t,i)=>e.endsWith(`
|
|
6
6
|
`)?$a(i,t):i.includes(`
|
|
7
7
|
`)?`
|
|
8
|
-
`+$a(i,t):(e.endsWith(" ")?"":" ")+i;
|
|
8
|
+
`+$a(i,t):(e.endsWith(" ")?"":" ")+i;Tr.indentComment=$a;Tr.lineComment=Sp;Tr.stringifyComment=kp});var Yc=y(gi=>{"use strict";var Ep="flow",Oa="block",Ir="quoted";function Pp(e,t,i="flow",{indentAtStart:r,lineWidth:n=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!n||n<0)return e;n<a&&(a=0);let c=Math.max(1+a,1+n-t.length);if(e.length<=c)return e;let l=[],u={},f=n-t.length;typeof r=="number"&&(r>n-Math.max(2,a)?l.push(0):f=n-r);let d,p,v=!1,h=-1,m=-1,g=-1;i===Oa&&(h=Kc(e,h,t.length),h!==-1&&(f=h+c));for(let w;w=e[h+=1];){if(i===Ir&&w==="\\"){switch(m=h,e[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}g=h}if(w===`
|
|
9
9
|
`)i===Oa&&(h=Kc(e,h,t.length)),f=h+t.length+c,d=void 0;else{if(w===" "&&p&&p!==" "&&p!==`
|
|
10
10
|
`&&p!==" "){let k=e[h+1];k&&k!==" "&&k!==`
|
|
11
|
-
`&&k!==" "&&(d=h)}if(h>=f)if(d)l.push(d),f=d+c,d=void 0;else if(i===
|
|
12
|
-
${t}${e.slice(0,S)}`:(i===
|
|
11
|
+
`&&k!==" "&&(d=h)}if(h>=f)if(d)l.push(d),f=d+c,d=void 0;else if(i===Ir){for(;p===" "||p===" ";)p=w,w=e[h+=1],v=!0;let k=h>g+1?h-2:m-1;if(u[k])return e;l.push(k),u[k]=!0,f=k+c,d=void 0}else v=!0}p=w}if(v&&s&&s(),l.length===0)return e;o&&o();let N=e.slice(0,l[0]);for(let w=0;w<l.length;++w){let k=l[w],S=l[w+1]||e.length;k===0?N=`
|
|
12
|
+
${t}${e.slice(0,S)}`:(i===Ir&&u[k]&&(N+=`${e[k]}\\`),N+=`
|
|
13
13
|
${t}${e.slice(k+1,S)}`)}return N}function Kc(e,t,i){let r=t,n=t+1,a=e[n];for(;a===" "||a===" ";)if(t<n+i)a=e[++t];else{do a=e[++t];while(a&&a!==`
|
|
14
|
-
`);r=t,n=t+1,a=e[n]}return r}gi.FOLD_BLOCK=Oa;gi.FOLD_FLOW=Ep;gi.FOLD_QUOTED=
|
|
15
|
-
`){if(a-o>r)return!0;if(o=a+1,n-o<=r)return!1}return!0}function wi(e,t){let i=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return i;let{implicitKey:r}=t,n=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(
|
|
14
|
+
`);r=t,n=t+1,a=e[n]}return r}gi.FOLD_BLOCK=Oa;gi.FOLD_FLOW=Ep;gi.FOLD_QUOTED=Ir;gi.foldFlowLines=Pp});var yi=y(Xc=>{"use strict";var me=$(),Ge=Yc(),$r=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),Or=e=>/^(%|---|\.\.\.)/m.test(e);function xp(e,t,i){if(!t||t<0)return!1;let r=t-i,n=e.length;if(n<=r)return!1;for(let a=0,o=0;a<n;++a)if(e[a]===`
|
|
15
|
+
`){if(a-o>r)return!0;if(o=a+1,n-o<=r)return!1}return!0}function wi(e,t){let i=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return i;let{implicitKey:r}=t,n=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(Or(e)?" ":""),o="",s=0;for(let c=0,l=i[c];l;l=i[++c])if(l===" "&&i[c+1]==="\\"&&i[c+2]==="n"&&(o+=i.slice(s,c)+"\\ ",c+=1,s=c,l="\\"),l==="\\")switch(i[c+1]){case"u":{o+=i.slice(s,c);let u=i.substr(c+2,4);switch(u){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:u.substr(0,2)==="00"?o+="\\x"+u.substr(2):o+=i.substr(c,6)}c+=5,s=c+1}break;case"n":if(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
|
-
`,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:Ge.foldFlowLines(o,a,Ge.FOLD_QUOTED
|
|
19
|
-
`)||/[ \t]\n|\n[ \t]/.test(e))return wi(e,t);let i=t.indent||(
|
|
20
|
-
${i}`)+"'";return t.implicitKey?r:Ge.foldFlowLines(r,i,Ge.FOLD_FLOW
|
|
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:Ge.foldFlowLines(o,a,Ge.FOLD_QUOTED,$r(t,!1))}function Ha(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
|
|
19
|
+
`)||/[ \t]\n|\n[ \t]/.test(e))return wi(e,t);let i=t.indent||(Or(e)?" ":""),r="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
|
|
20
|
+
${i}`)+"'";return t.implicitKey?r:Ge.foldFlowLines(r,i,Ge.FOLD_FLOW,$r(t,!1))}function jt(e,t){let{singleQuote:i}=t.options,r;if(i===!1)r=wi;else{let n=e.includes('"'),a=e.includes("'");n&&!a?r=Ha:a&&!n?r=wi:r=i?Ha:wi}return r(e,t)}var Da;try{Da=new RegExp(`(^|(?<!
|
|
21
21
|
))
|
|
22
22
|
+(?!
|
|
23
|
-
|$)`,"g")}catch{Da=/\n+(?!\n|$)/g}function
|
|
23
|
+
|$)`,"g")}catch{Da=/\n+(?!\n|$)/g}function jr({comment:e,type:t,value:i},r,n,a){let{blockQuote:o,commentString:s,lineWidth:c}=r.options;if(!o||/\n[\t ]+$/.test(i))return jt(i,r);let l=r.indent||(r.forceBlockIndent||Or(i)?" ":""),u=o==="literal"?!0:o==="folded"||t===me.Scalar.BLOCK_FOLDED?!1:t===me.Scalar.BLOCK_LITERAL?!0:!xp(i,c,l.length);if(!i)return u?`|
|
|
24
24
|
`:`>
|
|
25
25
|
`;let f,d;for(d=i.length;d>0;--d){let S=i[d-1];if(S!==`
|
|
26
26
|
`&&S!==" "&&S!==" ")break}let p=i.substring(d),v=p.indexOf(`
|
|
27
27
|
`);v===-1?f="-":i===p||v!==p.length-1?(f="+",a&&a()):f="",p&&(i=i.slice(0,-p.length),p[p.length-1]===`
|
|
28
28
|
`&&(p=p.slice(0,-1)),p=p.replace(Da,`$&${l}`));let h=!1,m,g=-1;for(m=0;m<i.length;++m){let S=i[m];if(S===" ")h=!0;else if(S===`
|
|
29
29
|
`)g=m;else break}let N=i.substring(0,g<m?g+1:m);N&&(i=i.substring(N.length),N=N.replace(/\n+/g,`$&${l}`));let k=(h?l?"2":"1":"")+f;if(e&&(k+=" "+s(e.replace(/ ?[\r\n]+/g," ")),n&&n()),!u){let S=i.replace(/\n+/g,`
|
|
30
|
-
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),E=!1,C
|
|
30
|
+
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),E=!1,C=$r(r,!0);o!=="folded"&&t!==me.Scalar.BLOCK_FOLDED&&(C.onOverflow=()=>{E=!0});let b=Ge.foldFlowLines(`${N}${S}${p}`,l,Ge.FOLD_BLOCK,C);if(!E)return`>${k}
|
|
31
31
|
${l}${b}`}return i=i.replace(/\n+/g,`$&${l}`),`|${k}
|
|
32
32
|
${l}${N}${i}${p}`}function Rp(e,t,i,r){let{type:n,value:a}=e,{actualString:o,implicitKey:s,indent:c,indentStep:l,inFlow:u}=t;if(s&&a.includes(`
|
|
33
33
|
`)||u&&/[[\]{},]/.test(a))return jt(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||u||!a.includes(`
|
|
34
|
-
`)?jt(a,t):
|
|
35
|
-
`))return
|
|
36
|
-
${c}`);if(o){let d=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(f),{compat:p,tags:v}=t.doc.schema;if(v.some(d)||p?.some(d))return jt(a,t)}return s?f:Ge.foldFlowLines(f,c,Ge.FOLD_FLOW
|
|
34
|
+
`)?jt(a,t):jr(e,t,i,r);if(!s&&!u&&n!==me.Scalar.PLAIN&&a.includes(`
|
|
35
|
+
`))return jr(e,t,i,r);if(Or(a)){if(c==="")return t.forceBlockIndent=!0,jr(e,t,i,r);if(s&&c===l)return jt(a,t)}let f=a.replace(/\n+/g,`$&
|
|
36
|
+
${c}`);if(o){let d=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(f),{compat:p,tags:v}=t.doc.schema;if(v.some(d)||p?.some(d))return jt(a,t)}return s?f:Ge.foldFlowLines(f,c,Ge.FOLD_FLOW,$r(t,!1))}function Cp(e,t,i,r){let{implicitKey:n,inFlow:a}=t,o=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)}),{type:s}=e;s!==me.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=me.Scalar.QUOTE_DOUBLE);let c=u=>{switch(u){case me.Scalar.BLOCK_FOLDED:case me.Scalar.BLOCK_LITERAL:return n||a?jt(o.value,t):jr(o,t,i,r);case me.Scalar.QUOTE_DOUBLE:return wi(o.value,t);case me.Scalar.QUOTE_SINGLE:return Ha(o.value,t);case me.Scalar.PLAIN:return Rp(o,t,i,r);default:return null}},l=c(s);if(l===null){let{defaultKeyType:u,defaultStringType:f}=t.options,d=n&&u||f;if(l=c(d),l===null)throw new Error(`Unsupported default string type ${d}`)}return l}Xc.stringifyString=Cp});var Ni=y(Ba=>{"use strict";var Ap=xr(),Ue=P(),_p=vi(),Tp=yi();function Ip(e,t){let i=Object.assign({blockQuote:!0,commentString:_p.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},e.schema.toStringOptions,t),r;switch(i.collectionStyle){case"block":r=!1;break;case"flow":r=!0;break;default:r=null}return{anchors:new Set,doc:e,flowCollectionPadding:i.flowCollectionPadding?" ":"",indent:"",indentStep:typeof i.indent=="number"?" ".repeat(i.indent):" ",inFlow:r,options:i}}function jp(e,t){if(t.tag){let n=e.filter(a=>a.tag===t.tag);if(n.length>0)return n.find(a=>a.format===t.format)??n[0]}let i,r;if(Ue.isScalar(t)){r=t.value;let n=e.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===t.format)??n.find(a=>!a.format)}else r=t,i=e.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 $p(e,t,{anchors:i,doc:r}){if(!r.directives)return"";let n=[],a=(Ue.isScalar(e)||Ue.isCollection(e))&&e.anchor;a&&Ap.anchorIsValid(a)&&(i.add(a),n.push(`&${a}`));let o=e.tag??(t.default?null:t.tag);return o&&n.push(r.directives.tagString(o)),n.join(" ")}function Op(e,t,i,r){if(Ue.isPair(e))return e.toString(t,i,r);if(Ue.isAlias(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw new TypeError("Cannot stringify circular structure without alias nodes");t.resolvedAliases?t.resolvedAliases.add(e):t.resolvedAliases=new Set([e]),e=e.resolve(t.doc)}let n,a=Ue.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>n=c});n??(n=jp(t.doc.schema.tags,a));let o=$p(a,n,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);let s=typeof n.stringify=="function"?n.stringify(a,t,i,r):Ue.isScalar(a)?Tp.stringifyString(a,t,i,r):a.toString(t,i,r);return o?Ue.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
|
|
37
37
|
${t.indent}${s}`:s}Ba.createStringifyContext=Ip;Ba.stringify=Op});var tl=y(el=>{"use strict";var $e=P(),Qc=$(),Zc=Ni(),bi=vi();function Hp({key:e,value:t},i,r,n){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:f}}=i,d=$e.isNode(e)&&e.comment||null;if(f){if(d)throw new Error("With simple keys, key nodes cannot have comments");if($e.isCollection(e)||!$e.isNode(e)&&typeof e=="object"){let C="With simple keys, collection cannot be used as a key value";throw new Error(C)}}let p=!f&&(!e||d&&t==null&&!i.inFlow||$e.isCollection(e)||($e.isScalar(e)?e.type===Qc.Scalar.BLOCK_FOLDED||e.type===Qc.Scalar.BLOCK_LITERAL:typeof e=="object"));i=Object.assign({},i,{allNullValues:!1,implicitKey:!p&&(f||!a),indent:s+c});let v=!1,h=!1,m=Zc.stringify(e,i,()=>v=!0,()=>h=!0);if(!p&&!i.inFlow&&m.length>1024){if(f)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");p=!0}if(i.inFlow){if(a||t==null)return v&&r&&r(),m===""?"?":p?`? ${m}`:m}else if(a&&!f||t==null&&p)return m=`? ${m}`,d&&!v?m+=bi.lineComment(m,i.indent,l(d)):h&&n&&n(),m;v&&(d=null),p?(d&&(m+=bi.lineComment(m,i.indent,l(d))),m=`? ${m}
|
|
38
38
|
${s}:`):(m=`${m}:`,d&&(m+=bi.lineComment(m,i.indent,l(d))));let g,N,w;$e.isNode(t)?(g=!!t.spaceBefore,N=t.commentBefore,w=t.comment):(g=!1,N=null,w=null,t&&typeof t=="object"&&(t=o.createNode(t))),i.implicitKey=!1,!p&&!d&&$e.isScalar(t)&&(i.indentAtStart=m.length+1),h=!1,!u&&c.length>=2&&!i.inFlow&&!p&&$e.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(i.indent=i.indent.substring(2));let k=!1,S=Zc.stringify(t,i,()=>k=!0,()=>h=!0),E=" ";if(d||g||N){if(E=g?`
|
|
39
39
|
`:"",N){let C=l(N);E+=`
|
|
@@ -44,28 +44,28 @@ ${bi.indentComment(C,i.indent)}`}S===""&&!i.inFlow?E===`
|
|
|
44
44
|
${i.indent}`}else if(!p&&$e.isCollection(t)){let C=S[0],b=S.indexOf(`
|
|
45
45
|
`),H=b!==-1,Ve=i.inFlow??t.flow??t.items.length===0;if(H||!Ve){let At=!1;if(H&&(C==="&"||C==="!")){let D=S.indexOf(" ");C==="&"&&D!==-1&&D<b&&S[D+1]==="!"&&(D=S.indexOf(" ",D+1)),(D===-1||b<D)&&(At=!0)}At||(E=`
|
|
46
46
|
${i.indent}`)}}else(S===""||S[0]===`
|
|
47
|
-
`)&&(E="");return m+=E+S,i.inFlow?k&&r&&r():w&&!k?m+=bi.lineComment(m,i.indent,l(w)):h&&n&&n(),m}el.stringifyPair=Hp});var qa=y(La=>{"use strict";var il=
|
|
47
|
+
`)&&(E="");return m+=E+S,i.inFlow?k&&r&&r():w&&!k?m+=bi.lineComment(m,i.indent,l(w)):h&&n&&n(),m}el.stringifyPair=Hp});var qa=y(La=>{"use strict";var il=yr("process");function Dp(e,...t){e==="debug"&&console.log(...t)}function Bp(e,t){(e==="debug"||e==="warn")&&(typeof il.emitWarning=="function"?il.emitWarning(t):console.warn(t))}La.debug=Dp;La.warn=Bp});var qr=y(Lr=>{"use strict";var Br=P(),rl=$(),Hr="<<",Dr={identify:e=>e===Hr||typeof e=="symbol"&&e.description===Hr,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new rl.Scalar(Symbol(Hr)),{addToJSMap:nl}),stringify:()=>Hr},Lp=(e,t)=>(Dr.identify(t)||Br.isScalar(t)&&(!t.type||t.type===rl.Scalar.PLAIN)&&Dr.identify(t.value))&&e?.doc.schema.tags.some(i=>i.tag===Dr.tag&&i.default);function nl(e,t,i){let r=al(e,i);if(Br.isSeq(r))for(let n of r.items)Fa(e,t,n);else if(Array.isArray(r))for(let n of r)Fa(e,t,n);else Fa(e,t,r)}function Fa(e,t,i){let r=al(e,i);if(!Br.isMap(r))throw new Error("Merge sources must be maps or map aliases");let n=r.toJSON(null,e,Map);for(let[a,o]of n)t instanceof Map?t.has(a)||t.set(a,o):t instanceof Set?t.add(a):Object.prototype.hasOwnProperty.call(t,a)||Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0});return t}function al(e,t){return e&&Br.isAlias(t)?t.resolve(e.doc,e):t}Lr.addMergeToJSMap=nl;Lr.isMergeKey=Lp;Lr.merge=Dr});var Va=y(cl=>{"use strict";var qp=qa(),ol=qr(),Fp=Ni(),sl=P(),Ma=ze();function Mp(e,t,{key:i,value:r}){if(sl.isNode(i)&&i.addToJSMap)i.addToJSMap(e,t,r);else if(ol.isMergeKey(e,i))ol.addMergeToJSMap(e,t,r);else{let n=Ma.toJS(i,"",e);if(t instanceof Map)t.set(n,Ma.toJS(r,n,e));else if(t instanceof Set)t.add(n);else{let a=Vp(i,n,e),o=Ma.toJS(r,a,e);a in t?Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[a]=o}}return t}function Vp(e,t,i){if(t===null)return"";if(typeof t!="object")return String(t);if(sl.isNode(e)&&i?.doc){let r=Fp.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=e.toString(r);if(!i.mapKeyWarned){let a=JSON.stringify(n);a.length>40&&(a=a.substring(0,36)+'..."'),qp.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(t)}cl.addPairToJSMap=Mp});var Ke=y(Wa=>{"use strict";var ll=mi(),Wp=tl(),zp=Va(),Fr=P();function Jp(e,t,i){let r=ll.createNode(e,void 0,i),n=ll.createNode(t,void 0,i);return new Mr(r,n)}var Mr=class e{constructor(t,i=null){Object.defineProperty(this,Fr.NODE_TYPE,{value:Fr.PAIR}),this.key=t,this.value=i}clone(t){let{key:i,value:r}=this;return Fr.isNode(i)&&(i=i.clone(t)),Fr.isNode(r)&&(r=r.clone(t)),new e(i,r)}toJSON(t,i){let r=i?.mapAsMap?new Map:{};return zp.addPairToJSMap(i,r,this)}toString(t,i,r){return t?.doc?Wp.stringifyPair(this,t,i,r):JSON.stringify(this)}};Wa.Pair=Mr;Wa.createPair=Jp});var za=y(dl=>{"use strict";var dt=P(),ul=Ni(),Vr=vi();function Gp(e,t,i){return(t.inFlow??e.flow?Kp:Up)(e,t,i)}function Up({comment:e,items:t},i,{blockItemPrefix:r,flowChars:n,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=i,u=Object.assign({},i,{indent:a,type:null}),f=!1,d=[];for(let v=0;v<t.length;++v){let h=t[v],m=null;if(dt.isNode(h))!f&&h.spaceBefore&&d.push(""),Wr(i,d,h.commentBefore,f),h.comment&&(m=h.comment);else if(dt.isPair(h)){let N=dt.isNode(h.key)?h.key:null;N&&(!f&&N.spaceBefore&&d.push(""),Wr(i,d,N.commentBefore,f))}f=!1;let g=ul.stringify(h,u,()=>m=null,()=>f=!0);m&&(g+=Vr.lineComment(g,a,l(m))),f&&m&&(f=!1),d.push(r+g)}let p;if(d.length===0)p=n.start+n.end;else{p=d[0];for(let v=1;v<d.length;++v){let h=d[v];p+=h?`
|
|
48
48
|
${c}${h}`:`
|
|
49
49
|
`}}return e?(p+=`
|
|
50
|
-
`+
|
|
51
|
-
`)),v<e.length-1?g+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(l||(l=f.reduce((N,w)=>N+w.length+2,2)+(g.length+2)>t.options.lineWidth)),l&&(g+=",")),m&&(g+=
|
|
50
|
+
`+Vr.indentComment(l(e),c),s&&s()):f&&o&&o(),p}function Kp({items:e},t,{flowChars:i,itemIndent:r}){let{indent:n,indentStep:a,flowCollectionPadding:o,options:{commentString:s}}=t;r+=a;let c=Object.assign({},t,{indent:r,inFlow:!0,type:null}),l=!1,u=0,f=[];for(let v=0;v<e.length;++v){let h=e[v],m=null;if(dt.isNode(h))h.spaceBefore&&f.push(""),Wr(t,f,h.commentBefore,!1),h.comment&&(m=h.comment);else if(dt.isPair(h)){let N=dt.isNode(h.key)?h.key:null;N&&(N.spaceBefore&&f.push(""),Wr(t,f,N.commentBefore,!1),N.comment&&(l=!0));let w=dt.isNode(h.value)?h.value:null;w?(w.comment&&(m=w.comment),w.commentBefore&&(l=!0)):h.value==null&&N?.comment&&(m=N.comment)}m&&(l=!0);let g=ul.stringify(h,c,()=>m=null);l||(l=f.length>u||g.includes(`
|
|
51
|
+
`)),v<e.length-1?g+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(l||(l=f.reduce((N,w)=>N+w.length+2,2)+(g.length+2)>t.options.lineWidth)),l&&(g+=",")),m&&(g+=Vr.lineComment(g,r,s(m))),f.push(g),u=f.length}let{start:d,end:p}=i;if(f.length===0)return d+p;if(!l){let v=f.reduce((h,m)=>h+m.length+2,2);l=t.options.lineWidth>0&&v>t.options.lineWidth}if(l){let v=d;for(let h of f)v+=h?`
|
|
52
52
|
${a}${n}${h}`:`
|
|
53
53
|
`;return`${v}
|
|
54
|
-
${n}${p}`}else return`${d}${o}${f.join(" ")}${o}${p}`}function
|
|
55
|
-
`:" ")}return Im.stringifyString({comment:e,type:t,value:s},r,n,a)}};Tl.binary=jm});var
|
|
54
|
+
${n}${p}`}else return`${d}${o}${f.join(" ")}${o}${p}`}function Wr({indent:e,options:{commentString:t}},i,r,n){if(r&&n&&(r=r.replace(/^\n+/,"")),r){let a=Vr.indentComment(t(r),e);i.push(a.trimStart())}}dl.stringifyCollection=Gp});var Xe=y(Ga=>{"use strict";var Yp=za(),Xp=Va(),Qp=_r(),Ye=P(),zr=Ke(),Zp=$();function ki(e,t){let i=Ye.isScalar(t)?t.value:t;for(let r of e)if(Ye.isPair(r)&&(r.key===t||r.key===i||Ye.isScalar(r.key)&&r.key.value===i))return r}var Ja=class extends Qp.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(Ye.MAP,t),this.items=[]}static from(t,i,r){let{keepUndefined:n,replacer:a}=r,o=new this(t),s=(c,l)=>{if(typeof a=="function")l=a.call(i,c,l);else if(Array.isArray(a)&&!a.includes(c))return;(l!==void 0||n)&&o.items.push(zr.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 t.sortMapEntries=="function"&&o.items.sort(t.sortMapEntries),o}add(t,i){let r;Ye.isPair(t)?r=t:!t||typeof t!="object"||!("key"in t)?r=new zr.Pair(t,t?.value):r=new zr.Pair(t.key,t.value);let n=ki(this.items,r.key),a=this.schema?.sortMapEntries;if(n){if(!i)throw new Error(`Key ${r.key} already set`);Ye.isScalar(n.value)&&Zp.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(t){let i=ki(this.items,t);return i?this.items.splice(this.items.indexOf(i),1).length>0:!1}get(t,i){let n=ki(this.items,t)?.value;return(!i&&Ye.isScalar(n)?n.value:n)??void 0}has(t){return!!ki(this.items,t)}set(t,i){this.add(new zr.Pair(t,i),!0)}toJSON(t,i,r){let n=r?new r:i?.mapAsMap?new Map:{};i?.onCreate&&i.onCreate(n);for(let a of this.items)Xp.addPairToJSMap(i,n,a);return n}toString(t,i,r){if(!t)return JSON.stringify(this);for(let n of this.items)if(!Ye.isPair(n))throw new Error(`Map items must all be pairs; found ${JSON.stringify(n)} instead`);return!t.allNullValues&&this.hasAllNullValues(!1)&&(t=Object.assign({},t,{allNullValues:!0})),Yp.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:r,onComment:i})}};Ga.YAMLMap=Ja;Ga.findPair=ki});var $t=y(hl=>{"use strict";var em=P(),fl=Xe(),tm={collection:"map",default:!0,nodeClass:fl.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return em.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,i)=>fl.YAMLMap.from(e,t,i)};hl.map=tm});var Qe=y(pl=>{"use strict";var im=mi(),rm=za(),nm=_r(),Gr=P(),am=$(),om=ze(),Ua=class extends nm.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(Gr.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let i=Jr(t);return typeof i!="number"?!1:this.items.splice(i,1).length>0}get(t,i){let r=Jr(t);if(typeof r!="number")return;let n=this.items[r];return!i&&Gr.isScalar(n)?n.value:n}has(t){let i=Jr(t);return typeof i=="number"&&i<this.items.length}set(t,i){let r=Jr(t);if(typeof r!="number")throw new Error(`Expected a valid index, not ${t}.`);let n=this.items[r];Gr.isScalar(n)&&am.isScalarValue(i)?n.value=i:this.items[r]=i}toJSON(t,i){let r=[];i?.onCreate&&i.onCreate(r);let n=0;for(let a of this.items)r.push(om.toJS(a,String(n++),i));return r}toString(t,i,r){return t?rm.stringifyCollection(this,t,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(t.indent||"")+" ",onChompKeep:r,onComment:i}):JSON.stringify(this)}static from(t,i,r){let{replacer:n}=r,a=new this(t);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(im.createNode(s,void 0,r))}}return a}};function Jr(e){let t=Gr.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}pl.YAMLSeq=Ua});var Ot=y(vl=>{"use strict";var sm=P(),ml=Qe(),cm={collection:"seq",default:!0,nodeClass:ml.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return sm.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,i)=>ml.YAMLSeq.from(e,t,i)};vl.seq=cm});var Si=y(gl=>{"use strict";var lm=yi(),um={identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify(e,t,i,r){return t=Object.assign({actualString:!0},t),lm.stringifyString(e,t,i,r)}};gl.string=um});var Ur=y(Nl=>{"use strict";var wl=$(),yl={identify:e=>e==null,createNode:()=>new wl.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new wl.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&yl.test.test(e)?e:t.options.nullStr};Nl.nullTag=yl});var Ka=y(kl=>{"use strict";var dm=$(),bl={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new dm.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},i){if(e&&bl.test.test(e)){let r=e[0]==="t"||e[0]==="T";if(t===r)return e}return t?i.options.trueStr:i.options.falseStr}};kl.boolTag=bl});var Ht=y(Sl=>{"use strict";function fm({format:e,minFractionDigits:t,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(!e&&t&&(!i||i==="tag:yaml.org,2002:float")&&/^-?\d/.test(a)&&!a.includes("e")){let o=a.indexOf(".");o<0&&(o=a.length,a+=".");let s=t-(a.length-o-1);for(;s-- >0;)a+="0"}return a}Sl.stringifyNumber=fm});var Xa=y(Kr=>{"use strict";var hm=$(),Ya=Ht(),pm={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()==="nan"?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Ya.stringifyNumber},mm={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():Ya.stringifyNumber(e)}},vm={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(e){let t=new hm.Scalar(parseFloat(e)),i=e.indexOf(".");return i!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-i-1),t},stringify:Ya.stringifyNumber};Kr.float=vm;Kr.floatExp=mm;Kr.floatNaN=pm});var Za=y(Xr=>{"use strict";var El=Ht(),Yr=e=>typeof e=="bigint"||Number.isInteger(e),Qa=(e,t,i,{intAsBigInt:r})=>r?BigInt(e):parseInt(e.substring(t),i);function Pl(e,t,i){let{value:r}=e;return Yr(r)&&r>=0?i+r.toString(t):El.stringifyNumber(e)}var gm={identify:e=>Yr(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,i)=>Qa(e,2,8,i),stringify:e=>Pl(e,8,"0o")},wm={identify:Yr,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,i)=>Qa(e,0,10,i),stringify:El.stringifyNumber},ym={identify:e=>Yr(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,i)=>Qa(e,2,16,i),stringify:e=>Pl(e,16,"0x")};Xr.int=wm;Xr.intHex=ym;Xr.intOct=gm});var Rl=y(xl=>{"use strict";var Nm=$t(),bm=Ur(),km=Ot(),Sm=Si(),Em=Ka(),eo=Xa(),to=Za(),Pm=[Nm.map,km.seq,Sm.string,bm.nullTag,Em.boolTag,to.intOct,to.int,to.intHex,eo.floatNaN,eo.floatExp,eo.float];xl.schema=Pm});var _l=y(Al=>{"use strict";var xm=$(),Rm=$t(),Cm=Ot();function Cl(e){return typeof e=="bigint"||Number.isInteger(e)}var Qr=({value:e})=>JSON.stringify(e),Am=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:Qr},{identify:e=>e==null,createNode:()=>new xm.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Qr},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:Qr},{identify:Cl,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:i})=>i?BigInt(e):parseInt(e,10),stringify:({value:e})=>Cl(e)?e.toString():JSON.stringify(e)},{identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:e=>parseFloat(e),stringify:Qr}],_m={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},Tm=[Rm.map,Cm.seq].concat(Am,_m);Al.schema=Tm});var ro=y(Tl=>{"use strict";var Ei=yr("buffer"),io=$(),Im=yi(),jm={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof Ei.Buffer=="function")return Ei.Buffer.from(e,"base64");if(typeof atob=="function"){let i=atob(e.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 t("This environment does not support reading binary tags; either Buffer or atob is required"),e},stringify({comment:e,type:t,value:i},r,n,a){if(!i)return"";let o=i,s;if(typeof Ei.Buffer=="function")s=o instanceof Ei.Buffer?o.toString("base64"):Ei.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(t??(t=io.Scalar.BLOCK_LITERAL),t!==io.Scalar.QUOTE_DOUBLE){let c=Math.max(r.options.lineWidth-r.indent.length,r.options.minContentWidth),l=Math.ceil(s.length/c),u=new Array(l);for(let f=0,d=0;f<l;++f,d+=c)u[f]=s.substr(d,c);s=u.join(t===io.Scalar.BLOCK_LITERAL?`
|
|
55
|
+
`:" ")}return Im.stringifyString({comment:e,type:t,value:s},r,n,a)}};Tl.binary=jm});var tn=y(en=>{"use strict";var Zr=P(),no=Ke(),$m=$(),Om=Qe();function Il(e,t){if(Zr.isSeq(e))for(let i=0;i<e.items.length;++i){let r=e.items[i];if(!Zr.isPair(r)){if(Zr.isMap(r)){r.items.length>1&&t("Each pair must have its own sequence indicator");let n=r.items[0]||new no.Pair(new $m.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}e.items[i]=Qr.isPair(r)?r:new no.Pair(r)}}else t("Expected a sequence for this tag");return e}function jl(e,t,i){let{replacer:r}=i,n=new Om.YAMLSeq(e);n.tag="tag:yaml.org,2002:pairs";let a=0;if(t&&Symbol.iterator in Object(t))for(let o of t){typeof r=="function"&&(o=r.call(t,String(a++),o));let s,c;if(Array.isArray(o))if(o.length===2)s=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)s=l[0],c=o[s];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else s=o;n.items.push(no.createPair(s,c,i))}return n}var Hm={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Il,createNode:jl};Zr.createPairs=jl;Zr.pairs=Hm;Zr.resolvePairs=Il});var so=y(oo=>{"use strict";var $l=P(),ao=ze(),Pi=Xe(),Dm=Qe(),Ol=en(),ft=class e extends Dm.YAMLSeq{constructor(){super(),this.add=Pi.YAMLMap.prototype.add.bind(this),this.delete=Pi.YAMLMap.prototype.delete.bind(this),this.get=Pi.YAMLMap.prototype.get.bind(this),this.has=Pi.YAMLMap.prototype.has.bind(this),this.set=Pi.YAMLMap.prototype.set.bind(this),this.tag=e.tag}toJSON(t,i){if(!i)return super.toJSON(t);let r=new Map;i?.onCreate&&i.onCreate(r);for(let n of this.items){let a,o;if($l.isPair(n)?(a=ao.toJS(n.key,"",i),o=ao.toJS(n.value,a,i)):a=ao.toJS(n,"",i),r.has(a))throw new Error("Ordered maps must not include duplicate keys");r.set(a,o)}return r}static from(t,i,r){let n=Ol.createPairs(t,i,r),a=new this;return a.items=n.items,a}};ft.tag="tag:yaml.org,2002:omap";var Bm={collection:"seq",identify:e=>e instanceof Map,nodeClass:ft,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let i=Ol.resolvePairs(e,t),r=[];for(let{key:n}of i.items)$l.isScalar(n)&&(r.includes(n.value)?t(`Ordered maps must not include duplicate keys: ${n.value}`):r.push(n.value));return Object.assign(new ft,i)},createNode:(e,t,i)=>ft.from(e,t,i)};oo.YAMLOMap=ft;oo.omap=Bm});var ql=y(co=>{"use strict";var Hl=$();function Dl({value:e,source:t},i){return t&&(e?Bl:Ll).test.test(t)?t:e?i.options.trueStr:i.options.falseStr}var Bl={identify:e=>e===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new Hl.Scalar(!0),stringify:Dl},Ll={identify:e=>e===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new Hl.Scalar(!1),stringify:Dl};co.falseTag=Ll;co.trueTag=Bl});var Fl=y(tn=>{"use strict";var Lm=$(),lo=Ht(),qm={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()==="nan"?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:lo.stringifyNumber},Fm={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e.replace(/_/g,"")),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():lo.stringifyNumber(e)}},Mm={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(e){let t=new Lm.Scalar(parseFloat(e.replace(/_/g,""))),i=e.indexOf(".");if(i!==-1){let r=e.substring(i+1).replace(/_/g,"");r[r.length-1]==="0"&&(t.minFractionDigits=r.length)}return t},stringify:lo.stringifyNumber};tn.float=Mm;tn.floatExp=Fm;tn.floatNaN=qm});var Vl=y(Ri=>{"use strict";var Ml=Ht(),xi=e=>typeof e=="bigint"||Number.isInteger(e);function rn(e,t,i,{intAsBigInt:r}){let n=e[0];if((n==="-"||n==="+")&&(t+=1),e=e.substring(t).replace(/_/g,""),r){switch(i){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`;break}let o=BigInt(e);return n==="-"?BigInt(-1)*o:o}let a=parseInt(e,i);return n==="-"?-1*a:a}function uo(e,t,i){let{value:r}=e;if(xi(r)){let n=r.toString(t);return r<0?"-"+i+n.substr(1):i+n}return Ml.stringifyNumber(e)}var Vm={identify:xi,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,i)=>rn(e,2,2,i),stringify:e=>uo(e,2,"0b")},Wm={identify:xi,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,i)=>rn(e,1,8,i),stringify:e=>uo(e,8,"0")},zm={identify:xi,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,i)=>rn(e,0,10,i),stringify:Ml.stringifyNumber},Jm={identify:xi,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,i)=>rn(e,2,16,i),stringify:e=>uo(e,16,"0x")};Ri.int=zm;Ri.intBin=Vm;Ri.intHex=Jm;Ri.intOct=Wm});var ho=y(fo=>{"use strict";var on=P(),nn=Ke(),an=Xe(),ht=class e extends an.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let i;on.isPair(t)?i=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?i=new nn.Pair(t.key,null):i=new nn.Pair(t,null),an.findPair(this.items,i.key)||this.items.push(i)}get(t,i){let r=an.findPair(this.items,t);return!i&&on.isPair(r)?on.isScalar(r.key)?r.key.value:r.key:r}set(t,i){if(typeof i!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof i}`);let r=an.findPair(this.items,t);r&&!i?this.items.splice(this.items.indexOf(r),1):!r&&i&&this.items.push(new nn.Pair(t))}toJSON(t,i){return super.toJSON(t,i,Set)}toString(t,i,r){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),i,r);throw new Error("Set items must all have null values")}static from(t,i,r){let{replacer:n}=r,a=new this(t);if(i&&Symbol.iterator in Object(i))for(let o of i)typeof n=="function"&&(o=n.call(i,o,o)),a.items.push(nn.createPair(o,null,r));return a}};ht.tag="tag:yaml.org,2002:set";var Gm={collection:"map",identify:e=>e instanceof Set,nodeClass:ht,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,i)=>ht.from(e,t,i),resolve(e,t){if(on.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new ht,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};fo.YAMLSet=ht;fo.set=Gm});var mo=y(sn=>{"use strict";var Um=Ht();function po(e,t){let i=e[0],r=i==="-"||i==="+"?e.substring(1):e,n=o=>t?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 Wl(e){let{value:t}=e,i=o=>o;if(typeof t=="bigint")i=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return Um.stringifyNumber(e);let r="";t<0&&(r="-",t*=i(-1));let n=i(60),a=[t%n];return t<60?a.unshift(0):(t=(t-a[0])/n,a.unshift(t%n),t>=60&&(t=(t-a[0])/n,a.unshift(t))),r+a.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var Km={identify:e=>typeof e=="bigint"||Number.isInteger(e),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(e,t,{intAsBigInt:i})=>po(e,i),stringify:Wl},Ym={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:e=>po(e,!1),stringify:Wl},zl={identify:e=>e instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(e){let t=e.match(zl.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,i,r,n,a,o,s]=t.map(Number),c=t[7]?Number((t[7]+"00").substr(1,3)):0,l=Date.UTC(i,r-1,n,a||0,o||0,s||0,c),u=t[8];if(u&&u!=="Z"){let f=po(u,!1);Math.abs(f)<30&&(f*=60),l-=6e4*f}return new Date(l)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};sn.floatTime=Ym;sn.intTime=Km;sn.timestamp=zl});var Ul=y(Gl=>{"use strict";var Xm=$t(),Qm=Gr(),Zm=Ot(),ev=Si(),tv=ro(),Jl=ql(),vo=Fl(),cn=Vl(),iv=Lr(),rv=so(),nv=en(),av=ho(),go=mo(),ov=[Xm.map,Zm.seq,ev.string,Qm.nullTag,Jl.trueTag,Jl.falseTag,cn.intBin,cn.intOct,cn.int,cn.intHex,vo.floatNaN,vo.floatExp,vo.float,tv.binary,iv.merge,rv.omap,nv.pairs,av.set,go.intTime,go.floatTime,go.timestamp];Gl.schema=ov});var nu=y(No=>{"use strict";var Ql=$t(),sv=Gr(),Zl=Ot(),cv=Si(),lv=Ka(),wo=Xa(),yo=Za(),uv=Rl(),dv=_l(),eu=ro(),Ci=Lr(),tu=so(),iu=en(),Kl=Ul(),ru=ho(),ln=mo(),Yl=new Map([["core",uv.schema],["failsafe",[Ql.map,Zl.seq,cv.string]],["json",dv.schema],["yaml11",Kl.schema],["yaml-1.1",Kl.schema]]),Xl={binary:eu.binary,bool:lv.boolTag,float:wo.float,floatExp:wo.floatExp,floatNaN:wo.floatNaN,floatTime:ln.floatTime,int:yo.int,intHex:yo.intHex,intOct:yo.intOct,intTime:ln.intTime,map:Ql.map,merge:Ci.merge,null:sv.nullTag,omap:tu.omap,pairs:iu.pairs,seq:Zl.seq,set:ru.set,timestamp:ln.timestamp},fv={"tag:yaml.org,2002:binary":eu.binary,"tag:yaml.org,2002:merge":Ci.merge,"tag:yaml.org,2002:omap":tu.omap,"tag:yaml.org,2002:pairs":iu.pairs,"tag:yaml.org,2002:set":ru.set,"tag:yaml.org,2002:timestamp":ln.timestamp};function hv(e,t,i){let r=Yl.get(t);if(r&&!e)return i&&!r.includes(Ci.merge)?r.concat(Ci.merge):r.slice();let n=r;if(!n)if(Array.isArray(e))n=[];else{let a=Array.from(Yl.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${t}"; use one of ${a} or define customTags array`)}if(Array.isArray(e))for(let a of e)n=n.concat(a);else typeof e=="function"&&(n=e(n.slice()));return i&&(n=n.concat(Ci.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?Xl[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(Xl).map(u=>JSON.stringify(u)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return a.includes(s)||a.push(s),a},[])}No.coreKnownTags=fv;No.getTags=hv});var So=y(au=>{"use strict";var bo=P(),pv=$t(),mv=Ot(),vv=Si(),un=nu(),gv=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,ko=class e{constructor({compat:t,customTags:i,merge:r,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?un.getTags(t,"compat"):t?un.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?un.coreKnownTags:{},this.tags=un.getTags(i,this.name,r),this.toStringOptions=s??null,Object.defineProperty(this,bo.MAP,{value:pv.map}),Object.defineProperty(this,bo.SCALAR,{value:vv.string}),Object.defineProperty(this,bo.SEQ,{value:mv.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?gv:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};au.Schema=ko});var su=y(ou=>{"use strict";var wv=P(),Eo=Ni(),Ai=vi();function yv(e,t){let i=[],r=t.directives===!0;if(t.directives!==!1&&e.directives){let c=e.directives.toString(e);c?(i.push(c),r=!0):e.directives.docStart&&(r=!0)}r&&i.push("---");let n=Eo.createStringifyContext(e,t),{commentString:a}=n.options;if(e.commentBefore){i.length!==1&&i.unshift("");let c=a(e.commentBefore);i.unshift(Ai.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(wv.isNode(e.contents)){if(e.contents.spaceBefore&&r&&i.push(""),e.contents.commentBefore){let u=a(e.contents.commentBefore);i.push(Ai.indentComment(u,""))}n.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=Eo.stringify(e.contents,n,()=>s=null,c);s&&(l+=Ai.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&i[i.length-1]==="---"?i[i.length-1]=`--- ${l}`:i.push(l)}else i.push(Eo.stringify(e.contents,n));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(`
|
|
57
|
+
${a.comment}`:r.comment}r=n}e.items[i]=Zr.isPair(r)?r:new no.Pair(r)}}else t("Expected a sequence for this tag");return e}function jl(e,t,i){let{replacer:r}=i,n=new Om.YAMLSeq(e);n.tag="tag:yaml.org,2002:pairs";let a=0;if(t&&Symbol.iterator in Object(t))for(let o of t){typeof r=="function"&&(o=r.call(t,String(a++),o));let s,c;if(Array.isArray(o))if(o.length===2)s=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)s=l[0],c=o[s];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else s=o;n.items.push(no.createPair(s,c,i))}return n}var Hm={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Il,createNode:jl};en.createPairs=jl;en.pairs=Hm;en.resolvePairs=Il});var so=y(oo=>{"use strict";var $l=P(),ao=ze(),Pi=Xe(),Dm=Qe(),Ol=tn(),ft=class e extends Dm.YAMLSeq{constructor(){super(),this.add=Pi.YAMLMap.prototype.add.bind(this),this.delete=Pi.YAMLMap.prototype.delete.bind(this),this.get=Pi.YAMLMap.prototype.get.bind(this),this.has=Pi.YAMLMap.prototype.has.bind(this),this.set=Pi.YAMLMap.prototype.set.bind(this),this.tag=e.tag}toJSON(t,i){if(!i)return super.toJSON(t);let r=new Map;i?.onCreate&&i.onCreate(r);for(let n of this.items){let a,o;if($l.isPair(n)?(a=ao.toJS(n.key,"",i),o=ao.toJS(n.value,a,i)):a=ao.toJS(n,"",i),r.has(a))throw new Error("Ordered maps must not include duplicate keys");r.set(a,o)}return r}static from(t,i,r){let n=Ol.createPairs(t,i,r),a=new this;return a.items=n.items,a}};ft.tag="tag:yaml.org,2002:omap";var Bm={collection:"seq",identify:e=>e instanceof Map,nodeClass:ft,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let i=Ol.resolvePairs(e,t),r=[];for(let{key:n}of i.items)$l.isScalar(n)&&(r.includes(n.value)?t(`Ordered maps must not include duplicate keys: ${n.value}`):r.push(n.value));return Object.assign(new ft,i)},createNode:(e,t,i)=>ft.from(e,t,i)};oo.YAMLOMap=ft;oo.omap=Bm});var ql=y(co=>{"use strict";var Hl=$();function Dl({value:e,source:t},i){return t&&(e?Bl:Ll).test.test(t)?t:e?i.options.trueStr:i.options.falseStr}var Bl={identify:e=>e===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new Hl.Scalar(!0),stringify:Dl},Ll={identify:e=>e===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new Hl.Scalar(!1),stringify:Dl};co.falseTag=Ll;co.trueTag=Bl});var Fl=y(rn=>{"use strict";var Lm=$(),lo=Ht(),qm={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()==="nan"?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:lo.stringifyNumber},Fm={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e.replace(/_/g,"")),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():lo.stringifyNumber(e)}},Mm={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(e){let t=new Lm.Scalar(parseFloat(e.replace(/_/g,""))),i=e.indexOf(".");if(i!==-1){let r=e.substring(i+1).replace(/_/g,"");r[r.length-1]==="0"&&(t.minFractionDigits=r.length)}return t},stringify:lo.stringifyNumber};rn.float=Mm;rn.floatExp=Fm;rn.floatNaN=qm});var Vl=y(Ri=>{"use strict";var Ml=Ht(),xi=e=>typeof e=="bigint"||Number.isInteger(e);function nn(e,t,i,{intAsBigInt:r}){let n=e[0];if((n==="-"||n==="+")&&(t+=1),e=e.substring(t).replace(/_/g,""),r){switch(i){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`;break}let o=BigInt(e);return n==="-"?BigInt(-1)*o:o}let a=parseInt(e,i);return n==="-"?-1*a:a}function uo(e,t,i){let{value:r}=e;if(xi(r)){let n=r.toString(t);return r<0?"-"+i+n.substr(1):i+n}return Ml.stringifyNumber(e)}var Vm={identify:xi,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,i)=>nn(e,2,2,i),stringify:e=>uo(e,2,"0b")},Wm={identify:xi,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,i)=>nn(e,1,8,i),stringify:e=>uo(e,8,"0")},zm={identify:xi,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,i)=>nn(e,0,10,i),stringify:Ml.stringifyNumber},Jm={identify:xi,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,i)=>nn(e,2,16,i),stringify:e=>uo(e,16,"0x")};Ri.int=zm;Ri.intBin=Vm;Ri.intHex=Jm;Ri.intOct=Wm});var ho=y(fo=>{"use strict";var sn=P(),an=Ke(),on=Xe(),ht=class e extends on.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let i;sn.isPair(t)?i=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?i=new an.Pair(t.key,null):i=new an.Pair(t,null),on.findPair(this.items,i.key)||this.items.push(i)}get(t,i){let r=on.findPair(this.items,t);return!i&&sn.isPair(r)?sn.isScalar(r.key)?r.key.value:r.key:r}set(t,i){if(typeof i!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof i}`);let r=on.findPair(this.items,t);r&&!i?this.items.splice(this.items.indexOf(r),1):!r&&i&&this.items.push(new an.Pair(t))}toJSON(t,i){return super.toJSON(t,i,Set)}toString(t,i,r){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),i,r);throw new Error("Set items must all have null values")}static from(t,i,r){let{replacer:n}=r,a=new this(t);if(i&&Symbol.iterator in Object(i))for(let o of i)typeof n=="function"&&(o=n.call(i,o,o)),a.items.push(an.createPair(o,null,r));return a}};ht.tag="tag:yaml.org,2002:set";var Gm={collection:"map",identify:e=>e instanceof Set,nodeClass:ht,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,i)=>ht.from(e,t,i),resolve(e,t){if(sn.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new ht,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};fo.YAMLSet=ht;fo.set=Gm});var mo=y(cn=>{"use strict";var Um=Ht();function po(e,t){let i=e[0],r=i==="-"||i==="+"?e.substring(1):e,n=o=>t?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 Wl(e){let{value:t}=e,i=o=>o;if(typeof t=="bigint")i=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return Um.stringifyNumber(e);let r="";t<0&&(r="-",t*=i(-1));let n=i(60),a=[t%n];return t<60?a.unshift(0):(t=(t-a[0])/n,a.unshift(t%n),t>=60&&(t=(t-a[0])/n,a.unshift(t))),r+a.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var Km={identify:e=>typeof e=="bigint"||Number.isInteger(e),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(e,t,{intAsBigInt:i})=>po(e,i),stringify:Wl},Ym={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:e=>po(e,!1),stringify:Wl},zl={identify:e=>e instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(e){let t=e.match(zl.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,i,r,n,a,o,s]=t.map(Number),c=t[7]?Number((t[7]+"00").substr(1,3)):0,l=Date.UTC(i,r-1,n,a||0,o||0,s||0,c),u=t[8];if(u&&u!=="Z"){let f=po(u,!1);Math.abs(f)<30&&(f*=60),l-=6e4*f}return new Date(l)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};cn.floatTime=Ym;cn.intTime=Km;cn.timestamp=zl});var Ul=y(Gl=>{"use strict";var Xm=$t(),Qm=Ur(),Zm=Ot(),ev=Si(),tv=ro(),Jl=ql(),vo=Fl(),ln=Vl(),iv=qr(),rv=so(),nv=tn(),av=ho(),go=mo(),ov=[Xm.map,Zm.seq,ev.string,Qm.nullTag,Jl.trueTag,Jl.falseTag,ln.intBin,ln.intOct,ln.int,ln.intHex,vo.floatNaN,vo.floatExp,vo.float,tv.binary,iv.merge,rv.omap,nv.pairs,av.set,go.intTime,go.floatTime,go.timestamp];Gl.schema=ov});var nu=y(No=>{"use strict";var Ql=$t(),sv=Ur(),Zl=Ot(),cv=Si(),lv=Ka(),wo=Xa(),yo=Za(),uv=Rl(),dv=_l(),eu=ro(),Ci=qr(),tu=so(),iu=tn(),Kl=Ul(),ru=ho(),un=mo(),Yl=new Map([["core",uv.schema],["failsafe",[Ql.map,Zl.seq,cv.string]],["json",dv.schema],["yaml11",Kl.schema],["yaml-1.1",Kl.schema]]),Xl={binary:eu.binary,bool:lv.boolTag,float:wo.float,floatExp:wo.floatExp,floatNaN:wo.floatNaN,floatTime:un.floatTime,int:yo.int,intHex:yo.intHex,intOct:yo.intOct,intTime:un.intTime,map:Ql.map,merge:Ci.merge,null:sv.nullTag,omap:tu.omap,pairs:iu.pairs,seq:Zl.seq,set:ru.set,timestamp:un.timestamp},fv={"tag:yaml.org,2002:binary":eu.binary,"tag:yaml.org,2002:merge":Ci.merge,"tag:yaml.org,2002:omap":tu.omap,"tag:yaml.org,2002:pairs":iu.pairs,"tag:yaml.org,2002:set":ru.set,"tag:yaml.org,2002:timestamp":un.timestamp};function hv(e,t,i){let r=Yl.get(t);if(r&&!e)return i&&!r.includes(Ci.merge)?r.concat(Ci.merge):r.slice();let n=r;if(!n)if(Array.isArray(e))n=[];else{let a=Array.from(Yl.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${t}"; use one of ${a} or define customTags array`)}if(Array.isArray(e))for(let a of e)n=n.concat(a);else typeof e=="function"&&(n=e(n.slice()));return i&&(n=n.concat(Ci.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?Xl[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(Xl).map(u=>JSON.stringify(u)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return a.includes(s)||a.push(s),a},[])}No.coreKnownTags=fv;No.getTags=hv});var So=y(au=>{"use strict";var bo=P(),pv=$t(),mv=Ot(),vv=Si(),dn=nu(),gv=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,ko=class e{constructor({compat:t,customTags:i,merge:r,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?dn.getTags(t,"compat"):t?dn.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?dn.coreKnownTags:{},this.tags=dn.getTags(i,this.name,r),this.toStringOptions=s??null,Object.defineProperty(this,bo.MAP,{value:pv.map}),Object.defineProperty(this,bo.SCALAR,{value:vv.string}),Object.defineProperty(this,bo.SEQ,{value:mv.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?gv:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};au.Schema=ko});var su=y(ou=>{"use strict";var wv=P(),Eo=Ni(),Ai=vi();function yv(e,t){let i=[],r=t.directives===!0;if(t.directives!==!1&&e.directives){let c=e.directives.toString(e);c?(i.push(c),r=!0):e.directives.docStart&&(r=!0)}r&&i.push("---");let n=Eo.createStringifyContext(e,t),{commentString:a}=n.options;if(e.commentBefore){i.length!==1&&i.unshift("");let c=a(e.commentBefore);i.unshift(Ai.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(wv.isNode(e.contents)){if(e.contents.spaceBefore&&r&&i.push(""),e.contents.commentBefore){let u=a(e.contents.commentBefore);i.push(Ai.indentComment(u,""))}n.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=Eo.stringify(e.contents,n,()=>s=null,c);s&&(l+=Ai.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&i[i.length-1]==="---"?i[i.length-1]=`--- ${l}`:i.push(l)}else i.push(Eo.stringify(e.contents,n));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(`
|
|
58
58
|
`)?(i.push("..."),i.push(Ai.indentComment(c,""))):i.push(`... ${c}`)}else i.push("...");else{let c=e.comment;c&&o&&(c=c.replace(/^\n+/,"")),c&&((!o||s)&&i[i.length-1]!==""&&i.push(""),i.push(Ai.indentComment(a(c),"")))}return i.join(`
|
|
59
59
|
`)+`
|
|
60
|
-
`}ou.stringifyDocument=yv});var _i=y(cu=>{"use strict";var Nv=pi(),Dt=
|
|
60
|
+
`}ou.stringifyDocument=yv});var _i=y(cu=>{"use strict";var Nv=pi(),Dt=_r(),le=P(),bv=Ke(),kv=ze(),Sv=So(),Ev=su(),Po=xr(),Pv=Ca(),xv=mi(),xo=Ra(),Ro=class e{constructor(t,i,r){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,le.NODE_TYPE,{value:le.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 xo.Directives({version:o}),this.setSchema(o,r),this.contents=t===void 0?null:this.createNode(t,n,r)}clone(){let t=Object.create(e.prototype,{[le.NODE_TYPE]:{value:le.DOC}});return t.commentBefore=this.commentBefore,t.comment=this.comment,t.errors=this.errors.slice(),t.warnings=this.warnings.slice(),t.options=Object.assign({},this.options),this.directives&&(t.directives=this.directives.clone()),t.schema=this.schema.clone(),t.contents=le.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){Bt(this.contents)&&this.contents.add(t)}addIn(t,i){Bt(this.contents)&&this.contents.addIn(t,i)}createAlias(t,i){if(!t.anchor){let r=Po.anchorNames(this);t.anchor=!i||r.has(i)?Po.findNewAnchor(i||"a",r):i}return new Nv.Alias(t.anchor)}createNode(t,i,r){let n;if(typeof i=="function")t=i.call({"":t},"",t),n=i;else if(Array.isArray(i)){let m=N=>typeof N=="number"||N instanceof String||N instanceof Number,g=i.filter(m).map(String);g.length>0&&(i=i.concat(g)),n=i}else r===void 0&&i&&(r=i,i=void 0);let{aliasDuplicateObjects:a,anchorPrefix:o,flow:s,keepUndefined:c,onTagObj:l,tag:u}=r??{},{onAnchor:f,setAnchors:d,sourceObjects:p}=Po.createNodeAnchors(this,o||"a"),v={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:f,onTagObj:l,replacer:n,schema:this.schema,sourceObjects:p},h=xv.createNode(t,u,v);return s&&le.isCollection(h)&&(h.flow=!0),d(),h}createPair(t,i,r={}){let n=this.createNode(t,null,r),a=this.createNode(i,null,r);return new bv.Pair(n,a)}delete(t){return Bt(this.contents)?this.contents.delete(t):!1}deleteIn(t){return Dt.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):Bt(this.contents)?this.contents.deleteIn(t):!1}get(t,i){return le.isCollection(this.contents)?this.contents.get(t,i):void 0}getIn(t,i){return Dt.isEmptyPath(t)?!i&&le.isScalar(this.contents)?this.contents.value:this.contents:le.isCollection(this.contents)?this.contents.getIn(t,i):void 0}has(t){return le.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return Dt.isEmptyPath(t)?this.contents!==void 0:le.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,i){this.contents==null?this.contents=Dt.collectionFromPath(this.schema,[t],i):Bt(this.contents)&&this.contents.set(t,i)}setIn(t,i){Dt.isEmptyPath(t)?this.contents=i:this.contents==null?this.contents=Dt.collectionFromPath(this.schema,Array.from(t),i):Bt(this.contents)&&this.contents.setIn(t,i)}setSchema(t,i={}){typeof t=="number"&&(t=String(t));let r;switch(t){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new xo.Directives({version:"1.1"}),r={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=t:this.directives=new xo.Directives({version:t}),r={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,r=null;break;default:{let n=JSON.stringify(t);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 Sv.Schema(Object.assign(r,i));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:t,jsonArg:i,mapAsMap:r,maxAliasCount:n,onAnchor:a,reviver:o}={}){let s={anchors:new Map,doc:this,keep:!t,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},c=kv.toJS(this.contents,i??"",s);if(typeof a=="function")for(let{count:l,res:u}of s.anchors.values())a(u,l);return typeof o=="function"?Pv.applyReviver(o,{"":c},"",c):c}toJSON(t,i){return this.toJS({json:!0,jsonArg:t,mapAsMap:!1,onAnchor:i})}toString(t={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in t&&(!Number.isInteger(t.indent)||Number(t.indent)<=0)){let i=JSON.stringify(t.indent);throw new Error(`"indent" option must be a positive integer, not ${i}`)}return Ev.stringifyDocument(this,t)}};function Bt(e){if(le.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}cu.Document=Ro});var ji=y(Ii=>{"use strict";var Ti=class extends Error{constructor(t,i,r,n){super(),this.name=t,this.code=r,this.message=n,this.pos=i}},Co=class extends Ti{constructor(t,i,r){super("YAMLParseError",t,i,r)}},Ao=class extends Ti{constructor(t,i,r){super("YAMLWarning",t,i,r)}},Rv=(e,t)=>i=>{if(i.pos[0]===-1)return;i.linePos=i.pos.map(s=>t.linePos(s));let{line:r,col:n}=i.linePos[0];i.message+=` at line ${r}, column ${n}`;let a=n-1,o=e.substring(t.lineStarts[r-1],t.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=e.substring(t.lineStarts[r-2],t.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
|
-
`}};Ii.YAMLError=Ti;Ii.YAMLParseError=Co;Ii.YAMLWarning=Ao;Ii.prettifyError=Rv});var $i=y(lu=>{"use strict";function Cv(e,{flow:t,indicator:i,next:r,offset:n,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,u=s,f="",d="",p=!1,v=!1,h=null,m=null,g=null,N=null,w=null,k=null,S=null;for(let b of e)switch(v&&(b.type!=="space"&&b.type!=="newline"&&b.type!=="comma"&&a(b.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),v=!1),h&&(l&&b.type!=="comment"&&b.type!=="newline"&&a(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),h=null),b.type){case"space":!t&&(i!=="doc-start"||r?.type!=="flow-collection")&&b.source.includes(" ")&&(h=b),u=!0;break;case"comment":{u||a(b,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let H=b.source.substring(1)||" ";f?f+=d+H:f=H,d="",l=!1;break}case"newline":l?f?f+=b.source:(!k||i!=="seq-item-ind")&&(c=!0):d+=b.source,l=!0,p=!0,(m||g)&&(N=b),u=!0;break;case"anchor":m&&a(b,"MULTIPLE_ANCHORS","A node can have at most one anchor"),b.source.endsWith(":")&&a(b.offset+b.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),m=b,S??(S=b.offset),l=!1,u=!1,v=!0;break;case"tag":{g&&a(b,"MULTIPLE_TAGS","A node can have at most one tag"),g=b,S??(S=b.offset),l=!1,u=!1,v=!0;break}case i:(m||g)&&a(b,"BAD_PROP_ORDER",`Anchors and tags must be after the ${b.source} indicator`),k&&a(b,"UNEXPECTED_TOKEN",`Unexpected ${b.source} in ${t??"collection"}`),k=b,l=i==="seq-item-ind"||i==="explicit-key-ind",u=!1;break;case"comma":if(t){w&&a(b,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),w=b,l=!1,u=!1;break}default:a(b,"UNEXPECTED_TOKEN",`Unexpected ${b.type} token`),l=!1,u=!1}let E=e[e.length-1],C=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:w,found:k,spaceBefore:c,comment:f,hasNewline:p,anchor:m,tag:g,newlineAfterProp:N,end:C,start:S??C}}lu.resolveProps=Cv});var
|
|
66
|
-
`))return!0;if(e.end){for(let t of e.end)if(t.type==="newline")return!0}return!1;case"flow-collection":for(let t of e.items){for(let i of t.start)if(i.type==="newline")return!0;if(t.sep){for(let i of t.sep)if(i.type==="newline")return!0}if(_o(t.key)||_o(t.value))return!0}return!1;default:return!0}}uu.containsNewline=_o});var To=y(du=>{"use strict";var Av=
|
|
65
|
+
`}};Ii.YAMLError=Ti;Ii.YAMLParseError=Co;Ii.YAMLWarning=Ao;Ii.prettifyError=Rv});var $i=y(lu=>{"use strict";function Cv(e,{flow:t,indicator:i,next:r,offset:n,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,u=s,f="",d="",p=!1,v=!1,h=null,m=null,g=null,N=null,w=null,k=null,S=null;for(let b of e)switch(v&&(b.type!=="space"&&b.type!=="newline"&&b.type!=="comma"&&a(b.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),v=!1),h&&(l&&b.type!=="comment"&&b.type!=="newline"&&a(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),h=null),b.type){case"space":!t&&(i!=="doc-start"||r?.type!=="flow-collection")&&b.source.includes(" ")&&(h=b),u=!0;break;case"comment":{u||a(b,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let H=b.source.substring(1)||" ";f?f+=d+H:f=H,d="",l=!1;break}case"newline":l?f?f+=b.source:(!k||i!=="seq-item-ind")&&(c=!0):d+=b.source,l=!0,p=!0,(m||g)&&(N=b),u=!0;break;case"anchor":m&&a(b,"MULTIPLE_ANCHORS","A node can have at most one anchor"),b.source.endsWith(":")&&a(b.offset+b.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),m=b,S??(S=b.offset),l=!1,u=!1,v=!0;break;case"tag":{g&&a(b,"MULTIPLE_TAGS","A node can have at most one tag"),g=b,S??(S=b.offset),l=!1,u=!1,v=!0;break}case i:(m||g)&&a(b,"BAD_PROP_ORDER",`Anchors and tags must be after the ${b.source} indicator`),k&&a(b,"UNEXPECTED_TOKEN",`Unexpected ${b.source} in ${t??"collection"}`),k=b,l=i==="seq-item-ind"||i==="explicit-key-ind",u=!1;break;case"comma":if(t){w&&a(b,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),w=b,l=!1,u=!1;break}default:a(b,"UNEXPECTED_TOKEN",`Unexpected ${b.type} token`),l=!1,u=!1}let E=e[e.length-1],C=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:w,found:k,spaceBefore:c,comment:f,hasNewline:p,anchor:m,tag:g,newlineAfterProp:N,end:C,start:S??C}}lu.resolveProps=Cv});var fn=y(uu=>{"use strict";function _o(e){if(!e)return null;switch(e.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(e.source.includes(`
|
|
66
|
+
`))return!0;if(e.end){for(let t of e.end)if(t.type==="newline")return!0}return!1;case"flow-collection":for(let t of e.items){for(let i of t.start)if(i.type==="newline")return!0;if(t.sep){for(let i of t.sep)if(i.type==="newline")return!0}if(_o(t.key)||_o(t.value))return!0}return!1;default:return!0}}uu.containsNewline=_o});var To=y(du=>{"use strict";var Av=fn();function _v(e,t,i){if(t?.type==="flow-collection"){let r=t.end[0];r.indent===e&&(r.source==="]"||r.source==="}")&&Av.containsNewline(t)&&i(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}du.flowIndentCheck=_v});var Io=y(hu=>{"use strict";var fu=P();function Tv(e,t,i){let{uniqueKeys:r}=e.options;if(r===!1)return!1;let n=typeof r=="function"?r:(a,o)=>a===o||fu.isScalar(a)&&fu.isScalar(o)&&a.value===o.value;return t.some(a=>n(a.key,i))}hu.mapIncludes=Tv});var yu=y(wu=>{"use strict";var pu=Ke(),Iv=Xe(),mu=$i(),jv=fn(),vu=To(),$v=Io(),gu="All mapping items must start at the same column";function Ov({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=a?.nodeClass??Iv.YAMLMap,s=new o(i.schema);i.atRoot&&(i.atRoot=!1);let c=r.offset,l=null;for(let u of r.items){let{start:f,key:d,sep:p,value:v}=u,h=mu.resolveProps(f,{indicator:"explicit-key-ind",next:d??p?.[0],offset:c,onError:n,parentIndent:r.indent,startOnNewline:!0}),m=!h.found;if(m){if(d&&(d.type==="block-seq"?n(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in d&&d.indent!==r.indent&&n(c,"BAD_INDENT",gu)),!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||jv.containsNewline(d))&&n(d??f[f.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else h.found?.indent!==r.indent&&n(c,"BAD_INDENT",gu);i.atKey=!0;let g=h.end,N=d?e(i,d,h,n):t(i,g,f,null,h,n);i.schema.compat&&vu.flowIndentCheck(r.indent,d,n),i.atKey=!1,$v.mapIncludes(i,s.items,N)&&n(g,"DUPLICATE_KEY","Map keys must be unique");let w=mu.resolveProps(p??[],{indicator:"map-value-ind",next:v,offset:N.range[2],onError:n,parentIndent:r.indent,startOnNewline:!d||d.type==="block-scalar"});if(c=w.end,w.found){m&&(v?.type==="block-map"&&!w.hasNewline&&n(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),i.options.strict&&h.start<w.found.offset-1024&&n(N.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?e(i,v,w,n):t(i,c,p,null,w,n);i.schema.compat&&vu.flowIndentCheck(r.indent,v,n),c=k.range[2];let S=new pu.Pair(N,k);i.options.keepSourceTokens&&(S.srcToken=u),s.items.push(S)}else{m&&n(N.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),w.comment&&(N.comment?N.comment+=`
|
|
68
|
-
`+w.comment:N.comment=w.comment);let k=new pu.Pair(N);i.options.keepSourceTokens&&(k.srcToken=u),s.items.push(k)}}return l&&l<c&&n(l,"IMPOSSIBLE","Map comment with trailing content"),s.range=[r.offset,c,l??c],s}wu.resolveBlockMap=Ov});var bu=y(Nu=>{"use strict";var Hv=Qe(),Dv=$i(),Bv=To();function Lv({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=a?.nodeClass??Hv.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:u,value:f}of r.items){let d=Dv.resolveProps(u,{indicator:"seq-item-ind",next:f,offset:c,onError:n,parentIndent:r.indent,startOnNewline:!0});if(!d.found)if(d.anchor||d.tag||f)f?.type==="block-seq"?n(d.end,"BAD_INDENT","All sequence items must start at the same column"):n(c,"MISSING_CHAR","Sequence item without - indicator");else{l=d.end,d.comment&&(s.comment=d.comment);continue}let p=f?e(i,f,d,n):t(i,d.end,u,null,d,n);i.schema.compat&&Bv.flowIndentCheck(r.indent,f,n),c=p.range[2],s.items.push(p)}return s.range=[r.offset,c,l??c],s}Nu.resolveBlockSeq=Lv});var Lt=y(ku=>{"use strict";function qv(e,t,i,r){let n="";if(e){let a=!1,o="";for(let s of e){let{source:c,type:l}=s;switch(l){case"space":a=!0;break;case"comment":{i&&!a&&r(s,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let u=c.substring(1)||" ";n?n+=o+u:n=u,o="";break}case"newline":n&&(o+=c),a=!0;break;default:r(s,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}t+=c.length}}return{comment:n,offset:t}}ku.resolveEnd=qv});var xu=y(Pu=>{"use strict";var Fv=P(),Mv=Ke(),Su=Xe(),Vv=Qe(),Wv=Lt(),Eu=$i(),zv=
|
|
68
|
+
`+w.comment:N.comment=w.comment);let k=new pu.Pair(N);i.options.keepSourceTokens&&(k.srcToken=u),s.items.push(k)}}return l&&l<c&&n(l,"IMPOSSIBLE","Map comment with trailing content"),s.range=[r.offset,c,l??c],s}wu.resolveBlockMap=Ov});var bu=y(Nu=>{"use strict";var Hv=Qe(),Dv=$i(),Bv=To();function Lv({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=a?.nodeClass??Hv.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:u,value:f}of r.items){let d=Dv.resolveProps(u,{indicator:"seq-item-ind",next:f,offset:c,onError:n,parentIndent:r.indent,startOnNewline:!0});if(!d.found)if(d.anchor||d.tag||f)f?.type==="block-seq"?n(d.end,"BAD_INDENT","All sequence items must start at the same column"):n(c,"MISSING_CHAR","Sequence item without - indicator");else{l=d.end,d.comment&&(s.comment=d.comment);continue}let p=f?e(i,f,d,n):t(i,d.end,u,null,d,n);i.schema.compat&&Bv.flowIndentCheck(r.indent,f,n),c=p.range[2],s.items.push(p)}return s.range=[r.offset,c,l??c],s}Nu.resolveBlockSeq=Lv});var Lt=y(ku=>{"use strict";function qv(e,t,i,r){let n="";if(e){let a=!1,o="";for(let s of e){let{source:c,type:l}=s;switch(l){case"space":a=!0;break;case"comment":{i&&!a&&r(s,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let u=c.substring(1)||" ";n?n+=o+u:n=u,o="";break}case"newline":n&&(o+=c),a=!0;break;default:r(s,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}t+=c.length}}return{comment:n,offset:t}}ku.resolveEnd=qv});var xu=y(Pu=>{"use strict";var Fv=P(),Mv=Ke(),Su=Xe(),Vv=Qe(),Wv=Lt(),Eu=$i(),zv=fn(),Jv=Io(),jo="Block collections are not allowed within flow collections",$o=e=>e&&(e.type==="block-map"||e.type==="block-seq");function Gv({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=r.start.source==="{",s=o?"flow map":"flow sequence",c=a?.nodeClass??(o?Su.YAMLMap:Vv.YAMLSeq),l=new c(i.schema);l.flow=!0;let u=i.atRoot;u&&(i.atRoot=!1),i.atKey&&(i.atKey=!1);let f=r.offset+r.start.source.length;for(let m=0;m<r.items.length;++m){let g=r.items[m],{start:N,key:w,sep:k,value:S}=g,E=Eu.resolveProps(N,{flow:s,indicator:"explicit-key-ind",next:w??k?.[0],offset:f,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),f=E.end;continue}!o&&i.options.strict&&zv.containsNewline(w)&&n(w,"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 C="";e:for(let b of N)switch(b.type){case"comma":case"space":break;case"comment":C=b.source.substring(1);break e;default:break e}if(C){let b=l.items[l.items.length-1];Fv.isPair(b)&&(b=b.value??b.key),b.comment?b.comment+=`
|
|
70
70
|
`+C:b.comment=C,E.comment=E.comment.substring(C.length+1)}}if(!o&&!k&&!E.found){let C=S?e(i,S,E,n):t(i,E.end,k,null,E,n);l.items.push(C),f=C.range[2],$o(S)&&n(C.range,"BLOCK_IN_FLOW",jo)}else{i.atKey=!0;let C=E.end,b=w?e(i,w,E,n):t(i,C,N,null,E,n);$o(w)&&n(b.range,"BLOCK_IN_FLOW",jo),i.atKey=!1;let H=Eu.resolveProps(k??[],{flow:s,indicator:"map-value-ind",next:S,offset:b.range[2],onError:n,parentIndent:r.indent,startOnNewline:!1});if(H.found){if(!o&&!E.found&&i.options.strict){if(k)for(let D of k){if(D===H.found)break;if(D.type==="newline"){n(D,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}E.start<H.found.offset-1024&&n(H.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(H.start,"MISSING_CHAR",`Missing , or : between ${s} items`));let Ve=S?e(i,S,H,n):H.found?t(i,H.end,k,null,H,n):null;Ve?$o(S)&&n(Ve.range,"BLOCK_IN_FLOW",jo):H.comment&&(b.comment?b.comment+=`
|
|
71
71
|
`+H.comment:b.comment=H.comment);let At=new Mv.Pair(b,Ve);if(i.options.keepSourceTokens&&(At.srcToken=g),o){let D=l;Jv.mapIncludes(i,D.items,b)&&n(C,"DUPLICATE_KEY","Map keys must be unique"),D.items.push(At)}else{let D=new Su.YAMLMap(i.schema);D.flow=!0,D.items.push(At);let bc=(Ve??b).range;D.range=[b.range[0],bc[1],bc[2]],l.items.push(D)}f=Ve?Ve.range[2]:H.end}}let d=o?"}":"]",[p,...v]=r.end,h=f;if(p?.source===d)h=p.offset+p.source.length;else{let m=s[0].toUpperCase()+s.substring(1),g=u?`${m} must end with a ${d}`:`${m} in block collection must be sufficiently indented and end with a ${d}`;n(f,u?"MISSING_CHAR":"BAD_INDENT",g),p&&p.source.length!==1&&v.unshift(p)}if(v.length>0){let m=Wv.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
|
`),t+=1,r=e[t+1];return i||(i=" "),{fold:i,offset:t}}var dg={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
|
|
102
|
-
`,r:"\r",t:" ",v:"\v",N:"
",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function fg(e,t,i,r){let n=e.substr(t,i),o=n.length===i&&/^[0-9a-fA-F]+$/.test(n)?parseInt(n,16):NaN;try{return String.fromCodePoint(o)}catch{let s=e.substr(t-2,i+2);return r(t-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),s}}Tu.resolveFlowScalar=og});var $u=y(ju=>{"use strict";var pt=P(),Iu=$(),hg=Do(),pg=Lo();function mg(e,t,i,r){let{value:n,type:a,comment:o,range:s}=t.type==="block-scalar"?hg.resolveBlockScalar(e,t,r):pg.resolveFlowScalar(t,e.options.strict,r),c=i?e.directives.tagName(i.source,f=>r(i,"TAG_RESOLVE_FAILED",f)):null,l;e.options.stringKeys&&e.atKey?l=e.schema[pt.SCALAR]:c?l=vg(e.schema,n,c,i,r):t.type==="scalar"?l=gg(e,n,t,r):l=e.schema[pt.SCALAR];let u;try{let f=l.resolve(n,d=>r(i??t,"TAG_RESOLVE_FAILED",d),e.options);u=pt.isScalar(f)?f:new Iu.Scalar(f)}catch(f){let d=f instanceof Error?f.message:String(f);r(i??t,"TAG_RESOLVE_FAILED",d),u=new Iu.Scalar(n)}return u.range=s,u.source=n,a&&(u.type=a),c&&(u.tag=c),l.format&&(u.format=l.format),o&&(u.comment=o),u}function vg(e,t,i,r,n){if(i==="!")return e[pt.SCALAR];let a=[];for(let s of e.tags)if(!s.collection&&s.tag===i)if(s.default&&s.test)a.push(s);else return s;for(let s of a)if(s.test?.test(t))return s;let o=e.knownTags[i];return o&&!o.collection?(e.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(n(r,"TAG_RESOLVE_FAILED",`Unresolved tag: ${i}`,i!=="tag:yaml.org,2002:str"),e[pt.SCALAR])}function gg({atKey:e,directives:t,schema:i},r,n,a){let o=i.tags.find(s=>(s.default===!0||e&&s.default==="key")&&s.test?.test(r))||i[pt.SCALAR];if(i.compat){let s=i.compat.find(c=>c.default&&c.test?.test(r))??i[pt.SCALAR];if(o.tag!==s.tag){let c=t.tagString(o.tag),l=t.tagString(s.tag),u=`Value may be parsed as either ${c} or ${l}`;a(n,"TAG_RESOLVE_FAILED",u,!0)}}return o}ju.composeScalar=mg});var Hu=y(Ou=>{"use strict";function wg(e,t,i){if(t){i??(i=t.length);for(let r=i-1;r>=0;--r){let n=t[r];switch(n.type){case"space":case"comment":case"newline":e-=n.source.length;continue}for(n=t[++r];n?.type==="space";)e+=n.source.length,n=t[++r];break}}return e}Ou.emptyScalarPosition=wg});var Lu=y(Fo=>{"use strict";var yg=pi(),Ng=P(),bg=Cu(),Du=$u(),kg=Lt(),Sg=Hu(),Eg={composeNode:Bu,composeEmptyNode:qo};function Bu(e,t,i,r){let n=e.atKey,{spaceBefore:a,comment:o,anchor:s,tag:c}=i,l,u=!0;switch(t.type){case"alias":l=Pg(e,t,r),(s||c)&&r(t,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=Du.composeScalar(e,t,c,r),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=bg.composeCollection(Eg,e,t,i,r),s&&(l.anchor=s.source.substring(1))}catch(f){let d=f instanceof Error?f.message:String(f);r(t,"RESOURCE_EXHAUSTION",d)}break;default:{let f=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;r(t,"UNEXPECTED_TOKEN",f),u=!1}}return l??(l=qo(e,t.offset,void 0,null,i,r)),s&&l.anchor===""&&r(s,"BAD_ALIAS","Anchor cannot be an empty string"),n&&e.options.stringKeys&&(!Ng.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&r(c??t,"NON_STRING_KEY","With stringKeys, all keys must be strings"),a&&(l.spaceBefore=!0),o&&(t.type==="scalar"&&t.source===""?l.comment=o:l.commentBefore=o),e.options.keepSourceTokens&&u&&(l.srcToken=t),l}function qo(e,t,i,r,{spaceBefore:n,comment:a,anchor:o,tag:s,end:c},l){let u={type:"scalar",offset:Sg.emptyScalarPosition(t,i,r),indent:-1,source:""},f=Du.composeScalar(e,u,s,l);return o&&(f.anchor=o.source.substring(1),f.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),n&&(f.spaceBefore=!0),a&&(f.comment=a,f.range[2]=c),f}function Pg({options:e},{offset:t,source:i,end:r},n){let a=new yg.Alias(i.substring(1));a.source===""&&n(t,"BAD_ALIAS","Alias cannot be an empty string"),a.source.endsWith(":")&&n(t+i.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=t+i.length,s=kg.resolveEnd(r,o,e.strict,n);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}Fo.composeEmptyNode=qo;Fo.composeNode=Bu});var Mu=y(Fu=>{"use strict";var xg=_i(),qu=Lu(),Rg=Lt(),Cg=$i();function Ag(e,t,{offset:i,start:r,value:n,end:a},o){let s=Object.assign({_directives:t},e),c=new xg.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=Cg.resolveProps(r,{indicator:"doc-start",next:n??a?.[0],offset:i,onError:o,parentIndent:0,startOnNewline:!0});u.found&&(c.directives.docStart=!0,n&&(n.type==="block-map"||n.type==="block-seq")&&!u.hasNewline&&o(u.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=n?qu.composeNode(l,n,u,o):qu.composeEmptyNode(l,u.end,r,null,u,o);let f=c.contents.range[2],d=Rg.resolveEnd(a,f,!1,o);return d.comment&&(c.comment=d.comment),c.range=[i,f,d.offset],c}Fu.composeDoc=Ag});var Vo=y(zu=>{"use strict";var _g=
|
|
102
|
+
`,r:"\r",t:" ",v:"\v",N:"
",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function fg(e,t,i,r){let n=e.substr(t,i),o=n.length===i&&/^[0-9a-fA-F]+$/.test(n)?parseInt(n,16):NaN;try{return String.fromCodePoint(o)}catch{let s=e.substr(t-2,i+2);return r(t-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),s}}Tu.resolveFlowScalar=og});var $u=y(ju=>{"use strict";var pt=P(),Iu=$(),hg=Do(),pg=Lo();function mg(e,t,i,r){let{value:n,type:a,comment:o,range:s}=t.type==="block-scalar"?hg.resolveBlockScalar(e,t,r):pg.resolveFlowScalar(t,e.options.strict,r),c=i?e.directives.tagName(i.source,f=>r(i,"TAG_RESOLVE_FAILED",f)):null,l;e.options.stringKeys&&e.atKey?l=e.schema[pt.SCALAR]:c?l=vg(e.schema,n,c,i,r):t.type==="scalar"?l=gg(e,n,t,r):l=e.schema[pt.SCALAR];let u;try{let f=l.resolve(n,d=>r(i??t,"TAG_RESOLVE_FAILED",d),e.options);u=pt.isScalar(f)?f:new Iu.Scalar(f)}catch(f){let d=f instanceof Error?f.message:String(f);r(i??t,"TAG_RESOLVE_FAILED",d),u=new Iu.Scalar(n)}return u.range=s,u.source=n,a&&(u.type=a),c&&(u.tag=c),l.format&&(u.format=l.format),o&&(u.comment=o),u}function vg(e,t,i,r,n){if(i==="!")return e[pt.SCALAR];let a=[];for(let s of e.tags)if(!s.collection&&s.tag===i)if(s.default&&s.test)a.push(s);else return s;for(let s of a)if(s.test?.test(t))return s;let o=e.knownTags[i];return o&&!o.collection?(e.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(n(r,"TAG_RESOLVE_FAILED",`Unresolved tag: ${i}`,i!=="tag:yaml.org,2002:str"),e[pt.SCALAR])}function gg({atKey:e,directives:t,schema:i},r,n,a){let o=i.tags.find(s=>(s.default===!0||e&&s.default==="key")&&s.test?.test(r))||i[pt.SCALAR];if(i.compat){let s=i.compat.find(c=>c.default&&c.test?.test(r))??i[pt.SCALAR];if(o.tag!==s.tag){let c=t.tagString(o.tag),l=t.tagString(s.tag),u=`Value may be parsed as either ${c} or ${l}`;a(n,"TAG_RESOLVE_FAILED",u,!0)}}return o}ju.composeScalar=mg});var Hu=y(Ou=>{"use strict";function wg(e,t,i){if(t){i??(i=t.length);for(let r=i-1;r>=0;--r){let n=t[r];switch(n.type){case"space":case"comment":case"newline":e-=n.source.length;continue}for(n=t[++r];n?.type==="space";)e+=n.source.length,n=t[++r];break}}return e}Ou.emptyScalarPosition=wg});var Lu=y(Fo=>{"use strict";var yg=pi(),Ng=P(),bg=Cu(),Du=$u(),kg=Lt(),Sg=Hu(),Eg={composeNode:Bu,composeEmptyNode:qo};function Bu(e,t,i,r){let n=e.atKey,{spaceBefore:a,comment:o,anchor:s,tag:c}=i,l,u=!0;switch(t.type){case"alias":l=Pg(e,t,r),(s||c)&&r(t,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=Du.composeScalar(e,t,c,r),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=bg.composeCollection(Eg,e,t,i,r),s&&(l.anchor=s.source.substring(1))}catch(f){let d=f instanceof Error?f.message:String(f);r(t,"RESOURCE_EXHAUSTION",d)}break;default:{let f=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;r(t,"UNEXPECTED_TOKEN",f),u=!1}}return l??(l=qo(e,t.offset,void 0,null,i,r)),s&&l.anchor===""&&r(s,"BAD_ALIAS","Anchor cannot be an empty string"),n&&e.options.stringKeys&&(!Ng.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&r(c??t,"NON_STRING_KEY","With stringKeys, all keys must be strings"),a&&(l.spaceBefore=!0),o&&(t.type==="scalar"&&t.source===""?l.comment=o:l.commentBefore=o),e.options.keepSourceTokens&&u&&(l.srcToken=t),l}function qo(e,t,i,r,{spaceBefore:n,comment:a,anchor:o,tag:s,end:c},l){let u={type:"scalar",offset:Sg.emptyScalarPosition(t,i,r),indent:-1,source:""},f=Du.composeScalar(e,u,s,l);return o&&(f.anchor=o.source.substring(1),f.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),n&&(f.spaceBefore=!0),a&&(f.comment=a,f.range[2]=c),f}function Pg({options:e},{offset:t,source:i,end:r},n){let a=new yg.Alias(i.substring(1));a.source===""&&n(t,"BAD_ALIAS","Alias cannot be an empty string"),a.source.endsWith(":")&&n(t+i.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=t+i.length,s=kg.resolveEnd(r,o,e.strict,n);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}Fo.composeEmptyNode=qo;Fo.composeNode=Bu});var Mu=y(Fu=>{"use strict";var xg=_i(),qu=Lu(),Rg=Lt(),Cg=$i();function Ag(e,t,{offset:i,start:r,value:n,end:a},o){let s=Object.assign({_directives:t},e),c=new xg.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=Cg.resolveProps(r,{indicator:"doc-start",next:n??a?.[0],offset:i,onError:o,parentIndent:0,startOnNewline:!0});u.found&&(c.directives.docStart=!0,n&&(n.type==="block-map"||n.type==="block-seq")&&!u.hasNewline&&o(u.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=n?qu.composeNode(l,n,u,o):qu.composeEmptyNode(l,u.end,r,null,u,o);let f=c.contents.range[2],d=Rg.resolveEnd(a,f,!1,o);return d.comment&&(c.comment=d.comment),c.range=[i,f,d.offset],c}Fu.composeDoc=Ag});var Vo=y(zu=>{"use strict";var _g=yr("process"),Tg=Ra(),Ig=_i(),Oi=ji(),Vu=P(),jg=Mu(),$g=Lt();function Hi(e){if(typeof e=="number")return[e,e+1];if(Array.isArray(e))return e.length===2?e:[e[0],e[1]];let{offset:t,source:i}=e;return[t,t+(typeof i=="string"?i.length:1)]}function Wu(e){let t="",i=!1,r=!1;for(let n=0;n<e.length;++n){let a=e[n];switch(a[0]){case"#":t+=(t===""?"":r?`
|
|
103
103
|
|
|
104
104
|
`:`
|
|
105
105
|
`)+(a.substring(1)||" "),i=!0,r=!1;break;case"%":e[n+1]?.[0]!=="#"&&(n+=1),i=!1;break;default:i||(r=!0),i=!1}}return{comment:t,afterEmptyLine:r}}var Mo=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(i,r,n,a)=>{let o=Hi(i);a?this.warnings.push(new Oi.YAMLWarning(o,r,n)):this.errors.push(new Oi.YAMLParseError(o,r,n))},this.directives=new Tg.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,i){let{comment:r,afterEmptyLine:n}=Wu(this.prelude);if(r){let a=t.contents;if(i)t.comment=t.comment?`${t.comment}
|
|
106
106
|
${r}`:r;else if(n||t.directives.docStart||!a)t.commentBefore=r;else if(Vu.isCollection(a)&&!a.flow&&a.items.length>0){let o=a.items[0];Vu.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
108
|
${o}`:r}}if(i){for(let a=0;a<this.errors.length;++a)t.errors.push(this.errors[a]);for(let a=0;a<this.warnings.length;++a)t.warnings.push(this.warnings[a])}else t.errors=this.errors,t.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:Wu(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(t,i=!1,r=-1){for(let n of t)yield*this.next(n);yield*this.end(i,r)}*next(t){switch(_g.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(i,r,n)=>{let a=Hi(t);a[0]+=i,this.onError(a,"BAD_DIRECTIVE",r,n)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let i=jg.composeDoc(this.options,this.directives,t,this.onError);this.atDirectives&&!i.directives.docStart&&this.onError(t,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(i,!1),this.doc&&(yield this.doc),this.doc=i,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(t.source);break;case"error":{let i=t.source?`${t.message}: ${JSON.stringify(t.source)}`:t.message,r=new Oi.YAMLParseError(Hi(t),"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 Oi.YAMLParseError(Hi(t),"UNEXPECTED_TOKEN",r));break}this.doc.directives.docEnd=!0;let i=$g.resolveEnd(t.end,t.offset+t.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 Oi.YAMLParseError(Hi(t),"UNEXPECTED_TOKEN",`Unsupported token ${t.type}`))}}*end(t=!1,i=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(t){let r=Object.assign({_directives:this.directives},this.options),n=new Ig.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}}};zu.Composer=Mo});var Uu=y(
|
|
109
|
+
${i.comment}`:i.comment}this.doc.range[2]=i.offset;break}default:this.errors.push(new Oi.YAMLParseError(Hi(t),"UNEXPECTED_TOKEN",`Unsupported token ${t.type}`))}}*end(t=!1,i=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(t){let r=Object.assign({_directives:this.directives},this.options),n=new Ig.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}}};zu.Composer=Mo});var Uu=y(hn=>{"use strict";var Og=Do(),Hg=Lo(),Dg=ji(),Ju=yi();function Bg(e,t=!0,i){if(e){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 Dg.YAMLParseError([s,s+1],a,o)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return Hg.resolveFlowScalar(e,t,r);case"block-scalar":return Og.resolveBlockScalar({options:{strict:t}},e,r)}}return null}function Lg(e,t){let{implicitKey:i=!1,indent:r,inFlow:n=!1,offset:a=-1,type:o="PLAIN"}=t,s=Ju.stringifyString({type:o,value:e},{implicitKey:i,indent:r>0?" ".repeat(r):"",inFlow:n,options:{blockQuote:!0,lineWidth:-1}}),c=t.end??[{type:"newline",offset:-1,indent:r,source:`
|
|
110
110
|
`}];switch(s[0]){case"|":case">":{let l=s.indexOf(`
|
|
111
111
|
`),u=s.substring(0,l),f=s.substring(l+1)+`
|
|
112
112
|
`,d=[{type:"block-scalar-header",offset:a,indent:r,source:u}];return Gu(d,c)||d.push({type:"newline",offset:-1,indent:r,source:`
|
|
@@ -114,10 +114,10 @@ ${i.comment}`:i.comment}this.doc.range[2]=i.offset;break}default:this.errors.pus
|
|
|
114
114
|
`),r=t.substring(0,i),n=t.substring(i+1)+`
|
|
115
115
|
`;if(e.type==="block-scalar"){let a=e.props[0];if(a.type!=="block-scalar-header")throw new Error("Invalid block scalar header");a.source=r,e.source=n}else{let{offset:a}=e,o="indent"in e?e.indent:-1,s=[{type:"block-scalar-header",offset:a,indent:o,source:r}];Gu(s,"end"in e?e.end:void 0)||s.push({type:"newline",offset:-1,indent:o,source:`
|
|
116
116
|
`});for(let c of Object.keys(e))c!=="type"&&c!=="offset"&&delete e[c];Object.assign(e,{type:"block-scalar",indent:o,props:s,source:n})}}function Gu(e,t){if(t)for(let i of t)switch(i.type){case"space":case"comment":e.push(i);break;case"newline":return e.push(i),!0}return!1}function Wo(e,t,i){switch(e.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":e.type=i,e.source=t;break;case"block-scalar":{let r=e.props.slice(1),n=t.length;e.props[0].type==="block-scalar-header"&&(n-=e.props[0].source.length);for(let a of r)a.offset+=n;delete e.props,Object.assign(e,{type:i,source:t,end:r});break}case"block-map":case"block-seq":{let n={type:"newline",offset:e.offset+t.length,indent:e.indent,source:`
|
|
117
|
-
`};delete e.items,Object.assign(e,{type:i,source:t,end:[n]});break}default:{let r="indent"in e?e.indent:-1,n="end"in e&&Array.isArray(e.end)?e.end.filter(a=>a.type==="space"||a.type==="comment"||a.type==="newline"):[];for(let a of Object.keys(e))a!=="type"&&a!=="offset"&&delete e[a];Object.assign(e,{type:i,indent:r,source:t,end:n})}}}
|
|
117
|
+
`};delete e.items,Object.assign(e,{type:i,source:t,end:[n]});break}default:{let r="indent"in e?e.indent:-1,n="end"in e&&Array.isArray(e.end)?e.end.filter(a=>a.type==="space"||a.type==="comment"||a.type==="newline"):[];for(let a of Object.keys(e))a!=="type"&&a!=="offset"&&delete e[a];Object.assign(e,{type:i,indent:r,source:t,end:n})}}}hn.createScalarToken=Lg;hn.resolveAsScalar=Bg;hn.setScalarValue=qg});var Yu=y(Ku=>{"use strict";var Mg=e=>"type"in e?mn(e):pn(e);function mn(e){switch(e.type){case"block-scalar":{let t="";for(let i of e.props)t+=mn(i);return t+e.source}case"block-map":case"block-seq":{let t="";for(let i of e.items)t+=pn(i);return t}case"flow-collection":{let t=e.start.source;for(let i of e.items)t+=pn(i);for(let i of e.end)t+=i.source;return t}case"document":{let t=pn(e);if(e.end)for(let i of e.end)t+=i.source;return t}default:{let t=e.source;if("end"in e&&e.end)for(let i of e.end)t+=i.source;return t}}}function pn({start:e,key:t,sep:i,value:r}){let n="";for(let a of e)n+=a.source;if(t&&(n+=mn(t)),i)for(let a of i)n+=a.source;return r&&(n+=mn(r)),n}Ku.stringify=Mg});var ed=y(Zu=>{"use strict";var zo=Symbol("break visit"),Vg=Symbol("skip children"),Xu=Symbol("remove item");function mt(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),Qu(Object.freeze([]),e,t)}mt.BREAK=zo;mt.SKIP=Vg;mt.REMOVE=Xu;mt.itemAtPath=(e,t)=>{let i=e;for(let[r,n]of t){let a=i?.[r];if(a&&"items"in a)i=a.items[n];else return}return i};mt.parentCollection=(e,t)=>{let i=mt.itemAtPath(e,t.slice(0,-1)),r=t[t.length-1][0],n=i?.[r];if(n&&"items"in n)return n;throw new Error("Parent collection not found")};function Qu(e,t,i){let r=i(t,e);if(typeof r=="symbol")return r;for(let n of["key","value"]){let a=t[n];if(a&&"items"in a){for(let o=0;o<a.items.length;++o){let s=Qu(Object.freeze(e.concat([[n,o]])),a.items[o],i);if(typeof s=="number")o=s-1;else{if(s===zo)return zo;s===Xu&&(a.items.splice(o,1),o-=1)}}typeof r=="function"&&n==="key"&&(r=r(t,e))}}return typeof r=="function"?r(t,e):r}Zu.visit=mt});var vn=y(Z=>{"use strict";var Jo=Uu(),Wg=Yu(),zg=ed(),Go="\uFEFF",Uo="",Ko="",Yo="",Jg=e=>!!e&&"items"in e,Gg=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function Ug(e){switch(e){case Go:return"<BOM>";case Uo:return"<DOC>";case Ko:return"<FLOW_END>";case Yo:return"<SCALAR>";default:return JSON.stringify(e)}}function Kg(e){switch(e){case Go:return"byte-order-mark";case Uo:return"doc-mode";case Ko:return"flow-error-end";case Yo: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(e[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}Z.createScalarToken=Jo.createScalarToken;Z.resolveAsScalar=Jo.resolveAsScalar;Z.setScalarValue=Jo.setScalarValue;Z.stringify=Wg.stringify;Z.visit=zg.visit;Z.BOM=Go;Z.DOCUMENT=Uo;Z.FLOW_END=Ko;Z.SCALAR=Yo;Z.isCollection=Jg;Z.isScalar=Gg;Z.prettyToken=Ug;Z.tokenType=Kg});var Zo=y(id=>{"use strict";var Di=
|
|
120
|
-
`:case"\r":case" ":return!0;default:return!1}}var td=new Set("0123456789ABCDEFabcdef"),Yg=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),
|
|
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(e[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}Z.createScalarToken=Jo.createScalarToken;Z.resolveAsScalar=Jo.resolveAsScalar;Z.setScalarValue=Jo.setScalarValue;Z.stringify=Wg.stringify;Z.visit=zg.visit;Z.BOM=Go;Z.DOCUMENT=Uo;Z.FLOW_END=Ko;Z.SCALAR=Yo;Z.isCollection=Jg;Z.isScalar=Gg;Z.prettyToken=Ug;Z.tokenType=Kg});var Zo=y(id=>{"use strict";var Di=vn();function ve(e){switch(e){case void 0:case" ":case`
|
|
120
|
+
`:case"\r":case" ":return!0;default:return!1}}var td=new Set("0123456789ABCDEFabcdef"),Yg=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),gn=new Set(",[]{}"),Xg=new Set(` ,[]{}
|
|
121
121
|
\r `),Xo=e=>!e||Xg.has(e),Qo=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(t,i=!1){if(t){if(typeof t!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+t:t,this.lineEndPos=null}this.atEnd=!i;let r=this.next??"stream";for(;r&&(i||this.hasChars(1));)r=yield*this.parseNext(r)}atLineEnd(){let t=this.pos,i=this.buffer[t];for(;i===" "||i===" ";)i=this.buffer[++t];return!i||i==="#"||i===`
|
|
122
122
|
`?!0:i==="\r"?this.buffer[t+1]===`
|
|
123
123
|
`:!1}charAt(t){return this.buffer[this.pos+t]}continueScalar(t){let i=this.buffer[t];if(this.indentNext>0){let r=0;for(;i===" ";)i=this.buffer[++r+t];if(i==="\r"){let n=this.buffer[r+t+1];if(n===`
|
|
@@ -130,25 +130,25 @@ ${i.comment}`:i.comment}this.doc.range[2]=i.offset;break}default:this.errors.pus
|
|
|
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(t+1);if(a===-1)break;t=this.buffer.indexOf(`
|
|
131
131
|
`,a)}while(t!==-1);if(t===-1){if(!this.atEnd)return this.setNext("block-scalar");t=this.buffer.length}}let n=t+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];t=n-1}else if(!this.blockScalarKeep)do{let a=t-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)t=a;else break}while(!0);return yield Di.SCALAR,yield*this.pushToIndex(t+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let t=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(ve(a)||t&&
|
|
133
|
+
`&&a>=this.pos&&a+1+i>s)t=a;else break}while(!0);return yield Di.SCALAR,yield*this.pushToIndex(t+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let t=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(ve(a)||t&&gn.has(a))break;i=r}else if(ve(n)){let a=this.buffer[r+1];if(n==="\r"&&(a===`
|
|
134
134
|
`?(r+=1,n=`
|
|
135
|
-
`,a=this.buffer[r+1]):i=r),a==="#"||t&&
|
|
136
|
-
`){let o=this.continueScalar(r+1);if(o===-1)break;r=Math.max(r,o-2)}}else{if(t&&
|
|
135
|
+
`,a=this.buffer[r+1]):i=r),a==="#"||t&&gn.has(a))break;if(n===`
|
|
136
|
+
`){let o=this.continueScalar(r+1);if(o===-1)break;r=Math.max(r,o-2)}}else{if(t&&gn.has(n))break;i=r}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield Di.SCALAR,yield*this.pushToIndex(i+1,!0),t?"flow":"doc")}*pushCount(t){return t>0?(yield this.buffer.substr(this.pos,t),this.pos+=t,t):0}*pushToIndex(t,i){let r=this.buffer.slice(this.pos,t);return r?(yield r,this.pos+=r.length,r.length):(i&&(yield""),0)}*pushIndicators(){let t=0;e:for(;;){switch(this.charAt(0)){case"!":t+=yield*this.pushTag(),t+=yield*this.pushSpaces(!0);continue e;case"&":t+=yield*this.pushUntil(Xo),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let i=this.flowLevel>0,r=this.charAt(1);if(ve(r)||i&&gn.has(r)){i?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,t+=yield*this.pushCount(1),t+=yield*this.pushSpaces(!0);continue e}}}break e}return t}*pushTag(){if(this.charAt(1)==="<"){let t=this.pos+2,i=this.buffer[t];for(;!ve(i)&&i!==">";)i=this.buffer[++t];return yield*this.pushToIndex(i===">"?t+1:t,!1)}else{let t=this.pos+1,i=this.buffer[t];for(;i;)if(Yg.has(i))i=this.buffer[++t];else if(i==="%"&&td.has(this.buffer[t+1])&&td.has(this.buffer[t+2]))i=this.buffer[t+=3];else break;return yield*this.pushToIndex(t,!1)}}*pushNewline(){let t=this.buffer[this.pos];return t===`
|
|
137
137
|
`?yield*this.pushCount(1):t==="\r"&&this.charAt(1)===`
|
|
138
|
-
`?yield*this.pushCount(2):0}*pushSpaces(t){let i=this.pos-1,r;do r=this.buffer[++i];while(r===" "||t&&r===" ");let n=i-this.pos;return n>0&&(yield this.buffer.substr(this.pos,n),this.pos=i),n}*pushUntil(t){let i=this.pos,r=this.buffer[i];for(;!t(r);)r=this.buffer[++i];return yield*this.pushToIndex(i,!1)}};id.Lexer=Qo});var ts=y(rd=>{"use strict";var es=class{constructor(){this.lineStarts=[],this.addNewLine=t=>this.lineStarts.push(t),this.linePos=t=>{let i=0,r=this.lineStarts.length;for(;i<r;){let a=i+r>>1;this.lineStarts[a]<t?i=a+1:r=a}if(this.lineStarts[i]===t)return{line:i+1,col:1};if(i===0)return{line:0,col:t};let n=this.lineStarts[i-1];return{line:i,col:t-n+1}}}};rd.LineCounter=es});var rs=y(cd=>{"use strict";var Qg=
|
|
138
|
+
`?yield*this.pushCount(2):0}*pushSpaces(t){let i=this.pos-1,r;do r=this.buffer[++i];while(r===" "||t&&r===" ");let n=i-this.pos;return n>0&&(yield this.buffer.substr(this.pos,n),this.pos=i),n}*pushUntil(t){let i=this.pos,r=this.buffer[i];for(;!t(r);)r=this.buffer[++i];return yield*this.pushToIndex(i,!1)}};id.Lexer=Qo});var ts=y(rd=>{"use strict";var es=class{constructor(){this.lineStarts=[],this.addNewLine=t=>this.lineStarts.push(t),this.linePos=t=>{let i=0,r=this.lineStarts.length;for(;i<r;){let a=i+r>>1;this.lineStarts[a]<t?i=a+1:r=a}if(this.lineStarts[i]===t)return{line:i+1,col:1};if(i===0)return{line:0,col:t};let n=this.lineStarts[i-1];return{line:i,col:t-n+1}}}};rd.LineCounter=es});var rs=y(cd=>{"use strict";var Qg=yr("process"),nd=vn(),Zg=Zo();function Ze(e,t){for(let i=0;i<e.length;++i)if(e[i].type===t)return!0;return!1}function ad(e){for(let t=0;t<e.length;++t)switch(e[t].type){case"space":case"comment":case"newline":break;default:return t}return-1}function sd(e){switch(e?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function wn(e){switch(e.type){case"document":return e.start;case"block-map":{let t=e.items[e.items.length-1];return t.sep??t.start}case"block-seq":return e.items[e.items.length-1].start;default:return[]}}function qt(e){if(e.length===0)return[];let t=e.length;e:for(;--t>=0;)switch(e[t].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;e[++t]?.type==="space";);return e.splice(t,e.length)}function yn(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let i=0;i<t.length;++i)e.push(t[i])}function od(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!Ze(t.start,"explicit-key-ind")&&!Ze(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,sd(t.value)?t.value.end?yn(t.value.end,t.sep):t.value.end=t.sep:yn(t.start,t.sep),delete t.sep)}var is=class{constructor(t){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new Zg.Lexer,this.onNewLine=t}*parse(t,i=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let r of this.lexer.lex(t,i))yield*this.next(r);i||(yield*this.end())}*next(t){if(this.source=t,Qg.env.LOG_TOKENS&&console.log("|",nd.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let i=nd.tokenType(t);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+t.length);break;case"space":this.atNewLine&&t[0]===" "&&(this.indent+=t.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=t.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=t.length}else{let r=`Not a YAML token: ${t}`;yield*this.pop({type:"error",offset:this.offset,message:r,source:t}),this.offset+=t.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 t=this.peek(1);if(this.type==="doc-end"&&t?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!t)return yield*this.stream();switch(t.type){case"document":return yield*this.document(t);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(t);case"block-scalar":return yield*this.blockScalar(t);case"block-map":return yield*this.blockMap(t);case"block-seq":return yield*this.blockSequence(t);case"flow-collection":return yield*this.flowCollection(t);case"doc-end":return yield*this.documentEnd(t)}yield*this.pop()}peek(t){return this.stack[this.stack.length-t]}*pop(t){let i=t??this.stack.pop();if(!i)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield i;else{let 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"&&od(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&&ad(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 t={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&t.start.push(this.sourceToken),this.stack.push(t);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(t){if(t.value)return yield*this.lineEnd(t);switch(this.type){case"doc-start":{ad(t.start)!==-1?(yield*this.pop(),yield*this.step()):t.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":t.start.push(this.sourceToken);return}let i=this.startBlockValue(t);i?this.stack.push(i):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(t){if(this.type==="map-value-ind"){let i=wn(this.peek(2)),r=qt(i),n;t.end?(n=t.end,n.push(this.sourceToken),delete t.end):n=[this.sourceToken];let a={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:r,key:t,sep:n}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(t)}*blockScalar(t){switch(this.type){case"space":case"comment":case"newline":t.props.push(this.sourceToken);return;case"scalar":if(t.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
|
-
`,i)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(t){let i=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,i.value){let 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):t.items.push({start:[this.sourceToken]})}else i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"space":case"comment":if(i.value)t.items.push({start:[this.sourceToken]});else if(i.sep)i.sep.push(this.sourceToken);else{if(this.atIndentedComment(i.start,t.indent)){let n=t.items[t.items.length-2]?.value?.end;if(Array.isArray(n)){
|
|
140
|
+
`,i)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(t){let i=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,i.value){let 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):t.items.push({start:[this.sourceToken]})}else i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"space":case"comment":if(i.value)t.items.push({start:[this.sourceToken]});else if(i.sep)i.sep.push(this.sourceToken);else{if(this.atIndentedComment(i.start,t.indent)){let n=t.items[t.items.length-2]?.value?.end;if(Array.isArray(n)){yn(n,i.start),n.push(this.sourceToken),t.items.pop();return}}i.start.push(this.sourceToken)}return}if(this.indent>=t.indent){let r=!this.onKeyLine&&this.indent===t.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>t.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),t.items.push({start:a}),this.onKeyLine=!0):i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"explicit-key-ind":!i.sep&&!i.explicitKey?(i.start.push(this.sourceToken),i.explicitKey=!0):n||i.value?(a.push(this.sourceToken),t.items.push({start:a,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(i.explicitKey)if(i.sep)if(i.value)t.items.push({start:[],key:null,sep:[this.sourceToken]});else if(Ze(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(sd(i.key)&&!Ze(i.sep,"newline")){let o=qt(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(Ze(i.start,"newline"))Object.assign(i,{key:null,sep:[this.sourceToken]});else{let o=qt(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?t.items.push({start:a,key:null,sep:[this.sourceToken]}):Ze(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?(t.items.push({start:a,key:o,sep:[]}),this.onKeyLine=!0):i.sep?this.stack.push(o):(Object.assign(i,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(t);if(o){if(o.type==="block-seq"){if(!i.explicitKey&&i.sep&&!Ze(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&&t.items.push({start:a});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(t){let i=t.items[t.items.length-1];switch(this.type){case"newline":if(i.value){let 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):t.items.push({start:[this.sourceToken]})}else i.start.push(this.sourceToken);return;case"space":case"comment":if(i.value)t.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(i.start,t.indent)){let n=t.items[t.items.length-2]?.value?.end;if(Array.isArray(n)){yn(n,i.start),n.push(this.sourceToken),t.items.pop();return}}i.start.push(this.sourceToken)}return;case"anchor":case"tag":if(i.value||this.indent<=t.indent)break;i.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==t.indent)break;i.value||Ze(i.start,"seq-item-ind")?t.items.push({start:[this.sourceToken]}):i.start.push(this.sourceToken);return}if(this.indent>t.indent){let r=this.startBlockValue(t);if(r){this.stack.push(r);return}}yield*this.pop(),yield*this.step()}*flowCollection(t){let i=t.items[t.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(t.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!i||i.sep?t.items.push({start:[this.sourceToken]}):i.start.push(this.sourceToken);return;case"map-value-ind":!i||i.value?t.items.push({start:[],key:null,sep:[this.sourceToken]}):i.sep?i.sep.push(this.sourceToken):Object.assign(i,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!i||i.value?t.items.push({start:[this.sourceToken]}):i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let n=this.flowScalar(this.type);!i||i.value?t.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":t.end.push(this.sourceToken);return}let r=this.startBlockValue(t);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===t.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=wn(r),a=qt(n);od(t);let o=t.end.splice(1,t.end.length);o.push(this.sourceToken);let s={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:a,key:t,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(t)}}flowScalar(t){if(this.onNewLine){let i=this.source.indexOf(`
|
|
141
141
|
`)+1;for(;i!==0;)this.onNewLine(this.offset+i),i=this.source.indexOf(`
|
|
142
|
-
`,i)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let i=
|
|
143
|
-
`,i)}import{createHash as qh}from"node:crypto";import{promises as pe}from"node:fs";import ce from"node:path";import{TextDecoder as Fh}from"node:util";var Dh=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),Bh=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function Lh(e){return e.toLowerCase().startsWith(".env")}function li(e){let i=e.replaceAll("\\","/").split("/").filter(Boolean).map(r=>r.toLowerCase());return i.some(r=>Lh(r))?"environment-file":i.some(r=>Bh.has(r))?"credential-config":i.includes(".git")?"git-metadata":i.some(r=>Dh.has(r))?"dependency-or-cache":i.join("/")===".comet/config.yaml"?"comet-config":i.join("/")===".comet/current-change.json"?"comet-selection":null}var Nr=1024*1024;function Sa(e,t){let i=ce.relative(e,t);return i===""||!ce.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${ce.sep}`)}function Mh(e){let t=ce.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(n=>{let a=n.codePointAt(0)??0;return a<=31||a===127})||ce.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||t!==e||t==="."||e.endsWith("/"))throw new Error(`Native artifact ref must be normalized and relative: ${e}`);let i=e.toLowerCase(),r=li(e);if(r||i==="runtime"||i.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${r??"native-runtime"}): ${e}`);return e}function Vh(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function Wh(e,t){return A({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function yr(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return Se(i,r)?A(i,r):A(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Pc(e){let t=await pe.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await pe.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function zh(e,t){let i=ce.resolve(e),r=ce.resolve(t);if(!Sa(i,r))throw new Error("Native artifact path is outside its root");let n=[await Pc(i)],a=i;for(let o of ce.relative(i,r).split(ce.sep).filter(Boolean)){a=ce.join(a,o);let s=await Pc(a);if(!Sa(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function xc(e){for(let t of e){let i=await pe.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!Wh(t,i)||await pe.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function j(e){let t=Mh(e.ref),i=e.maxBytes===null?null:Vh(e.maxBytes??Nr),r=ce.resolve(e.root,...t.split("/")),n=await zh(e.root,ce.dirname(r));await e.hooks?.afterParentChainCaptured?.();let a=await pe.lstat(r);if(!a.isFile()||a.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${t}`);if(i!==null&&a.size>i)throw new Error(`Native artifact exceeds ${i} bytes: ${t}`);let o=await pe.realpath(r);if(!Sa(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await pe.open(r,"r");try{let[c,l,u]=await Promise.all([s.stat(),pe.lstat(r),pe.realpath(r)]);if(await xc(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!yr(a,c)||!yr(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let f=[],d=0,p=Buffer.allocUnsafe(i===null?64*1024:Math.min(64*1024,i+1));for(;;){let w=i===null?p.length:i+1-d,k=await s.read(p,0,Math.min(p.length,w),null);if(k.bytesRead===0)break;if(d+=k.bytesRead,i!==null&&d>i)throw new Error(`Native artifact exceeds ${i} bytes: ${t}`);f.push(Buffer.from(p.subarray(0,k.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[v,h,m]=await Promise.all([s.stat(),pe.lstat(r),pe.realpath(r)]);if(await xc(n),!h.isFile()||h.isSymbolicLink()||m!==o||!yr(c,v)||!yr(c,h))throw new Error(`Native artifact changed while reading: ${t}`);let g=Buffer.concat(f,d),N;try{N=new Fh("utf-8",{fatal:!0}).decode(g)}catch(w){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:w})}return{ref:t,size:d,hash:e.includeHash===!1?null:qh("sha256").update(g).digest("hex"),text:N}}finally{await s.close()}}var zs=ai(Ft(),1);import Zt from"path";var os=ai(Ft(),1);import Mt from"path";var qi=64*1024,Nn=1024,bn=64,ss=5,yw=12e4,md=6e5,Nw=[".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/**"],bw=["**/.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"],kw=[...Nw,...bw].sort((e,t)=>e.localeCompare(t,"en"));var re={include:["**/*"],exclude:[...kw],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4};function Sw(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim();if(i.length===0||Mt.posix.isAbsolute(i)||Mt.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${t} must be a project-relative path`);if(i===".")return[];let r=i.replaceAll("\\","/").split("/");if(r.some(n=>n===".."))throw new Error(`${t} must stay inside the project root`);if(r.some(n=>n===""||n==="."))throw new Error(`${t} must not contain empty or dot path segments`);return r}function vt(e){let t=Sw(e,"native.artifact_root");return t.length===0?".":t.join("/")}function gd(e,t="docs"){let i=e??t;if(i!=="legacy"&&i!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return i}function kn(e,t,i=!1){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim().replaceAll("\\","/");if(r.length===0||Mt.posix.isAbsolute(r)||Mt.win32.isAbsolute(r)||/^(?:~|[\\/])/u.test(r))throw new Error(`${t} must be relative to its declared path base`);let n=r.split("/");if(n.some(a=>a===".."))throw new Error(`${t} must stay inside its declared path base`);if(n.some(a=>a===""||a==="."))throw new Error(`${t} must not contain empty or dot path segments`);if(!i&&/[*?]/u.test(r))throw new Error(`${t} cannot contain wildcards`);return n.join("/")}function tt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function wd(e,t,i){let r=e??t;if(r!=="en"&&r!=="zh-CN")throw new Error(`${i} must be en or zh-CN`);return r}function cs(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||e.startsWith("/")||e.split("/").includes(".."))throw new Error(`${t} contains an unsafe pattern`);if(e.length>Nn)throw new Error(`${t} exceeds ${Nn} characters`);let i=0;for(let r=0;r<e.length;r+=1)e[r]==="?"?i+=1:e[r]==="*"&&(i+=1,e[r+1]==="*"&&(r+=1));if(i>bn)throw new Error(`${t} contains more than ${bn} wildcard tokens`);return e}function vd(e,t,i){if(e===void 0)return[...i];if(!Array.isArray(e))throw new Error(`${t} contains an unsafe pattern`);return[...new Set(e.map(r=>cs(r,t)))].sort((r,n)=>r.localeCompare(n,"en"))}function as(e,t,i){let r=e??t;if(!Number.isSafeInteger(r)||r<1)throw new Error(`${i} must be a positive integer`);return r}function Ew(e){if(e===void 0)return{...re,include:[...re.include],exclude:[...re.exclude]};let t=tt(e,"native.snapshot");return{include:vd(t.include,"native.snapshot.include",re.include),exclude:vd(t.exclude,"native.snapshot.exclude",re.exclude),max_files:as(t.max_files,re.max_files,"native.snapshot.max_files"),max_total_bytes:as(t.max_total_bytes,re.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:as(t.max_duration_ms,re.max_duration_ms,"native.snapshot.max_duration_ms")}}function Pw(e){if(e===void 0)return;let t=tt(e,"native.pending_root_move"),i=t.id,r=t.from_artifact_root,n=t.to_artifact_root,a=t.stage;if(typeof i!="string"||!/^[a-f0-9-]{8,}$/u.test(i))throw new Error("native.pending_root_move.id is invalid");if(typeof 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(t.cleanup!==void 0){let s=tt(t.cleanup,"native.pending_root_move.cleanup"),c=s.kind,l=s.state,u=s.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof u!="string"||!/^[a-f0-9]{64}$/u.test(u))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:u}}return{id:i,fromArtifactRoot:vt(r),toArtifactRoot:vt(n),stage:a,...o?{cleanup:o}:{}}}function xw(e){if(e===void 0)return;let t=tt(e,"native.finish");if(t.pull_request===void 0)return{};let i=tt(t.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(Mt.posix.isAbsolute(r[0])||Mt.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??yw;if(!Number.isSafeInteger(n)||n<1||n>md)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${md}`);return{pull_request:{provider:"repository-command",command:r,timeout_ms:n}}}function Rw(e,t={}){let i=tt(e,"native"),r=i.artifact_root??(t.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??ss;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=Pw(i.pending_root_move),c=xw(i.finish);return{artifact_root:vt(r),language:wd(i.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,snapshot:Ew(i.snapshot),...c?{finish:c}:{},...s?{pending_root_move:s}:{}}}function Cw(e){let t=tt(e,"classic"),i=t.context_compression??"off";if(i!=="off"&&i!=="beta")throw new Error("classic.context_compression must be off or beta");let r=t.review_mode??"standard";if(r!=="off"&&r!=="standard"&&r!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let n=t.auto_transition??!0;if(typeof n!="boolean")throw new Error("classic.auto_transition must be true or false");return{artifact_layout:gd(t.artifact_layout),language:wd(t.language,"zh-CN","classic.language"),context_compression:i,review_mode:r,auto_transition:n}}function Aw(e){let i=tt(e,"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)=>kn(r,`hook.allow_paths[${n}]`)))]}}function _w(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function Tw(e,t,i,r,n,a){let o=e.schema!==void 0;if(!(o||e.default_workflow!==void 0||e.workflows!==void 0||!a.allowPartialProject&&e.native!==void 0)||a.allowPartialProject&&!o)return null;if(e.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(e.default_workflow!=="native"&&e.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let c=e.workflows??[e.default_workflow];if(!Array.isArray(c)||c.length===0||c.some(u=>u!=="native"&&u!=="classic"))throw new Error("workflows must contain native and/or classic");let l=[...new Set(c)];if(!l.includes(e.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:e.default_workflow,workflows:l,ambient_resume:n,...t?{hook:t}:{},...i?{native:i}:{},...r?{classic:r}:{}}}function Fi(e,t={}){let i=(0,os.parseDocument)(e,{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=_w(n.ambient_resume),o=n.hook===void 0?void 0:Aw(n.hook),s=n.native===void 0?void 0:Rw(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),c=n.classic===void 0?void 0:Cw(n.classic),l=Tw(n,o,s,c,a,{allowPartialProject:t.allowPartialProject??!1});return{value:n,config:l,ambient_resume:a,...o?{hook:o}:{},...s?{native:s}:{},...c?{classic:c}:{}}}function Sn(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,native:{artifact_root:vt(e),language:t,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:ss,snapshot:{...re,include:[...re.include],exclude:[...re.exclude]}}}}import{createHash as jw}from"crypto";import{promises as xn}from"fs";import it from"path";import{constants as En,promises as gt}from"fs";var ge=class extends Error{reason;constructor(t,i,r){super(i,r),this.name="RaceSafeReadError",this.reason=t}};function ls(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function yd(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function Mi(e){return{dev:e.dev,ino:e.ino,birthtime:ls(e)}}function Pn(e,t){let i=Mi(e),r=Mi(t);return Se(i,r)?A(i,r):A(i,r)&&ls(e)===ls(t)&&yd(e)===yd(t)&&e.size===t.size}async function wt(e,t,i={}){if(!Number.isSafeInteger(t)||t<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 gt.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new ge("not-regular-file",`${r} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new ge("too-large",`${r} exceeds ${t} bytes`);let o=await gt.realpath(e);await i.verify?.("pre-open",{realPath:o,identity:Mi(a)});let s=process.platform==="win32"?En.O_RDONLY:En.O_RDONLY|En.O_NOFOLLOW|En.O_NONBLOCK,c;try{c=await gt.open(e,s)}catch(l){throw l.code==="ELOOP"?new ge("not-regular-file",`${r} must be a regular file`,{cause:l}):l}try{let[l,u,f]=await Promise.all([c.stat({bigint:n}),gt.lstat(e,{bigint:n}),gt.realpath(e)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||f!==o||!Pn(a,l)||!Pn(a,u))throw new ge("changed",`${r} changed while opening`);await i.verify?.("post-open",{realPath:f,identity:Mi(l)}),await i.hooks?.afterOpen?.();let d=[],p=0,v=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let N=t+1-p,{bytesRead:w}=await c.read(v,0,Math.min(v.length,N),null);if(w===0)break;if(p+=w,p>t)throw new ge("too-large",`${r} exceeds ${t} bytes`);d.push(Buffer.from(v.subarray(0,w)))}await i.hooks?.beforeFinalCheck?.();let[h,m,g]=await Promise.all([c.stat({bigint:n}),gt.lstat(e,{bigint:n}),gt.realpath(e)]);if(!m.isFile()||m.isSymbolicLink()||g!==o||!Pn(a,h)||!Pn(a,m))throw new ge("changed",`${r} changed while reading`);return await i.verify?.("post-read",{realPath:g,identity:Mi(h)}),{bytes:Buffer.concat(d,p),stat:h,realPath:g}}finally{await c.close()}}function Iw(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function us(e,t){let i=it.relative(e,t);return i===""||!it.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${it.sep}`)}async function Nd(e,t){let i=it.resolve(e),r=await xn.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return xn.realpath(i)}async function bd(e,t,i,r){let n=e;for(let a=0;a<i.length;a++){n=it.join(n,i[a]);let o;try{o=await xn.lstat(n)}catch(u){if(Iw(u))return{exists:!1,kind:"missing"};throw u}let s=it.relative(e,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 xn.realpath(n);if(!us(t,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 Vt(e,t,i){let r=kn(t,i.label),n=it.resolve(e),a=await Nd(n,i.label),o=r.split("/"),s=it.resolve(n,...o);if(!us(n,s))throw new Error(`${i.label} must stay inside the project root`);let c=await bd(n,a,o,i);return{projectRoot:n,target:s,relative:r,exists:c.exists,kind:c.kind}}async function rt(e,t,i,r){let n=await Vt(e,t,{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 Nd(n.projectRoot,r.label);return wt(n.target,i,{...r,verify:async(o,s)=>{if(!us(a,s.realPath))throw new Error(`${r.label} resolves outside the project root`);await bd(n.projectRoot,a,n.relative.split("/"),{label:r.label,expected:"file"})}})}var Vi=".comet/config.yaml";function $w(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function Rn(e,t={}){return(await Cn(e,t)).document}async function Ow(e){try{return(await rt(e,Vi,qi,{label:Vi})).bytes}catch(t){if($w(t))return null;throw t}}function Hw(e){return e?{exists:!0,sha256:jw("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function Cn(e,t={}){let i=await Ow(e);return{document:i?Fi(i.toString("utf8"),t):null,identity:Hw(i)}}async function ds(e){return(await Rn(e))?.config??null}var gP=16*1024;import{existsSync as Sd,promises as yt}from"fs";import R from"path";import Fw from"os";var An=".comet/config.yaml",Mw=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;async function ps(e){try{return await yt.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Vw(e){try{let t=await yt.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function zt(e,t){let i=R.relative(e,t);return i===""||!R.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${R.sep}`)}async function Wt(e){let t=[],i=e;for(;!await ps(i);){let n=R.dirname(i);if(n===i)break;t.push(R.basename(i)),i=n}let r=await yt.realpath(i);return R.resolve(r,...t.reverse())}async function ms(e){try{return(await yt.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function _n(e){let t=R.resolve(e);try{(await yt.stat(t)).isDirectory()||(t=R.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let i=t,r=R.resolve(Fw.homedir());for(;;){if(!(t===r&&i!==r)){let o=R.join(t,...An.split("/")),s=t===i||await Vw(o);if(await ps(o)&&s)return t}if(await ps(R.join(t,".git")))return t;let a=R.dirname(t);if(a===t)return i;t=a}}function Tn(e){return vt(e)}async function Ww(e,t){let i=Tn(t),r=R.resolve(e,...i.split("/")),n=await yt.realpath(e),a=await Wt(r);if(!zt(n,a))throw new Error("native.artifact_root resolves outside the project root");return r}async function nt(e,t){let i=Tn(t),r=await Ww(e,i),n=R.join(r,"comet");if(await ms(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([Wt(r),Wt(n)]);if(!zt(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=R.resolve(e),c=R.join(s,".comet","runtime","native");if(await ms(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,u]=await Promise.all([yt.realpath(s),Wt(c)]);if(!zt(l,u))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:R.join(e,...An.split("/")),artifactRoot:r,artifactRootRef:i,nativeRoot:n,specsDir:R.join(n,"specs"),changesDir:R.join(n,"changes"),archiveDir:R.join(n,"archive"),runtimeDir:c,changesRuntimeDir:R.join(c,"changes"),locksDir:R.join(c,"locks"),transactionsDir:R.join(c,"transactions")}}function Ed(e){if(!Mw.test(e))throw new Error(`Invalid Native change name: ${e}`)}function xe(e,t){Ed(t);let i=R.join(e.changesRuntimeDir,t);if(!L(e.changesRuntimeDir,i))throw new Error("Native change Runtime path escaped");return i}function vs(e,t){Ed(t);let i=R.join(e.changesDir,t,"runtime");if(!L(e.changesDir,i))throw new Error("Legacy Native change Runtime path escaped");return i}function Re(e,t){let i=xe(e,t);if(Sd(i))return i;let r=vs(e,t);return Sd(r)?r:i}function Ce(e,t){let i=R.resolve(t);if(L(e.runtimeDir,i))return e.runtimeDir;if(L(e.nativeRoot,i))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function L(e,t){return zt(R.resolve(e),R.resolve(t))}async function T(e,t){let i=R.resolve(e),r=R.resolve(t);if(!zt(i,r))throw new Error(`Path is outside the Native root: ${t}`);if(await ms(i))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([Wt(i),Wt(r)]);if(!zt(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return r}function Jw(e="docs",t="en"){return Sn(e,t)}async function we(e){let t=(await Rn(e))?.config??null;return t?.native?t:null}async function zi(e){let t=await we(e);if(t?.native.pending_root_move)throw new Error(`Native root move ${t.native.pending_root_move.id} is incomplete; use comet native doctor --repair`)}async function Pd(e){let t=await _n(e.startPath),i=await we(t);if(!i&&e.allowMissingConfig===!1)throw new Error(`${An} 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=e.explicitArtifactRoot?Tn(e.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??Jw(r??"docs"),a=await nt(t,n.native.artifact_root);return{config:n,paths:a,configured:i!==null}}import{promises as kN}from"fs";import SN from"path";import{AsyncLocalStorage as Gw}from"async_hooks";import{randomUUID as Cd}from"crypto";import{promises as ue}from"fs";import Ad from"os";import U from"path";var xd=16*1024,_d=".coordinator",Uw=5e3,Rd=new Gw,In=new Map;function Kw(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function Yw(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Invalid Native lock metadata: ${t}`);let i=e;if(typeof i.id!="string"||i.id.length===0||typeof i.pid!="number"||!Number.isSafeInteger(i.pid)||i.pid<1||typeof i.hostname!="string"||i.hostname.length===0||typeof i.createdAt!="string"||i.createdAt.length===0||typeof i.operation!="string"||i.operation.length===0)throw new Error(`Invalid Native lock metadata: ${t}`);return i}function Td(e){return{device:e.dev.toString(),inode:e.ino.toString(),size:e.size.toString(),birthtimeNs:e.birthtimeNs.toString(),ctimeNs:e.ctimeNs.toString(),mtimeNs:e.mtimeNs.toString()}}function gs(e,t){let i={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},r={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return Se(i,r)?A(i,r):A(i,r)&&e.size===t.size}function ws(e,t){return gs(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}async function Oe(e){let t,i;try{let r=await wt(e,xd,{bigint:!0,label:"Native lock"});t=r.bytes,i=r.stat}catch(r){if(r.code==="ENOENT")return null;throw r instanceof ge?r.reason==="too-large"?new Error(`Native lock metadata exceeds ${xd} bytes: ${e}`,{cause:r}):r.reason==="not-regular-file"?new Error(`Native lock must be a regular file: ${e}`,{cause:r}):new Error(`Native lock changed while reading: ${e}`,{cause:r}):r}return{file:e,owner:Yw(JSON.parse(t.toString("utf8")),e),identity:Td(i)}}async function Xw(e){return(await Oe(e))?.owner??null}function Id(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==Ad.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=ry(e.owner.pid);return{status:t===!0?"active":t===!1?"stale":"unknown",owner:e.owner,identity:e.identity}}async function Qw(e,t){try{await ue.lstat(t);return}catch(i){if(i.code!=="ENOENT")throw i}try{await ue.rename(e,t)}catch(i){if(i.code!=="ENOENT")throw i}}async function ys(e,t){let i=await Oe(e.file);if(!i)return"missing";if(i.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!ws(i.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await ue.mkdir(t,{recursive:!0});let r=U.join(t,`${U.basename(e.file)}.${e.owner.id}.${Cd()}.removed`);try{await ue.rename(e.file,r)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await Oe(r);if(!n||n.owner.id!==e.owner.id||!gs(n.identity,e.identity))throw await Qw(r,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await ue.rm(r,{force:!0}),"removed"}function jd(e){return{id:Cd(),pid:process.pid,hostname:Ad.hostname(),createdAt:new Date().toISOString(),operation:e}}async function $d(e,t){let i;try{i=await ue.open(e,"wx")}catch(r){if(r.code==="EEXIST"){let n=await Xw(e);throw new Error(`Native lock is already held: ${e}${n?` by pid ${n.pid} for ${n.operation}`:""}`,{cause:r})}throw r}try{return await i.writeFile(JSON.stringify(t,null,2)+`
|
|
144
|
-
`,"utf8"),await i.sync(),Td(await i.stat({bigint:!0}))}finally{await i.close()}}async function Zw(e,t){let i=await T(e.runtimeDir,e.locksDir);await ue.mkdir(i,{recursive:!0});let r=await T(e.runtimeDir,U.join(i,_d));await ue.mkdir(r,{recursive:!0});let n=jd(t),a=U.join(r,`.${n.id}.tmp`),o=U.join(r,`${n.id}.claim`);try{let s=await $d(a,n);await ue.rename(a,o);let c=await Oe(o);if(!c||!gs(s,c.identity))throw new Error(`Native lock coordinator claim changed while publishing: ${o}`);return{file:o,nativeRoot:e.runtimeDir,locksDir:i,owner:n,identity:c.identity}}finally{await ue.rm(a,{force:!0})}}async function ey(e){let t=U.dirname(e.file),i=!1,r=U.basename(e.file);for(let n of await ue.readdir(t,{withFileTypes:!0})){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".claim"))continue;let a=U.join(t,n.name);if(U.resolve(a)!==U.resolve(e.file))try{let o=await Oe(a),s=Id(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await ys(o,t);continue}n.name<r&&(i=!0)}catch{n.name<r&&(i=!0)}}return i}async function Od(e){let t=await Oe(e.file);if(t){if(t.owner.id!==e.owner.id||!ws(t.identity,e.identity))throw new Error(`Native lock coordinator ownership changed: ${e.file}`);await ys(t,U.dirname(e.file))}}async function ty(e,t){let i=Date.now()+Uw;for(;;){let r=await Zw(e,t);if(!await ey(r))return r;if(await Od(r),Date.now()>=i)throw new Error(`Native lock coordinator is busy: ${e.locksDir}`);await new Promise(n=>setTimeout(n,2+Math.floor(Math.random()*7)))}}async function iy(e){let t=
|
|
145
|
-
${bs(t)}`).digest("hex")}var sy="comet.native.acceptance.v1";var
|
|
142
|
+
`,i)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let i=wn(t),r=qt(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=wn(t),r=qt(i);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(t,i){return this.type!=="comment"||this.indent<=i?!1:t.every(r=>r.type==="newline"||r.type==="space")}*documentEnd(t){this.type!=="doc-mode"&&(t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(t){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};cd.Parser=is});var hd=y(Li=>{"use strict";var ld=Vo(),ew=_i(),Bi=ji(),tw=qa(),iw=P(),rw=ts(),ud=rs();function dd(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new rw.LineCounter||null,prettyErrors:t}}function nw(e,t={}){let{lineCounter:i,prettyErrors:r}=dd(t),n=new ud.Parser(i?.addNewLine),a=new ld.Composer(t),o=Array.from(a.compose(n.parse(e)));if(r&&i)for(let s of o)s.errors.forEach(Bi.prettifyError(e,i)),s.warnings.forEach(Bi.prettifyError(e,i));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function fd(e,t={}){let{lineCounter:i,prettyErrors:r}=dd(t),n=new ud.Parser(i?.addNewLine),a=new ld.Composer(t),o=null;for(let s of a.compose(n.parse(e),!0,e.length))if(!o)o=s;else if(o.options.logLevel!=="silent"){o.errors.push(new Bi.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return r&&i&&(o.errors.forEach(Bi.prettifyError(e,i)),o.warnings.forEach(Bi.prettifyError(e,i))),o}function aw(e,t,i){let r;typeof t=="function"?r=t:i===void 0&&t&&typeof t=="object"&&(i=t);let n=fd(e,i);if(!n)return null;if(n.warnings.forEach(a=>tw.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 ow(e,t,i){let r=null;if(typeof t=="function"||Array.isArray(t)?r=t:i===void 0&&t&&(i=t),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(e===void 0){let{keepUndefined:n}=i??t??{};if(!n)return}return iw.isDocument(e)&&!r?e.toString(i):new ew.Document(e,r,i).toString(i)}Li.parse=aw;Li.parseAllDocuments=nw;Li.parseDocument=fd;Li.stringify=ow});var Ft=y(x=>{"use strict";var sw=Vo(),cw=_i(),lw=So(),ns=ji(),uw=pi(),et=P(),dw=Ke(),fw=$(),hw=Xe(),pw=Qe(),mw=vn(),vw=Zo(),gw=ts(),ww=rs(),Nn=hd(),pd=ui();x.Composer=sw.Composer;x.Document=cw.Document;x.Schema=lw.Schema;x.YAMLError=ns.YAMLError;x.YAMLParseError=ns.YAMLParseError;x.YAMLWarning=ns.YAMLWarning;x.Alias=uw.Alias;x.isAlias=et.isAlias;x.isCollection=et.isCollection;x.isDocument=et.isDocument;x.isMap=et.isMap;x.isNode=et.isNode;x.isPair=et.isPair;x.isScalar=et.isScalar;x.isSeq=et.isSeq;x.Pair=dw.Pair;x.Scalar=fw.Scalar;x.YAMLMap=hw.YAMLMap;x.YAMLSeq=pw.YAMLSeq;x.CST=mw;x.Lexer=vw.Lexer;x.LineCounter=gw.LineCounter;x.Parser=ww.Parser;x.parse=Nn.parse;x.parseAllDocuments=Nn.parseAllDocuments;x.parseDocument=Nn.parseDocument;x.stringify=Nn.stringify;x.visit=pd.visit;x.visitAsync=pd.visitAsync});import{randomUUID as zb}from"node:crypto";import{promises as z}from"node:fs";import K from"node:path";import{execFileSync as Ah}from"child_process";import si from"path";function oi(e,t){return Ah("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function _h(e,t){let i=si.normalize(e),r=si.normalize(t);return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function F(e){try{let t=si.resolve(oi(e,["rev-parse","--show-toplevel"])),r=oi(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=r?si.resolve(r.slice(9)):t,a=null;try{a=oi(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!_h(t,n),currentWorktreeRoot:t,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function Sc(e){try{oi(e,["rev-parse","--is-inside-work-tree"]);let t=oi(e,["worktree","list","--porcelain"]).split(/\r?\n/u),i=[],r=null;for(let n of t)n.startsWith("worktree ")?(r&&i.push(r),r={root:si.resolve(n.slice(9)),branch:null,detached:!1}):r&&n.startsWith("branch refs/heads/")?r.branch=n.slice(18):r&&n==="detached"&&(r.detached=!0);return r&&i.push(r),i}catch{return[]}}function lt(e){return Sc(e).map(t=>t.root)}import{randomUUID as Th}from"crypto";import{promises as J}from"fs";import he from"path";function We(e){return e!==0&&e!==0n&&e!=="0"}function Se(e,t){return We(e.dev)&&We(t.dev)&&We(e.ino)&&We(t.ino)}function A(e,t){let i=We(e.dev)&&We(t.dev);if(i&&e.dev!==t.dev)return!1;let r=We(e.ino)&&We(t.ino);return r&&e.ino!==t.ino?!1:i&&r?!0:e.birthtime===t.birthtime}function ba(e,t){let i=he.relative(e,t);return i===""||!he.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${he.sep}`)}function Ih(e,t){return A({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function ka(e,t){return A({dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs},{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs})}function jh(e,t){return ka(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function Ec(e){let t=await J.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native atomic write parent must be a real directory: ${e}`);return{path:e,realPath:await J.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function ci(e){for(let t of e){let i=await J.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!Ih(t,i)||await J.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function $h(e,t){let i=he.resolve(e),r=he.resolve(t);if(!ba(i,r))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let n=[await Ec(i)],a=he.relative(i,r).split(he.sep).filter(Boolean),o=i;for(let s of a){await ci(n),o=he.join(o,s);try{await J.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await Ec(o);if(!ba(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await ci(n),n}async function Oh(e){let t;try{t=await J.open(e,"r"),await t.sync()}catch(i){let r=i.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(r??""))throw i}finally{await t?.close()}}async function Hh(e,t,i={}){let r=he.dirname(e),n=i.containedRoot?await $h(i.containedRoot,r):null;n||await J.mkdir(r,{recursive:!0});let a=he.join(r,`.${he.basename(e)}.${Th()}.tmp`),o,s,c;try{if(await i.beforeTemporaryOpen?.(),o=await J.open(a,"wx"),s=await o.stat(),n){let[l,u]=await Promise.all([J.lstat(a),J.realpath(a)]);if(await ci(n),!l.isFile()||l.isSymbolicLink()||!ka(s,l)||!ba(n[0].realPath,u))throw new Error("Native atomic write temporary file opened outside its managed parent")}if(typeof t=="string"?await o.writeFile(t,"utf8"):await o.writeFile(t),await o.sync(),c=await o.stat(),!ka(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 ci(n);let l=await J.lstat(a);if(!l.isFile()||l.isSymbolicLink()||!c||!jh(l,c))throw new Error("Native atomic write temporary file changed before commit")}i.exclusive?(await J.link(a,e),await J.unlink(a)):await J.rename(a,e),await Oh(r)}catch(l){if(await o?.close(),!n)await J.rm(a,{force:!0});else try{await ci(n),await J.rm(a,{force:!0})}catch{}throw l}}async function Y(e,t,i={}){await Hh(e,t,i)}async function X(e,t,i={}){await Y(e,JSON.stringify(t,null,2)+`
|
|
143
|
+
`,i)}import{createHash as qh}from"node:crypto";import{promises as pe}from"node:fs";import ce from"node:path";import{TextDecoder as Fh}from"node:util";var Dh=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),Bh=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function Lh(e){return e.toLowerCase().startsWith(".env")}function li(e){let i=e.replaceAll("\\","/").split("/").filter(Boolean).map(r=>r.toLowerCase());return i.some(r=>Lh(r))?"environment-file":i.some(r=>Bh.has(r))?"credential-config":i.includes(".git")?"git-metadata":i.some(r=>Dh.has(r))?"dependency-or-cache":i.join("/")===".comet/config.yaml"?"comet-config":i.join("/")===".comet/current-change.json"?"comet-selection":null}var br=1024*1024;function Sa(e,t){let i=ce.relative(e,t);return i===""||!ce.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${ce.sep}`)}function Mh(e){let t=ce.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(n=>{let a=n.codePointAt(0)??0;return a<=31||a===127})||ce.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||t!==e||t==="."||e.endsWith("/"))throw new Error(`Native artifact ref must be normalized and relative: ${e}`);let i=e.toLowerCase(),r=li(e);if(r||i==="runtime"||i.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${r??"native-runtime"}): ${e}`);return e}function Vh(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function Wh(e,t){return A({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Nr(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return Se(i,r)?A(i,r):A(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Pc(e){let t=await pe.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await pe.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function zh(e,t){let i=ce.resolve(e),r=ce.resolve(t);if(!Sa(i,r))throw new Error("Native artifact path is outside its root");let n=[await Pc(i)],a=i;for(let o of ce.relative(i,r).split(ce.sep).filter(Boolean)){a=ce.join(a,o);let s=await Pc(a);if(!Sa(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function xc(e){for(let t of e){let i=await pe.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!Wh(t,i)||await pe.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function j(e){let t=Mh(e.ref),i=e.maxBytes===null?null:Vh(e.maxBytes??br),r=ce.resolve(e.root,...t.split("/")),n=await zh(e.root,ce.dirname(r));await e.hooks?.afterParentChainCaptured?.();let a=await pe.lstat(r);if(!a.isFile()||a.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${t}`);if(i!==null&&a.size>i)throw new Error(`Native artifact exceeds ${i} bytes: ${t}`);let o=await pe.realpath(r);if(!Sa(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await pe.open(r,"r");try{let[c,l,u]=await Promise.all([s.stat(),pe.lstat(r),pe.realpath(r)]);if(await xc(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!Nr(a,c)||!Nr(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let f=[],d=0,p=Buffer.allocUnsafe(i===null?64*1024:Math.min(64*1024,i+1));for(;;){let w=i===null?p.length:i+1-d,k=await s.read(p,0,Math.min(p.length,w),null);if(k.bytesRead===0)break;if(d+=k.bytesRead,i!==null&&d>i)throw new Error(`Native artifact exceeds ${i} bytes: ${t}`);f.push(Buffer.from(p.subarray(0,k.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[v,h,m]=await Promise.all([s.stat(),pe.lstat(r),pe.realpath(r)]);if(await xc(n),!h.isFile()||h.isSymbolicLink()||m!==o||!Nr(c,v)||!Nr(c,h))throw new Error(`Native artifact changed while reading: ${t}`);let g=Buffer.concat(f,d),N;try{N=new Fh("utf-8",{fatal:!0}).decode(g)}catch(w){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:w})}return{ref:t,size:d,hash:e.includeHash===!1?null:qh("sha256").update(g).digest("hex"),text:N}}finally{await s.close()}}var zs=ai(Ft(),1);import Zt from"path";var os=ai(Ft(),1);import Mt from"path";var qi=64*1024,bn=1024,kn=64,ss=5,yw=12e4,md=6e5,Nw=[".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/**"],bw=["**/.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"],kw=[...Nw,...bw].sort((e,t)=>e.localeCompare(t,"en"));var re={include:["**/*"],exclude:[...kw],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4};function Sw(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim();if(i.length===0||Mt.posix.isAbsolute(i)||Mt.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${t} must be a project-relative path`);if(i===".")return[];let r=i.replaceAll("\\","/").split("/");if(r.some(n=>n===".."))throw new Error(`${t} must stay inside the project root`);if(r.some(n=>n===""||n==="."))throw new Error(`${t} must not contain empty or dot path segments`);return r}function vt(e){let t=Sw(e,"native.artifact_root");return t.length===0?".":t.join("/")}function gd(e,t="docs"){let i=e??t;if(i!=="legacy"&&i!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return i}function Sn(e,t,i=!1){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim().replaceAll("\\","/");if(r.length===0||Mt.posix.isAbsolute(r)||Mt.win32.isAbsolute(r)||/^(?:~|[\\/])/u.test(r))throw new Error(`${t} must be relative to its declared path base`);let n=r.split("/");if(n.some(a=>a===".."))throw new Error(`${t} must stay inside its declared path base`);if(n.some(a=>a===""||a==="."))throw new Error(`${t} must not contain empty or dot path segments`);if(!i&&/[*?]/u.test(r))throw new Error(`${t} cannot contain wildcards`);return n.join("/")}function tt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function wd(e,t,i){let r=e??t;if(r!=="en"&&r!=="zh-CN")throw new Error(`${i} must be en or zh-CN`);return r}function cs(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||e.startsWith("/")||e.split("/").includes(".."))throw new Error(`${t} contains an unsafe pattern`);if(e.length>bn)throw new Error(`${t} exceeds ${bn} characters`);let i=0;for(let r=0;r<e.length;r+=1)e[r]==="?"?i+=1:e[r]==="*"&&(i+=1,e[r+1]==="*"&&(r+=1));if(i>kn)throw new Error(`${t} contains more than ${kn} wildcard tokens`);return e}function vd(e,t,i){if(e===void 0)return[...i];if(!Array.isArray(e))throw new Error(`${t} contains an unsafe pattern`);return[...new Set(e.map(r=>cs(r,t)))].sort((r,n)=>r.localeCompare(n,"en"))}function as(e,t,i){let r=e??t;if(!Number.isSafeInteger(r)||r<1)throw new Error(`${i} must be a positive integer`);return r}function Ew(e){if(e===void 0)return{...re,include:[...re.include],exclude:[...re.exclude]};let t=tt(e,"native.snapshot");return{include:vd(t.include,"native.snapshot.include",re.include),exclude:vd(t.exclude,"native.snapshot.exclude",re.exclude),max_files:as(t.max_files,re.max_files,"native.snapshot.max_files"),max_total_bytes:as(t.max_total_bytes,re.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:as(t.max_duration_ms,re.max_duration_ms,"native.snapshot.max_duration_ms")}}function Pw(e){if(e===void 0)return;let t=tt(e,"native.pending_root_move"),i=t.id,r=t.from_artifact_root,n=t.to_artifact_root,a=t.stage;if(typeof i!="string"||!/^[a-f0-9-]{8,}$/u.test(i))throw new Error("native.pending_root_move.id is invalid");if(typeof 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(t.cleanup!==void 0){let s=tt(t.cleanup,"native.pending_root_move.cleanup"),c=s.kind,l=s.state,u=s.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof u!="string"||!/^[a-f0-9]{64}$/u.test(u))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:u}}return{id:i,fromArtifactRoot:vt(r),toArtifactRoot:vt(n),stage:a,...o?{cleanup:o}:{}}}function xw(e){if(e===void 0)return;let t=tt(e,"native.finish");if(t.pull_request===void 0)return{};let i=tt(t.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(Mt.posix.isAbsolute(r[0])||Mt.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??yw;if(!Number.isSafeInteger(n)||n<1||n>md)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${md}`);return{pull_request:{provider:"repository-command",command:r,timeout_ms:n}}}function Rw(e,t={}){let i=tt(e,"native"),r=i.artifact_root??(t.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??ss;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=Pw(i.pending_root_move),c=xw(i.finish);return{artifact_root:vt(r),language:wd(i.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,snapshot:Ew(i.snapshot),...c?{finish:c}:{},...s?{pending_root_move:s}:{}}}function Cw(e){let t=tt(e,"classic"),i=t.context_compression??"off";if(i!=="off"&&i!=="beta")throw new Error("classic.context_compression must be off or beta");let r=t.review_mode??"standard";if(r!=="off"&&r!=="standard"&&r!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let n=t.auto_transition??!0;if(typeof n!="boolean")throw new Error("classic.auto_transition must be true or false");return{artifact_layout:gd(t.artifact_layout),language:wd(t.language,"zh-CN","classic.language"),context_compression:i,review_mode:r,auto_transition:n}}function Aw(e){let i=tt(e,"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)=>Sn(r,`hook.allow_paths[${n}]`)))]}}function _w(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function Tw(e,t,i,r,n,a){let o=e.schema!==void 0;if(!(o||e.default_workflow!==void 0||e.workflows!==void 0||!a.allowPartialProject&&e.native!==void 0)||a.allowPartialProject&&!o)return null;if(e.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(e.default_workflow!=="native"&&e.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let c=e.workflows??[e.default_workflow];if(!Array.isArray(c)||c.length===0||c.some(u=>u!=="native"&&u!=="classic"))throw new Error("workflows must contain native and/or classic");let l=[...new Set(c)];if(!l.includes(e.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:e.default_workflow,workflows:l,ambient_resume:n,...t?{hook:t}:{},...i?{native:i}:{},...r?{classic:r}:{}}}function Fi(e,t={}){let i=(0,os.parseDocument)(e,{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=_w(n.ambient_resume),o=n.hook===void 0?void 0:Aw(n.hook),s=n.native===void 0?void 0:Rw(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),c=n.classic===void 0?void 0:Cw(n.classic),l=Tw(n,o,s,c,a,{allowPartialProject:t.allowPartialProject??!1});return{value:n,config:l,ambient_resume:a,...o?{hook:o}:{},...s?{native:s}:{},...c?{classic:c}:{}}}function En(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,native:{artifact_root:vt(e),language:t,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:ss,snapshot:{...re,include:[...re.include],exclude:[...re.exclude]}}}}import{createHash as jw}from"crypto";import{promises as Rn}from"fs";import it from"path";import{constants as Pn,promises as gt}from"fs";var ge=class extends Error{reason;constructor(t,i,r){super(i,r),this.name="RaceSafeReadError",this.reason=t}};function ls(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function yd(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function Mi(e){return{dev:e.dev,ino:e.ino,birthtime:ls(e)}}function xn(e,t){let i=Mi(e),r=Mi(t);return Se(i,r)?A(i,r):A(i,r)&&ls(e)===ls(t)&&yd(e)===yd(t)&&e.size===t.size}async function wt(e,t,i={}){if(!Number.isSafeInteger(t)||t<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 gt.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new ge("not-regular-file",`${r} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new ge("too-large",`${r} exceeds ${t} bytes`);let o=await gt.realpath(e);await i.verify?.("pre-open",{realPath:o,identity:Mi(a)});let s=process.platform==="win32"?Pn.O_RDONLY:Pn.O_RDONLY|Pn.O_NOFOLLOW|Pn.O_NONBLOCK,c;try{c=await gt.open(e,s)}catch(l){throw l.code==="ELOOP"?new ge("not-regular-file",`${r} must be a regular file`,{cause:l}):l}try{let[l,u,f]=await Promise.all([c.stat({bigint:n}),gt.lstat(e,{bigint:n}),gt.realpath(e)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||f!==o||!xn(a,l)||!xn(a,u))throw new ge("changed",`${r} changed while opening`);await i.verify?.("post-open",{realPath:f,identity:Mi(l)}),await i.hooks?.afterOpen?.();let d=[],p=0,v=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let N=t+1-p,{bytesRead:w}=await c.read(v,0,Math.min(v.length,N),null);if(w===0)break;if(p+=w,p>t)throw new ge("too-large",`${r} exceeds ${t} bytes`);d.push(Buffer.from(v.subarray(0,w)))}await i.hooks?.beforeFinalCheck?.();let[h,m,g]=await Promise.all([c.stat({bigint:n}),gt.lstat(e,{bigint:n}),gt.realpath(e)]);if(!m.isFile()||m.isSymbolicLink()||g!==o||!xn(a,h)||!xn(a,m))throw new ge("changed",`${r} changed while reading`);return await i.verify?.("post-read",{realPath:g,identity:Mi(h)}),{bytes:Buffer.concat(d,p),stat:h,realPath:g}}finally{await c.close()}}function Iw(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function us(e,t){let i=it.relative(e,t);return i===""||!it.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${it.sep}`)}async function Nd(e,t){let i=it.resolve(e),r=await Rn.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return Rn.realpath(i)}async function bd(e,t,i,r){let n=e;for(let a=0;a<i.length;a++){n=it.join(n,i[a]);let o;try{o=await Rn.lstat(n)}catch(u){if(Iw(u))return{exists:!1,kind:"missing"};throw u}let s=it.relative(e,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 Rn.realpath(n);if(!us(t,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 Vt(e,t,i){let r=Sn(t,i.label),n=it.resolve(e),a=await Nd(n,i.label),o=r.split("/"),s=it.resolve(n,...o);if(!us(n,s))throw new Error(`${i.label} must stay inside the project root`);let c=await bd(n,a,o,i);return{projectRoot:n,target:s,relative:r,exists:c.exists,kind:c.kind}}async function rt(e,t,i,r){let n=await Vt(e,t,{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 Nd(n.projectRoot,r.label);return wt(n.target,i,{...r,verify:async(o,s)=>{if(!us(a,s.realPath))throw new Error(`${r.label} resolves outside the project root`);await bd(n.projectRoot,a,n.relative.split("/"),{label:r.label,expected:"file"})}})}var Vi=".comet/config.yaml";function $w(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function Cn(e,t={}){return(await An(e,t)).document}async function Ow(e){try{return(await rt(e,Vi,qi,{label:Vi})).bytes}catch(t){if($w(t))return null;throw t}}function Hw(e){return e?{exists:!0,sha256:jw("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function An(e,t={}){let i=await Ow(e);return{document:i?Fi(i.toString("utf8"),t):null,identity:Hw(i)}}async function ds(e){return(await Cn(e))?.config??null}var vP=16*1024;import{existsSync as Sd,promises as yt}from"fs";import R from"path";import Fw from"os";var _n=".comet/config.yaml",Mw=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;async function ps(e){try{return await yt.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Vw(e){try{let t=await yt.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function zt(e,t){let i=R.relative(e,t);return i===""||!R.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${R.sep}`)}async function Wt(e){let t=[],i=e;for(;!await ps(i);){let n=R.dirname(i);if(n===i)break;t.push(R.basename(i)),i=n}let r=await yt.realpath(i);return R.resolve(r,...t.reverse())}async function ms(e){try{return(await yt.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Tn(e){let t=R.resolve(e);try{(await yt.stat(t)).isDirectory()||(t=R.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let i=t,r=R.resolve(Fw.homedir());for(;;){if(!(t===r&&i!==r)){let o=R.join(t,..._n.split("/")),s=t===i||await Vw(o);if(await ps(o)&&s)return t}if(await ps(R.join(t,".git")))return t;let a=R.dirname(t);if(a===t)return i;t=a}}function In(e){return vt(e)}async function Ww(e,t){let i=In(t),r=R.resolve(e,...i.split("/")),n=await yt.realpath(e),a=await Wt(r);if(!zt(n,a))throw new Error("native.artifact_root resolves outside the project root");return r}async function nt(e,t){let i=In(t),r=await Ww(e,i),n=R.join(r,"comet");if(await ms(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([Wt(r),Wt(n)]);if(!zt(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=R.resolve(e),c=R.join(s,".comet","runtime","native");if(await ms(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,u]=await Promise.all([yt.realpath(s),Wt(c)]);if(!zt(l,u))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:R.join(e,..._n.split("/")),artifactRoot:r,artifactRootRef:i,nativeRoot:n,specsDir:R.join(n,"specs"),changesDir:R.join(n,"changes"),archiveDir:R.join(n,"archive"),runtimeDir:c,changesRuntimeDir:R.join(c,"changes"),locksDir:R.join(c,"locks"),transactionsDir:R.join(c,"transactions")}}function Ed(e){if(!Mw.test(e))throw new Error(`Invalid Native change name: ${e}`)}function xe(e,t){Ed(t);let i=R.join(e.changesRuntimeDir,t);if(!L(e.changesRuntimeDir,i))throw new Error("Native change Runtime path escaped");return i}function vs(e,t){Ed(t);let i=R.join(e.changesDir,t,"runtime");if(!L(e.changesDir,i))throw new Error("Legacy Native change Runtime path escaped");return i}function Re(e,t){let i=xe(e,t);if(Sd(i))return i;let r=vs(e,t);return Sd(r)?r:i}function Ce(e,t){let i=R.resolve(t);if(L(e.runtimeDir,i))return e.runtimeDir;if(L(e.nativeRoot,i))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function L(e,t){return zt(R.resolve(e),R.resolve(t))}async function T(e,t){let i=R.resolve(e),r=R.resolve(t);if(!zt(i,r))throw new Error(`Path is outside the Native root: ${t}`);if(await ms(i))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([Wt(i),Wt(r)]);if(!zt(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return r}function Jw(e="docs",t="en"){return En(e,t)}async function we(e){let t=(await Cn(e))?.config??null;return t?.native?t:null}async function zi(e){let t=await we(e);if(t?.native.pending_root_move)throw new Error(`Native root move ${t.native.pending_root_move.id} is incomplete; use comet native doctor --repair`)}async function Pd(e){let t=await Tn(e.startPath),i=await we(t);if(!i&&e.allowMissingConfig===!1)throw new Error(`${_n} 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=e.explicitArtifactRoot?In(e.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??Jw(r??"docs"),a=await nt(t,n.native.artifact_root);return{config:n,paths:a,configured:i!==null}}import{promises as kN}from"fs";import SN from"path";import{AsyncLocalStorage as Gw}from"async_hooks";import{randomUUID as Cd}from"crypto";import{promises as ue}from"fs";import Ad from"os";import U from"path";var xd=16*1024,_d=".coordinator",Uw=5e3,Rd=new Gw,jn=new Map;function Kw(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function Yw(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Invalid Native lock metadata: ${t}`);let i=e;if(typeof i.id!="string"||i.id.length===0||typeof i.pid!="number"||!Number.isSafeInteger(i.pid)||i.pid<1||typeof i.hostname!="string"||i.hostname.length===0||typeof i.createdAt!="string"||i.createdAt.length===0||typeof i.operation!="string"||i.operation.length===0)throw new Error(`Invalid Native lock metadata: ${t}`);return i}function Td(e){return{device:e.dev.toString(),inode:e.ino.toString(),size:e.size.toString(),birthtimeNs:e.birthtimeNs.toString(),ctimeNs:e.ctimeNs.toString(),mtimeNs:e.mtimeNs.toString()}}function gs(e,t){let i={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},r={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return Se(i,r)?A(i,r):A(i,r)&&e.size===t.size}function ws(e,t){return gs(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}async function Oe(e){let t,i;try{let r=await wt(e,xd,{bigint:!0,label:"Native lock"});t=r.bytes,i=r.stat}catch(r){if(r.code==="ENOENT")return null;throw r instanceof ge?r.reason==="too-large"?new Error(`Native lock metadata exceeds ${xd} bytes: ${e}`,{cause:r}):r.reason==="not-regular-file"?new Error(`Native lock must be a regular file: ${e}`,{cause:r}):new Error(`Native lock changed while reading: ${e}`,{cause:r}):r}return{file:e,owner:Yw(JSON.parse(t.toString("utf8")),e),identity:Td(i)}}async function Xw(e){return(await Oe(e))?.owner??null}function Id(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==Ad.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=ry(e.owner.pid);return{status:t===!0?"active":t===!1?"stale":"unknown",owner:e.owner,identity:e.identity}}async function Qw(e,t){try{await ue.lstat(t);return}catch(i){if(i.code!=="ENOENT")throw i}try{await ue.rename(e,t)}catch(i){if(i.code!=="ENOENT")throw i}}async function ys(e,t){let i=await Oe(e.file);if(!i)return"missing";if(i.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!ws(i.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await ue.mkdir(t,{recursive:!0});let r=U.join(t,`${U.basename(e.file)}.${e.owner.id}.${Cd()}.removed`);try{await ue.rename(e.file,r)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await Oe(r);if(!n||n.owner.id!==e.owner.id||!gs(n.identity,e.identity))throw await Qw(r,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await ue.rm(r,{force:!0}),"removed"}function jd(e){return{id:Cd(),pid:process.pid,hostname:Ad.hostname(),createdAt:new Date().toISOString(),operation:e}}async function $d(e,t){let i;try{i=await ue.open(e,"wx")}catch(r){if(r.code==="EEXIST"){let n=await Xw(e);throw new Error(`Native lock is already held: ${e}${n?` by pid ${n.pid} for ${n.operation}`:""}`,{cause:r})}throw r}try{return await i.writeFile(JSON.stringify(t,null,2)+`
|
|
144
|
+
`,"utf8"),await i.sync(),Td(await i.stat({bigint:!0}))}finally{await i.close()}}async function Zw(e,t){let i=await T(e.runtimeDir,e.locksDir);await ue.mkdir(i,{recursive:!0});let r=await T(e.runtimeDir,U.join(i,_d));await ue.mkdir(r,{recursive:!0});let n=jd(t),a=U.join(r,`.${n.id}.tmp`),o=U.join(r,`${n.id}.claim`);try{let s=await $d(a,n);await ue.rename(a,o);let c=await Oe(o);if(!c||!gs(s,c.identity))throw new Error(`Native lock coordinator claim changed while publishing: ${o}`);return{file:o,nativeRoot:e.runtimeDir,locksDir:i,owner:n,identity:c.identity}}finally{await ue.rm(a,{force:!0})}}async function ey(e){let t=U.dirname(e.file),i=!1,r=U.basename(e.file);for(let n of await ue.readdir(t,{withFileTypes:!0})){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".claim"))continue;let a=U.join(t,n.name);if(U.resolve(a)!==U.resolve(e.file))try{let o=await Oe(a),s=Id(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await ys(o,t);continue}n.name<r&&(i=!0)}catch{n.name<r&&(i=!0)}}return i}async function Od(e){let t=await Oe(e.file);if(t){if(t.owner.id!==e.owner.id||!ws(t.identity,e.identity))throw new Error(`Native lock coordinator ownership changed: ${e.file}`);await ys(t,U.dirname(e.file))}}async function ty(e,t){let i=Date.now()+Uw;for(;;){let r=await Zw(e,t);if(!await ey(r))return r;if(await Od(r),Date.now()>=i)throw new Error(`Native lock coordinator is busy: ${e.locksDir}`);await new Promise(n=>setTimeout(n,2+Math.floor(Math.random()*7)))}}async function iy(e){let t=jn.get(e)??Promise.resolve(),i,r=new Promise(a=>{i=a}),n=t.then(()=>r);return jn.set(e,n),await t,()=>{i(),jn.get(e)===n&&jn.delete(e)}}async function Hd(e,t,i){let r=U.resolve(e.locksDir),n=Rd.getStore();if(n?.has(r))return i();let a=await iy(r);try{let o=await ty(e,t),s=new Map(n??[]);return s.set(r,o),await Rd.run(s,async()=>{try{return await i()}finally{await Od(o)}})}finally{a()}}async function $n(e,t,i){return Hd(e,`acquire ${t}`,async()=>{let r=await T(e.runtimeDir,e.locksDir);await ue.mkdir(r,{recursive:!0});let n=await T(e.runtimeDir,U.join(r,Kw(t))),a=jd(i),o=await $d(n,a);return{file:n,nativeRoot:e.runtimeDir,locksDir:r,owner:a,identity:o}})}async function On(e){await Oe(e.file)&&await Hd({runtimeDir:e.nativeRoot,locksDir:e.locksDir},`release ${U.basename(e.file)}`,async()=>{let t=await Oe(e.file);if(!t)return;if(t.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!ws(t.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);let i=U.join(e.locksDir,_d);await ys(t,i)})}function ry(e){try{return process.kill(e,0),!0}catch(t){let i=t.code;return i==="ESRCH"?!1:i==="EPERM"?!0:null}}async function Dd(e){return Id(await Oe(e))}import $s from"node:path";import Oy from"node:path";import Ld from"node:path";import{createHash as ny}from"crypto";function ye(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function ay(e,t){t.has(e)&&ye("cyclic structures are not supported"),t.add(e);try{let i=Object.keys(e);for(let r=0;r<e.length;r+=1)Object.prototype.hasOwnProperty.call(e,r)||ye("sparse arrays are not supported");return(i.length!==e.length||i.some((r,n)=>r!==String(n)))&&ye("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&ye("symbol properties are not supported"),`[${e.map(r=>Ns(r,t)).join(",")}]`}finally{t.delete(e)}}function oy(e,t){let i=Object.getPrototypeOf(e);i!==Object.prototype&&i!==null&&ye("only plain objects are supported"),t.has(e)&&ye("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&ye("symbol properties are not supported"),t.add(e);try{let r=Object.getOwnPropertyDescriptors(e);return`{${Object.keys(e).sort().map(o=>{let s=r[o];return(!s||!("value"in s))&&ye("accessor properties are not supported"),`${JSON.stringify(o)}:${Ns(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function Ns(e,t){if(e===null)return"null";switch(typeof e){case"boolean":return e?"true":"false";case"string":return JSON.stringify(e);case"number":return Number.isFinite(e)||ye("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?ay(e,t):oy(e,t);case"bigint":case"function":case"symbol":case"undefined":return ye(`${typeof e} values are not supported`)}return ye("unsupported value type")}function bs(e){return Ns(e,new Set)}function ee(e,t){if(e.length===0)throw new TypeError("Canonical hash tag must be non-empty");if(/[\r\n]/u.test(e))throw new TypeError("Canonical hash tag must not contain a line break");return ny("sha256").update(`${e}
|
|
145
|
+
${bs(t)}`).digest("hex")}var sy="comet.native.acceptance.v1";var KP=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),Ui=Object.freeze({maxCriteria:1024});function Ss(e){let t=/^ {0,3}(#{1,6})[ \t]+(.+?)[ \t]*$/u.exec(e);return t?{level:t[1].length,text:t[2].replace(/[ \t]+#+[ \t]*$/u,"").trim()}:null}function ks(e,t){let i=/^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(e);if(!i)return t;let r=i[1][0];return t===null?{marker:r,length:i[1].length}:r===t.marker&&i[1].length>=t.length&&i[2].trim().length===0?null:t}function Bd(e){return e.includes("-->")||e.includes("--!>")}function*Ji(e){let t=null,i=!1,r=null,n=new Set(["code","pre","script","style","svg","template"]),a=e.replace(/\r\n?/gu,`
|
|
146
146
|
`),o=0,s=0;for(;o<=a.length;){let c=a.indexOf(`
|
|
147
147
|
`,o),l=c===-1?a.slice(o):a.slice(o,c);if(yield{line:l,body:t===null&&!i&&r===null,index:s},s+=1,t!==null)t=ks(l,t);else if(i)Bd(l)&&(i=!1);else if(r!==null)new RegExp(`</${r}\\s*>`,"iu").test(l)&&(r=null);else{let f=ks(l,null);if(f!==null)t=f;else{let d=l.trimStart();if(d.startsWith("<!--")&&!Bd(d))i=!0;else{let p=/^<([A-Za-z][A-Za-z0-9-]*)\b[^>]*>/u.exec(d);p&&n.has(p[1].toLowerCase())&&!d.startsWith("</")&&!d.endsWith("/>")&&!new RegExp(`</${p[1]}\\s*>`,"iu").test(d)&&(r=p[1])}}}if(c===-1)break;o=c+1}}function Gi(e){return e.normalize("NFC").replace(/\s+/gu," ").trim()}function Es(e,t,i,r=[],n="content-hash"){let a=Gi(i),o=t.replaceAll("\\","/").trim(),s=r.map(Gi);if(a.length===0)throw new Error(`${e} acceptance criterion must not be empty`);if(o.length===0)throw new Error(`${e} acceptance criterion source must not be empty`);return{id:n==="content-hash"?`acceptance-${ee(sy,{kind:e,source:o,context:s,text:a})}`:"",kind:e,source:o,context:s,text:a}}function Ps(e,t,i="content-hash"){let r=new Set;for(let n of e){let a=i==="content-hash"?n.id:JSON.stringify([n.kind,n.source,n.context,n.text]);if(r.has(a))throw new Error(`${t} contains duplicate acceptance criteria`);r.add(a)}return e}function cy(e){let t=null,i=null,r=0,n=0;for(let{line:a,body:o,index:s}of Ji(e)){n=s+1;let c=o?Ss(a):null;c?.level===1&&(c.text.toLocaleLowerCase("en-US")==="acceptance examples"?(r+=1,r===1&&(t=s+1)):t!==null&&i===null&&(i=s))}if(r===0||t===null)return null;if(r!==1)throw new Error("Brief must contain exactly one Acceptance examples section");return{start:t,end:i??n}}function xs(e,t="brief.md",i=Ui.maxCriteria,r="content-hash"){if(!Number.isSafeInteger(i)||i<0)throw new Error("Native brief acceptance budget is invalid");let n=cy(e);if(n===null)return[];let a=null;for(let{line:l,body:u,index:f}of Ji(e)){if(f<n.start||f>=n.end)continue;let d=u?/^( {0,3})[-*+][ \t]+/u.exec(l):null;if(d===null)continue;let p=d[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:u,index:f}of Ji(e)){if(f<n.start||f>=n.end)continue;let d=u?/^( {0,3})[-*+][ \t]+(.*)$/u.exec(l):null;d&&d[1].length===a?(c(),s=[d[2]]):s!==null&&s.push(l)}return c(),Ps(o.map(l=>Es("brief-example",t,l.join(`
|
|
148
148
|
`),[],r)),"Brief",r)}function Rs(e,t="spec.md",i=Ui.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(Es("spec-scenario",t,[o.title,...o.body].join(`
|
|
149
|
-
`),o.context,r)),o=null}};for(let{line:c,body:l}of Ji(e)){let u=l?Ss(c):null,f=u?/^Scenario\s*:\s*(.*)$/iu.exec(u.text):null;if(f){for(s();a.at(-1)&&a.at(-1).level>=u.level;)a.pop();let d=Gi(f[1]);if(d.length===0)throw new Error("Scenario title must not be empty");o={level:u.level,title:d,body:[],context:a.map(p=>p.text)}}else if(u){for(o!==null&&u.level<=o.level?s():o!==null&&o.body.push(c);a.at(-1)&&a.at(-1).level>=u.level;)a.pop();a.push(u)}else o!==null&&l&&o.body.push(c)}return s(),Ps(n,"Specification",r)}function Cs(e,t="spec.md",i=Ui.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(Es("spec-must",t,s.parts.join(" "),s.context,r)),s=null}},l=()=>a.some(u=>/^(?:non-?goals?|非目标)$/iu.test(u.text.trim()));for(let{line:u,body:f}of Ji(e)){let d=f?Ss(u):null;if(d){for(c(),o!==null&&d.level<=o&&(o=null);a.at(-1)&&a.at(-1).level>=d.level;)a.pop();a.push(d),/^Scenario\s*:/iu.test(d.text)&&(o=d.level);continue}let p=u.trim();if(!f||o!==null||l()){c();continue}if(p.length===0||ks(u,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(u);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(),Ps(n,"Specification mandatory requirements",r)}var ly=/^A[1-9]\d*$/u;function qd(e,t){if(e.length===0||e!==e.trim()||e.includes("\\")||Ld.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||Ld.posix.normalize(e)!==e||e==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized change-relative ref`);return e}function uy(e,t){return e.localeCompare(t,"en")}function On(e){let t=qd(e.briefSource??"brief.md","Native brief source"),i=[...e.specs??[]].sort((a,o)=>uy(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=xs(e.briefMarkdown,t,Number.MAX_SAFE_INTEGER,"none").map(({source:a,text:o})=>({source:a,text:o}));for(let a of i){let o=qd(a.source,`Native spec source for ${a.capability}`);r.push(...Rs(a.markdown,o,Number.MAX_SAFE_INTEGER,"none").map(({text:s})=>({source:o,text:s})),...Cs(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=Gi(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 Fd(e){let t=e.map(({id:i})=>i);if(new Set(t).size!==t.length)throw new Error("Native acceptance IDs must be unique");for(let i=0;i<t.length;i+=1)if(!ly.test(t[i])||t[i]!==`A${i+1}`)throw new Error("Native acceptance IDs must be the contiguous sequence A1..An")}function Md(e,t){return e.length===t.length&&e.every((i,r)=>i.source===t[r]?.source&&i.text===t[r]?.text)}var Bn=ai(Ft(),1);import{promises as dy}from"node:fs";var Jt="comet.native.v4",Ki="comet.native.local-execution.v4";function As(){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 fy=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,hy=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,py=/^A[1-9][0-9]*$/u,my=/^[a-f0-9]{64}$/u,vy=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"]),Dn=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 te(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ie(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function W(e,t,i){if(typeof e!="string"||!i?.empty&&e.length===0)throw new Error(`${t} must be ${i?.empty?"a string":"a non-empty string"}`);return e}function Ts(e,t){return e===null?null:W(e,t)}function gy(e,t){let i=W(e,t);if(!my.test(i))throw new Error(`${t} must be a SHA-256 hash`);return i}function Gt(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function _(e,t,i=0){if(!Number.isSafeInteger(e)||e<i)throw new Error(`${t} must be a safe integer greater than or equal to ${i}`);return e}function wy(e,t){return e===null?null:_(e,t,Number.MIN_SAFE_INTEGER)}function V(e,t,i){if(typeof e!="string"||!t.includes(e))throw new Error(`${i} must be one of: ${t.join(", ")}`);return e}function Ae(e,t,i){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((r,n)=>i(r,n))}function Ln(e,t){return Ae(e,t,(i,r)=>W(i,`${t}[${r}]`))}function Nt(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function Ut(e,t){let i=W(e,t);if(Number.isNaN(Date.parse(i)))throw new Error(`${t} must be an ISO date or timestamp`);return i}function Is(e,t,i=!1){let r=W(e,t);if(r.includes("\\")||r.startsWith("/")||/^[A-Za-z]:/u.test(r)||r.split("/").includes("..")||!i&&(r==="."||r.split("/").includes(".")))throw new Error(`${t} must be a portable relative path`);return r}function Ne(e,t){let i=te(e,t);return ie(i,new Set(["text","truncated"]),t),{text:W(i.text,`${t}.text`,{empty:!0}),truncated:Gt(i.truncated,`${t}.truncated`)}}function yy(e,t){let i=`Native spec_changes[${t}]`,r=te(e,i);ie(r,new Set(["capability","operation","source"]),i);let n=W(r.capability,`${i}.capability`);if(!hy.test(n))throw new Error(`${i}.capability is invalid`);let a=V(r.operation,["create","modify","remove"],`${i}.operation`),o=r.source===null?null:Is(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 Ny(e){let t="Native workspace",i=te(e,t);ie(i,new Set(["isolation","change_branch","target_branch","finish"]),t);let r=V(i.isolation,["current","branch","worktree"],`${t}.isolation`),n=Ts(i.change_branch,`${t}.change_branch`),a=Ts(i.target_branch,`${t}.target_branch`),o=i.finish===null?null:V(i.finish,["merge","push","pull-request","keep"],`${t}.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 by(e){let t="Native loop",i=te(e,t);ie(i,new Set(["stage","goal_cycle","iteration","attempt","retry_epoch","failed_iteration_count","no_progress_count","execution_failure_count","previous_unresolved_ids","next_action"]),t);let r=Ln(i.previous_unresolved_ids,`${t}.previous_unresolved_ids`);return Nt(r,`${t}.previous_unresolved_ids`),{stage:V(i.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:_(i.goal_cycle,`${t}.goal_cycle`,1),iteration:_(i.iteration,`${t}.iteration`),attempt:_(i.attempt,`${t}.attempt`),retry_epoch:_(i.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:_(i.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:_(i.no_progress_count,`${t}.no_progress_count`),execution_failure_count:_(i.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:r,next_action:Ts(i.next_action,`${t}.next_action`)}}function ky(e,t){let i=`Native acceptance[${t}]`,r=te(e,i);ie(r,new Set(["id","source","text","result","reason"]),i);let n=W(r.id,`${i}.id`);if(!py.test(n))throw new Error(`${i}.id must use A1, A2, ...`);return{id:n,source:Is(r.source,`${i}.source`),text:W(r.text,`${i}.text`),result:V(r.result,["pending","passed","failed","blocked"],`${i}.result`),reason:r.reason===null?null:Ne(r.reason,`${i}.reason`)}}function Sy(e,t){let i=`Native builder_handoff.checks[${t}]`,r=te(e,i);return ie(r,new Set(["name","result","note"]),i),{name:Ne(r.name,`${i}.name`),result:V(r.result,["passed","failed","not-run"],`${i}.result`),note:r.note===null?null:Ne(r.note,`${i}.note`)}}function Ey(e){let t="Native builder_handoff",i=te(e,t);ie(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"]),t);let r=Ln(i.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);return Nt(r,`${t}.addressed_acceptance_ids`),{candidate_id:W(i.candidate_id,`${t}.candidate_id`),identity_provider:W(i.identity_provider,`${t}.identity_provider`),builder_execution_ref:W(i.builder_execution_ref,`${t}.builder_execution_ref`),iteration:_(i.iteration,`${t}.iteration`,1),summary:Ne(i.summary,`${t}.summary`),addressed_acceptance_ids:r,checks:Ae(i.checks,`${t}.checks`,Sy),checks_truncated:Gt(i.checks_truncated,`${t}.checks_truncated`),known_limits:Ae(i.known_limits,`${t}.known_limits`,(n,a)=>Ne(n,`${t}.known_limits[${a}]`)),known_limits_truncated:Gt(i.known_limits_truncated,`${t}.known_limits_truncated`),submitted_at:Ut(i.submitted_at,`${t}.submitted_at`)}}function Py(e,t){let i=`Native blockers[${t}]`,r=te(e,i);ie(r,new Set(["owner","reason","acceptance_ids","resolution_action"]),i);let n=Ln(r.acceptance_ids,`${i}.acceptance_ids`);return Nt(n,`${i}.acceptance_ids`),{owner:V(r.owner,["builder","runtime","verifier","user","external"],`${i}.owner`),reason:Ne(r.reason,`${i}.reason`),acceptance_ids:n,resolution_action:V(r.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${i}.resolution_action`)}}function xy(e,t){let i=`Native verification.checks[${t}]`,r=te(e,i);return ie(r,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),i),{id:W(r.id,`${i}.id`),name:Ne(r.name,`${i}.name`),argv_display:Ae(r.argv_display,`${i}.argv_display`,(n,a)=>Ne(n,`${i}.argv_display[${a}]`)),argv_truncated:Gt(r.argv_truncated,`${i}.argv_truncated`),cwd_ref:Is(r.cwd_ref,`${i}.cwd_ref`,!0),status:V(r.status,["passed","failed","interrupted"],`${i}.status`),exit_code:wy(r.exit_code,`${i}.exit_code`),duration_ms:_(r.duration_ms,`${i}.duration_ms`)}}function Ry(e){let t="Native verification",i=te(e,t);ie(i,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let r=Ae(i.checks,`${t}.checks`,xy);Nt(r.map(a=>a.id),`${t}.checks IDs`);let n=W(i.identity_provider,`${t}.identity_provider`);return{candidate_id:W(i.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:W(i.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:_(i.iteration,`${t}.iteration`,1),attempt:_(i.attempt,`${t}.attempt`,1),assurance:i.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":V(i.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:V(i.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:r,summary:Ne(i.summary,`${t}.summary`),risks:Ae(i.risks,`${t}.risks`,(a,o)=>Ne(a,`${t}.risks[${o}]`)),risks_truncated:Gt(i.risks_truncated,`${t}.risks_truncated`),completed_at:Ut(i.completed_at,`${t}.completed_at`)}}function Vd(e,t){let i=`Native history[${t}]`,r=te(e,i);ie(r,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),i);let n=Ln(r.unresolved_ids,`${i}.unresolved_ids`);return Nt(n,`${i}.unresolved_ids`),{goal_cycle:_(r.goal_cycle,`${i}.goal_cycle`,1),iteration:_(r.iteration,`${i}.iteration`),attempt:_(r.attempt,`${i}.attempt`),outcome:V(r.outcome,["pass","fail","blocked","execution-error","recovery"],`${i}.outcome`),unresolved_ids:n,summary:Ne(r.summary,`${i}.summary`),completed_at:Ut(r.completed_at,`${i}.completed_at`)}}function Cy(e){let t="Native history_overflow.outcome_counts",i=te(e,t),r=["pass","fail","blocked","execution-error","recovery"];return ie(i,new Set(r),t),{pass:_(i.pass,`${t}.pass`),fail:_(i.fail,`${t}.fail`),blocked:_(i.blocked,`${t}.blocked`),"execution-error":_(i["execution-error"],`${t}.execution-error`),recovery:_(i.recovery,`${t}.recovery`)}}function Ay(e){let t="Native history_overflow",i=te(e,t);ie(i,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let r=_(i.dropped_entries,`${t}.dropped_entries`),n=i.first_dropped_at===null?null:Ut(i.first_dropped_at,`${t}.first_dropped_at`),a=i.last_dropped_at===null?null:Ut(i.last_dropped_at,`${t}.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=Cy(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 _y(e){let t=new Set(e.acceptance.map(i=>i.id));for(let i of e.loop.previous_unresolved_ids)if(!t.has(i))throw new Error(`Native loop references unknown acceptance ID ${i}`);for(let i of e.builder_handoff?.addressed_acceptance_ids??[])if(!t.has(i))throw new Error(`Native builder handoff references unknown ID ${i}`);for(let i of e.blockers)for(let r of i.acceptance_ids)if(!t.has(r))throw new Error(`Native blocker references unknown ID ${r}`);if(e.builder_handoff&&!(e.builder_handoff.iteration===e.loop.iteration||e.phase==="build"&&e.loop.stage==="repairing"&&e.builder_handoff.iteration===e.loop.iteration-1))throw new Error("Native builder handoff iteration is not current or the prior repair result");if(e.verification){if(!e.builder_handoff)throw new Error("Native verification requires a builder handoff");if(e.verification.candidate_id!==e.builder_handoff.candidate_id)throw new Error("Native verification candidate must match the builder handoff");if(e.verification.identity_provider!==e.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(e.verification.assurance)!==(e.verification.identity_provider==="skill-coordinated"))throw new Error("Native verification assurance does not match its identity provider");if(e.verification.assurance==="semantic-verification-unavailable"&&e.verification.verdict!=="blocked")throw new Error("Native unavailable semantic verification must remain blocked");if(e.verification.assurance==="user-confirmed-degraded"&&e.verification.verdict!=="pass")throw new Error("Native user-confirmed degraded verification must be passing");if(e.verification.verifier_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native Builder and Verifier execution refs must differ");let r=e.verification.iteration===e.loop.iteration&&e.verification.attempt===e.loop.attempt,n=e.phase==="build"&&e.loop.stage==="repairing"&&e.verification.iteration===e.loop.iteration-1&&e.verification.iteration===e.builder_handoff.iteration;if(!r&&!n)throw new Error("Native verification iteration and attempt do not match a stable loop result")}}function Ty(e){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"])}[e.phase].has(e.loop.stage))throw new Error(`Native loop stage ${e.loop.stage} is invalid for phase ${e.phase}`);let i=e.status==="await-user"?"await-user":e.status==="blocked"?"blocked":e.status==="done"?"done":null;if(i!==null&&e.loop.stage!==i)throw new Error(`Native status ${e.status} requires loop stage ${i}`);if(e.status==="active"&&["await-user","blocked","done"].includes(e.loop.stage))throw new Error(`Native active status cannot use loop stage ${e.loop.stage}`);if(e.archived!==(e.status==="done"))throw new Error("Native archived must be true exactly when status is done");if(e.archived&&e.phase!=="archive")throw new Error("Native archived state must be in Archive");if(e.verification_result==="pass"){if(e.verification?.verdict!=="pass")throw new Error("Native pass requires a persisted passing verification");if(e.acceptance.some(r=>r.result!=="passed"))throw new Error("Native pass requires every acceptance item to pass");if(e.verification.checks.some(r=>r.status!=="passed"))throw new Error("Native pass requires every persisted check to pass")}if(e.verification?.assurance==="semantic-verification-unavailable"&&(e.phase!=="verify"||e.status!=="await-user"||e.verification_result!=="blocked"||e.loop.next_action!=="confirm-verifier-unavailable"))throw new Error("Native unavailable semantic verification must await explicit user confirmation");if(e.verification_report!==null&&e.verification===null)throw new Error("Native verification report requires persisted verification")}function ne(e){let t=te(e,"Native portable state");if(ie(t,vy,"Native portable state"),t.schema!==Jt)throw new Error(`Native portable state schema must be ${Jt}`);let i=W(t.name,"Native state name");if(!fy.test(i))throw new Error("Native state name is invalid");if(t.brief!=="brief.md")throw new Error("Native state brief must be brief.md");let r=Ae(t.spec_changes,"Native spec_changes",yy);Nt(r.map(s=>s.capability),"Native spec change capabilities");let n=Ae(t.acceptance,"Native acceptance",ky);Nt(n.map(s=>s.id),"Native acceptance IDs");let a=Ae(t.history,"Native history",Vd);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:Jt,name:i,language:V(t.language,["en","zh-CN"],"Native state language"),phase:V(t.phase,["shape","build","verify","archive"],"Native state phase"),status:V(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:_(t.state_version,"Native state_version",1),brief:"brief.md",...t.children_contract_hash===void 0?{}:{children_contract_hash:gy(t.children_contract_hash,"Native children contract hash")},spec_changes:r,workspace:Ny(t.workspace),loop:by(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:Ey(t.builder_handoff),blockers:Ae(t.blockers,"Native blockers",Py),verification:t.verification===null?null:Ry(t.verification),history:a,history_overflow:Ay(t.history_overflow),verification_result:V(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:V(t.verification_report,["verification.md"],"Native verification_report"),archived:Gt(t.archived,"Native archived"),created_at:Ut(t.created_at,"Native created_at")};return _y(o),Ty(o),o}function Kt(e,t){let i=ne(e),r=Vd(t,i.history.length),n=[...i.history,r],a={...i.history_overflow,outcome_counts:{...i.history_overflow.outcome_counts}};for(;n.length>50;){let o=n.shift();a.dropped_entries+=1,a.first_dropped_at??=o.completed_at,a.last_dropped_at=o.completed_at,a.outcome_counts[o.outcome]+=1}return ne({...i,history:n,history_overflow:a})}function Iy(e,t){let i=(0,Bn.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`${t} is invalid YAML: ${i.errors[0].message}`);return i.toJS({mapAsMap:!1})}async function ae(e){let t=await dy.readFile(e,"utf8");return ne(Iy(t,"Native portable state"))}async function qn(e,t,i={}){let r=ne(t);await Y(e,(0,Bn.stringify)(r),i)}var Hn=new Map;async function jy(e,t){let i=Hn.get(e)??Promise.resolve(),r,n=new Promise(o=>{r=o}),a=i.then(()=>n);Hn.set(e,a),await i;try{return await t()}finally{r(),Hn.get(e)===a&&Hn.delete(e)}}async function bt(e){return jy(e.file,async()=>{let t=_(e.expectedStateVersion,"Native expected state version",1),i=ne(e.next);if(i.state_version!==t+1)throw new Error("Native CAS next state_version must increment exactly once");let r=await ae(e.file);if(r.state_version===i.state_version&&JSON.stringify(r)===JSON.stringify(i))return r;if(r.state_version!==t)throw new Dn(t,r.state_version);return await qn(e.file,i,{...e.containedRoot?{containedRoot:e.containedRoot}:{},beforeCommit:async()=>{let n=await ae(e.file);if(n.state_version!==t)throw new Dn(t,n.state_version)}}),i})}function $y(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("Native portable text byte budget must be a non-negative safe integer")}function at(e,t=16384){if(typeof e!="string")throw new Error("Native portable text must be a string");if($y(t),Buffer.byteLength(e,"utf8")<=t)return{text:e,truncated:!1};let i="",r=0;for(let n of e){let a=Buffer.byteLength(n,"utf8");if(r+a>t)break;i+=n,r+=a}return{text:i,truncated:!0}}var He="comet.native.v3",_e="comet.native.v2",Te="comet.native.v1";var Fn="comet.native.portable-migration.v1",Hy=new Set(["schema","id","change","fromSchema","status","createdAt"]),Dy=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,By=/^[a-z0-9][a-z0-9-]{7,127}$/u,Ly=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),qy=new Set([Te,_e,He]);function Fy(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function My(e,t){let i=e instanceof Date?new Date(e.valueOf()):new Date(e);if(Number.isNaN(i.valueOf()))throw new Error(`${t} must be a valid timestamp`);return i.toISOString()}function Vy(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let i=new Date(e);if(Number.isNaN(i.valueOf())||i.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function Wy(e){return e.schema===Te?Yi(e):e.schema===_e?Xi(e):Qi(e)}function zy(e){return Oy.posix.normalize(e.replaceAll("\\","/"))}function Jy(e){return e.spec_changes.map(t=>t.operation==="remove"?{capability:t.capability,operation:"remove",source:null}:{capability:t.capability,operation:t.operation==="replace"?"modify":"create",source:zy(t.source)})}function Gy(e){return e==="shape"?"shape":"build"}function Uy(e,t){return e==="zh-CN"?t==="shape"?"继续澄清并确认验收项":"重新提交候选实现":t==="shape"?"Continue clarification and confirm acceptance":"Submit a fresh implementation candidate"}function Ky(e,t,i){return e==="zh-CN"?`从旧版 ${t} ${i} 状态恢复;旧版 Loop、验证结论和运行记录未继承。`:`Recovered from legacy ${t} ${i} state; prior Loop, verification results, and execution records were not inherited.`}function Wd(e){let t=Wy(e.state);Fd(e.acceptance);let i=Gy(t.phase),r=i==="shape"?0:1,n=My(e.migratedAt??`${t.created_at}T00:00:00.000Z`,"Native portable migration time"),a=e.acceptance.map(o=>({id:o.id,source:o.source,text:o.text,result:"pending",reason:null}));return ne({schema:Jt,name:t.name,language:t.language,phase:i,status:"active",state_version:1,brief:"brief.md",spec_changes:Jy(t),workspace:e.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:Uy(t.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:at(Ky(t.language,t.schema,t.phase)),completed_at:n}],history_overflow:As(),verification_result:"pending",verification_report:null,archived:!1,created_at:`${t.created_at}T00:00:00.000Z`})}function js(e){let t=Fy(e,"Native portable migration transaction"),i=Object.keys(t).filter(r=>!Hy.has(r));if(i.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${i.join(", ")}`);if(t.schema!==Fn)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!By.test(t.id))throw new Error("Native portable migration transaction id is invalid");if(typeof t.change!="string"||!Dy.test(t.change))throw new Error("Native portable migration transaction change is invalid");if(typeof t.fromSchema!="string"||!qy.has(t.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof t.status!="string"||!Ly.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:Fn,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:Vy(t.createdAt,"Native portable migration transaction createdAt")}}function zd(e){switch(js(e).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 Mn="comet.native.archive-transaction.v4",Jd="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",Yy=new RegExp(`^portable-archive-(${Jd})\\.json$`,"u"),Xy=new RegExp(`^portable-migration-(${Jd})\\.json$`,"u"),Qy=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Zy=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,eN=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),tN=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),iN=new Set(["capability","operation","source","content"]),Gd=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function Ud(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Kd(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`);if(Object.keys(e).length!==t.size)throw new Error(`${i} fields are invalid`)}function rN(e,t){let i=`Native portable Archive spec_changes[${t}]`,r=Ud(e,i);if(Kd(r,iN,i),typeof r.capability!="string"||!Gd.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 nN(e){let t=Ud(e,"Native portable Archive transaction");if(Kd(t,tN,"Native portable Archive transaction"),t.schema!==Mn)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!Qy.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!Gd.test(t.change))throw new Error("Native portable Archive transaction change is invalid");if(!Number.isSafeInteger(t.start_state_version)||Number(t.start_state_version)<0)throw new Error("Native portable Archive transaction state version is invalid");if(typeof t.archive_ref!="string"||!Zy.test(t.archive_ref)||!t.archive_ref.endsWith(`-${t.change}`))throw new Error("Native portable Archive transaction ref is invalid");if(typeof t.status!="string"||!eN.has(t.status))throw new Error("Native portable Archive transaction status is invalid");if(!Array.isArray(t.spec_changes))throw new Error("Native portable Archive transaction spec changes are invalid");let i=t.spec_changes.map(rN);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(t.next_spec_index)||Number(t.next_spec_index)<0||Number(t.next_spec_index)>i.length)throw new Error("Native portable Archive transaction spec cursor is invalid");if(typeof t.created_at!="string")throw new Error("Native portable Archive transaction timestamp is invalid");let r=new Date(t.created_at);if(Number.isNaN(r.valueOf())||r.toISOString()!==t.created_at)throw new Error("Native portable Archive transaction timestamp is invalid");return{schema:Mn,id:t.id,change:t.change,start_state_version:Number(t.start_state_version),archive_ref:t.archive_ref,status:t.status,next_spec_index:Number(t.next_spec_index),spec_changes:i,created_at:t.created_at}}function Vn(e){let t=Yy.exec(e);if(t)return{kind:"archive",change:t[1]};let i=Xy.exec(e);return i?{kind:"migration",change:i[1]}:null}function kt(e,t){let i=`${t.kind==="archive"?"portable-archive":"portable-migration"}-${t.change}.json`,r=Vn(i);if(!r||r.kind!==t.kind||r.change!==t.change)throw new Error(`Invalid Native portable transaction change: ${t.change}`);return $s.join(e.transactionsDir,i)}async function Os(e,t){let i=Vn(t);if(!i)return null;let r=await j({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),n=JSON.parse(r.text),a=$s.join(e.transactionsDir,t);if(i.kind==="archive"){let s=nN(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=js(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 Yt(e,t){let i=kt(e,t);try{return await Os(e,$s.basename(i))}catch(r){if(r.code==="ENOENT")return null;throw r}}function Yd(e){return e.kind==="archive"||e.journal.status!=="committed"}import De from"path";import{TextDecoder as fN}from"util";import{createHash as aN}from"node:crypto";import{constants as Wn,promises as be}from"node:fs";import ke from"node:path";function Jn(e,t){let i=ke.relative(e,t);return i===""||!ke.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${ke.sep}`)}function oN(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function sN(e,t){return A({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function cN(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function zn(e,t){return A({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function Hs(e,t){let i=await be.lstat(e);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await be.realpath(e),dev:i.dev,ino:i.ino,birthtimeMs:i.birthtimeMs}}async function lN(e,t,i){let r=ke.resolve(e),n=ke.resolve(t);if(!Jn(r,n))throw new Error(`${i} is outside its managed root`);let a=[await Hs(r,i)],o=r;for(let s of ke.relative(r,n).split(ke.sep).filter(Boolean)){await St(a,i),o=ke.join(o,s);let c=await Hs(o,i);if(!Jn(a[0].realPath,c.realPath))throw new Error(`${i} parent resolves outside its managed root: ${o}`);a.push(c)}return await St(a,i),a}async function St(e,t){for(let i of e){let r=await be.lstat(i.path);if(!r.isDirectory()||r.isSymbolicLink()||!sN(i,r)||await be.realpath(i.path)!==i.realPath)throw new Error(`${t} parent changed during I/O: ${i.path}`)}}async function uN(e,t,i){let r=[],n=0,a=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let o=t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,n>t)throw new Error(`${i} exceeds ${t} bytes`);r.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(r,n)}async function Xt(e){let t=oN(e.maxBytes),i=ke.resolve(e.file),r=await lN(e.root,ke.dirname(i),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(u=>Hs(ke.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await St(r,e.label);let a=await be.lstat(i);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);if(a.size>t)throw new Error(`${e.label} exceeds ${t} bytes`);let o=cN(a),s=await be.realpath(i);if(!Jn(r[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(u=>Jn(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?Wn.O_RDONLY:Wn.O_RDONLY|Wn.O_NOFOLLOW|Wn.O_NONBLOCK,l=await be.open(i,c);try{let u=await l.stat();await e.hooks?.afterOpen?.();let[f,d]=await Promise.all([be.lstat(i),be.realpath(i)]);if(await St(r,e.label),await St(n,e.label),!u.isFile()||!f.isFile()||f.isSymbolicLink()||d!==s||!zn(o,u)||!zn(o,f))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let p=await uN(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[v,h,m]=await Promise.all([l.stat(),be.lstat(i),be.realpath(i)]);if(await St(r,e.label),await St(n,e.label),!h.isFile()||h.isSymbolicLink()||m!==s||!zn(o,v)||!zn(o,h))throw new Error(`${e.label} changed while reading`);return{bytes:p,hash:aN("sha256").update(p).digest("hex"),size:p.length}}finally{await l.close()}}var hN=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),pN=new Set(["id","type","source","target","staged","backup"]),mN=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),vN=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]);var Zd=new Set(["prepared","applying","committed","rolling-back","rolled-back"]);var gN=256*1024,$x=1024*1024,Ox=16*1024;var Hx=64*1024*1024;var wN=new fN("utf-8",{fatal:!0});function Un(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Kn(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function ef(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function Ds(e,t){if(typeof e!="string"||e.length===0||De.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function Gn(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function Xd(e,t){if(Ds(e,t),e.includes("\\")||e!==De.posix.normalize(e)||e.split("/").includes(".")||e.endsWith("/")||Buffer.byteLength(e,"utf8")>1024)throw new Error(`${t} must be a normalized Native-relative ref`)}function yN(e,t){let i=Un(e,`transaction operations[${t}]`);if(Kn(i,pN,`transaction operations[${t}]`),typeof i.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(i.id))throw new Error(`transaction operations[${t}].id is invalid`);if(i.type!=="write"&&i.type!=="remove"&&i.type!=="move")throw new Error(`transaction operation ${i.id} has an invalid type`);Ds(i.target,`transaction operation ${i.id} target`);for(let r of["source","staged","backup"])i[r]!==void 0&&Ds(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 tf(e){let t=Un(e,"Native Archive transaction journal");if(Kn(t,mN,"Native Archive transaction journal"),t.schema!=="comet.native.transaction.v2")throw new Error("Unsupported Native Archive transaction schema");if(typeof t.id!="string"||!/^[a-f0-9-]{8,}$/u.test(t.id))throw new Error("Native Archive transaction id is invalid");if(t.kind!=="archive")throw new Error("Native v2 transaction kind must be archive");if(typeof t.status!="string"||!Zd.has(t.status))throw new Error("Native Archive transaction status is invalid");if(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change))throw new Error("Native Archive transaction change name is invalid");if(!ef(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(Gn(t.preflightHash,"Native Archive transaction preflightHash"),!Array.isArray(t.operations)||t.operations.length>65)throw new Error("Native Archive transaction operations must be an array");let i=t.operations.map((s,c)=>{let l=Un(s,`Archive transaction operations[${c}]`);if(Kn(l,vN,`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`);Xd(l.target,`Archive transaction operation ${l.id} target`);for(let u of["source","staged","backup"])l[u]!==void 0&&Xd(l[u],`Archive transaction operation ${l.id} ${u}`);if(l.expectedTargetHash!==null&&Gn(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(Gn(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`);Gn(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/${t.id}`,a=i.filter(s=>s.type==="move");if(a.length!==1||a[0].id!=="archive-change"||a[0].source!==`changes/${t.change}`||!new RegExp(`^archive/\\d{4}-\\d{2}-\\d{2}-${t.change}$`,"u").test(a[0].target)||i.at(-1)!==a[0])throw new Error("Native Archive transaction must end with its exact change move");let o=new Set;for(let s of i.slice(0,-1)){if(s.type==="move"||!/^specs\/[a-z][a-z0-9]*(?:-[a-z0-9]+)*\/spec\.md$/u.test(s.target)||o.has(s.target))throw new Error(`Native Archive transaction spec target is invalid: ${s.target}`);if(o.add(s.target),s.staged!==void 0&&!s.staged.startsWith(`${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:t.id,kind:"archive",status:t.status,change:t.change,createdAt:t.createdAt,preflightHash:t.preflightHash,operations:i}}function NN(e){let t=Un(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return tf(t);if(Kn(t,hN,"Native transaction journal"),t.schema!=="comet.native.transaction.v1")throw new Error("Unsupported Native transaction schema");if(typeof t.id!="string"||!/^[a-f0-9-]{8,}$/u.test(t.id))throw new Error("Native transaction id is invalid");if(t.kind!=="archive"&&t.kind!=="root-move")throw new Error("Native transaction kind is invalid");if(typeof t.status!="string"||!Zd.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!De.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!De.isAbsolute(t.nativeRoot))throw new Error("Native transaction roots must be absolute paths");if(t.change!==void 0&&(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change)))throw new Error("Native transaction change name is invalid");if(!ef(t.createdAt))throw new Error("Native transaction createdAt is invalid");if(!Array.isArray(t.operations))throw new Error("Native transaction operations must be an array");let i=t.operations.map(yN),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:t.id,kind:t.kind,status:t.status,projectRoot:t.projectRoot,nativeRoot:t.nativeRoot,...typeof t.change=="string"?{change:t.change}:{},createdAt:t.createdAt,operations:i}}function bN(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return De.join(e.transactionsDir,t)}function rf(e,t){let i=bN(e,t);return{directory:i,journal:De.join(i,"transaction.json"),events:De.join(i,"events.jsonl"),staged:De.join(i,"staged"),backups:De.join(i,"backups")}}async function Ls(e,t){let i=rf(e,t);return await Promise.all(Object.values(i).map(r=>T(e.runtimeDir,r))),i}async function qs(e,t,i={}){let r=await Ls(e,t),n=await Xt({root:e.runtimeDir,file:r.journal,maxBytes:gN,label:`Native transaction journal ${t}`,hooks:i.hooks}),a=JSON.parse(wN.decode(n.bytes)),o=NN(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}async function EN(e,t,i){let r;try{r=await kN.readdir(e.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 qs(e,n.name);if(a.id!==t&&a.status!=="committed"&&a.status!=="rolled-back")return!0}catch{return!0}for(let n of r)if(Vn(n.name))try{let a=await Os(e,n.name);if(!a||i?.kind===a.kind&&i.change===a.change)continue;if(Yd(a))return!0}catch{return!0}return!1}async function PN(e,t){let i=Date.now()+5e3,r=SN.join(e.locksDir,"root-move.lock");for(;;)try{return await jn(e,"root-move",t)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await Dd(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 G(e,t,i,r){let n=await PN(e,t);try{if(await zi(e.projectRoot),await EN(e,r?.allowedTransactionId,r?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await i()}finally{await $n(n)}}import{createHash as xN}from"crypto";function de(e){return xN("sha256").update(e).digest("hex")}var rR={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024};var nR=8*1024*1024;var aR=64*1024,oR=64*1024;var sR={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},cR={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};var lR=(1n<<256n)-1n;var jN=ai(Ft(),1);var PR=4*1024*1024;var $N=null;function ON(e,t){let i=e;for(let r of t)i+="\0"+(typeof r=="string"?r:JSON.stringify(r));return i}function nf(e,t){return(...i)=>{let r=$N;if(r===null)return t(...i);let n=ON(`async:${e}`,i),a=r.entries.get(n);if(a)return a.value;let o=t(...i).catch(s=>{throw r.entries.delete(n),s});return r.entries.set(n,{value:o}),o}}var _R=nf("hookWritePolicy",async e=>(await ds(e))?.hook??{allow_paths:[]});var PC=256*1024;var BC={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 Qt from"node:path";var Zi=/^[a-f0-9]{64}$/u,of=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,BN=16*1024,eA=process.platform;function LN(e,t){let i=Qt.relative(e,t);return Qt.isAbsolute(i)||i===".."||i.startsWith(`..${Qt.sep}`)?null:i.replaceAll("\\","/")||"."}function sf(e){return Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127})}function cf(e,t){if(e.length===0||sf(e)||e.includes("\\")||Qt.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes(".."))throw new Error(`${t} must be a portable project-relative path`);let i=Qt.posix.normalize(e);if(i!==e||i===".."||i.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return i}function qN(e){if(typeof e!="string")throw new Error("Native workspace capturedAt is invalid");let t=new Date(e);if(!Number.isFinite(t.getTime())||t.toISOString()!==e)throw new Error("Native workspace capturedAt is invalid");return e}function Fs(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||sf(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function FN(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(Fs(e.changeBranch,"Native workspace change branch"),Fs(e.targetBranch,"Native workspace target branch"),(e.isolation==="branch"||e.isolation==="worktree")&&(e.changeBranch===null||e.targetBranch===null))throw new Error("Native isolated workspace requires change and target branches")}function MN(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace Git provenance must be an object");let t=e,i=new Set(["provider","baseCommit","targetBranch","targetCommit"]),r=Object.keys(t).filter(n=>!i.has(n));if(r.length>0)throw new Error(`Native workspace Git provenance has unknown field(s): ${r.join(", ")}`);if(t.provider!=="git"||typeof t.baseCommit!="string"||!of.test(t.baseCommit)||typeof t.targetCommit!="string"||!of.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");Fs(t.targetBranch,"Native workspace Git target branch")}function VN(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace identity must be an object");let t=e,i=new Set(["schema","capturedAt","capturedRevision","nativeRootRef","projectRootId","nativeRootId","projectRootPathId","nativeRootPathId","sessionHash","git","isolation","changeBranch","targetBranch","finish"]),r=Object.keys(t).filter(o=>!i.has(o));if(r.length>0)throw new Error(`Native workspace identity has unknown field(s): ${r.join(", ")}`);if(t.schema!=="comet.native.workspace.v2"&&t.schema!=="comet.native.workspace.v3")throw new Error("Unsupported Native workspace identity");if(!Number.isSafeInteger(t.capturedRevision)||t.capturedRevision<1||typeof t.nativeRootRef!="string"||!Zi.test(String(t.projectRootId))||!Zi.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");qN(t.capturedAt),cf(t.nativeRootRef,"Native workspace root ref");let n=t.projectRootPathId!==void 0,a=t.nativeRootPathId!==void 0;if(n!==a)throw new Error("Native workspace path identities must be provided together");if(n&&!Zi.test(String(t.projectRootPathId))||a&&!Zi.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!Zi.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&MN(t.git),t.schema==="comet.native.workspace.v2"){if(t.isolation!==void 0||t.changeBranch!==void 0||t.targetBranch!==void 0||t.finish!==void 0)throw new Error("Native workspace v2 identity cannot contain a workspace binding");return}if(typeof t.isolation!="string"||t.changeBranch===void 0||t.targetBranch===void 0||t.finish===void 0)throw new Error("Native workspace v3 identity requires a workspace binding");if(FN(t),t.finish!==null&&!new Set(["merge","push","pull-request","keep"]).has(t.finish))throw new Error("Native workspace finish must be merge, push, pull-request, keep, or null")}function WN(e,t){return Qt.join(Re(e,t),"workspace.json")}function zN(e,t){let i=WN(e,t),r=Ce(e,i),n=LN(r,i);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:r,ref:cf(n,"Native workspace file ref")}}async function JN(e,t){try{let i=zN(e,t),r=await j({root:i.root,ref:i.ref,maxBytes:BN});return JSON.parse(r.text)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function er(e,t){let i=await JN(e,t);return i===null||i&&typeof i=="object"&&!Array.isArray(i)&&i.schema==="comet.native.workspace.v1"?null:(VN(i),i)}var uf=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],KN=new Set(uf),df=new Set([...uf,"minimum_runtime_version","revision"]),YN=new Set([...df,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),XN=new Set(["capability","operation","source","base_hash"]),QN=new Set(["shape","build","verify","archive"]),ZN=new Set(["implicit","confirmed"]),eb=new Set(["pending","pass","fail"]),Et="comet-state.yaml",Vs=/^[a-f0-9]{64}$/u,ff=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,tb=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,Ws=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"},ei=class extends Error{constructor(i,r){super(i!==He||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"},tr=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"},Xn=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"},EA=["# Outcome","","# Scope","","# Non-goals","","# Acceptance examples","","# Constraints and invariants","","# Decisions","","# Open questions","","# Verification expectations",""].join(`
|
|
150
|
-
`);function rr(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function hf(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function Js(e){if(!ff.test(e))throw new Error(`Invalid Native change name: ${e}`)}function ib(e){if(!ff.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function pf(e,t){if(e.length===0||Zt.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function rb(e,t){let i=rr(e,`spec_changes[${t}]`);if(hf(i,XN,`spec_changes[${t}]`),typeof i.capability!="string")throw new Error("spec change capability is required");if(ib(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"&&pf(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"||!Vs.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"||!Vs.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 nb(e){return/^\d{4}-\d{2}-\d{2}$/u.test(e)?new Date(`${e}T00:00:00.000Z`).toISOString().slice(0,10)===e:!1}function Gs(e,t){if(hf(e,t,Et),typeof e.name!="string")throw new Error("Native change name is required");if(Js(e.name),e.language!=="en"&&e.language!=="zh-CN")throw new Error("Native change language must be en or zh-CN");if(typeof e.phase!="string"||!QN.has(e.phase))throw new Error("Native change phase is invalid");if(e.brief!=="brief.md")throw new Error("Native change brief must be brief.md");if(e.approval!==null&&!ZN.has(e.approval))throw new Error("Native change approval is invalid");if(!Array.isArray(e.spec_changes))throw new Error("Native spec_changes must be an array");let i=e.spec_changes.map(rb),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 e.verification_result!="string"||!eb.has(e.verification_result))throw new Error("Native verification_result is invalid");if(e.verification_report!==null&&typeof e.verification_report!="string")throw new Error("Native verification_report must be a string or null");if(typeof e.verification_report=="string"&&pf(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!nb(e.created_at))throw new Error("Native created_at must be a valid YYYY-MM-DD date");if(e.run_id!==null&&(typeof e.run_id!="string"||e.run_id.length===0))throw new Error("Native run_id must be a non-empty string or null");return{name:e.name,language:e.language,phase:e.phase,brief:"brief.md",approval:e.approval,spec_changes:i,verification_result:e.verification_result,verification_report:e.verification_report,archived:e.archived,created_at:e.created_at,run_id:e.run_id}}function Yi(e){let t=rr(e,Et);if(t.schema!==Te)throw new Error(`Expected ${Te}`);return{schema:Te,...Gs(t,KN)}}function ir(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Ms(e,t,i){if(e===null)return null;let r=typeof e=="string"?tb.exec(e):null;if(!r||r[1]!==i)throw new Error(`${t} must be null or runtime/evidence/${i}/<sha256>.json relative to the Native change`);return e}function ab(e){if(e==null)return null;if(typeof e!="string"||!Vs.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function ob(e){if(e===void 0)return"legacy-v1";if(e!=="legacy-v1")throw new Error("Native verification_protocol must be legacy-v1");return e}function Xi(e){let t=rr(e,Et);if(t.schema!==_e)throw new Error(`Expected ${_e}`);if(ir(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${_e} minimum_runtime_version must be 2`);return{schema:_e,minimum_runtime_version:2,revision:ir(t.revision,"Native v2 revision"),...Gs(t,df)}}function Qi(e){let t=rr(e,Et);if(t.schema!==He){if(t.schema===Te||t.schema===_e){let o=t.schema===Te?Yi(t):Xi(t);throw new Ws(o.name,o.schema)}throw new ei(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let i=ir(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)throw new ei(t.schema,i);if(i!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let r=ir(t.revision,"Native revision"),n=Gs(t,YN),a=ab(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:He,minimum_runtime_version:3,revision:r,verification_protocol:ob(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:Ms(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:Ms(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:Ms(t.partial_allowance,"Native partial_allowance","allowances")}}function sb(e){let t=rr(e,Et);if(t.schema===Te){let n=Yi(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${He}`}}if(t.schema===_e){let n=Xi(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${He}`}}if(t.schema!==He){let n=typeof t.minimum_runtime_version=="number"&&Number.isSafeInteger(t.minimum_runtime_version)?t.minimum_runtime_version:null;return{status:"runtime-incompatible",schema:typeof t.schema=="string"?t.schema:"(missing)",minimumRuntimeVersion:n,state:null,message:new ei(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let i=ir(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:i,state:null,message:new ei(t.schema,i).message};let r=Qi(t);return{status:"current",schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,state:r}}function oe(e,t){Js(t);let i=Zt.join(e.changesDir,t);if(!L(e.changesDir,i))throw new Error("Native change path escaped");return i}var cb=256*1024;async function lb(e,t=Zt.dirname(e)){let i=Zt.relative(t,e).split(Zt.sep).join("/"),r=await j({root:t,ref:i,maxBytes:cb}),n=(0,zs.parseDocument)(r.text,{uniqueKeys:!0});if(n.errors.length>0)throw new Error(`Invalid Native change file ${e}: ${n.errors[0].message}`);return n.toJS()}async function Qn(e,t){let i=Zt.join(oe(e,t),Et);await T(e.nativeRoot,i);let r=sb(await lb(i,e.nativeRoot));if(r.state&&r.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return r}import{promises as lr}from"node:fs";import qe from"node:path";var Nf=ai(Ft(),1);import{promises as hb}from"node:fs";import pb from"node:path";import{execFileSync as ub}from"node:child_process";var db=3e4,fb=8*1024*1024,Us=class extends Error{constructor(i,r,n){super(`git ${r.join(" ")} failed${n?`: ${n}`:""}`);this.cwd=i;this.args=r;this.stderr=n;this.name="GitCommandError"}cwd;args;stderr};function mf(e,t){try{return ub("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:db,maxBuffer:fb,windowsHide:!0})}catch(i){let r=typeof i.stderr=="string"?i.stderr.trim():Buffer.isBuffer(i.stderr)?i.stderr.toString("utf8").trim():"";throw new Us(e,t,r)}}function I(e,t){return mf(e,t).trim()}function Zn(e){return I(e,["status","--porcelain=v1","-z","--untracked-files=all"])===""}function Ks(e){let t=mf(e,["status","--porcelain=v1","-z","--untracked-files=all"]);if(!t)return[];let i=t.split("\0").filter(Boolean),r=[];for(let n=0;n<i.length;n+=1){let a=i[n];if(a.length<4)throw new Error("Git status returned an invalid porcelain record");if(r.push(a.slice(3).replaceAll("\\","/")),a[0]==="R"||a[0]==="C"||a[1]==="R"||a[1]==="C"){let o=i[n+1];if(!o)throw new Error("Git status returned an incomplete rename record");r.push(o.replaceAll("\\","/")),n+=1}}return[...new Set(r)].sort()}function vf(e,t){try{let r=I(e,["config","--get",`branch.${t}.remote`]);if(r&&r!==".")return r}catch{}let i=I(e,["remote"]).split(/\r?\n/u).map(r=>r.trim()).filter(Boolean);if(i.includes("origin"))return"origin";if(i.length===1)return i[0];throw new Error(i.length===0?"Native workspace finish requires a configured Git remote":`Native workspace finish requires an unambiguous Git remote: ${i.join(", ")}`)}var gf="children.yaml",Ys="comet.native.children.v1",nr="comet.native.children.v2",mb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,vb=new Set(["schema","children"]),gb=new Set(["schema","acceptance_index","children"]),wb=new Set(["name","depends_on","covers"]);function ta(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ea(e,t,i){let r=Object.keys(e).filter(a=>!t.has(a)),n=[...t].filter(a=>!(a in e));if(r.length>0||n.length>0)throw new Error(`${i} fields are invalid`)}function wf(e,t){if(!Array.isArray(e)||!e.every(i=>typeof i=="string"))throw new Error(`${t} must be an array of strings`);return[...new Set(e)].sort((i,r)=>i.localeCompare(r,"en"))}function yb(e){let t=new Map(e.map(a=>[a.name,a])),i=new Set,r=new Set,n=a=>{if(!r.has(a)){if(i.has(a))throw new Error(`Native children dependency cycle includes ${a}`);i.add(a);for(let o of t.get(a).depends_on)n(o);i.delete(a),r.add(a)}};for(let a of e)n(a.name)}function yf(e,t,i=t){let r=new Set(t);for(let o of e){let s=o.covers.filter(c=>!r.has(c));if(s.length>0)throw new Error(`Native child ${o.name} covers unknown acceptance: ${s.join(", ")}`)}let n=new Set(e.flatMap(o=>o.covers)),a=i.filter(o=>!n.has(o));if(a.length>0)throw new Error(`Native children do not cover parent acceptance: ${a.join(", ")}`)}function bf(e){let t=new Set(e.acceptance.filter(({source:i})=>i===e.brief).map(({id:i})=>i));if(e.loop.stage==="repairing"&&e.verification_result==="fail"){let i=[...e.history].reverse().find(({outcome:r})=>r==="fail");for(let r of i?.unresolved_ids??[])t.add(r)}return{acceptanceCatalog:e.acceptance,requiredAcceptanceIds:[...t]}}function Nb(e){let t=ta(e,"Native children acceptance_index"),i={};for(let[r,n]of Object.entries(t)){let a=ta(n,`Native children acceptance_index.${r}`);if(ea(a,new Set(["source","text"]),`Native children acceptance_index.${r}`),typeof a.source!="string"||a.source.length===0)throw new Error(`Native children acceptance_index.${r}.source must be a non-empty string`);if(typeof a.text!="string"||a.text.length===0)throw new Error(`Native children acceptance_index.${r}.text must be a non-empty string`);i[r]={source:a.source,text:a.text}}return i}function bb(e,t,i){let r=i.requiredAcceptanceIds??t??[],n=Object.keys(e),a=r.filter(c=>!(c in e)),o=n.filter(c=>!r.includes(c));if(a.length>0||o.length>0)throw new Error(`Native children acceptance_index must match the required acceptance: missing ${a.join(", ")||"none"}; extra ${o.join(", ")||"none"}`);let s=new Map((i.acceptanceCatalog??[]).map(c=>[c.id,c]));for(let c of r){let l=s.get(c);if(!l)continue;let u=e[c];if(u.source!==l.source||u.text!==l.text)throw new Error(`Native children acceptance_index.${c} does not match the acceptance catalog`)}}function kb(e,t,i={}){let r=(0,Nf.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${r.errors[0].message}`);let n=ta(r.toJS({mapAsMap:!1}),"Native children contract"),a=n.schema;if(a===nr?ea(n,gb,"Native children contract"):ea(n,vb,"Native children contract"),a!==Ys&&a!==nr)throw new Error(`Native children schema must be ${Ys} or ${nr}`);if(!Array.isArray(n.children)||n.children.length===0)throw new Error("Native children must be a non-empty array");let o=n.children.map((l,u)=>{let f=ta(l,`Native child ${u}`);if(ea(f,wb,`Native child ${u}`),typeof f.name!="string"||!mb.test(f.name))throw new Error(`Native child ${u} name is invalid`);return{name:f.name,depends_on:wf(f.depends_on,`Native child ${f.name} depends_on`),covers:wf(f.covers,`Native child ${f.name} covers`)}}),s=o.map(({name:l})=>l);if(new Set(s).size!==s.length)throw new Error("Native child names must be unique");let c=new Set(s);for(let l of o){let u=l.depends_on.filter(f=>!c.has(f));if(u.length>0)throw new Error(`Native child ${l.name} depends on unknown child: ${u.join(", ")}`)}if(yb(o),a===nr){let l=Nb(n.acceptance_index);if(bb(l,t,i),t){let u=Object.keys(l);yf(o,u,u)}return{schema:nr,acceptance_index:l,children:o}}return t&&yf(o,t),{schema:Ys,children:o}}async function kf(e){let t=pb.join(e.changeDir,gf);try{await hb.lstat(t)}catch(r){if(r.code==="ENOENT")return null;throw r}let i=await j({root:e.changeDir,ref:gf});return{contract:kb(i.text,e.acceptanceIds,e.validation),size:i.size}}function Sf(e){return ee("comet.native.parent-contract.v1",{acceptance:e.acceptance.map(({id:t,source:i,text:r})=>({id:t,source:i,text:r})),children:e.children})}var BA=["$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("; ");var ia="skill-coordinated";function xb(e){return e.state_version+1}function Rb(e){return e.map(t=>({...t,result:"pending",reason:null}))}function Cb(e){return{goal_cycle:e.state.loop.goal_cycle,iteration:e.state.loop.iteration,attempt:e.state.loop.attempt,outcome:e.outcome,unresolved_ids:e.unresolvedIds??[],summary:at(e.summary),completed_at:e.completedAt}}function Xs(e){let t=ne(e.state);if(t.phase!=="verify"&&t.phase!=="archive")throw new Error("Only Verify or Archive can return a candidate to Build");let i=(e.now??new Date).toISOString(),r=Kt(t,Cb({state:t,outcome:"recovery",summary:e.reason,completedAt:i}));return ne({...r,phase:"build",status:"active",state_version:xb(t),verification_result:"pending",verification_report:null,verification:null,builder_handoff:null,blockers:[],acceptance:Rb(t.acceptance),loop:{...t.loop,stage:"repairing",iteration:t.loop.iteration+1,attempt:0,execution_failure_count:0,next_action:"submit-builder-candidate"}})}import{promises as Pf}from"node:fs";import or from"node:path";function ra(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function na(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function Ie(e,t,i=!1){if(typeof e!="string"||!i&&e.length===0)throw new Error(`${t} must be ${i?"a string":"a non-empty string"}`);return e}function Ef(e,t){return e===null?null:Ie(e,t)}function oa(e,t,i=0){if(!Number.isSafeInteger(e)||e<i)throw new Error(`${t} must be a safe integer greater than or equal to ${i}`);return e}function Ab(e,t){if(e===null)return null;if(!Number.isSafeInteger(e))throw new Error(`${t} must be null or a safe integer`);return e}function _b(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function aa(e,t,i){if(typeof e!="string"||!t.includes(e))throw new Error(`${i} must be one of: ${t.join(", ")}`);return e}function Qs(e,t){if(e===null)return null;let i=Ie(e,t);if(Number.isNaN(Date.parse(i)))throw new Error(`${t} must be an ISO timestamp`);return i}function Zs(e,t){let i=Ie(e,t);if(!or.isAbsolute(i))throw new Error(`${t} must be absolute`);return or.resolve(i)}function Tb(e,t){let i=`Native local checks[${t}]`,r=ra(e,i);if(na(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,u)=>Ie(l,`${i}.argv[${u}]`,!0)),a=aa(r.status,["planned","running","passed","failed","interrupted"],`${i}.status`),o=Qs(r.startedAt,`${i}.startedAt`),s=Qs(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=oa(r.timeoutMs,`${i}.timeoutMs`);if(c<1)throw new Error(`${i}.timeoutMs must be positive`);return{id:Ie(r.id,`${i}.id`),name:Ie(r.name,`${i}.name`),operationId:Ie(r.operationId,`${i}.operationId`),status:a,repeatable:_b(r.repeatable,`${i}.repeatable`),timeoutMs:c,executionCount:oa(r.executionCount,`${i}.executionCount`),argv:n,cwd:Zs(r.cwd,`${i}.cwd`),exitCode:Ab(r.exitCode,`${i}.exitCode`),startedAt:o,completedAt:s,log:Ie(r.log,`${i}.log`)}}function ec(e){let t="Native local execution state",i=ra(e,t);if(na(i,new Set(["schema","change","basedOnStateVersion","workspace","execution","checks"]),t),i.schema!==Ki)throw new Error(`Native local execution schema must be ${Ki}`);let r=ra(i.workspace,"Native local workspace");na(r,new Set(["projectRoot","worktreeRoot","branch"]),"Native local workspace");let n=null;if(i.execution!==null){let o=ra(i.execution,"Native local execution");na(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds"]),"Native local execution");let s=Qs(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:Ie(o.operationId,"Native local execution.operationId"),stage:aa(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:aa(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:Ef(o.executionId,"Native local execution.executionId"),status:aa(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:oa(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(Tb);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:Ie(i.change,"Native local change"),basedOnStateVersion:oa(i.basedOnStateVersion,"Native local basedOnStateVersion",1),workspace:{projectRoot:Zs(r.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:Zs(r.worktreeRoot,"Native local workspace.worktreeRoot"),branch:Ef(r.branch,"Native local workspace.branch")},execution:n,checks:a}}function st(e){return ec({schema:Ki,change:e.portableState.name,basedOnStateVersion:e.portableState.state_version,workspace:{projectRoot:or.resolve(e.projectRoot),worktreeRoot:or.resolve(e.worktreeRoot??e.projectRoot),branch:e.branch??null},execution:null,checks:[]})}async function tc(e){let t;try{t=await Pf.readFile(e,"utf8")}catch(r){if(r.code==="ENOENT")return null;throw r}let i;try{i=JSON.parse(t)}catch(r){throw new Error(`Native local execution state is invalid JSON: ${r.message}`,{cause:r})}return ec(i)}async function Be(e,t,i={}){let r=ec(t);await Pf.mkdir(or.dirname(e),{recursive:!0}),await X(e,r,i)}import{promises as Ib}from"node:fs";function ct(e){return e===null?"—":`${e.text.replace(/\r\n?/gu,`
|
|
151
|
-
`).replace(/\s+/gu," ").trim()||"—"}${e.truncated?" … (truncated)":""}`}function Le(e){return e.replaceAll("|","\\|").replace(/\r?\n/gu,"<br>")}function
|
|
149
|
+
`),o.context,r)),o=null}};for(let{line:c,body:l}of Ji(e)){let u=l?Ss(c):null,f=u?/^Scenario\s*:\s*(.*)$/iu.exec(u.text):null;if(f){for(s();a.at(-1)&&a.at(-1).level>=u.level;)a.pop();let d=Gi(f[1]);if(d.length===0)throw new Error("Scenario title must not be empty");o={level:u.level,title:d,body:[],context:a.map(p=>p.text)}}else if(u){for(o!==null&&u.level<=o.level?s():o!==null&&o.body.push(c);a.at(-1)&&a.at(-1).level>=u.level;)a.pop();a.push(u)}else o!==null&&l&&o.body.push(c)}return s(),Ps(n,"Specification",r)}function Cs(e,t="spec.md",i=Ui.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(Es("spec-must",t,s.parts.join(" "),s.context,r)),s=null}},l=()=>a.some(u=>/^(?:non-?goals?|非目标)$/iu.test(u.text.trim()));for(let{line:u,body:f}of Ji(e)){let d=f?Ss(u):null;if(d){for(c(),o!==null&&d.level<=o&&(o=null);a.at(-1)&&a.at(-1).level>=d.level;)a.pop();a.push(d),/^Scenario\s*:/iu.test(d.text)&&(o=d.level);continue}let p=u.trim();if(!f||o!==null||l()){c();continue}if(p.length===0||ks(u,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(u);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(),Ps(n,"Specification mandatory requirements",r)}var ly=/^A[1-9]\d*$/u;function qd(e,t){if(e.length===0||e!==e.trim()||e.includes("\\")||Ld.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||Ld.posix.normalize(e)!==e||e==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized change-relative ref`);return e}function uy(e,t){return e.localeCompare(t,"en")}function Hn(e){let t=qd(e.briefSource??"brief.md","Native brief source"),i=[...e.specs??[]].sort((a,o)=>uy(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=xs(e.briefMarkdown,t,Number.MAX_SAFE_INTEGER,"none").map(({source:a,text:o})=>({source:a,text:o}));for(let a of i){let o=qd(a.source,`Native spec source for ${a.capability}`);r.push(...Rs(a.markdown,o,Number.MAX_SAFE_INTEGER,"none").map(({text:s})=>({source:o,text:s})),...Cs(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=Gi(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 Fd(e){let t=e.map(({id:i})=>i);if(new Set(t).size!==t.length)throw new Error("Native acceptance IDs must be unique");for(let i=0;i<t.length;i+=1)if(!ly.test(t[i])||t[i]!==`A${i+1}`)throw new Error("Native acceptance IDs must be the contiguous sequence A1..An")}function Md(e,t){return e.length===t.length&&e.every((i,r)=>i.source===t[r]?.source&&i.text===t[r]?.text)}var Ln=ai(Ft(),1);import{promises as dy}from"node:fs";var Jt="comet.native.v4",Ki="comet.native.local-execution.v4";function As(){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 fy=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,hy=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,py=/^A[1-9][0-9]*$/u,my=/^[a-f0-9]{64}$/u,vy=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"]),Bn=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 te(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ie(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function W(e,t,i){if(typeof e!="string"||!i?.empty&&e.length===0)throw new Error(`${t} must be ${i?.empty?"a string":"a non-empty string"}`);return e}function Ts(e,t){return e===null?null:W(e,t)}function gy(e,t){let i=W(e,t);if(!my.test(i))throw new Error(`${t} must be a SHA-256 hash`);return i}function Gt(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function _(e,t,i=0){if(!Number.isSafeInteger(e)||e<i)throw new Error(`${t} must be a safe integer greater than or equal to ${i}`);return e}function wy(e,t){return e===null?null:_(e,t,Number.MIN_SAFE_INTEGER)}function V(e,t,i){if(typeof e!="string"||!t.includes(e))throw new Error(`${i} must be one of: ${t.join(", ")}`);return e}function Ae(e,t,i){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((r,n)=>i(r,n))}function qn(e,t){return Ae(e,t,(i,r)=>W(i,`${t}[${r}]`))}function Nt(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function Ut(e,t){let i=W(e,t);if(Number.isNaN(Date.parse(i)))throw new Error(`${t} must be an ISO date or timestamp`);return i}function Is(e,t,i=!1){let r=W(e,t);if(r.includes("\\")||r.startsWith("/")||/^[A-Za-z]:/u.test(r)||r.split("/").includes("..")||!i&&(r==="."||r.split("/").includes(".")))throw new Error(`${t} must be a portable relative path`);return r}function Ne(e,t){let i=te(e,t);return ie(i,new Set(["text","truncated"]),t),{text:W(i.text,`${t}.text`,{empty:!0}),truncated:Gt(i.truncated,`${t}.truncated`)}}function yy(e,t){let i=`Native spec_changes[${t}]`,r=te(e,i);ie(r,new Set(["capability","operation","source"]),i);let n=W(r.capability,`${i}.capability`);if(!hy.test(n))throw new Error(`${i}.capability is invalid`);let a=V(r.operation,["create","modify","remove"],`${i}.operation`),o=r.source===null?null:Is(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 Ny(e){let t="Native workspace",i=te(e,t);ie(i,new Set(["isolation","change_branch","target_branch","finish"]),t);let r=V(i.isolation,["current","branch","worktree"],`${t}.isolation`),n=Ts(i.change_branch,`${t}.change_branch`),a=Ts(i.target_branch,`${t}.target_branch`),o=i.finish===null?null:V(i.finish,["merge","push","pull-request","keep"],`${t}.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 by(e){let t="Native loop",i=te(e,t);ie(i,new Set(["stage","goal_cycle","iteration","attempt","retry_epoch","failed_iteration_count","no_progress_count","execution_failure_count","previous_unresolved_ids","next_action"]),t);let r=qn(i.previous_unresolved_ids,`${t}.previous_unresolved_ids`);return Nt(r,`${t}.previous_unresolved_ids`),{stage:V(i.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:_(i.goal_cycle,`${t}.goal_cycle`,1),iteration:_(i.iteration,`${t}.iteration`),attempt:_(i.attempt,`${t}.attempt`),retry_epoch:_(i.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:_(i.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:_(i.no_progress_count,`${t}.no_progress_count`),execution_failure_count:_(i.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:r,next_action:Ts(i.next_action,`${t}.next_action`)}}function ky(e,t){let i=`Native acceptance[${t}]`,r=te(e,i);ie(r,new Set(["id","source","text","result","reason"]),i);let n=W(r.id,`${i}.id`);if(!py.test(n))throw new Error(`${i}.id must use A1, A2, ...`);return{id:n,source:Is(r.source,`${i}.source`),text:W(r.text,`${i}.text`),result:V(r.result,["pending","passed","failed","blocked"],`${i}.result`),reason:r.reason===null?null:Ne(r.reason,`${i}.reason`)}}function Sy(e,t){let i=`Native builder_handoff.checks[${t}]`,r=te(e,i);return ie(r,new Set(["name","result","note"]),i),{name:Ne(r.name,`${i}.name`),result:V(r.result,["passed","failed","not-run"],`${i}.result`),note:r.note===null?null:Ne(r.note,`${i}.note`)}}function Ey(e){let t="Native builder_handoff",i=te(e,t);ie(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"]),t);let r=qn(i.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);return Nt(r,`${t}.addressed_acceptance_ids`),{candidate_id:W(i.candidate_id,`${t}.candidate_id`),identity_provider:W(i.identity_provider,`${t}.identity_provider`),builder_execution_ref:W(i.builder_execution_ref,`${t}.builder_execution_ref`),iteration:_(i.iteration,`${t}.iteration`,1),summary:Ne(i.summary,`${t}.summary`),addressed_acceptance_ids:r,checks:Ae(i.checks,`${t}.checks`,Sy),checks_truncated:Gt(i.checks_truncated,`${t}.checks_truncated`),known_limits:Ae(i.known_limits,`${t}.known_limits`,(n,a)=>Ne(n,`${t}.known_limits[${a}]`)),known_limits_truncated:Gt(i.known_limits_truncated,`${t}.known_limits_truncated`),submitted_at:Ut(i.submitted_at,`${t}.submitted_at`)}}function Py(e,t){let i=`Native blockers[${t}]`,r=te(e,i);ie(r,new Set(["owner","reason","acceptance_ids","resolution_action"]),i);let n=qn(r.acceptance_ids,`${i}.acceptance_ids`);return Nt(n,`${i}.acceptance_ids`),{owner:V(r.owner,["builder","runtime","verifier","user","external"],`${i}.owner`),reason:Ne(r.reason,`${i}.reason`),acceptance_ids:n,resolution_action:V(r.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${i}.resolution_action`)}}function xy(e,t){let i=`Native verification.checks[${t}]`,r=te(e,i);return ie(r,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),i),{id:W(r.id,`${i}.id`),name:Ne(r.name,`${i}.name`),argv_display:Ae(r.argv_display,`${i}.argv_display`,(n,a)=>Ne(n,`${i}.argv_display[${a}]`)),argv_truncated:Gt(r.argv_truncated,`${i}.argv_truncated`),cwd_ref:Is(r.cwd_ref,`${i}.cwd_ref`,!0),status:V(r.status,["passed","failed","interrupted"],`${i}.status`),exit_code:wy(r.exit_code,`${i}.exit_code`),duration_ms:_(r.duration_ms,`${i}.duration_ms`)}}function Ry(e){let t="Native verification",i=te(e,t);ie(i,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let r=Ae(i.checks,`${t}.checks`,xy);Nt(r.map(a=>a.id),`${t}.checks IDs`);let n=W(i.identity_provider,`${t}.identity_provider`);return{candidate_id:W(i.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:W(i.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:_(i.iteration,`${t}.iteration`,1),attempt:_(i.attempt,`${t}.attempt`,1),assurance:i.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":V(i.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:V(i.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:r,summary:Ne(i.summary,`${t}.summary`),risks:Ae(i.risks,`${t}.risks`,(a,o)=>Ne(a,`${t}.risks[${o}]`)),risks_truncated:Gt(i.risks_truncated,`${t}.risks_truncated`),completed_at:Ut(i.completed_at,`${t}.completed_at`)}}function Vd(e,t){let i=`Native history[${t}]`,r=te(e,i);ie(r,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),i);let n=qn(r.unresolved_ids,`${i}.unresolved_ids`);return Nt(n,`${i}.unresolved_ids`),{goal_cycle:_(r.goal_cycle,`${i}.goal_cycle`,1),iteration:_(r.iteration,`${i}.iteration`),attempt:_(r.attempt,`${i}.attempt`),outcome:V(r.outcome,["pass","fail","blocked","execution-error","recovery"],`${i}.outcome`),unresolved_ids:n,summary:Ne(r.summary,`${i}.summary`),completed_at:Ut(r.completed_at,`${i}.completed_at`)}}function Cy(e){let t="Native history_overflow.outcome_counts",i=te(e,t),r=["pass","fail","blocked","execution-error","recovery"];return ie(i,new Set(r),t),{pass:_(i.pass,`${t}.pass`),fail:_(i.fail,`${t}.fail`),blocked:_(i.blocked,`${t}.blocked`),"execution-error":_(i["execution-error"],`${t}.execution-error`),recovery:_(i.recovery,`${t}.recovery`)}}function Ay(e){let t="Native history_overflow",i=te(e,t);ie(i,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let r=_(i.dropped_entries,`${t}.dropped_entries`),n=i.first_dropped_at===null?null:Ut(i.first_dropped_at,`${t}.first_dropped_at`),a=i.last_dropped_at===null?null:Ut(i.last_dropped_at,`${t}.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=Cy(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 _y(e){let t=new Set(e.acceptance.map(i=>i.id));for(let i of e.loop.previous_unresolved_ids)if(!t.has(i))throw new Error(`Native loop references unknown acceptance ID ${i}`);for(let i of e.builder_handoff?.addressed_acceptance_ids??[])if(!t.has(i))throw new Error(`Native builder handoff references unknown ID ${i}`);for(let i of e.blockers)for(let r of i.acceptance_ids)if(!t.has(r))throw new Error(`Native blocker references unknown ID ${r}`);if(e.builder_handoff&&!(e.builder_handoff.iteration===e.loop.iteration||e.phase==="build"&&e.loop.stage==="repairing"&&e.builder_handoff.iteration===e.loop.iteration-1))throw new Error("Native builder handoff iteration is not current or the prior repair result");if(e.verification){if(!e.builder_handoff)throw new Error("Native verification requires a builder handoff");if(e.verification.candidate_id!==e.builder_handoff.candidate_id)throw new Error("Native verification candidate must match the builder handoff");if(e.verification.identity_provider!==e.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(e.verification.assurance)!==(e.verification.identity_provider==="skill-coordinated"))throw new Error("Native verification assurance does not match its identity provider");if(e.verification.assurance==="semantic-verification-unavailable"&&e.verification.verdict!=="blocked")throw new Error("Native unavailable semantic verification must remain blocked");if(e.verification.assurance==="user-confirmed-degraded"&&e.verification.verdict!=="pass")throw new Error("Native user-confirmed degraded verification must be passing");if(e.verification.verifier_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native Builder and Verifier execution refs must differ");let r=e.verification.iteration===e.loop.iteration&&e.verification.attempt===e.loop.attempt,n=e.phase==="build"&&e.loop.stage==="repairing"&&e.verification.iteration===e.loop.iteration-1&&e.verification.iteration===e.builder_handoff.iteration;if(!r&&!n)throw new Error("Native verification iteration and attempt do not match a stable loop result")}}function Ty(e){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"])}[e.phase].has(e.loop.stage))throw new Error(`Native loop stage ${e.loop.stage} is invalid for phase ${e.phase}`);let i=e.status==="await-user"?"await-user":e.status==="blocked"?"blocked":e.status==="done"?"done":null;if(i!==null&&e.loop.stage!==i)throw new Error(`Native status ${e.status} requires loop stage ${i}`);if(e.status==="active"&&["await-user","blocked","done"].includes(e.loop.stage))throw new Error(`Native active status cannot use loop stage ${e.loop.stage}`);if(e.archived!==(e.status==="done"))throw new Error("Native archived must be true exactly when status is done");if(e.archived&&e.phase!=="archive")throw new Error("Native archived state must be in Archive");if(e.verification_result==="pass"){if(e.verification?.verdict!=="pass")throw new Error("Native pass requires a persisted passing verification");if(e.acceptance.some(r=>r.result!=="passed"))throw new Error("Native pass requires every acceptance item to pass");if(e.verification.checks.some(r=>r.status!=="passed"))throw new Error("Native pass requires every persisted check to pass")}if(e.verification?.assurance==="semantic-verification-unavailable"&&(e.phase!=="verify"||e.status!=="await-user"||e.verification_result!=="blocked"||e.loop.next_action!=="confirm-verifier-unavailable"))throw new Error("Native unavailable semantic verification must await explicit user confirmation");if(e.verification_report!==null&&e.verification===null)throw new Error("Native verification report requires persisted verification")}function ne(e){let t=te(e,"Native portable state");if(ie(t,vy,"Native portable state"),t.schema!==Jt)throw new Error(`Native portable state schema must be ${Jt}`);let i=W(t.name,"Native state name");if(!fy.test(i))throw new Error("Native state name is invalid");if(t.brief!=="brief.md")throw new Error("Native state brief must be brief.md");let r=Ae(t.spec_changes,"Native spec_changes",yy);Nt(r.map(s=>s.capability),"Native spec change capabilities");let n=Ae(t.acceptance,"Native acceptance",ky);Nt(n.map(s=>s.id),"Native acceptance IDs");let a=Ae(t.history,"Native history",Vd);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:Jt,name:i,language:V(t.language,["en","zh-CN"],"Native state language"),phase:V(t.phase,["shape","build","verify","archive"],"Native state phase"),status:V(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:_(t.state_version,"Native state_version",1),brief:"brief.md",...t.children_contract_hash===void 0?{}:{children_contract_hash:gy(t.children_contract_hash,"Native children contract hash")},spec_changes:r,workspace:Ny(t.workspace),loop:by(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:Ey(t.builder_handoff),blockers:Ae(t.blockers,"Native blockers",Py),verification:t.verification===null?null:Ry(t.verification),history:a,history_overflow:Ay(t.history_overflow),verification_result:V(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:V(t.verification_report,["verification.md"],"Native verification_report"),archived:Gt(t.archived,"Native archived"),created_at:Ut(t.created_at,"Native created_at")};return _y(o),Ty(o),o}function Kt(e,t){let i=ne(e),r=Vd(t,i.history.length),n=[...i.history,r],a={...i.history_overflow,outcome_counts:{...i.history_overflow.outcome_counts}};for(;n.length>50;){let o=n.shift();a.dropped_entries+=1,a.first_dropped_at??=o.completed_at,a.last_dropped_at=o.completed_at,a.outcome_counts[o.outcome]+=1}return ne({...i,history:n,history_overflow:a})}function Iy(e,t){let i=(0,Ln.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`${t} is invalid YAML: ${i.errors[0].message}`);return i.toJS({mapAsMap:!1})}async function ae(e){let t=await dy.readFile(e,"utf8");return ne(Iy(t,"Native portable state"))}async function Fn(e,t,i={}){let r=ne(t);await Y(e,(0,Ln.stringify)(r),i)}var Dn=new Map;async function jy(e,t){let i=Dn.get(e)??Promise.resolve(),r,n=new Promise(o=>{r=o}),a=i.then(()=>n);Dn.set(e,a),await i;try{return await t()}finally{r(),Dn.get(e)===a&&Dn.delete(e)}}async function bt(e){return jy(e.file,async()=>{let t=_(e.expectedStateVersion,"Native expected state version",1),i=ne(e.next);if(i.state_version!==t+1)throw new Error("Native CAS next state_version must increment exactly once");let r=await ae(e.file);if(r.state_version===i.state_version&&JSON.stringify(r)===JSON.stringify(i))return r;if(r.state_version!==t)throw new Bn(t,r.state_version);return await Fn(e.file,i,{...e.containedRoot?{containedRoot:e.containedRoot}:{},beforeCommit:async()=>{let n=await ae(e.file);if(n.state_version!==t)throw new Bn(t,n.state_version)}}),i})}function $y(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("Native portable text byte budget must be a non-negative safe integer")}function at(e,t=16384){if(typeof e!="string")throw new Error("Native portable text must be a string");if($y(t),Buffer.byteLength(e,"utf8")<=t)return{text:e,truncated:!1};let i="",r=0;for(let n of e){let a=Buffer.byteLength(n,"utf8");if(r+a>t)break;i+=n,r+=a}return{text:i,truncated:!0}}var He="comet.native.v3",_e="comet.native.v2",Te="comet.native.v1";var Mn="comet.native.portable-migration.v1",Hy=new Set(["schema","id","change","fromSchema","status","createdAt"]),Dy=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,By=/^[a-z0-9][a-z0-9-]{7,127}$/u,Ly=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),qy=new Set([Te,_e,He]);function Fy(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function My(e,t){let i=e instanceof Date?new Date(e.valueOf()):new Date(e);if(Number.isNaN(i.valueOf()))throw new Error(`${t} must be a valid timestamp`);return i.toISOString()}function Vy(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let i=new Date(e);if(Number.isNaN(i.valueOf())||i.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function Wy(e){return e.schema===Te?Yi(e):e.schema===_e?Xi(e):Qi(e)}function zy(e){return Oy.posix.normalize(e.replaceAll("\\","/"))}function Jy(e){return e.spec_changes.map(t=>t.operation==="remove"?{capability:t.capability,operation:"remove",source:null}:{capability:t.capability,operation:t.operation==="replace"?"modify":"create",source:zy(t.source)})}function Gy(e){return e==="shape"?"shape":"build"}function Uy(e,t){return e==="zh-CN"?t==="shape"?"继续澄清并确认验收项":"重新提交候选实现":t==="shape"?"Continue clarification and confirm acceptance":"Submit a fresh implementation candidate"}function Ky(e,t,i){return e==="zh-CN"?`从旧版 ${t} ${i} 状态恢复;旧版 Loop、验证结论和运行记录未继承。`:`Recovered from legacy ${t} ${i} state; prior Loop, verification results, and execution records were not inherited.`}function Wd(e){let t=Wy(e.state);Fd(e.acceptance);let i=Gy(t.phase),r=i==="shape"?0:1,n=My(e.migratedAt??`${t.created_at}T00:00:00.000Z`,"Native portable migration time"),a=e.acceptance.map(o=>({id:o.id,source:o.source,text:o.text,result:"pending",reason:null}));return ne({schema:Jt,name:t.name,language:t.language,phase:i,status:"active",state_version:1,brief:"brief.md",spec_changes:Jy(t),workspace:e.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:Uy(t.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:at(Ky(t.language,t.schema,t.phase)),completed_at:n}],history_overflow:As(),verification_result:"pending",verification_report:null,archived:!1,created_at:`${t.created_at}T00:00:00.000Z`})}function js(e){let t=Fy(e,"Native portable migration transaction"),i=Object.keys(t).filter(r=>!Hy.has(r));if(i.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${i.join(", ")}`);if(t.schema!==Mn)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!By.test(t.id))throw new Error("Native portable migration transaction id is invalid");if(typeof t.change!="string"||!Dy.test(t.change))throw new Error("Native portable migration transaction change is invalid");if(typeof t.fromSchema!="string"||!qy.has(t.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof t.status!="string"||!Ly.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:Mn,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:Vy(t.createdAt,"Native portable migration transaction createdAt")}}function zd(e){switch(js(e).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 Vn="comet.native.archive-transaction.v4",Jd="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",Yy=new RegExp(`^portable-archive-(${Jd})\\.json$`,"u"),Xy=new RegExp(`^portable-migration-(${Jd})\\.json$`,"u"),Qy=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Zy=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,eN=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),tN=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),iN=new Set(["capability","operation","source","content"]),Gd=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function Ud(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Kd(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`);if(Object.keys(e).length!==t.size)throw new Error(`${i} fields are invalid`)}function rN(e,t){let i=`Native portable Archive spec_changes[${t}]`,r=Ud(e,i);if(Kd(r,iN,i),typeof r.capability!="string"||!Gd.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 nN(e){let t=Ud(e,"Native portable Archive transaction");if(Kd(t,tN,"Native portable Archive transaction"),t.schema!==Vn)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!Qy.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!Gd.test(t.change))throw new Error("Native portable Archive transaction change is invalid");if(!Number.isSafeInteger(t.start_state_version)||Number(t.start_state_version)<0)throw new Error("Native portable Archive transaction state version is invalid");if(typeof t.archive_ref!="string"||!Zy.test(t.archive_ref)||!t.archive_ref.endsWith(`-${t.change}`))throw new Error("Native portable Archive transaction ref is invalid");if(typeof t.status!="string"||!eN.has(t.status))throw new Error("Native portable Archive transaction status is invalid");if(!Array.isArray(t.spec_changes))throw new Error("Native portable Archive transaction spec changes are invalid");let i=t.spec_changes.map(rN);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(t.next_spec_index)||Number(t.next_spec_index)<0||Number(t.next_spec_index)>i.length)throw new Error("Native portable Archive transaction spec cursor is invalid");if(typeof t.created_at!="string")throw new Error("Native portable Archive transaction timestamp is invalid");let r=new Date(t.created_at);if(Number.isNaN(r.valueOf())||r.toISOString()!==t.created_at)throw new Error("Native portable Archive transaction timestamp is invalid");return{schema:Vn,id:t.id,change:t.change,start_state_version:Number(t.start_state_version),archive_ref:t.archive_ref,status:t.status,next_spec_index:Number(t.next_spec_index),spec_changes:i,created_at:t.created_at}}function Wn(e){let t=Yy.exec(e);if(t)return{kind:"archive",change:t[1]};let i=Xy.exec(e);return i?{kind:"migration",change:i[1]}:null}function kt(e,t){let i=`${t.kind==="archive"?"portable-archive":"portable-migration"}-${t.change}.json`,r=Wn(i);if(!r||r.kind!==t.kind||r.change!==t.change)throw new Error(`Invalid Native portable transaction change: ${t.change}`);return $s.join(e.transactionsDir,i)}async function Os(e,t){let i=Wn(t);if(!i)return null;let r=await j({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),n=JSON.parse(r.text),a=$s.join(e.transactionsDir,t);if(i.kind==="archive"){let s=nN(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=js(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 Yt(e,t){let i=kt(e,t);try{return await Os(e,$s.basename(i))}catch(r){if(r.code==="ENOENT")return null;throw r}}function Yd(e){return e.kind==="archive"||e.journal.status!=="committed"}import De from"path";import{TextDecoder as fN}from"util";import{createHash as aN}from"node:crypto";import{constants as zn,promises as be}from"node:fs";import ke from"node:path";function Gn(e,t){let i=ke.relative(e,t);return i===""||!ke.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${ke.sep}`)}function oN(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function sN(e,t){return A({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function cN(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Jn(e,t){return A({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function Hs(e,t){let i=await be.lstat(e);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await be.realpath(e),dev:i.dev,ino:i.ino,birthtimeMs:i.birthtimeMs}}async function lN(e,t,i){let r=ke.resolve(e),n=ke.resolve(t);if(!Gn(r,n))throw new Error(`${i} is outside its managed root`);let a=[await Hs(r,i)],o=r;for(let s of ke.relative(r,n).split(ke.sep).filter(Boolean)){await St(a,i),o=ke.join(o,s);let c=await Hs(o,i);if(!Gn(a[0].realPath,c.realPath))throw new Error(`${i} parent resolves outside its managed root: ${o}`);a.push(c)}return await St(a,i),a}async function St(e,t){for(let i of e){let r=await be.lstat(i.path);if(!r.isDirectory()||r.isSymbolicLink()||!sN(i,r)||await be.realpath(i.path)!==i.realPath)throw new Error(`${t} parent changed during I/O: ${i.path}`)}}async function uN(e,t,i){let r=[],n=0,a=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let o=t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,n>t)throw new Error(`${i} exceeds ${t} bytes`);r.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(r,n)}async function Xt(e){let t=oN(e.maxBytes),i=ke.resolve(e.file),r=await lN(e.root,ke.dirname(i),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(u=>Hs(ke.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await St(r,e.label);let a=await be.lstat(i);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);if(a.size>t)throw new Error(`${e.label} exceeds ${t} bytes`);let o=cN(a),s=await be.realpath(i);if(!Gn(r[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(u=>Gn(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?zn.O_RDONLY:zn.O_RDONLY|zn.O_NOFOLLOW|zn.O_NONBLOCK,l=await be.open(i,c);try{let u=await l.stat();await e.hooks?.afterOpen?.();let[f,d]=await Promise.all([be.lstat(i),be.realpath(i)]);if(await St(r,e.label),await St(n,e.label),!u.isFile()||!f.isFile()||f.isSymbolicLink()||d!==s||!Jn(o,u)||!Jn(o,f))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let p=await uN(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[v,h,m]=await Promise.all([l.stat(),be.lstat(i),be.realpath(i)]);if(await St(r,e.label),await St(n,e.label),!h.isFile()||h.isSymbolicLink()||m!==s||!Jn(o,v)||!Jn(o,h))throw new Error(`${e.label} changed while reading`);return{bytes:p,hash:aN("sha256").update(p).digest("hex"),size:p.length}}finally{await l.close()}}var hN=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),pN=new Set(["id","type","source","target","staged","backup"]),mN=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),vN=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]);var Zd=new Set(["prepared","applying","committed","rolling-back","rolled-back"]);var gN=256*1024,jx=1024*1024,$x=16*1024;var Ox=64*1024*1024;var wN=new fN("utf-8",{fatal:!0});function Kn(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Yn(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function ef(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function Ds(e,t){if(typeof e!="string"||e.length===0||De.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function Un(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function Xd(e,t){if(Ds(e,t),e.includes("\\")||e!==De.posix.normalize(e)||e.split("/").includes(".")||e.endsWith("/")||Buffer.byteLength(e,"utf8")>1024)throw new Error(`${t} must be a normalized Native-relative ref`)}function yN(e,t){let i=Kn(e,`transaction operations[${t}]`);if(Yn(i,pN,`transaction operations[${t}]`),typeof i.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(i.id))throw new Error(`transaction operations[${t}].id is invalid`);if(i.type!=="write"&&i.type!=="remove"&&i.type!=="move")throw new Error(`transaction operation ${i.id} has an invalid type`);Ds(i.target,`transaction operation ${i.id} target`);for(let r of["source","staged","backup"])i[r]!==void 0&&Ds(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 tf(e){let t=Kn(e,"Native Archive transaction journal");if(Yn(t,mN,"Native Archive transaction journal"),t.schema!=="comet.native.transaction.v2")throw new Error("Unsupported Native Archive transaction schema");if(typeof t.id!="string"||!/^[a-f0-9-]{8,}$/u.test(t.id))throw new Error("Native Archive transaction id is invalid");if(t.kind!=="archive")throw new Error("Native v2 transaction kind must be archive");if(typeof t.status!="string"||!Zd.has(t.status))throw new Error("Native Archive transaction status is invalid");if(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change))throw new Error("Native Archive transaction change name is invalid");if(!ef(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(Un(t.preflightHash,"Native Archive transaction preflightHash"),!Array.isArray(t.operations)||t.operations.length>65)throw new Error("Native Archive transaction operations must be an array");let i=t.operations.map((s,c)=>{let l=Kn(s,`Archive transaction operations[${c}]`);if(Yn(l,vN,`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`);Xd(l.target,`Archive transaction operation ${l.id} target`);for(let u of["source","staged","backup"])l[u]!==void 0&&Xd(l[u],`Archive transaction operation ${l.id} ${u}`);if(l.expectedTargetHash!==null&&Un(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(Un(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`);Un(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/${t.id}`,a=i.filter(s=>s.type==="move");if(a.length!==1||a[0].id!=="archive-change"||a[0].source!==`changes/${t.change}`||!new RegExp(`^archive/\\d{4}-\\d{2}-\\d{2}-${t.change}$`,"u").test(a[0].target)||i.at(-1)!==a[0])throw new Error("Native Archive transaction must end with its exact change move");let o=new Set;for(let s of i.slice(0,-1)){if(s.type==="move"||!/^specs\/[a-z][a-z0-9]*(?:-[a-z0-9]+)*\/spec\.md$/u.test(s.target)||o.has(s.target))throw new Error(`Native Archive transaction spec target is invalid: ${s.target}`);if(o.add(s.target),s.staged!==void 0&&!s.staged.startsWith(`${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:t.id,kind:"archive",status:t.status,change:t.change,createdAt:t.createdAt,preflightHash:t.preflightHash,operations:i}}function NN(e){let t=Kn(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return tf(t);if(Yn(t,hN,"Native transaction journal"),t.schema!=="comet.native.transaction.v1")throw new Error("Unsupported Native transaction schema");if(typeof t.id!="string"||!/^[a-f0-9-]{8,}$/u.test(t.id))throw new Error("Native transaction id is invalid");if(t.kind!=="archive"&&t.kind!=="root-move")throw new Error("Native transaction kind is invalid");if(typeof t.status!="string"||!Zd.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!De.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!De.isAbsolute(t.nativeRoot))throw new Error("Native transaction roots must be absolute paths");if(t.change!==void 0&&(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change)))throw new Error("Native transaction change name is invalid");if(!ef(t.createdAt))throw new Error("Native transaction createdAt is invalid");if(!Array.isArray(t.operations))throw new Error("Native transaction operations must be an array");let i=t.operations.map(yN),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:t.id,kind:t.kind,status:t.status,projectRoot:t.projectRoot,nativeRoot:t.nativeRoot,...typeof t.change=="string"?{change:t.change}:{},createdAt:t.createdAt,operations:i}}function bN(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return De.join(e.transactionsDir,t)}function rf(e,t){let i=bN(e,t);return{directory:i,journal:De.join(i,"transaction.json"),events:De.join(i,"events.jsonl"),staged:De.join(i,"staged"),backups:De.join(i,"backups")}}async function Ls(e,t){let i=rf(e,t);return await Promise.all(Object.values(i).map(r=>T(e.runtimeDir,r))),i}async function qs(e,t,i={}){let r=await Ls(e,t),n=await Xt({root:e.runtimeDir,file:r.journal,maxBytes:gN,label:`Native transaction journal ${t}`,hooks:i.hooks}),a=JSON.parse(wN.decode(n.bytes)),o=NN(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}async function EN(e,t,i){let r;try{r=await kN.readdir(e.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 qs(e,n.name);if(a.id!==t&&a.status!=="committed"&&a.status!=="rolled-back")return!0}catch{return!0}for(let n of r)if(Wn(n.name))try{let a=await Os(e,n.name);if(!a||i?.kind===a.kind&&i.change===a.change)continue;if(Yd(a))return!0}catch{return!0}return!1}async function PN(e,t){let i=Date.now()+5e3,r=SN.join(e.locksDir,"root-move.lock");for(;;)try{return await $n(e,"root-move",t)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await Dd(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 G(e,t,i,r){let n=await PN(e,t);try{if(await zi(e.projectRoot),await EN(e,r?.allowedTransactionId,r?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await i()}finally{await On(n)}}import{createHash as xN}from"crypto";function de(e){return xN("sha256").update(e).digest("hex")}var iR={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024};var rR=8*1024*1024;var nR=64*1024,aR=64*1024;var oR={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},sR={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};var cR=(1n<<256n)-1n;var jN=ai(Ft(),1);var ER=4*1024*1024;var $N=null;function ON(e,t){let i=e;for(let r of t)i+="\0"+(typeof r=="string"?r:JSON.stringify(r));return i}function nf(e,t){return(...i)=>{let r=$N;if(r===null)return t(...i);let n=ON(`async:${e}`,i),a=r.entries.get(n);if(a)return a.value;let o=t(...i).catch(s=>{throw r.entries.delete(n),s});return r.entries.set(n,{value:o}),o}}var AR=nf("hookWritePolicy",async e=>(await ds(e))?.hook??{allow_paths:[]});var EC=256*1024;var DC={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 Qt from"node:path";var Zi=/^[a-f0-9]{64}$/u,of=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,BN=16*1024,ZC=process.platform;function LN(e,t){let i=Qt.relative(e,t);return Qt.isAbsolute(i)||i===".."||i.startsWith(`..${Qt.sep}`)?null:i.replaceAll("\\","/")||"."}function sf(e){return Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127})}function cf(e,t){if(e.length===0||sf(e)||e.includes("\\")||Qt.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes(".."))throw new Error(`${t} must be a portable project-relative path`);let i=Qt.posix.normalize(e);if(i!==e||i===".."||i.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return i}function qN(e){if(typeof e!="string")throw new Error("Native workspace capturedAt is invalid");let t=new Date(e);if(!Number.isFinite(t.getTime())||t.toISOString()!==e)throw new Error("Native workspace capturedAt is invalid");return e}function Fs(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||sf(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function FN(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(Fs(e.changeBranch,"Native workspace change branch"),Fs(e.targetBranch,"Native workspace target branch"),(e.isolation==="branch"||e.isolation==="worktree")&&(e.changeBranch===null||e.targetBranch===null))throw new Error("Native isolated workspace requires change and target branches")}function MN(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace Git provenance must be an object");let t=e,i=new Set(["provider","baseCommit","targetBranch","targetCommit"]),r=Object.keys(t).filter(n=>!i.has(n));if(r.length>0)throw new Error(`Native workspace Git provenance has unknown field(s): ${r.join(", ")}`);if(t.provider!=="git"||typeof t.baseCommit!="string"||!of.test(t.baseCommit)||typeof t.targetCommit!="string"||!of.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");Fs(t.targetBranch,"Native workspace Git target branch")}function VN(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace identity must be an object");let t=e,i=new Set(["schema","capturedAt","capturedRevision","nativeRootRef","projectRootId","nativeRootId","projectRootPathId","nativeRootPathId","sessionHash","git","isolation","changeBranch","targetBranch","finish"]),r=Object.keys(t).filter(o=>!i.has(o));if(r.length>0)throw new Error(`Native workspace identity has unknown field(s): ${r.join(", ")}`);if(t.schema!=="comet.native.workspace.v2"&&t.schema!=="comet.native.workspace.v3")throw new Error("Unsupported Native workspace identity");if(!Number.isSafeInteger(t.capturedRevision)||t.capturedRevision<1||typeof t.nativeRootRef!="string"||!Zi.test(String(t.projectRootId))||!Zi.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");qN(t.capturedAt),cf(t.nativeRootRef,"Native workspace root ref");let n=t.projectRootPathId!==void 0,a=t.nativeRootPathId!==void 0;if(n!==a)throw new Error("Native workspace path identities must be provided together");if(n&&!Zi.test(String(t.projectRootPathId))||a&&!Zi.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!Zi.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&MN(t.git),t.schema==="comet.native.workspace.v2"){if(t.isolation!==void 0||t.changeBranch!==void 0||t.targetBranch!==void 0||t.finish!==void 0)throw new Error("Native workspace v2 identity cannot contain a workspace binding");return}if(typeof t.isolation!="string"||t.changeBranch===void 0||t.targetBranch===void 0||t.finish===void 0)throw new Error("Native workspace v3 identity requires a workspace binding");if(FN(t),t.finish!==null&&!new Set(["merge","push","pull-request","keep"]).has(t.finish))throw new Error("Native workspace finish must be merge, push, pull-request, keep, or null")}function WN(e,t){return Qt.join(Re(e,t),"workspace.json")}function zN(e,t){let i=WN(e,t),r=Ce(e,i),n=LN(r,i);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:r,ref:cf(n,"Native workspace file ref")}}async function JN(e,t){try{let i=zN(e,t),r=await j({root:i.root,ref:i.ref,maxBytes:BN});return JSON.parse(r.text)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function er(e,t){let i=await JN(e,t);return i===null||i&&typeof i=="object"&&!Array.isArray(i)&&i.schema==="comet.native.workspace.v1"?null:(VN(i),i)}var uf=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],KN=new Set(uf),df=new Set([...uf,"minimum_runtime_version","revision"]),YN=new Set([...df,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),XN=new Set(["capability","operation","source","base_hash"]),QN=new Set(["shape","build","verify","archive"]),ZN=new Set(["implicit","confirmed"]),eb=new Set(["pending","pass","fail"]),Et="comet-state.yaml",Vs=/^[a-f0-9]{64}$/u,ff=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,tb=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,Ws=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"},ei=class extends Error{constructor(i,r){super(i!==He||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"},Xn=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"},tr=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"},Qn=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"},SA=["# Outcome","","# Scope","","# Non-goals","","# Acceptance examples","","# Constraints and invariants","","# Decisions","","# Open questions","","# Verification expectations",""].join(`
|
|
150
|
+
`);function rr(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function hf(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function Js(e){if(!ff.test(e))throw new Error(`Invalid Native change name: ${e}`)}function ib(e){if(!ff.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function pf(e,t){if(e.length===0||Zt.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function rb(e,t){let i=rr(e,`spec_changes[${t}]`);if(hf(i,XN,`spec_changes[${t}]`),typeof i.capability!="string")throw new Error("spec change capability is required");if(ib(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"&&pf(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"||!Vs.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"||!Vs.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 nb(e){return/^\d{4}-\d{2}-\d{2}$/u.test(e)?new Date(`${e}T00:00:00.000Z`).toISOString().slice(0,10)===e:!1}function Gs(e,t){if(hf(e,t,Et),typeof e.name!="string")throw new Error("Native change name is required");if(Js(e.name),e.language!=="en"&&e.language!=="zh-CN")throw new Error("Native change language must be en or zh-CN");if(typeof e.phase!="string"||!QN.has(e.phase))throw new Error("Native change phase is invalid");if(e.brief!=="brief.md")throw new Error("Native change brief must be brief.md");if(e.approval!==null&&!ZN.has(e.approval))throw new Error("Native change approval is invalid");if(!Array.isArray(e.spec_changes))throw new Error("Native spec_changes must be an array");let i=e.spec_changes.map(rb),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 e.verification_result!="string"||!eb.has(e.verification_result))throw new Error("Native verification_result is invalid");if(e.verification_report!==null&&typeof e.verification_report!="string")throw new Error("Native verification_report must be a string or null");if(typeof e.verification_report=="string"&&pf(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!nb(e.created_at))throw new Error("Native created_at must be a valid YYYY-MM-DD date");if(e.run_id!==null&&(typeof e.run_id!="string"||e.run_id.length===0))throw new Error("Native run_id must be a non-empty string or null");return{name:e.name,language:e.language,phase:e.phase,brief:"brief.md",approval:e.approval,spec_changes:i,verification_result:e.verification_result,verification_report:e.verification_report,archived:e.archived,created_at:e.created_at,run_id:e.run_id}}function Yi(e){let t=rr(e,Et);if(t.schema!==Te)throw new Error(`Expected ${Te}`);return{schema:Te,...Gs(t,KN)}}function ir(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Ms(e,t,i){if(e===null)return null;let r=typeof e=="string"?tb.exec(e):null;if(!r||r[1]!==i)throw new Error(`${t} must be null or runtime/evidence/${i}/<sha256>.json relative to the Native change`);return e}function ab(e){if(e==null)return null;if(typeof e!="string"||!Vs.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function ob(e){if(e===void 0)return"legacy-v1";if(e!=="legacy-v1")throw new Error("Native verification_protocol must be legacy-v1");return e}function Xi(e){let t=rr(e,Et);if(t.schema!==_e)throw new Error(`Expected ${_e}`);if(ir(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${_e} minimum_runtime_version must be 2`);return{schema:_e,minimum_runtime_version:2,revision:ir(t.revision,"Native v2 revision"),...Gs(t,df)}}function Qi(e){let t=rr(e,Et);if(t.schema!==He){if(t.schema===Te||t.schema===_e){let o=t.schema===Te?Yi(t):Xi(t);throw new Ws(o.name,o.schema)}throw new ei(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let i=ir(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)throw new ei(t.schema,i);if(i!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let r=ir(t.revision,"Native revision"),n=Gs(t,YN),a=ab(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:He,minimum_runtime_version:3,revision:r,verification_protocol:ob(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:Ms(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:Ms(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:Ms(t.partial_allowance,"Native partial_allowance","allowances")}}function sb(e){let t=rr(e,Et);if(t.schema===Te){let n=Yi(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${He}`}}if(t.schema===_e){let n=Xi(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${He}`}}if(t.schema!==He){let n=typeof t.minimum_runtime_version=="number"&&Number.isSafeInteger(t.minimum_runtime_version)?t.minimum_runtime_version:null;return{status:"runtime-incompatible",schema:typeof t.schema=="string"?t.schema:"(missing)",minimumRuntimeVersion:n,state:null,message:new ei(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let i=ir(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:i,state:null,message:new ei(t.schema,i).message};let r=Qi(t);return{status:"current",schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,state:r}}function oe(e,t){Js(t);let i=Zt.join(e.changesDir,t);if(!L(e.changesDir,i))throw new Error("Native change path escaped");return i}async function cb(e,t=Zt.dirname(e)){let i=Zt.relative(t,e).split(Zt.sep).join("/"),r=await j({root:t,ref:i,maxBytes:null,includeHash:!1}),n=(0,zs.parseDocument)(r.text,{uniqueKeys:!0});if(n.errors.length>0)throw new Error(`Invalid Native change file ${e}: ${n.errors[0].message}`);return n.toJS()}async function Zn(e,t){let i=Zt.join(oe(e,t),Et);await T(e.nativeRoot,i);let r=sb(await cb(i,e.nativeRoot));if(r.state&&r.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return r}import{promises as lr}from"node:fs";import qe from"node:path";var Nf=ai(Ft(),1);import{promises as fb}from"node:fs";import hb from"node:path";import{execFileSync as lb}from"node:child_process";var ub=3e4,db=8*1024*1024,Us=class extends Error{constructor(i,r,n){super(`git ${r.join(" ")} failed${n?`: ${n}`:""}`);this.cwd=i;this.args=r;this.stderr=n;this.name="GitCommandError"}cwd;args;stderr};function mf(e,t){try{return lb("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:ub,maxBuffer:db,windowsHide:!0})}catch(i){let r=typeof i.stderr=="string"?i.stderr.trim():Buffer.isBuffer(i.stderr)?i.stderr.toString("utf8").trim():"";throw new Us(e,t,r)}}function I(e,t){return mf(e,t).trim()}function ea(e){return I(e,["status","--porcelain=v1","-z","--untracked-files=all"])===""}function Ks(e){let t=mf(e,["status","--porcelain=v1","-z","--untracked-files=all"]);if(!t)return[];let i=t.split("\0").filter(Boolean),r=[];for(let n=0;n<i.length;n+=1){let a=i[n];if(a.length<4)throw new Error("Git status returned an invalid porcelain record");if(r.push(a.slice(3).replaceAll("\\","/")),a[0]==="R"||a[0]==="C"||a[1]==="R"||a[1]==="C"){let o=i[n+1];if(!o)throw new Error("Git status returned an incomplete rename record");r.push(o.replaceAll("\\","/")),n+=1}}return[...new Set(r)].sort()}function vf(e,t){try{let r=I(e,["config","--get",`branch.${t}.remote`]);if(r&&r!==".")return r}catch{}let i=I(e,["remote"]).split(/\r?\n/u).map(r=>r.trim()).filter(Boolean);if(i.includes("origin"))return"origin";if(i.length===1)return i[0];throw new Error(i.length===0?"Native workspace finish requires a configured Git remote":`Native workspace finish requires an unambiguous Git remote: ${i.join(", ")}`)}var gf="children.yaml",Ys="comet.native.children.v1",nr="comet.native.children.v2",pb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,mb=new Set(["schema","children"]),vb=new Set(["schema","acceptance_index","children"]),gb=new Set(["name","depends_on","covers"]);function ia(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ta(e,t,i){let r=Object.keys(e).filter(a=>!t.has(a)),n=[...t].filter(a=>!(a in e));if(r.length>0||n.length>0)throw new Error(`${i} fields are invalid`)}function wf(e,t){if(!Array.isArray(e)||!e.every(i=>typeof i=="string"))throw new Error(`${t} must be an array of strings`);return[...new Set(e)].sort((i,r)=>i.localeCompare(r,"en"))}function wb(e){let t=new Map(e.map(a=>[a.name,a])),i=new Set,r=new Set,n=a=>{if(!r.has(a)){if(i.has(a))throw new Error(`Native children dependency cycle includes ${a}`);i.add(a);for(let o of t.get(a).depends_on)n(o);i.delete(a),r.add(a)}};for(let a of e)n(a.name)}function yf(e,t,i=t){let r=new Set(t);for(let o of e){let s=o.covers.filter(c=>!r.has(c));if(s.length>0)throw new Error(`Native child ${o.name} covers unknown acceptance: ${s.join(", ")}`)}let n=new Set(e.flatMap(o=>o.covers)),a=i.filter(o=>!n.has(o));if(a.length>0)throw new Error(`Native children do not cover parent acceptance: ${a.join(", ")}`)}function bf(e){let t=new Set(e.acceptance.filter(({source:i})=>i===e.brief).map(({id:i})=>i));if(e.loop.stage==="repairing"&&e.verification_result==="fail"){let i=[...e.history].reverse().find(({outcome:r})=>r==="fail");for(let r of i?.unresolved_ids??[])t.add(r)}return{acceptanceCatalog:e.acceptance,requiredAcceptanceIds:[...t]}}function yb(e){let t=ia(e,"Native children acceptance_index"),i={};for(let[r,n]of Object.entries(t)){let a=ia(n,`Native children acceptance_index.${r}`);if(ta(a,new Set(["source","text"]),`Native children acceptance_index.${r}`),typeof a.source!="string"||a.source.length===0)throw new Error(`Native children acceptance_index.${r}.source must be a non-empty string`);if(typeof a.text!="string"||a.text.length===0)throw new Error(`Native children acceptance_index.${r}.text must be a non-empty string`);i[r]={source:a.source,text:a.text}}return i}function Nb(e,t,i){let r=i.requiredAcceptanceIds??t??[],n=Object.keys(e),a=r.filter(c=>!(c in e)),o=n.filter(c=>!r.includes(c));if(a.length>0||o.length>0)throw new Error(`Native children acceptance_index must match the required acceptance: missing ${a.join(", ")||"none"}; extra ${o.join(", ")||"none"}`);let s=new Map((i.acceptanceCatalog??[]).map(c=>[c.id,c]));for(let c of r){let l=s.get(c);if(!l)continue;let u=e[c];if(u.source!==l.source||u.text!==l.text)throw new Error(`Native children acceptance_index.${c} does not match the acceptance catalog`)}}function bb(e,t,i={}){let r=(0,Nf.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${r.errors[0].message}`);let n=ia(r.toJS({mapAsMap:!1}),"Native children contract"),a=n.schema;if(a===nr?ta(n,vb,"Native children contract"):ta(n,mb,"Native children contract"),a!==Ys&&a!==nr)throw new Error(`Native children schema must be ${Ys} or ${nr}`);if(!Array.isArray(n.children)||n.children.length===0)throw new Error("Native children must be a non-empty array");let o=n.children.map((l,u)=>{let f=ia(l,`Native child ${u}`);if(ta(f,gb,`Native child ${u}`),typeof f.name!="string"||!pb.test(f.name))throw new Error(`Native child ${u} name is invalid`);return{name:f.name,depends_on:wf(f.depends_on,`Native child ${f.name} depends_on`),covers:wf(f.covers,`Native child ${f.name} covers`)}}),s=o.map(({name:l})=>l);if(new Set(s).size!==s.length)throw new Error("Native child names must be unique");let c=new Set(s);for(let l of o){let u=l.depends_on.filter(f=>!c.has(f));if(u.length>0)throw new Error(`Native child ${l.name} depends on unknown child: ${u.join(", ")}`)}if(wb(o),a===nr){let l=yb(n.acceptance_index);if(Nb(l,t,i),t){let u=Object.keys(l);yf(o,u,u)}return{schema:nr,acceptance_index:l,children:o}}return t&&yf(o,t),{schema:Ys,children:o}}async function kf(e){let t=hb.join(e.changeDir,gf);try{await fb.lstat(t)}catch(r){if(r.code==="ENOENT")return null;throw r}let i=await j({root:e.changeDir,ref:gf});return{contract:bb(i.text,e.acceptanceIds,e.validation),size:i.size}}function Sf(e){return ee("comet.native.parent-contract.v1",{acceptance:e.acceptance.map(({id:t,source:i,text:r})=>({id:t,source:i,text:r})),children:e.children})}var DA=["$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("; ");var ra="skill-coordinated";function Pb(e){return e.state_version+1}function xb(e){return e.map(t=>({...t,result:"pending",reason:null}))}function Rb(e){return{goal_cycle:e.state.loop.goal_cycle,iteration:e.state.loop.iteration,attempt:e.state.loop.attempt,outcome:e.outcome,unresolved_ids:e.unresolvedIds??[],summary:at(e.summary),completed_at:e.completedAt}}function Xs(e){let t=ne(e.state);if(t.phase!=="verify"&&t.phase!=="archive")throw new Error("Only Verify or Archive can return a candidate to Build");let i=(e.now??new Date).toISOString(),r=Kt(t,Rb({state:t,outcome:"recovery",summary:e.reason,completedAt:i}));return ne({...r,phase:"build",status:"active",state_version:Pb(t),verification_result:"pending",verification_report:null,verification:null,builder_handoff:null,blockers:[],acceptance:xb(t.acceptance),loop:{...t.loop,stage:"repairing",iteration:t.loop.iteration+1,attempt:0,execution_failure_count:0,next_action:"submit-builder-candidate"}})}import{promises as Pf}from"node:fs";import or from"node:path";function na(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function aa(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function Ie(e,t,i=!1){if(typeof e!="string"||!i&&e.length===0)throw new Error(`${t} must be ${i?"a string":"a non-empty string"}`);return e}function Ef(e,t){return e===null?null:Ie(e,t)}function sa(e,t,i=0){if(!Number.isSafeInteger(e)||e<i)throw new Error(`${t} must be a safe integer greater than or equal to ${i}`);return e}function Cb(e,t){if(e===null)return null;if(!Number.isSafeInteger(e))throw new Error(`${t} must be null or a safe integer`);return e}function Ab(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function oa(e,t,i){if(typeof e!="string"||!t.includes(e))throw new Error(`${i} must be one of: ${t.join(", ")}`);return e}function Qs(e,t){if(e===null)return null;let i=Ie(e,t);if(Number.isNaN(Date.parse(i)))throw new Error(`${t} must be an ISO timestamp`);return i}function Zs(e,t){let i=Ie(e,t);if(!or.isAbsolute(i))throw new Error(`${t} must be absolute`);return or.resolve(i)}function _b(e,t){let i=`Native local checks[${t}]`,r=na(e,i);if(aa(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,u)=>Ie(l,`${i}.argv[${u}]`,!0)),a=oa(r.status,["planned","running","passed","failed","interrupted"],`${i}.status`),o=Qs(r.startedAt,`${i}.startedAt`),s=Qs(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=sa(r.timeoutMs,`${i}.timeoutMs`);if(c<1)throw new Error(`${i}.timeoutMs must be positive`);return{id:Ie(r.id,`${i}.id`),name:Ie(r.name,`${i}.name`),operationId:Ie(r.operationId,`${i}.operationId`),status:a,repeatable:Ab(r.repeatable,`${i}.repeatable`),timeoutMs:c,executionCount:sa(r.executionCount,`${i}.executionCount`),argv:n,cwd:Zs(r.cwd,`${i}.cwd`),exitCode:Cb(r.exitCode,`${i}.exitCode`),startedAt:o,completedAt:s,log:Ie(r.log,`${i}.log`)}}function ec(e){let t="Native local execution state",i=na(e,t);if(aa(i,new Set(["schema","change","basedOnStateVersion","workspace","execution","checks"]),t),i.schema!==Ki)throw new Error(`Native local execution schema must be ${Ki}`);let r=na(i.workspace,"Native local workspace");aa(r,new Set(["projectRoot","worktreeRoot","branch"]),"Native local workspace");let n=null;if(i.execution!==null){let o=na(i.execution,"Native local execution");aa(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds"]),"Native local execution");let s=Qs(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:Ie(o.operationId,"Native local execution.operationId"),stage:oa(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:oa(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:Ef(o.executionId,"Native local execution.executionId"),status:oa(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:sa(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(_b);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:Ie(i.change,"Native local change"),basedOnStateVersion:sa(i.basedOnStateVersion,"Native local basedOnStateVersion",1),workspace:{projectRoot:Zs(r.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:Zs(r.worktreeRoot,"Native local workspace.worktreeRoot"),branch:Ef(r.branch,"Native local workspace.branch")},execution:n,checks:a}}function st(e){return ec({schema:Ki,change:e.portableState.name,basedOnStateVersion:e.portableState.state_version,workspace:{projectRoot:or.resolve(e.projectRoot),worktreeRoot:or.resolve(e.worktreeRoot??e.projectRoot),branch:e.branch??null},execution:null,checks:[]})}async function tc(e){let t;try{t=await Pf.readFile(e,"utf8")}catch(r){if(r.code==="ENOENT")return null;throw r}let i;try{i=JSON.parse(t)}catch(r){throw new Error(`Native local execution state is invalid JSON: ${r.message}`,{cause:r})}return ec(i)}async function Be(e,t,i={}){let r=ec(t);await Pf.mkdir(or.dirname(e),{recursive:!0}),await X(e,r,i)}import{promises as Tb}from"node:fs";function ct(e){return e===null?"—":`${e.text.replace(/\r\n?/gu,`
|
|
151
|
+
`).replace(/\s+/gu," ").trim()||"—"}${e.truncated?" … (truncated)":""}`}function Le(e){return e.replaceAll("|","\\|").replace(/\r?\n/gu,"<br>")}function Ib(e){return e.verification?.assurance==="semantic-verification-unavailable"?"Semantic verification unavailable, user confirmation required":e.verification?.assurance==="user-confirmed-degraded"?"Passed with user-confirmed degraded assurance":e.verification_result==="pass"?e.phase==="verify"&&e.loop.next_action==="confirm-skill-coordinated-pass"?"Passed, user confirmation required":"Passed":e.verification_result==="blocked"?"Blocked":e.verification_result==="fail"?"Failed":"Pending"}function jb(e){return e.verification?.assurance??(e.builder_handoff?.identity_provider===ra?ra:"host-attested")}function $b(e){if(e.verification===null)throw new Error("Native verification report requires a stable Verifier result");let t=e.acceptance.map(o=>`| ${Le(o.id)} | ${Le(o.result)} | ${Le(o.source)} | ${Le(o.text)} | ${Le(ct(o.reason))} |`).join(`
|
|
152
152
|
`),i=e.verification.checks.length===0?"_No Runtime checks were recorded._":["| Check | Command | Working directory | Status | Exit | Duration |","| --- | --- | --- | --- | ---: | ---: |",...e.verification.checks.map(o=>{let s=o.argv_display.map(ct).join(" ");return`| ${Le(ct(o.name))} | ${Le(s||"—")} | ${Le(o.cwd_ref)} | ${o.status} | ${o.exit_code??"—"} | ${o.duration_ms} ms |`})].join(`
|
|
153
153
|
`),r=e.blockers.length===0?"_None._":e.blockers.map(o=>`- **${o.owner}**: ${ct(o.reason)}${o.acceptance_ids.length>0?` (acceptance: ${o.acceptance_ids.join(", ")})`:""} — next: \`${o.resolution_action}\``).join(`
|
|
154
154
|
`),n=e.verification.risks.length===0?"_None reported._":e.verification.risks.map(o=>`- ${ct(o)}`).join(`
|
|
@@ -161,8 +161,8 @@ generated_from_state_version: ${e.state_version}
|
|
|
161
161
|
|
|
162
162
|
## Current result
|
|
163
163
|
|
|
164
|
-
- Result: **${
|
|
165
|
-
- Assurance: **${
|
|
164
|
+
- Result: **${Ib(e)}**
|
|
165
|
+
- Assurance: **${jb(e)}**
|
|
166
166
|
- Goal cycle: ${e.loop.goal_cycle}
|
|
167
167
|
- Iteration: ${e.verification.iteration}
|
|
168
168
|
- Verifier attempt: ${e.verification.attempt}
|
|
@@ -196,22 +196,22 @@ ${e.history_overflow.dropped_entries>0?`Earlier history entries folded into summ
|
|
|
196
196
|
`:""}## Conclusion
|
|
197
197
|
|
|
198
198
|
${ct(e.verification.summary)}
|
|
199
|
-
`}function Hb(e){let t=/^---\r?\ngenerated_from_state_version: ([1-9]\d*)\r?\n---(?:\r?\n|$)/u.exec(e);if(!t)return null;let i=Number(t[1]);return Number.isSafeInteger(i)?i:null}async function sr(e){let t;try{t=await Ib.readFile(e.file,"utf8")}catch(r){if(r.code==="ENOENT")return"missing";throw r}let i=Hb(t);return i===null?"invalid":i===e.stateVersion?"aligned":"stale"}async function cr(e){await Y(e.file,Ob(e.state))}var xf=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Db="comet-state.yaml",Bb="state.json";function fe(e,t){if(!xf.test(t))throw new Error(`Invalid Native change name: ${t}`);let i=qe.join(e.changesDir,t);if(!L(e.changesDir,i))throw new Error("Native change path escaped");return i}function se(e,t){return qe.join(fe(e,t),Db)}function Pt(e,t){return qe.join(xe(e,t),Bb)}async function ur(e,t){try{let i=await lr.readFile(se(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(i)}catch(i){if(i.code==="ENOENT")return!1;throw i}}function Rf(e){return F(e).currentBranch}async function Fe(e,t){return ae(se(e,t))}async function Cf(e){let t=await bt({file:se(e.paths,e.previous.name),expectedStateVersion:e.previous.state_version,next:e.next,containedRoot:e.paths.nativeRoot});if(t.verification===null&&t.verification_report===null){let i=qe.join(fe(e.paths,t.name),"verification.md");await T(e.paths.nativeRoot,i),await lr.rm(i,{force:!0})}return t}async function Lb(e){let t=fe(e.paths,e.state.name),i=qe.join(t,"specs"),r=new Map(e.state.spec_changes.filter(({operation:o})=>o==="remove").map(o=>[o.capability,o])),n;try{n=await lr.readdir(i,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")n=[];else throw o}let a=[];for(let o of n.sort((s,c)=>s.name.localeCompare(c.name,"en"))){if(o.isSymbolicLink())throw new Error(`Native spec capability is unsafe: ${o.name}`);if(!o.isDirectory())continue;if(!xf.test(o.name))throw new Error(`Invalid Native capability: ${o.name}`);if(r.has(o.name))throw new Error(`Capability ${o.name} cannot be proposed and removed together`);let s=`specs/${o.name}/spec.md`,c=qe.join(t,...s.split("/")),l=await lr.lstat(c);if(!l.isFile()||l.isSymbolicLink())throw new Error(`Native proposed spec must be a regular file: ${s}`);let u=qe.join(e.paths.specsDir,o.name,"spec.md"),f="create";try{let d=await lr.lstat(u);if(!d.isFile()||d.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${o.name}`);f="modify"}catch(d){if(d.code!=="ENOENT")throw d}a.push({capability:o.name,operation:f,source:s})}return a.push(...r.values()),a.sort((o,s)=>o.capability.localeCompare(s.capability,"en"))}async function qb(e){let t=fe(e.paths,e.state.name),i=await j({root:t,ref:"brief.md",maxBytes:null,includeHash:!1}),r=[];for(let n of e.specChanges){if(n.source===null)continue;let a=await j({root:t,ref:n.source,maxBytes:null,includeHash:!1});r.push({capability:n.capability,source:a.ref,markdown:a.text})}return On({briefMarkdown:i.text,specs:r})}async function ic(e){let t=await Lb(e),i=e.ignoreSpecOperationFor??(e.state.children_contract_hash?new Set(e.state.spec_changes.map(({capability:c})=>c)):void 0);if(!(t.length===e.state.spec_changes.length&&t.every((c,l)=>{let u=e.state.spec_changes[l];return u!==void 0&&c.capability===u.capability&&c.source===u.source&&(c.operation===u.operation||i?.has(c.capability)===!0)})))return{drifted:!0,reason:"Native target specification declarations changed"};let n=await qb({...e,specChanges:t}),a=e.state.acceptance.map(({source:c,text:l})=>({source:c,text:l}));if(!Md(a,n))return{drifted:!0,reason:"Native confirmed acceptance criteria changed"};let o;try{o=await kf({changeDir:fe(e.paths,e.state.name),acceptanceIds:n.map(({id:c})=>c),validation:bf({...e.state,acceptance:n})})}catch{return{drifted:!0,reason:"Native child declarations changed"}}return(o?Sf({acceptance:n,children:o.contract}):null)===(e.state.children_contract_hash??null)?{drifted:!1,reason:null}:{drifted:!0,reason:"Native child declarations changed"}}async function Af(e){return G(e.paths,`set portable workspace finish ${e.name}`,async()=>{let t=await Fe(e.paths,e.name);if(t.workspace.isolation==="current")throw new Error("Native current-workspace isolation does not accept a finish action");let i={...t,state_version:t.state_version+1,workspace:{...t.workspace,finish:e.finish}},r=await Cf({paths:e.paths,previous:t,next:i});return await Be(Pt(e.paths,t.name),st({portableState:r,projectRoot:e.paths.projectRoot,branch:Rf(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),r.verification!==null&&await cr({file:qe.join(fe(e.paths,t.name),"verification.md"),state:r}),r})}async function _f(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);let r={...Kt(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:at(e.reason),completed_at:new Date().toISOString()}),phase:"shape",status:"active",state_version:t.state_version+1,acceptance:[],builder_handoff:null,blockers:[],verification:null,verification_result:"pending",verification_report:null,loop:{stage:"shape",goal_cycle:t.loop.goal_cycle+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 Cf({paths:e.paths,previous:t,next:r});return await Be(Pt(e.paths,t.name),st({portableState:n,projectRoot:e.paths.projectRoot,branch:Rf(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}async function sa(e){if(e.state.verification===null)return"not-applicable";let t=qe.join(fe(e.paths,e.state.name),"verification.md");return await sr({file:t,stateVersion:e.state.state_version})==="aligned"?"aligned":(await cr({file:t,state:e.state}),"rebuilt")}import{promises as Fb}from"fs";import Mb from"path";var rc="comet.selection.v2",Vb=16*1024;function ca(e){return Mb.join(e,".comet","current-change.json")}function Wb(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Tf(e){return e===null||typeof e=="string"}function zb(e){let t;try{t=JSON.parse(e)}catch(i){throw new Error(`current change selection contains invalid JSON: ${i instanceof Error?i.message:String(i)}`,{cause:i})}if(!Wb(t))throw new Error("current change selection must be a JSON object");if(t.version===1){if(typeof t.change!="string")throw new Error("legacy current change selection change must be a string");if(t.branch!==void 0&&!Tf(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:rc,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==rc)throw new Error(`current change selection schema must be ${rc}`);if(t.workflow!=="native"&&t.workflow!=="classic")throw new Error("current change selection workflow must be native or classic");if(typeof t.change!="string")throw new Error("current change selection change must be a string");if(!Tf(t.branch))throw new Error("current change selection branch must be a string or null");if(t.workflow==="native"&&t.branch!==null)throw new Error("Native current change selection branch must be null");return{selection:t,legacy:!1}}async function If(e){let t;try{let r=ca(e),{bytes:n}=await wt(r,Vb,{label:"current change selection"});t=n.toString("utf8")}catch(r){if(r.code==="ENOENT")return{status:"missing"};throw new Error(`cannot read current change selection: ${r instanceof Error?r.message:String(r)}`,{cause:r})}return{status:"selected",...zb(t)}}async function jf(e){await Fb.rm(ca(e),{force:!0})}async function $f(e,t,i){let r=await If(e);return r.status!=="selected"||r.selection.workflow!==t||r.selection.change!==i?!1:(await jf(e),!0)}var uT=16*1024;function nc(e){return ca(e.projectRoot)}async function la(e,t){return await zi(e.projectRoot),$f(e.projectRoot,"native",t)}var dr=class extends Error{peers;constructor(t){super(t.length===0?"Native Archive serial capability decision is stale":`Native Archive requires a serial capability decision: ${t.join(", ")}`),this.name="NativePortableArchiveOrderRequiredError",this.peers=[...t]}};function ac(e){return`${(e.verification?.completed_at??e.created_at).slice(0,10)}-${e.name}`}function oc(e,t){if(!/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t))throw new Error("Native portable Archive ref is invalid");let i=K.join(e.archiveDir,t);if(!L(e.archiveDir,i))throw new Error("Native Archive path escaped");return i}async function ua(e){try{return await z.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Of(e,t){let i=K.normalize(K.resolve(e)),r=K.normalize(K.resolve(t));return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}async function Hf(e,t){let i;try{i=await z.readdir(e.archiveDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return null;throw n}let r=[];for(let n of i){if(!n.isDirectory()||n.isSymbolicLink())continue;let a=K.join(e.archiveDir,n.name);try{let o=await ae(K.join(a,"comet-state.yaml"));o.name===t&&r.push({dir:a,state:o})}catch{}}if(r.length>1)throw new Error(`Multiple Native portable archives exist for ${t}`);return r[0]??null}async function sc(e,t){let i=await Yt(e,{kind:"archive",change:t});return i?.kind==="archive"?i.journal:null}async function Df(e,t){return await sc(e,t)!==null||await Hf(e,t)!==null}async function xt(e,t){await z.mkdir(e.transactionsDir,{recursive:!0}),await X(kt(e,{kind:"archive",change:t.change}),t,{containedRoot:e.runtimeDir})}async function Bf(e){let t=new Set(e.state.spec_changes.map(({capability:a})=>a));if(t.size===0)return[];let i=lt(e.paths.projectRoot);i.some(a=>Of(a,e.paths.projectRoot))||i.push(e.paths.projectRoot);let r=[];for(let a of i){let o=await we(a);if(!o)continue;let s=await nt(a,o.native.artifact_root);r.some(c=>Of(c.changesDir,s.changesDir))||r.push(s)}r.length===0&&r.push(e.paths);let n=new Set;for(let a of r){let o;try{o=await z.readdir(a.changesDir,{withFileTypes:!0})}catch(s){if(s.code==="ENOENT")continue;throw s}for(let s of o)if(!(!s.isDirectory()||s.isSymbolicLink()||s.name===e.state.name))try{let c=await ae(K.join(a.changesDir,s.name,"comet-state.yaml"));c.status!=="done"&&c.spec_changes.some(({capability:l})=>t.has(l))&&n.add(c.name)}catch{let c=await Qn(a,s.name).catch(()=>null);c?.state&&c.state.spec_changes.some(({capability:l})=>t.has(l))&&n.add(c.state.name)}}return[...n].sort((a,o)=>a.localeCompare(o,"en"))}function Gb(e){if(e===void 0)return null;if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error("Native Archive serial capability decision is invalid");return e}async function Ub(e){let t=K.join(e.paths.specsDir,e.change.capability),i=K.join(t,"spec.md");if(!L(e.paths.specsDir,i))throw new Error("Native canonical spec path escaped");if(e.change.operation==="remove"){let n;try{n=await z.lstat(e.paths.specsDir)}catch(c){if(c.code==="ENOENT")return;throw c}if(!n.isDirectory()||n.isSymbolicLink())throw new Error("Native canonical specs root is unsafe");let a;try{a=await z.lstat(t)}catch(c){if(c.code==="ENOENT")return;throw c}if(!a.isDirectory()||a.isSymbolicLink())throw new Error(`Canonical Native capability directory is unsafe: ${e.change.capability}`);let[o,s]=await Promise.all([z.realpath(e.paths.specsDir),z.realpath(t)]);if(!L(o,s))throw new Error("Native canonical capability path escaped");try{let c=await z.lstat(i);if(!c.isFile()||c.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${e.change.capability}`);await z.unlink(i)}catch(c){if(c.code!=="ENOENT")throw c}await z.rmdir(t).catch(c=>{if(c.code!=="ENOENT"&&c.code!=="ENOTEMPTY")throw c});return}if(e.change.source===null||e.change.content===null)throw new Error(`Native ${e.change.operation} spec requires frozen source content`);let r=K.join(fe(e.paths,e.state.name),e.change.source);await Y(r,e.change.content,{containedRoot:e.paths.nativeRoot}),await z.mkdir(t,{recursive:!0}),await Y(i,e.change.content,{containedRoot:e.paths.nativeRoot})}function cc(e){if(e.phase!=="archive"||e.status!=="active"||e.loop.stage!=="archive-ready"||e.verification_result!=="pass"||e.verification?.verdict!=="pass"||e.verification_report!=="verification.md")throw new Error(`Native change ${e.name} is not archive-ready`)}async function Kb(e,t){let i=fe(e,t.name),r=[];for(let n of t.spec_changes){if(n.source===null){r.push({...n,content:null});continue}let a=await j({root:i,ref:n.source,maxBytes:null,includeHash:!1});r.push({...n,content:a.text})}return r}function Yb(e,t){if(t.archived){if(t.status!=="done"||t.loop.stage!=="done"||t.state_version!==e.start_state_version+1)throw new Error("Native Archive transaction no longer matches the finalized portable state");return}if(t.state_version!==e.start_state_version)throw new Error("Native Archive transaction is stale for the current portable state");if(cc(t),e.status!=="prepared"&&e.status!=="specs-applied")throw new Error(`Native Archive transaction ${e.status} requires a finalized portable state`)}async function lc(e){let t=await Fe(e.paths,e.name),i=[];try{cc(t)}catch(o){i.push(o.message)}if(await sc(e.paths,e.name)===null)try{let o=await ic({paths:e.paths,state:t});o.drifted&&i.push(o.reason??"Native confirmed requirements changed")}catch(o){i.push(o.message)}let n=t.verification===null?"missing":await sr({file:K.join(fe(e.paths,t.name),"verification.md"),stateVersion:t.state_version});n!=="aligned"&&i.push(`verification.md is ${n}`);let a=await Bf({paths:e.paths,state:t});return a.length>0&&i.push(`capabilities are also declared by: ${a.join(", ")}`),{ready:i.length===0,blockers:i,capabilityPeers:a,archiveDir:oc(e.paths,ac(t)),stateVersion:t.state_version}}async function Lf(e){return G(e.paths,`archive portable change ${e.name}`,async()=>{let t=Gb(e.serialFirstChange);if(t!==null&&t!==e.name)throw new Error("Native Archive --serial-first must name the change being archived");let i=await sc(e.paths,e.name),r=fe(e.paths,e.name),n=await ua(r),a=n?null:await Hf(e.paths,e.name),o;if(n)o=await Fe(e.paths,e.name);else if(i)o=await ae(K.join(oc(e.paths,i.archive_ref),"comet-state.yaml"));else if(a)o=a.state;else throw new Error(`Native active change is missing: ${e.name}`);if(n&&!o.archived&&i===null){let l=await ic({paths:e.paths,state:o});if(l.drifted){let u=l.reason??"Native confirmed requirements changed";throw await _f({paths:e.paths,state:o,reason:u}),new Error(`${u}; Native change returned to Shape and requires confirmation`)}}let s=oc(e.paths,i?.archive_ref??ac(o)),c=await ua(s);if(i&&Yb(i,o),n&&c)throw new Error("Native active and archive directories both exist; doctor intervention is required");if(!n&&!i&&a){if(!o.archived||o.status!=="done"||o.loop.stage!=="done")throw new Error("Native archive exists without a completed portable state");return await la(e.paths,o.name),await z.rm(xe(e.paths,o.name),{recursive:!0,force:!0}),{change:o.name,archiveDir:a.dir,transactionId:`recovered-${o.state_version}`,state:o}}if(!i){if(!o.archived)cc(o);else if(o.status!=="done"||o.loop.stage!=="done")throw new Error("Native active archived state is inconsistent");let l=await Bf({paths:e.paths,state:o});if(!o.archived&&l.length>0&&t!==o.name)throw new dr(l);i={schema:Mn,id:Jb(),change:o.name,start_state_version:o.archived?o.state_version-1:o.state_version,archive_ref:ac(o),status:o.archived?"state-finalized":"prepared",next_spec_index:o.archived?o.spec_changes.length:0,spec_changes:await Kb(e.paths,o),created_at:new Date().toISOString()},await xt(e.paths,i)}if(!n&&c&&i.status==="report-aligned")i={...i,status:"moved"},await xt(e.paths,i);else if(!n&&c&&i.status!=="moved")throw new Error(`Native Archive layout contradicts transaction state ${i.status}; doctor intervention is required`);if(i.status==="prepared"){for(let l=i.next_spec_index;l<i.spec_changes.length;l+=1)await Ub({paths:e.paths,state:o,change:i.spec_changes[l]}),i={...i,next_spec_index:l+1},await xt(e.paths,i),await e.hooks?.afterSpecApplied?.(l);i={...i,status:"specs-applied"},await xt(e.paths,i)}if(i.status==="specs-applied"){if(!o.archived){let l={...o,phase:"archive",status:"done",state_version:o.state_version+1,archived:!0,blockers:[],loop:{...o.loop,stage:"done",next_action:null}};o=await bt({file:se(e.paths,o.name),expectedStateVersion:o.state_version,next:l,containedRoot:e.paths.nativeRoot})}i={...i,status:"state-finalized"},await xt(e.paths,i),await e.hooks?.afterFinalState?.()}if(i.status==="state-finalized"){let l=await ua(r)?r:s;if(await cr({file:K.join(l,"verification.md"),state:o}),await sr({file:K.join(l,"verification.md"),stateVersion:o.state_version})!=="aligned")throw new Error("Native final verification report is not aligned");i={...i,status:"report-aligned"},await xt(e.paths,i),await e.hooks?.afterReportAligned?.()}if(i.status==="report-aligned"){if(await z.mkdir(e.paths.archiveDir,{recursive:!0}),await ua(s))throw new Error(`Native Archive target already exists: ${s}`);await z.rename(r,s),i={...i,status:"moved"},await xt(e.paths,i),await e.hooks?.afterMove?.()}return i.status==="moved"&&(await la(e.paths,o.name),await z.rm(xe(e.paths,o.name),{recursive:!0,force:!0}),await e.hooks?.afterRuntimeCleanup?.(),await z.rm(kt(e.paths,{kind:"archive",change:o.name}),{force:!0})),{change:o.name,archiveDir:s,transactionId:i.id,state:o}},{allowedPortableTransaction:{kind:"archive",change:e.name}})}function da(e){return["comet","native","next",e.change,"--summary","<summary>",e.flag,"--expected-state-version",String(e.stateVersion),"--expected-action",e.action]}function fa(e,t){return{name:e,flag:t,valueKind:"text",required:!0,template:null}}function Xb(e,t){return{name:e,flag:t,valueKind:"confirmation",required:!0,template:null}}function ha(e){return{name:e.name,stateVersion:e.stateVersion,expectedAction:e.expectedAction,commandArgs:da({change:e.change,stateVersion:e.stateVersion,action:e.expectedAction,flag:e.flag}),requiredInputs:["summary",e.confirmationInput],inputOptions:[fa("summary","--summary"),Xb(e.name,e.flag)]}}function uc(e){return[ha({name:"revise-implementation",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),ha({name:"revise-requirements",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function fr(e,t){let i={schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:e.phase,status:e.status,stateVersion:e.state_version,inputOptions:[]},r=n=>({kind:n,candidateId:e.builder_handoff?.candidate_id??null,iteration:e.loop.iteration,attempt:e.loop.attempt});if(e.status==="done")return{...i,disposition:"done",action:"none",commandArgs:null,requiredInputs:[],runnerAction:r("none")};if(e.status==="await-user")return e.phase==="verify"&&e.verification_result==="pass"&&e.loop.next_action==="confirm-skill-coordinated-pass"?{...i,disposition:"await-user",action:"confirm-skill-coordinated-pass",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[fa("summary","--summary")],commandAlternatives:[ha({name:"accept-result",change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...uc({change:e.name,stateVersion:e.state_version})],runnerAction:r("none")}:e.phase==="verify"&&e.verification?.assurance==="semantic-verification-unavailable"&&e.loop.next_action==="confirm-verifier-unavailable"?{...i,disposition:"await-user",action:"confirm-verifier-unavailable",commandArgs:da({change:e.name,stateVersion:e.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")}:e.phase==="verify"&&e.loop.next_action==="resolve-verifier-blocker"?{...i,disposition:"await-user",action:"resolve-verifier-blocker",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[fa("summary","--summary")],commandAlternatives:[ha({name:"resolve-verifier-blocker",change:e.name,stateVersion:e.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...uc({change:e.name,stateVersion:e.state_version})],runnerAction:r("none")}:e.phase==="verify"&&e.loop.next_action==="await-user"?{...i,disposition:"await-user",action:"resolve-loop-stop",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[fa("summary","--summary")],commandAlternatives:uc({change:e.name,stateVersion:e.state_version}),runnerAction:r("none")}:{...i,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["resolve-blocker"],runnerAction:r("none")};if(e.status==="blocked"){let n=e.blockers.some(({resolution_action:a})=>a==="retry-verifier");return{...i,disposition:"blocked",action:n?"retry-verifier":"none",commandArgs:n?da({change:e.name,stateVersion:e.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(e.phase==="shape")return{...i,disposition:"continue",action:"confirm-shape",commandArgs:da({change:e.name,stateVersion:e.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(e.phase==="build"){if(t){if(!t.confirmed)return{...i,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:r("none")};if(e.loop.stage==="repairing"&&e.verification_result==="fail")return{...i,disposition:"continue",action:"repair",commandArgs:null,requiredInputs:["repair-child"],inputOptions:[],runnerAction:r("none")};if(t.allDone)return{...i,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:r("none")};let n=t.children.some(({status:o})=>o==="blocked"),a=t.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:e.loop.stage==="repairing"?"repair":"builder-handoff",commandArgs:["comet","native","next",e.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(e.phase==="verify"){let n=e.loop.next_action==="await-verifier-result";return{...i,disposition:"continue",action:n?"await-verifier":"dispatch-verifier",commandArgs:["comet","native","next",e.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:e.loop.iteration,attempt:e.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:e.loop.iteration,attempt:e.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:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:"<from verifierDispatch>"},{kind:"verifier-unavailable",summary:"<why no independent semantic execution is available>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.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",e.name,"--confirmed"],requiredInputs:[],runnerAction:r("none")}}import{randomUUID as Qb}from"node:crypto";import{promises as hr}from"node:fs";import Zb from"node:path";var qf=["evidence.md","repair.md","archive.md","checkpoint.md"],ek="verification.md";async function tk(e,t){let i=await Yt(e,{kind:"migration",change:t});return i?.kind==="migration"?i.journal:null}async function Ff(e,t){await hr.mkdir(e.transactionsDir,{recursive:!0}),await X(kt(e,{kind:"migration",change:t.change}),t,{containedRoot:e.runtimeDir})}async function Mf(e,t,i={}){let r=i.removeVerificationReport===!1?qf:[...qf,ek];await Promise.all([hr.rm(xe(e,t),{recursive:!0,force:!0}),hr.rm(vs(e,t),{recursive:!0,force:!0}),...r.map(n=>hr.rm(Zb.join(oe(e,t),n),{force:!0}))])}async function Vf(e,t){await Be(Pt(e,t.name),st({portableState:t,projectRoot:e.projectRoot}),{containedRoot:e.runtimeDir})}async function Wf(e,t){try{let i=await er(e,t);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 zf(e,t){if(t.isolation==="current"&&t.change_branch===null)return;let i=F(e.projectRoot);if(!i.isGitWorktree)throw new Error("Native legacy migration requires its bound Git branch or worktree");if(i.currentBranch!==t.change_branch)throw new Error(`Native legacy migration expected branch ${t.change_branch??"(missing)"}, current branch is ${i.currentBranch??"(detached)"}`);if(t.isolation==="worktree"&&!i.isSecondaryWorktree)throw new Error("Native legacy migration requires its bound linked worktree")}async function ik(e){let t=oe(e.paths,e.state.name),i=await j({root:t,ref:e.state.brief,maxBytes:null,includeHash:!1}),r=[];for(let n of e.state.spec_changes){if(n.operation==="remove"||!n.source)continue;let a=await j({root:t,ref:n.source,maxBytes:null,includeHash:!1});r.push({capability:n.capability,source:a.ref,markdown:a.text})}try{return On({briefMarkdown:i.text,specs:r})}catch(n){if(e.state.phase==="shape"&&n.message.includes("at least one acceptance"))return[];throw n}}async function Jf(e,t){let i=await Qn(e,t);if(!i.state)throw new Error(`Native legacy change ${t} is unreadable`);return i.state}async function Gf(e){return G(e.paths,`migrate ${e.name} to portable Native`,async()=>{let t=await tk(e.paths,e.name),i=await ur(e.paths,e.name)?await ae(se(e.paths,e.name)):null;if(!t&&i)return await Mf(e.paths,e.name,{removeVerificationReport:!1}),await Vf(e.paths,i),i;let r=null,n=null;for(t||(r=await Jf(e.paths,e.name),n=await Wf(e.paths,e.name),zf(e.paths,n),t={schema:Fn,id:Qb(),change:r.name,fromSchema:r.schema,status:"prepared",createdAt:(e.now??new Date).toISOString()},await Ff(e.paths,t));;){let a=zd(t);if(a.action==="done")break;a.action==="commit-portable-yaml"?i||(r??=await Jf(e.paths,e.name),n??=await Wf(e.paths,e.name),zf(e.paths,n),i=Wd({state:r,acceptance:await ik({paths:e.paths,state:r}),workspace:n,migratedAt:e.now}),await qn(se(e.paths,e.name),i,{containedRoot:e.paths.nativeRoot})):a.action==="cleanup-legacy-runtime"?await Mf(e.paths,e.name):a.action==="commit-transaction"&&(i??=await ae(se(e.paths,e.name)),await Vf(e.paths,i)),t={...t,status:a.nextStatus},await Ff(e.paths,t)}return await hr.rm(kt(e.paths,{kind:"migration",change:e.name}),{force:!0}),i??ae(se(e.paths,e.name))},{allowedPortableTransaction:{kind:"migration",change:e.name}})}import{promises as Uf}from"node:fs";import Kf from"node:path";function rk(e,t){let i=F(e.projectRoot);if(t.workspace.change_branch!==null){if(!i.isGitWorktree)return"The portable change requires a Git branch/worktree";if(i.currentBranch!==t.workspace.change_branch)return`Expected Native change branch ${t.workspace.change_branch}, current branch is ${i.currentBranch??"(detached)"}`}return t.workspace.isolation==="current"?null:i.isGitWorktree?t.workspace.isolation==="worktree"&&!i.isSecondaryWorktree?"The portable change requires its linked worktree":null:"The portable change requires a Git branch/worktree"}function nk(e){return e.acceptance.map(t=>({...t,result:"pending",reason:null}))}function ak(e,t){let i=new Date().toISOString(),r=e.verification===null?e:Kt(e,{goal_cycle:e.loop.goal_cycle,iteration:e.loop.iteration,attempt:e.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:at(t),completed_at:i});return ne({...r,phase:"verify",status:"active",state_version:e.state_version+1,acceptance:nk(e),verification:null,verification_result:"pending",verification_report:null,blockers:[],loop:{...e.loop,stage:"verify-ready",next_action:"run-required-checks-and-dispatch-verifier"}})}async function ok(e){try{let t=await tc(e);return t===null?{local:null,reason:"missing"}:{local:t,reason:"available"}}catch(t){if(t.code&&t.code!=="ENOENT")throw t;return{local:null,reason:"invalid"}}}async function Yf(e){return G(e.paths,`recover portable change ${e.name}`,async()=>{let t=await Fe(e.paths,e.name);if(t.status==="done")return await sa({paths:e.paths,state:t}),{state:t,local:null,action:"done",reason:"done",message:"Archived Native changes do not require a local execution overlay."};let i=rk(e.paths,t);if(i)return{state:t,local:null,action:"await-user",reason:"workspace-mismatch",message:i};let r=Pt(e.paths,e.name),n=await ok(r),a=n.reason==="available"&&(n.local?.change!==t.name||n.local?.basedOnStateVersion!==t.state_version)?"stale":n.reason;if(a==="available"&&!e.preserveRunningExecution&&n.local?.execution!==null&&n.local?.execution?.status!=="completed"&&n.local&&(a="interrupted",n.local.execution?.status==="running"&&(n.local={...n.local,execution:{...n.local.execution,status:"interrupted"},checks:n.local.checks.map(d=>d.status==="planned"||d.status==="running"?{...d,status:"interrupted"}:d)},await Be(r,n.local,{containedRoot:e.paths.runtimeDir}))),a==="available")return await sa({paths:e.paths,state:t}),{state:t,local:n.local,action:"resume-stable-boundary",reason:a,message:"Native local execution overlay matches the portable state."};let s=a==="interrupted"?n.local?.checks.find(d=>d.status==="interrupted"&&!d.repeatable):void 0;if(s){let d=Xs({state:t,reason:`Check ${s.id} was interrupted and is not declared repeatable; a new Builder candidate is required before retrying.`});t=await bt({file:se(e.paths,t.name),expectedStateVersion:t.state_version,next:d,containedRoot:e.paths.nativeRoot}),await Uf.rm(Kf.join(e.paths.changesDir,e.name,"verification.md"),{force:!0});let p=st({portableState:t,projectRoot:e.paths.projectRoot,branch:t.workspace.change_branch});return await Be(r,p,{containedRoot:e.paths.runtimeDir}),{state:t,local:p,action:"resume-stable-boundary",reason:a,message:`Native check ${s.id} was not repeatable; the change returned to Build for a new candidate.`}}let c=t.phase==="verify"&&t.loop.next_action==="await-verifier-result",l=t.phase==="archive"&&t.loop.stage==="archive-ready"&&t.verification_result==="pass",u=c||l;if(u){let d=ak(t,l?"Local Runtime was unavailable at Archive ready; the synchronized implementation must be verified again.":"The previous Verifier execution was unavailable; dispatch a new attempt from the stable Verify boundary.");t=await bt({file:se(e.paths,t.name),expectedStateVersion:t.state_version,next:d,containedRoot:e.paths.nativeRoot})}let f=st({portableState:t,projectRoot:e.paths.projectRoot,branch:F(e.paths.projectRoot).currentBranch});return await Uf.mkdir(Kf.dirname(Pt(e.paths,t.name)),{recursive:!0}),await Be(r,f,{containedRoot:e.paths.runtimeDir}),await sa({paths:e.paths,state:t}),{state:t,local:f,action:u?"reverify":"resume-stable-boundary",reason:a,message:u?"Rebuilt local execution from the portable boundary; previous pass/execution was not reused.":`Rebuilt local execution from the portable ${t.phase}/${t.loop.stage} boundary.`}})}import{accessSync as yk,constants as Nk,promises as bk}from"node:fs";import Me from"node:path";import{execFileSync as sk}from"node:child_process";var ck=6e4,lk=8*1024*1024,dc=class extends Error{constructor(i,r,n,a){super(`${i} ${r.join(" ")} failed${n?`: ${n}`:""}`,a);this.command=i;this.args=r;this.stderr=n;this.name="ExternalCommandError"}command;args;stderr};function ii(e,t,i={}){let r=i.timeoutMs??ck,n=i.maxBufferBytes??lk;if(!Number.isSafeInteger(r)||r<1)throw new Error("External command timeout must be a positive integer");if(!Number.isSafeInteger(n)||n<1)throw new Error("External command max buffer must be a positive integer");try{return sk(e,[...t],{...i.cwd?{cwd:i.cwd}:{},...i.input!==void 0?{input:i.input}:{},encoding:"utf8",stdio:[i.input===void 0?"ignore":"pipe","pipe","pipe"],timeout:r,maxBuffer:n,windowsHide:!0,shell:!1})}catch(a){let o=typeof a.stderr=="string"?a.stderr.trim():Buffer.isBuffer(a.stderr)?a.stderr.toString("utf8").trim():"";throw new dc(e,t,o,{cause:a})}}import dk from"path";var fk=["Outcome","Scope","Non-goals","Acceptance examples"],lI=[...fk,"Constraints and invariants","Decisions","Open questions","Verification expectations"];function pa(e,t){return dk.join(e.specsDir,t,"spec.md")}var hk=6e4,q=class extends Error{constructor(i,r,n){super(i,n);this.pullRequest=r;this.name="NativePullRequestFinishError"}pullRequest};function fc(e,t){try{return ii("gh",t,{cwd:e,timeoutMs:hk}).trim()}catch(i){throw new Error(`gh ${t.join(" ")} failed: ${i.message}`,{cause:i})}}function hc(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a JSON object`);return e}function pc(e,t){try{return JSON.parse(e)}catch(i){throw new Error(`${t} must be valid JSON`,{cause:i})}}function Xf(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Rt(e,t){if(typeof e!="string"||e.trim().length===0)throw new Error(`${t} must be a non-empty string`);return e}function Qf(e,t){let i=Rt(e,t),r;try{r=new URL(i)}catch(n){throw new Error(`${t} must be an absolute HTTP URL`,{cause:n})}if(r.protocol!=="https:"&&r.protocol!=="http:")throw new Error(`${t} must be an absolute HTTP URL`);return i}function va(e,t){let i=Rt(e,t);if(!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/iu.test(i))throw new Error(`${t} must be a Git object ID`);return i.toLowerCase()}function Zf(e,t){let i=hc(e,t);if(Rt(i.state,`${t}.state`)!=="OPEN")throw new Error(`${t}.state must be OPEN`);return{number:Xf(i.number,`${t}.number`),url:Qf(i.url,`${t}.url`),baseBranch:Rt(i.baseRefName,`${t}.baseRefName`),headBranch:Rt(i.headRefName,`${t}.headRefName`),headSha:va(i.headRefOid,`${t}.headRefOid`),state:"OPEN"}}function pk(e){let t=hc(e,"pull request finish provider output.pullRequest");return{number:Xf(t.number,"pull request finish provider output.pullRequest.number"),url:Qf(t.url,"pull request finish provider output.pullRequest.url"),baseBranch:Rt(t.baseBranch,"pull request finish provider output.pullRequest.baseBranch"),headBranch:Rt(t.headBranch,"pull request finish provider output.pullRequest.headBranch"),headSha:va(t.headSha,"pull request finish provider output.pullRequest.headSha")}}function mk(e){let t=hc(pc(e,"pull request finish provider output"),"pull request finish provider output");if(t.schema!=="comet.native.pull-request-finish-result.v1")throw new Error("pull request finish provider output.schema must be comet.native.pull-request-finish-result.v1");if(t.disposition!=="created"&&t.disposition!=="reused")throw new Error("pull request finish provider output.disposition must be created or reused");if(t.remoteVerified!==!0)throw new Error("pull request finish provider did not confirm repository-owned remote verification");let i=pk(t.pullRequest);return{schema:"comet.native.pull-request-finish-result.v1",disposition:t.disposition,remoteVerified:!0,pullRequest:i}}function mc(e){let t=fc(e.projectRoot,["pr","list","--state","open","--base",e.baseBranch,"--head",e.headBranch,"--limit","2","--json","number,url,baseRefName,headRefName,headRefOid,state"]),i=pc(t,"gh pr list output");if(!Array.isArray(i))throw new Error("gh pr list output must be a JSON array");if(i.length>1)throw new Error(`Multiple open pull requests match ${e.headBranch} -> ${e.baseBranch}`);return i.length===0?null:Zf(i[0],"gh pr list output[0]")}function eh(e){let t=fc(e.projectRoot,["pr","view",String(e.pullRequest.number),"--json","number,url,baseRefName,headRefName,headRefOid,state"]),i=Zf(pc(t,"gh pr view output"),"gh pr view output"),r=va(e.headSha,"Native Archive head SHA");if(i.number!==e.pullRequest.number||i.url!==e.pullRequest.url)throw new q("Pull request provider result does not match the pull request observed from GitHub",i);if(i.baseBranch!==e.baseBranch)throw new q(`Pull request base branch mismatch: expected ${e.baseBranch}, got ${i.baseBranch}`,i);if(i.headBranch!==e.headBranch)throw new q(`Pull request head branch mismatch: expected ${e.headBranch}, got ${i.headBranch}`,i);if(i.headSha!==r)throw new q(`Pull request head SHA mismatch: expected ${r}, got ${i.headSha}`,i);return i}function ma(e){try{return mc(e)}catch{return null}}function vk(e){return JSON.stringify({schema:"comet.native.pull-request-finish-input.v1",projectRoot:e.projectRoot,change:{name:e.changeName,branch:e.headBranch,headSha:e.headSha},target:{branch:e.baseBranch},remote:e.remote,transactionId:e.transactionId,existingPullRequest:e.existingPullRequest},null,2)}function gk(e){let t=e.existingPullRequest,i=t?"reused":"created";if(!t)try{let a=fc(e.projectRoot,["pr","create","--base",e.baseBranch,"--head",e.headBranch,"--fill"]).split(/\r?\n/u).map(o=>o.trim()).find(o=>/^https?:\/\//u.test(o));if(!a)throw new Error("GitHub CLI did not return a pull request URL");if(t=mc(e),!t)throw new Error("GitHub CLI created a pull request that could not be observed uniquely");if(t.url!==a)throw new q("GitHub CLI returned a pull request URL that does not match the remotely observed pull request",t)}catch(n){if(n instanceof q)throw n;let a=ma(e);if(!a)throw new q(n.message,null,{cause:n});t=a,i="reused"}let r;try{r=eh({...e,pullRequest:t})}catch(n){throw n instanceof q?n:new q(`Final GitHub pull request verification failed: ${n.message}`,t,{cause:n})}return{provider:"github-fill",disposition:i,pullRequest:r,remoteVerified:!0}}function wk(e){let[t,...i]=e.config.command,r;try{let o=ii(t,i,{cwd:e.projectRoot,timeoutMs:e.config.timeout_ms,input:`${vk(e)}
|
|
200
|
-
`}).trim();r=mk(o)}catch(o){if(o instanceof q)throw o;let s=ma(e)??e.existingPullRequest;throw new q(`Repository pull request finish provider failed: ${o.message}`,s,{cause:o})}let n={...r.pullRequest,state:"OPEN"};if(n.baseBranch!==e.baseBranch||n.headBranch!==e.headBranch||n.headSha!==va(e.headSha,"Native Archive head SHA")){let o=ma(e)??e.existingPullRequest;throw new q("Repository pull request finish provider returned a pull request outside the authorized base, head, or head SHA",o)}let a;try{a=eh({...e,pullRequest:n})}catch(o){if(o instanceof q)throw o;let s=ma(e)??e.existingPullRequest??n;throw new q(`Final repository pull request verification failed: ${o.message}`,s,{cause:o})}return{provider:"repository-command",disposition:r.disposition,pullRequest:a,remoteVerified:!0}}function th(e){let t=mc(e);return e.config?wk({...e,existingPullRequest:t,config:e.config}):gk({...e,existingPullRequest:t})}var pr=class extends Error{constructor(i){super(i.message??"Native workspace finish is blocked");this.result=i;this.name="NativeWorkspaceFinishError"}result};function ih(e,t){let i=Me.relative(e,t);return i===""||!Me.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Me.sep}`)}function Ct(e,t){let i=Me.relative(e,t).replaceAll("\\","/");if(!i||i===".."||i.startsWith("../")||Me.isAbsolute(i))throw new Error(`Native workspace finish path escaped the project: ${t}`);return i}function rh(e,t){return t.some(i=>e===i||e.startsWith(`${i}/`))}function nh(e){return e.split("\0").filter(Boolean)}function kk(e,t){return nh(I(e,["ls-files","-z","--",t]))}function Sk(e,t){return nh(I(e,["ls-files","--others","--exclude-standard","-z","--",t]))}function Ek(e){try{if(I(e,["config","--get","user.name"])&&I(e,["config","--get","user.email"]))return}catch{}throw new Error("Native workspace finish requires configured Git user.name and user.email")}function Pk(e,t){for(let i of lt(e))if(F(i).currentBranch===t)return i;return null}function xk(e,t){try{ii(e,t,{timeoutMs:1e4})}catch(i){throw new Error(`${e} is required for the selected Native workspace finish`,{cause:i})}}function Rk(e,t){if(!t)return;let i=t.command[0];try{if(Me.posix.isAbsolute(i)||Me.win32.isAbsolute(i))throw new Error("configured executable must not be an absolute path");if(/[\\/]/u.test(i)){let n=Me.resolve(e,i);if(!ih(e,n))throw new Error("configured executable escapes the project root");yk(n,Nk.X_OK);return}ii(process.platform==="win32"?"where":"which",[i],{timeoutMs:1e4})}catch(r){throw new Error(`Configured Native pull request finish executable is not available: ${i}`,{cause:r})}}async function vc(e){let{paths:t,state:i}=e,r=i.workspace;if(r.isolation==="current")return null;if(!r.finish||!r.change_branch||!r.target_branch)throw new Error("Native isolated workspace finish is not persisted");if(r.change_branch===r.target_branch)throw new Error("Native change and target branches must be different for workspace finish");let n=F(t.projectRoot);if(!n.primaryWorktreeRoot||n.currentBranch!==r.change_branch)throw new Error(`Native workspace finish requires branch ${r.change_branch} in the current registered worktree`);Ek(t.projectRoot);let a=[Ct(t.projectRoot,nc(t))];e.archiveDir&&a.push(Ct(t.projectRoot,oe(t,i.name)),Ct(t.projectRoot,e.archiveDir));let o=Ks(t.projectRoot).filter(l=>!rh(l,a));if(o.length>0)throw new Error(`Native workspace finish is blocked until change-owned implementation and artifacts are committed; remaining paths: ${o.slice(0,20).join(", ")}${o.length>20?", ...":""}`);let s=r.isolation==="branch"?t.projectRoot:Pk(n.primaryWorktreeRoot,r.target_branch);if(r.finish==="merge"&&r.isolation==="worktree"){if(!s)throw new Error(`Native merge finish requires a registered worktree on target branch ${r.target_branch}`);if(!Zn(s))throw new Error(`Native merge target worktree is not clean: ${s}`)}let c=r.finish==="push"||r.finish==="pull-request"?vf(t.projectRoot,r.change_branch):null;return r.finish==="pull-request"&&(xk("gh",["--version"]),Rk(t.projectRoot,e.pullRequestFinish)),{finish:r.finish,changeRoot:t.projectRoot,primaryRoot:n.primaryWorktreeRoot,changeBranch:r.change_branch,targetBranch:r.target_branch,targetRoot:s,remote:c,isolation:r.isolation,pullRequestFinish:e.pullRequestFinish??null}}async function Ck(e){try{return await bk.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Ak(e){return{action:e.finish,status:e.finish==="keep"?"kept":"completed",commit:null,remote:e.remote,pushed:!1,pullRequestUrl:null,pullRequest:null,merged:!1,targetRoot:e.targetRoot,cleanup:{performed:!1,reason:null},message:null,recoveryArgs:null}}async function ah(e){let t=Ak(e.plan),i=null;try{let r=[Ct(e.paths.projectRoot,oe(e.paths,e.name)),Ct(e.paths.projectRoot,e.archiveDir),...e.state.spec_changes.map(l=>Ct(e.paths.projectRoot,pa(e.paths,l.capability))),Ct(e.paths.projectRoot,nc(e.paths))],n=Ks(e.plan.changeRoot).filter(l=>!rh(l,r));if(n.length>0)throw new Error(`Native Archive produced or encountered paths outside the authorized finish scope: ${n.slice(0,20).join(", ")}${n.length>20?", ...":""}`);let a=[],o=new Set;for(let l of r){let u=Me.resolve(e.paths.projectRoot,...l.split("/"));if(kk(e.plan.changeRoot,l).length>0&&a.push(l),await Ck(u))for(let d of Sk(e.plan.changeRoot,l))o.add(d)}if(a.length>0&&I(e.plan.changeRoot,["add","-u","--",...a]),o.size>0&&I(e.plan.changeRoot,["add","--",...o]),I(e.plan.changeRoot,["diff","--cached","--name-only","-z"])&&I(e.plan.changeRoot,["commit","-m",`chore(native): archive ${e.name}`]),t.commit=I(e.plan.changeRoot,["rev-parse","HEAD"]),!Zn(e.plan.changeRoot))throw new Error("Native archive commit left unexpected working-tree changes");if(e.plan.finish==="keep")return t;if(e.plan.finish==="push"||e.plan.finish==="pull-request"){I(e.plan.changeRoot,["push","--set-upstream",e.plan.remote,e.plan.changeBranch]),t.pushed=!0,e.plan.finish==="pull-request"&&(t.pullRequest=th({projectRoot:e.plan.changeRoot,changeName:e.name,transactionId:e.transactionId,remote:e.plan.remote,baseBranch:e.plan.targetBranch,headBranch:e.plan.changeBranch,headSha:t.commit,config:e.plan.pullRequestFinish}),t.pullRequestUrl=t.pullRequest.pullRequest.url);let l=ih(e.plan.changeRoot,process.cwd());return e.plan.isolation==="worktree"&&!l?(I(e.plan.primaryRoot,["worktree","remove",e.plan.changeRoot]),t.cleanup={performed:!0,reason:null}):e.plan.isolation==="worktree"&&(t.cleanup={performed:!1,reason:"invocation-working-directory-is-the-change-worktree"}),t}let c=e.plan.targetRoot??e.plan.changeRoot;return e.plan.isolation==="branch"&&(I(c,["switch",e.plan.targetBranch]),i=c),I(c,["merge","--no-ff","--no-edit",e.plan.changeBranch]),t.merged=!0,t.targetRoot=c,t.cleanup={performed:!1,reason:"post-merge-validation-required-before-cleanup"},t}catch(r){if(r instanceof q&&r.pullRequest&&(t.pullRequestUrl=r.pullRequest.url),i!==null){let n;try{I(i,["merge","--abort"])}catch{}try{F(i).currentBranch===e.plan.targetBranch&&I(i,["switch",e.plan.changeBranch]),n=F(i).currentBranch===e.plan.changeBranch}catch{n=!1}n||(t.targetRoot=i)}throw t.status="blocked",t.message=r.message,t.recoveryArgs=e.plan.finish==="pull-request"?["comet","native","archive",e.name,"--confirmed"]:e.plan.finish==="merge"&&t.targetRoot?["git","-C",t.targetRoot,"status","--short"]:["git","-C",e.plan.changeRoot,"status","--short"],new pr(t)}}import vr from"path";import{realpathSync as dS}from"fs";var _k=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 oh=1024*1024;var ch="scoped-text-safety",Tk=1,Ik=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128});var jk="comet.native.checker-policy.v1";var UI=ee(jk,{policy:ch,version:Tk,limits:Ik,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"});var $k=["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"],KI=new Set($k);var Dk=oh,fj=3*Dk;var lh={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:[]},Lk=de("comet-native-runtime:v3:scope-reopen"),Lj=[{skillVersion:"3",skillHash:de("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:de("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:de("comet-native-runtime:v1")}];var dh=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],y$=new Set(dh),Jk=new Set([...dh,"minimum_runtime_version","revision"]),N$=new Set([...Jk,"operation"]),b$=512*1024,Gk=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),k$=new Set([...Gk,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]);var x$={maxAcceptanceCriteria:Ui.maxCriteria};var T$={maxSpecs:64,maxFileBytes:Nr,maxTotalBytes:4*1024*1024};import{execFile as iS}from"node:child_process";import{promisify as rS}from"node:util";var F$={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024};var cO=512*1024;var mr=class extends Error{recovery;constructor(t,i){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=i}};var TO=64*1024;var IO=3600*1e3;var jO=rS(iS);var ga=class extends Error{details;constructor(t){let i=t.length===0?"Native verification receipt binding is invalid":`Native verification receipt binding is invalid (${t.length} receipt(s)): ${t.map(r=>`${r.ref}${r.acceptanceId?`[${r.acceptanceId}]`:""} -> ${r.mismatches.join("; ")}`).join(" | ")}`;super(i),this.name="NativeVerificationReceiptBindingError",this.details=t}};var w0={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};var C0=16*1024*1024,A0=256*1024,_0=16*1024;var O0=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});var EH=16*1024*1024,wa=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"},ya=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 Na=class extends Error{constructor(i,r,n){super(i,n);this.preparation=r;this.name="NativeWorkspacePreparationError"}preparation};var ph=["--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."],wc=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:ph,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]
|
|
201
|
-
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]
|
|
199
|
+
`}function Ob(e){let t=/^---\r?\ngenerated_from_state_version: ([1-9]\d*)\r?\n---(?:\r?\n|$)/u.exec(e);if(!t)return null;let i=Number(t[1]);return Number.isSafeInteger(i)?i:null}async function sr(e){let t;try{t=await Tb.readFile(e.file,"utf8")}catch(r){if(r.code==="ENOENT")return"missing";throw r}let i=Ob(t);return i===null?"invalid":i===e.stateVersion?"aligned":"stale"}async function cr(e){await Y(e.file,$b(e.state))}var xf=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Hb="comet-state.yaml",Db="state.json";function fe(e,t){if(!xf.test(t))throw new Error(`Invalid Native change name: ${t}`);let i=qe.join(e.changesDir,t);if(!L(e.changesDir,i))throw new Error("Native change path escaped");return i}function se(e,t){return qe.join(fe(e,t),Hb)}function Pt(e,t){return qe.join(xe(e,t),Db)}async function ur(e,t){try{let i=await lr.readFile(se(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(i)}catch(i){if(i.code==="ENOENT")return!1;throw i}}function Rf(e){return F(e).currentBranch}async function Fe(e,t){return ae(se(e,t))}async function Cf(e){let t=await bt({file:se(e.paths,e.previous.name),expectedStateVersion:e.previous.state_version,next:e.next,containedRoot:e.paths.nativeRoot});if(t.verification===null&&t.verification_report===null){let i=qe.join(fe(e.paths,t.name),"verification.md");await T(e.paths.nativeRoot,i),await lr.rm(i,{force:!0})}return t}async function Bb(e){let t=fe(e.paths,e.state.name),i=qe.join(t,"specs"),r=new Map(e.state.spec_changes.filter(({operation:o})=>o==="remove").map(o=>[o.capability,o])),n;try{n=await lr.readdir(i,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")n=[];else throw o}let a=[];for(let o of n.sort((s,c)=>s.name.localeCompare(c.name,"en"))){if(o.isSymbolicLink())throw new Error(`Native spec capability is unsafe: ${o.name}`);if(!o.isDirectory())continue;if(!xf.test(o.name))throw new Error(`Invalid Native capability: ${o.name}`);if(r.has(o.name))throw new Error(`Capability ${o.name} cannot be proposed and removed together`);let s=`specs/${o.name}/spec.md`,c=qe.join(t,...s.split("/")),l=await lr.lstat(c);if(!l.isFile()||l.isSymbolicLink())throw new Error(`Native proposed spec must be a regular file: ${s}`);let u=qe.join(e.paths.specsDir,o.name,"spec.md"),f="create";try{let d=await lr.lstat(u);if(!d.isFile()||d.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${o.name}`);f="modify"}catch(d){if(d.code!=="ENOENT")throw d}a.push({capability:o.name,operation:f,source:s})}return a.push(...r.values()),a.sort((o,s)=>o.capability.localeCompare(s.capability,"en"))}async function Lb(e){let t=fe(e.paths,e.state.name),i=await j({root:t,ref:"brief.md",maxBytes:null,includeHash:!1}),r=[];for(let n of e.specChanges){if(n.source===null)continue;let a=await j({root:t,ref:n.source,maxBytes:null,includeHash:!1});r.push({capability:n.capability,source:a.ref,markdown:a.text})}return Hn({briefMarkdown:i.text,specs:r})}async function ic(e){let t=await Bb(e),i=e.ignoreSpecOperationFor??(e.state.children_contract_hash?new Set(e.state.spec_changes.map(({capability:c})=>c)):void 0);if(!(t.length===e.state.spec_changes.length&&t.every((c,l)=>{let u=e.state.spec_changes[l];return u!==void 0&&c.capability===u.capability&&c.source===u.source&&(c.operation===u.operation||i?.has(c.capability)===!0)})))return{drifted:!0,reason:"Native target specification declarations changed"};let n=await Lb({...e,specChanges:t}),a=e.state.acceptance.map(({source:c,text:l})=>({source:c,text:l}));if(!Md(a,n))return{drifted:!0,reason:"Native confirmed acceptance criteria changed"};let o;try{o=await kf({changeDir:fe(e.paths,e.state.name),acceptanceIds:n.map(({id:c})=>c),validation:bf({...e.state,acceptance:n})})}catch{return{drifted:!0,reason:"Native child declarations changed"}}return(o?Sf({acceptance:n,children:o.contract}):null)===(e.state.children_contract_hash??null)?{drifted:!1,reason:null}:{drifted:!0,reason:"Native child declarations changed"}}async function Af(e){return G(e.paths,`set portable workspace finish ${e.name}`,async()=>{let t=await Fe(e.paths,e.name);if(t.workspace.isolation==="current")throw new Error("Native current-workspace isolation does not accept a finish action");let i={...t,state_version:t.state_version+1,workspace:{...t.workspace,finish:e.finish}},r=await Cf({paths:e.paths,previous:t,next:i});return await Be(Pt(e.paths,t.name),st({portableState:r,projectRoot:e.paths.projectRoot,branch:Rf(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),r.verification!==null&&await cr({file:qe.join(fe(e.paths,t.name),"verification.md"),state:r}),r})}async function _f(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);let r={...Kt(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:at(e.reason),completed_at:new Date().toISOString()}),phase:"shape",status:"active",state_version:t.state_version+1,acceptance:[],builder_handoff:null,blockers:[],verification:null,verification_result:"pending",verification_report:null,loop:{stage:"shape",goal_cycle:t.loop.goal_cycle+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 Cf({paths:e.paths,previous:t,next:r});return await Be(Pt(e.paths,t.name),st({portableState:n,projectRoot:e.paths.projectRoot,branch:Rf(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}async function ca(e){if(e.state.verification===null)return"not-applicable";let t=qe.join(fe(e.paths,e.state.name),"verification.md");return await sr({file:t,stateVersion:e.state.state_version})==="aligned"?"aligned":(await cr({file:t,state:e.state}),"rebuilt")}import{promises as qb}from"fs";import Fb from"path";var rc="comet.selection.v2",Mb=16*1024;function la(e){return Fb.join(e,".comet","current-change.json")}function Vb(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Tf(e){return e===null||typeof e=="string"}function Wb(e){let t;try{t=JSON.parse(e)}catch(i){throw new Error(`current change selection contains invalid JSON: ${i instanceof Error?i.message:String(i)}`,{cause:i})}if(!Vb(t))throw new Error("current change selection must be a JSON object");if(t.version===1){if(typeof t.change!="string")throw new Error("legacy current change selection change must be a string");if(t.branch!==void 0&&!Tf(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:rc,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==rc)throw new Error(`current change selection schema must be ${rc}`);if(t.workflow!=="native"&&t.workflow!=="classic")throw new Error("current change selection workflow must be native or classic");if(typeof t.change!="string")throw new Error("current change selection change must be a string");if(!Tf(t.branch))throw new Error("current change selection branch must be a string or null");if(t.workflow==="native"&&t.branch!==null)throw new Error("Native current change selection branch must be null");return{selection:t,legacy:!1}}async function If(e){let t;try{let r=la(e),{bytes:n}=await wt(r,Mb,{label:"current change selection"});t=n.toString("utf8")}catch(r){if(r.code==="ENOENT")return{status:"missing"};throw new Error(`cannot read current change selection: ${r instanceof Error?r.message:String(r)}`,{cause:r})}return{status:"selected",...Wb(t)}}async function jf(e){await qb.rm(la(e),{force:!0})}async function $f(e,t,i){let r=await If(e);return r.status!=="selected"||r.selection.workflow!==t||r.selection.change!==i?!1:(await jf(e),!0)}var lT=16*1024;function nc(e){return la(e.projectRoot)}async function ua(e,t){return await zi(e.projectRoot),$f(e.projectRoot,"native",t)}var dr=class extends Error{peers;constructor(t){super(t.length===0?"Native Archive serial capability decision is stale":`Native Archive requires a serial capability decision: ${t.join(", ")}`),this.name="NativePortableArchiveOrderRequiredError",this.peers=[...t]}};function ac(e){return`${(e.verification?.completed_at??e.created_at).slice(0,10)}-${e.name}`}function oc(e,t){if(!/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t))throw new Error("Native portable Archive ref is invalid");let i=K.join(e.archiveDir,t);if(!L(e.archiveDir,i))throw new Error("Native Archive path escaped");return i}async function da(e){try{return await z.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Of(e,t){let i=K.normalize(K.resolve(e)),r=K.normalize(K.resolve(t));return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}async function Hf(e,t){let i;try{i=await z.readdir(e.archiveDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return null;throw n}let r=[];for(let n of i){if(!n.isDirectory()||n.isSymbolicLink())continue;let a=K.join(e.archiveDir,n.name);try{let o=await ae(K.join(a,"comet-state.yaml"));o.name===t&&r.push({dir:a,state:o})}catch{}}if(r.length>1)throw new Error(`Multiple Native portable archives exist for ${t}`);return r[0]??null}async function sc(e,t){let i=await Yt(e,{kind:"archive",change:t});return i?.kind==="archive"?i.journal:null}async function Df(e,t){return await sc(e,t)!==null||await Hf(e,t)!==null}async function xt(e,t){await z.mkdir(e.transactionsDir,{recursive:!0}),await X(kt(e,{kind:"archive",change:t.change}),t,{containedRoot:e.runtimeDir})}async function Bf(e){let t=new Set(e.state.spec_changes.map(({capability:a})=>a));if(t.size===0)return[];let i=lt(e.paths.projectRoot);i.some(a=>Of(a,e.paths.projectRoot))||i.push(e.paths.projectRoot);let r=[];for(let a of i){let o=await we(a);if(!o)continue;let s=await nt(a,o.native.artifact_root);r.some(c=>Of(c.changesDir,s.changesDir))||r.push(s)}r.length===0&&r.push(e.paths);let n=new Set;for(let a of r){let o;try{o=await z.readdir(a.changesDir,{withFileTypes:!0})}catch(s){if(s.code==="ENOENT")continue;throw s}for(let s of o)if(!(!s.isDirectory()||s.isSymbolicLink()||s.name===e.state.name))try{let c=await ae(K.join(a.changesDir,s.name,"comet-state.yaml"));c.status!=="done"&&c.spec_changes.some(({capability:l})=>t.has(l))&&n.add(c.name)}catch{let c=await Zn(a,s.name).catch(()=>null);c?.state&&c.state.spec_changes.some(({capability:l})=>t.has(l))&&n.add(c.state.name)}}return[...n].sort((a,o)=>a.localeCompare(o,"en"))}function Jb(e){if(e===void 0)return null;if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error("Native Archive serial capability decision is invalid");return e}async function Gb(e){let t=K.join(e.paths.specsDir,e.change.capability),i=K.join(t,"spec.md");if(!L(e.paths.specsDir,i))throw new Error("Native canonical spec path escaped");if(e.change.operation==="remove"){let n;try{n=await z.lstat(e.paths.specsDir)}catch(c){if(c.code==="ENOENT")return;throw c}if(!n.isDirectory()||n.isSymbolicLink())throw new Error("Native canonical specs root is unsafe");let a;try{a=await z.lstat(t)}catch(c){if(c.code==="ENOENT")return;throw c}if(!a.isDirectory()||a.isSymbolicLink())throw new Error(`Canonical Native capability directory is unsafe: ${e.change.capability}`);let[o,s]=await Promise.all([z.realpath(e.paths.specsDir),z.realpath(t)]);if(!L(o,s))throw new Error("Native canonical capability path escaped");try{let c=await z.lstat(i);if(!c.isFile()||c.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${e.change.capability}`);await z.unlink(i)}catch(c){if(c.code!=="ENOENT")throw c}await z.rmdir(t).catch(c=>{if(c.code!=="ENOENT"&&c.code!=="ENOTEMPTY")throw c});return}if(e.change.source===null||e.change.content===null)throw new Error(`Native ${e.change.operation} spec requires frozen source content`);let r=K.join(fe(e.paths,e.state.name),e.change.source);await Y(r,e.change.content,{containedRoot:e.paths.nativeRoot}),await z.mkdir(t,{recursive:!0}),await Y(i,e.change.content,{containedRoot:e.paths.nativeRoot})}function cc(e){if(e.phase!=="archive"||e.status!=="active"||e.loop.stage!=="archive-ready"||e.verification_result!=="pass"||e.verification?.verdict!=="pass"||e.verification_report!=="verification.md")throw new Error(`Native change ${e.name} is not archive-ready`)}async function Ub(e,t){let i=fe(e,t.name),r=[];for(let n of t.spec_changes){if(n.source===null){r.push({...n,content:null});continue}let a=await j({root:i,ref:n.source,maxBytes:null,includeHash:!1});r.push({...n,content:a.text})}return r}function Kb(e,t){if(t.archived){if(t.status!=="done"||t.loop.stage!=="done"||t.state_version!==e.start_state_version+1)throw new Error("Native Archive transaction no longer matches the finalized portable state");return}if(t.state_version!==e.start_state_version)throw new Error("Native Archive transaction is stale for the current portable state");if(cc(t),e.status!=="prepared"&&e.status!=="specs-applied")throw new Error(`Native Archive transaction ${e.status} requires a finalized portable state`)}async function lc(e){let t=await Fe(e.paths,e.name),i=[];try{cc(t)}catch(o){i.push(o.message)}if(await sc(e.paths,e.name)===null)try{let o=await ic({paths:e.paths,state:t});o.drifted&&i.push(o.reason??"Native confirmed requirements changed")}catch(o){i.push(o.message)}let n=t.verification===null?"missing":await sr({file:K.join(fe(e.paths,t.name),"verification.md"),stateVersion:t.state_version});n!=="aligned"&&i.push(`verification.md is ${n}`);let a=await Bf({paths:e.paths,state:t});return a.length>0&&i.push(`capabilities are also declared by: ${a.join(", ")}`),{ready:i.length===0,blockers:i,capabilityPeers:a,archiveDir:oc(e.paths,ac(t)),stateVersion:t.state_version}}async function Lf(e){return G(e.paths,`archive portable change ${e.name}`,async()=>{let t=Jb(e.serialFirstChange);if(t!==null&&t!==e.name)throw new Error("Native Archive --serial-first must name the change being archived");let i=await sc(e.paths,e.name),r=fe(e.paths,e.name),n=await da(r),a=n?null:await Hf(e.paths,e.name),o;if(n)o=await Fe(e.paths,e.name);else if(i)o=await ae(K.join(oc(e.paths,i.archive_ref),"comet-state.yaml"));else if(a)o=a.state;else throw new Error(`Native active change is missing: ${e.name}`);if(n&&!o.archived&&i===null){let l=await ic({paths:e.paths,state:o});if(l.drifted){let u=l.reason??"Native confirmed requirements changed";throw await _f({paths:e.paths,state:o,reason:u}),new Error(`${u}; Native change returned to Shape and requires confirmation`)}}let s=oc(e.paths,i?.archive_ref??ac(o)),c=await da(s);if(i&&Kb(i,o),n&&c)throw new Error("Native active and archive directories both exist; doctor intervention is required");if(!n&&!i&&a){if(!o.archived||o.status!=="done"||o.loop.stage!=="done")throw new Error("Native archive exists without a completed portable state");return await ua(e.paths,o.name),await z.rm(xe(e.paths,o.name),{recursive:!0,force:!0}),{change:o.name,archiveDir:a.dir,transactionId:`recovered-${o.state_version}`,state:o}}if(!i){if(!o.archived)cc(o);else if(o.status!=="done"||o.loop.stage!=="done")throw new Error("Native active archived state is inconsistent");let l=await Bf({paths:e.paths,state:o});if(!o.archived&&l.length>0&&t!==o.name)throw new dr(l);i={schema:Vn,id:zb(),change:o.name,start_state_version:o.archived?o.state_version-1:o.state_version,archive_ref:ac(o),status:o.archived?"state-finalized":"prepared",next_spec_index:o.archived?o.spec_changes.length:0,spec_changes:await Ub(e.paths,o),created_at:new Date().toISOString()},await xt(e.paths,i)}if(!n&&c&&i.status==="report-aligned")i={...i,status:"moved"},await xt(e.paths,i);else if(!n&&c&&i.status!=="moved")throw new Error(`Native Archive layout contradicts transaction state ${i.status}; doctor intervention is required`);if(i.status==="prepared"){for(let l=i.next_spec_index;l<i.spec_changes.length;l+=1)await Gb({paths:e.paths,state:o,change:i.spec_changes[l]}),i={...i,next_spec_index:l+1},await xt(e.paths,i),await e.hooks?.afterSpecApplied?.(l);i={...i,status:"specs-applied"},await xt(e.paths,i)}if(i.status==="specs-applied"){if(!o.archived){let l={...o,phase:"archive",status:"done",state_version:o.state_version+1,archived:!0,blockers:[],loop:{...o.loop,stage:"done",next_action:null}};o=await bt({file:se(e.paths,o.name),expectedStateVersion:o.state_version,next:l,containedRoot:e.paths.nativeRoot})}i={...i,status:"state-finalized"},await xt(e.paths,i),await e.hooks?.afterFinalState?.()}if(i.status==="state-finalized"){let l=await da(r)?r:s;if(await cr({file:K.join(l,"verification.md"),state:o}),await sr({file:K.join(l,"verification.md"),stateVersion:o.state_version})!=="aligned")throw new Error("Native final verification report is not aligned");i={...i,status:"report-aligned"},await xt(e.paths,i),await e.hooks?.afterReportAligned?.()}if(i.status==="report-aligned"){if(await z.mkdir(e.paths.archiveDir,{recursive:!0}),await da(s))throw new Error(`Native Archive target already exists: ${s}`);await z.rename(r,s),i={...i,status:"moved"},await xt(e.paths,i),await e.hooks?.afterMove?.()}return i.status==="moved"&&(await ua(e.paths,o.name),await z.rm(xe(e.paths,o.name),{recursive:!0,force:!0}),await e.hooks?.afterRuntimeCleanup?.(),await z.rm(kt(e.paths,{kind:"archive",change:o.name}),{force:!0})),{change:o.name,archiveDir:s,transactionId:i.id,state:o}},{allowedPortableTransaction:{kind:"archive",change:e.name}})}function fa(e){return["comet","native","next",e.change,"--summary","<summary>",e.flag,"--expected-state-version",String(e.stateVersion),"--expected-action",e.action]}function ha(e,t){return{name:e,flag:t,valueKind:"text",required:!0,template:null}}function Yb(e,t){return{name:e,flag:t,valueKind:"confirmation",required:!0,template:null}}function fr(e){return{name:e.name,stateVersion:e.stateVersion,expectedAction:e.expectedAction,commandArgs:fa({change:e.change,stateVersion:e.stateVersion,action:e.expectedAction,flag:e.flag}),requiredInputs:["summary",e.confirmationInput],inputOptions:[ha("summary","--summary"),Yb(e.name,e.flag)]}}function uc(e){return[fr({name:"revise-implementation",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),fr({name:"revise-requirements",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function hr(e,t){let i={schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:e.phase,status:e.status,stateVersion:e.state_version,inputOptions:[]},r=n=>({kind:n,candidateId:e.builder_handoff?.candidate_id??null,iteration:e.loop.iteration,attempt:e.loop.attempt});if(e.status==="done")return{...i,disposition:"done",action:"none",commandArgs:null,requiredInputs:[],runnerAction:r("none")};if(e.status==="await-user")return e.phase==="verify"&&e.verification_result==="pass"&&e.loop.next_action==="confirm-skill-coordinated-pass"?{...i,disposition:"await-user",action:"confirm-skill-coordinated-pass",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[ha("summary","--summary")],commandAlternatives:[fr({name:"accept-result",change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...uc({change:e.name,stateVersion:e.state_version})],runnerAction:r("none")}:e.phase==="verify"&&e.verification?.assurance==="semantic-verification-unavailable"&&e.loop.next_action==="confirm-verifier-unavailable"?{...i,disposition:"await-user",action:"confirm-verifier-unavailable",commandArgs:fa({change:e.name,stateVersion:e.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")}:e.phase==="verify"&&e.loop.next_action==="resolve-verifier-blocker"?{...i,disposition:"await-user",action:"resolve-verifier-blocker",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[ha("summary","--summary")],commandAlternatives:[fr({name:"resolve-verifier-blocker",change:e.name,stateVersion:e.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...uc({change:e.name,stateVersion:e.state_version})],runnerAction:r("none")}:e.phase==="verify"&&e.loop.next_action==="await-user"?{...i,disposition:"await-user",action:"resolve-loop-stop",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[ha("summary","--summary")],commandAlternatives:uc({change:e.name,stateVersion:e.state_version}),runnerAction:r("none")}:{...i,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["resolve-blocker"],runnerAction:r("none")};if(e.status==="blocked"){let n=e.blockers.some(({resolution_action:a})=>a==="retry-verifier");return{...i,disposition:"blocked",action:n?"retry-verifier":"none",commandArgs:n?fa({change:e.name,stateVersion:e.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(e.phase==="shape")return{...i,disposition:"continue",action:"confirm-shape",commandArgs:fa({change:e.name,stateVersion:e.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(e.phase==="build"){if(t){if(!t.confirmed)return{...i,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:r("none")};if(e.loop.stage==="repairing"&&e.verification_result==="fail")return{...i,disposition:"continue",action:"repair",commandArgs:null,requiredInputs:["repair-child"],inputOptions:[],runnerAction:r("none")};if(t.allDone)return{...i,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:r("none")};let n=t.children.some(({status:o})=>o==="blocked"),a=t.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:e.loop.stage==="repairing"?"repair":"builder-handoff",commandArgs:["comet","native","next",e.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(e.phase==="verify"){let n=e.loop.next_action==="await-verifier-result";return{...i,disposition:"continue",action:n?"await-verifier":"dispatch-verifier",commandArgs:["comet","native","next",e.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:e.loop.iteration,attempt:e.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:e.loop.iteration,attempt:e.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:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:"<from verifierDispatch>"},{kind:"verifier-unavailable",summary:"<why no independent semantic execution is available>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:"<from verifierDispatch>"}]:{kind:"dispatch-verifier",checks:[]}}],runnerAction:r(n?"await-verifier":"dispatch-verifier")}}return e.phase==="archive"&&e.status==="active"&&e.loop.stage==="archive-ready"&&!e.archived?{...i,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],commandAlternatives:[fr({name:"revise-requirements",change:e.name,stateVersion:e.state_version,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})],runnerAction:r("none")}:{...i,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:r("none")}}import{randomUUID as Xb}from"node:crypto";import{promises as pr}from"node:fs";import Qb from"node:path";var qf=["evidence.md","repair.md","archive.md","checkpoint.md"],Zb="verification.md";async function ek(e,t){let i=await Yt(e,{kind:"migration",change:t});return i?.kind==="migration"?i.journal:null}async function Ff(e,t){await pr.mkdir(e.transactionsDir,{recursive:!0}),await X(kt(e,{kind:"migration",change:t.change}),t,{containedRoot:e.runtimeDir})}async function Mf(e,t,i={}){let r=i.removeVerificationReport===!1?qf:[...qf,Zb];await Promise.all([pr.rm(xe(e,t),{recursive:!0,force:!0}),pr.rm(vs(e,t),{recursive:!0,force:!0}),...r.map(n=>pr.rm(Qb.join(oe(e,t),n),{force:!0}))])}async function Vf(e,t){await Be(Pt(e,t.name),st({portableState:t,projectRoot:e.projectRoot}),{containedRoot:e.runtimeDir})}async function Wf(e,t){try{let i=await er(e,t);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 zf(e,t){if(t.isolation==="current"&&t.change_branch===null)return;let i=F(e.projectRoot);if(!i.isGitWorktree)throw new Error("Native legacy migration requires its bound Git branch or worktree");if(i.currentBranch!==t.change_branch)throw new Error(`Native legacy migration expected branch ${t.change_branch??"(missing)"}, current branch is ${i.currentBranch??"(detached)"}`);if(t.isolation==="worktree"&&!i.isSecondaryWorktree)throw new Error("Native legacy migration requires its bound linked worktree")}async function tk(e){let t=oe(e.paths,e.state.name),i=await j({root:t,ref:e.state.brief,maxBytes:null,includeHash:!1}),r=[];for(let n of e.state.spec_changes){if(n.operation==="remove"||!n.source)continue;let a=await j({root:t,ref:n.source,maxBytes:null,includeHash:!1});r.push({capability:n.capability,source:a.ref,markdown:a.text})}try{return Hn({briefMarkdown:i.text,specs:r})}catch(n){if(e.state.phase==="shape"&&n.message.includes("at least one acceptance"))return[];throw n}}async function Jf(e,t){let i=await Zn(e,t);if(!i.state)throw new Error(`Native legacy change ${t} is unreadable`);return i.state}async function Gf(e){return G(e.paths,`migrate ${e.name} to portable Native`,async()=>{let t=await ek(e.paths,e.name),i=await ur(e.paths,e.name)?await ae(se(e.paths,e.name)):null;if(!t&&i)return await Mf(e.paths,e.name,{removeVerificationReport:!1}),await Vf(e.paths,i),i;let r=null,n=null;for(t||(r=await Jf(e.paths,e.name),n=await Wf(e.paths,e.name),zf(e.paths,n),t={schema:Mn,id:Xb(),change:r.name,fromSchema:r.schema,status:"prepared",createdAt:(e.now??new Date).toISOString()},await Ff(e.paths,t));;){let a=zd(t);if(a.action==="done")break;a.action==="commit-portable-yaml"?i||(r??=await Jf(e.paths,e.name),n??=await Wf(e.paths,e.name),zf(e.paths,n),i=Wd({state:r,acceptance:await tk({paths:e.paths,state:r}),workspace:n,migratedAt:e.now}),await Fn(se(e.paths,e.name),i,{containedRoot:e.paths.nativeRoot})):a.action==="cleanup-legacy-runtime"?await Mf(e.paths,e.name):a.action==="commit-transaction"&&(i??=await ae(se(e.paths,e.name)),await Vf(e.paths,i)),t={...t,status:a.nextStatus},await Ff(e.paths,t)}return await pr.rm(kt(e.paths,{kind:"migration",change:e.name}),{force:!0}),i??ae(se(e.paths,e.name))},{allowedPortableTransaction:{kind:"migration",change:e.name}})}import{promises as Uf}from"node:fs";import Kf from"node:path";function ik(e,t){let i=F(e.projectRoot);if(t.workspace.change_branch!==null){if(!i.isGitWorktree)return"The portable change requires a Git branch/worktree";if(i.currentBranch!==t.workspace.change_branch)return`Expected Native change branch ${t.workspace.change_branch}, current branch is ${i.currentBranch??"(detached)"}`}return t.workspace.isolation==="current"?null:i.isGitWorktree?t.workspace.isolation==="worktree"&&!i.isSecondaryWorktree?"The portable change requires its linked worktree":null:"The portable change requires a Git branch/worktree"}function rk(e){return e.acceptance.map(t=>({...t,result:"pending",reason:null}))}function nk(e,t){let i=new Date().toISOString(),r=e.verification===null?e:Kt(e,{goal_cycle:e.loop.goal_cycle,iteration:e.loop.iteration,attempt:e.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:at(t),completed_at:i});return ne({...r,phase:"verify",status:"active",state_version:e.state_version+1,acceptance:rk(e),verification:null,verification_result:"pending",verification_report:null,blockers:[],loop:{...e.loop,stage:"verify-ready",next_action:"run-required-checks-and-dispatch-verifier"}})}async function ak(e){try{let t=await tc(e);return t===null?{local:null,reason:"missing"}:{local:t,reason:"available"}}catch(t){if(t.code&&t.code!=="ENOENT")throw t;return{local:null,reason:"invalid"}}}async function Yf(e){return G(e.paths,`recover portable change ${e.name}`,async()=>{let t=await Fe(e.paths,e.name);if(t.status==="done")return await ca({paths:e.paths,state:t}),{state:t,local:null,action:"done",reason:"done",message:"Archived Native changes do not require a local execution overlay."};let i=ik(e.paths,t);if(i)return{state:t,local:null,action:"await-user",reason:"workspace-mismatch",message:i};let r=Pt(e.paths,e.name),n=await ak(r),a=n.reason==="available"&&(n.local?.change!==t.name||n.local?.basedOnStateVersion!==t.state_version)?"stale":n.reason;if(a==="available"&&!e.preserveRunningExecution&&n.local?.execution!==null&&n.local?.execution?.status!=="completed"&&n.local&&(a="interrupted",n.local.execution?.status==="running"&&(n.local={...n.local,execution:{...n.local.execution,status:"interrupted"},checks:n.local.checks.map(d=>d.status==="planned"||d.status==="running"?{...d,status:"interrupted"}:d)},await Be(r,n.local,{containedRoot:e.paths.runtimeDir}))),a==="available")return await ca({paths:e.paths,state:t}),{state:t,local:n.local,action:"resume-stable-boundary",reason:a,message:"Native local execution overlay matches the portable state."};let s=a==="interrupted"?n.local?.checks.find(d=>d.status==="interrupted"&&!d.repeatable):void 0;if(s){let d=Xs({state:t,reason:`Check ${s.id} was interrupted and is not declared repeatable; a new Builder candidate is required before retrying.`});t=await bt({file:se(e.paths,t.name),expectedStateVersion:t.state_version,next:d,containedRoot:e.paths.nativeRoot}),await Uf.rm(Kf.join(e.paths.changesDir,e.name,"verification.md"),{force:!0});let p=st({portableState:t,projectRoot:e.paths.projectRoot,branch:t.workspace.change_branch});return await Be(r,p,{containedRoot:e.paths.runtimeDir}),{state:t,local:p,action:"resume-stable-boundary",reason:a,message:`Native check ${s.id} was not repeatable; the change returned to Build for a new candidate.`}}let c=t.phase==="verify"&&t.loop.next_action==="await-verifier-result",l=t.phase==="archive"&&t.loop.stage==="archive-ready"&&t.verification_result==="pass",u=c||l;if(u){let d=nk(t,l?"Local Runtime was unavailable at Archive ready; the synchronized implementation must be verified again.":"The previous Verifier execution was unavailable; dispatch a new attempt from the stable Verify boundary.");t=await bt({file:se(e.paths,t.name),expectedStateVersion:t.state_version,next:d,containedRoot:e.paths.nativeRoot})}let f=st({portableState:t,projectRoot:e.paths.projectRoot,branch:F(e.paths.projectRoot).currentBranch});return await Uf.mkdir(Kf.dirname(Pt(e.paths,t.name)),{recursive:!0}),await Be(r,f,{containedRoot:e.paths.runtimeDir}),await ca({paths:e.paths,state:t}),{state:t,local:f,action:u?"reverify":"resume-stable-boundary",reason:a,message:u?"Rebuilt local execution from the portable boundary; previous pass/execution was not reused.":`Rebuilt local execution from the portable ${t.phase}/${t.loop.stage} boundary.`}})}import{accessSync as wk,constants as yk,promises as Nk}from"node:fs";import Me from"node:path";import{execFileSync as ok}from"node:child_process";var sk=6e4,ck=8*1024*1024,dc=class extends Error{constructor(i,r,n,a){super(`${i} ${r.join(" ")} failed${n?`: ${n}`:""}`,a);this.command=i;this.args=r;this.stderr=n;this.name="ExternalCommandError"}command;args;stderr};function ii(e,t,i={}){let r=i.timeoutMs??sk,n=i.maxBufferBytes??ck;if(!Number.isSafeInteger(r)||r<1)throw new Error("External command timeout must be a positive integer");if(!Number.isSafeInteger(n)||n<1)throw new Error("External command max buffer must be a positive integer");try{return ok(e,[...t],{...i.cwd?{cwd:i.cwd}:{},...i.input!==void 0?{input:i.input}:{},encoding:"utf8",stdio:[i.input===void 0?"ignore":"pipe","pipe","pipe"],timeout:r,maxBuffer:n,windowsHide:!0,shell:!1})}catch(a){let o=typeof a.stderr=="string"?a.stderr.trim():Buffer.isBuffer(a.stderr)?a.stderr.toString("utf8").trim():"";throw new dc(e,t,o,{cause:a})}}import uk from"path";var dk=["Outcome","Scope","Non-goals","Acceptance examples"],cI=[...dk,"Constraints and invariants","Decisions","Open questions","Verification expectations"];function pa(e,t){return uk.join(e.specsDir,t,"spec.md")}var fk=6e4,q=class extends Error{constructor(i,r,n){super(i,n);this.pullRequest=r;this.name="NativePullRequestFinishError"}pullRequest};function fc(e,t){try{return ii("gh",t,{cwd:e,timeoutMs:fk}).trim()}catch(i){throw new Error(`gh ${t.join(" ")} failed: ${i.message}`,{cause:i})}}function hc(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a JSON object`);return e}function pc(e,t){try{return JSON.parse(e)}catch(i){throw new Error(`${t} must be valid JSON`,{cause:i})}}function Xf(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Rt(e,t){if(typeof e!="string"||e.trim().length===0)throw new Error(`${t} must be a non-empty string`);return e}function Qf(e,t){let i=Rt(e,t),r;try{r=new URL(i)}catch(n){throw new Error(`${t} must be an absolute HTTP URL`,{cause:n})}if(r.protocol!=="https:"&&r.protocol!=="http:")throw new Error(`${t} must be an absolute HTTP URL`);return i}function va(e,t){let i=Rt(e,t);if(!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/iu.test(i))throw new Error(`${t} must be a Git object ID`);return i.toLowerCase()}function Zf(e,t){let i=hc(e,t);if(Rt(i.state,`${t}.state`)!=="OPEN")throw new Error(`${t}.state must be OPEN`);return{number:Xf(i.number,`${t}.number`),url:Qf(i.url,`${t}.url`),baseBranch:Rt(i.baseRefName,`${t}.baseRefName`),headBranch:Rt(i.headRefName,`${t}.headRefName`),headSha:va(i.headRefOid,`${t}.headRefOid`),state:"OPEN"}}function hk(e){let t=hc(e,"pull request finish provider output.pullRequest");return{number:Xf(t.number,"pull request finish provider output.pullRequest.number"),url:Qf(t.url,"pull request finish provider output.pullRequest.url"),baseBranch:Rt(t.baseBranch,"pull request finish provider output.pullRequest.baseBranch"),headBranch:Rt(t.headBranch,"pull request finish provider output.pullRequest.headBranch"),headSha:va(t.headSha,"pull request finish provider output.pullRequest.headSha")}}function pk(e){let t=hc(pc(e,"pull request finish provider output"),"pull request finish provider output");if(t.schema!=="comet.native.pull-request-finish-result.v1")throw new Error("pull request finish provider output.schema must be comet.native.pull-request-finish-result.v1");if(t.disposition!=="created"&&t.disposition!=="reused")throw new Error("pull request finish provider output.disposition must be created or reused");if(t.remoteVerified!==!0)throw new Error("pull request finish provider did not confirm repository-owned remote verification");let i=hk(t.pullRequest);return{schema:"comet.native.pull-request-finish-result.v1",disposition:t.disposition,remoteVerified:!0,pullRequest:i}}function mc(e){let t=fc(e.projectRoot,["pr","list","--state","open","--base",e.baseBranch,"--head",e.headBranch,"--limit","2","--json","number,url,baseRefName,headRefName,headRefOid,state"]),i=pc(t,"gh pr list output");if(!Array.isArray(i))throw new Error("gh pr list output must be a JSON array");if(i.length>1)throw new Error(`Multiple open pull requests match ${e.headBranch} -> ${e.baseBranch}`);return i.length===0?null:Zf(i[0],"gh pr list output[0]")}function eh(e){let t=fc(e.projectRoot,["pr","view",String(e.pullRequest.number),"--json","number,url,baseRefName,headRefName,headRefOid,state"]),i=Zf(pc(t,"gh pr view output"),"gh pr view output"),r=va(e.headSha,"Native Archive head SHA");if(i.number!==e.pullRequest.number||i.url!==e.pullRequest.url)throw new q("Pull request provider result does not match the pull request observed from GitHub",i);if(i.baseBranch!==e.baseBranch)throw new q(`Pull request base branch mismatch: expected ${e.baseBranch}, got ${i.baseBranch}`,i);if(i.headBranch!==e.headBranch)throw new q(`Pull request head branch mismatch: expected ${e.headBranch}, got ${i.headBranch}`,i);if(i.headSha!==r)throw new q(`Pull request head SHA mismatch: expected ${r}, got ${i.headSha}`,i);return i}function ma(e){try{return mc(e)}catch{return null}}function mk(e){return JSON.stringify({schema:"comet.native.pull-request-finish-input.v1",projectRoot:e.projectRoot,change:{name:e.changeName,branch:e.headBranch,headSha:e.headSha},target:{branch:e.baseBranch},remote:e.remote,transactionId:e.transactionId,existingPullRequest:e.existingPullRequest},null,2)}function vk(e){let t=e.existingPullRequest,i=t?"reused":"created";if(!t)try{let a=fc(e.projectRoot,["pr","create","--base",e.baseBranch,"--head",e.headBranch,"--fill"]).split(/\r?\n/u).map(o=>o.trim()).find(o=>/^https?:\/\//u.test(o));if(!a)throw new Error("GitHub CLI did not return a pull request URL");if(t=mc(e),!t)throw new Error("GitHub CLI created a pull request that could not be observed uniquely");if(t.url!==a)throw new q("GitHub CLI returned a pull request URL that does not match the remotely observed pull request",t)}catch(n){if(n instanceof q)throw n;let a=ma(e);if(!a)throw new q(n.message,null,{cause:n});t=a,i="reused"}let r;try{r=eh({...e,pullRequest:t})}catch(n){throw n instanceof q?n:new q(`Final GitHub pull request verification failed: ${n.message}`,t,{cause:n})}return{provider:"github-fill",disposition:i,pullRequest:r,remoteVerified:!0}}function gk(e){let[t,...i]=e.config.command,r;try{let o=ii(t,i,{cwd:e.projectRoot,timeoutMs:e.config.timeout_ms,input:`${mk(e)}
|
|
200
|
+
`}).trim();r=pk(o)}catch(o){if(o instanceof q)throw o;let s=ma(e)??e.existingPullRequest;throw new q(`Repository pull request finish provider failed: ${o.message}`,s,{cause:o})}let n={...r.pullRequest,state:"OPEN"};if(n.baseBranch!==e.baseBranch||n.headBranch!==e.headBranch||n.headSha!==va(e.headSha,"Native Archive head SHA")){let o=ma(e)??e.existingPullRequest;throw new q("Repository pull request finish provider returned a pull request outside the authorized base, head, or head SHA",o)}let a;try{a=eh({...e,pullRequest:n})}catch(o){if(o instanceof q)throw o;let s=ma(e)??e.existingPullRequest??n;throw new q(`Final repository pull request verification failed: ${o.message}`,s,{cause:o})}return{provider:"repository-command",disposition:r.disposition,pullRequest:a,remoteVerified:!0}}function th(e){let t=mc(e);return e.config?gk({...e,existingPullRequest:t,config:e.config}):vk({...e,existingPullRequest:t})}var mr=class extends Error{constructor(i){super(i.message??"Native workspace finish is blocked");this.result=i;this.name="NativeWorkspaceFinishError"}result};function ih(e,t){let i=Me.relative(e,t);return i===""||!Me.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Me.sep}`)}function Ct(e,t){let i=Me.relative(e,t).replaceAll("\\","/");if(!i||i===".."||i.startsWith("../")||Me.isAbsolute(i))throw new Error(`Native workspace finish path escaped the project: ${t}`);return i}function rh(e,t){return t.some(i=>e===i||e.startsWith(`${i}/`))}function nh(e){return e.split("\0").filter(Boolean)}function bk(e,t){return nh(I(e,["ls-files","-z","--",t]))}function kk(e,t){return nh(I(e,["ls-files","--others","--exclude-standard","-z","--",t]))}function Sk(e){try{if(I(e,["config","--get","user.name"])&&I(e,["config","--get","user.email"]))return}catch{}throw new Error("Native workspace finish requires configured Git user.name and user.email")}function Ek(e,t){for(let i of lt(e))if(F(i).currentBranch===t)return i;return null}function Pk(e,t){try{ii(e,t,{timeoutMs:1e4})}catch(i){throw new Error(`${e} is required for the selected Native workspace finish`,{cause:i})}}function xk(e,t){if(!t)return;let i=t.command[0];try{if(Me.posix.isAbsolute(i)||Me.win32.isAbsolute(i))throw new Error("configured executable must not be an absolute path");if(/[\\/]/u.test(i)){let n=Me.resolve(e,i);if(!ih(e,n))throw new Error("configured executable escapes the project root");wk(n,yk.X_OK);return}ii(process.platform==="win32"?"where":"which",[i],{timeoutMs:1e4})}catch(r){throw new Error(`Configured Native pull request finish executable is not available: ${i}`,{cause:r})}}async function vc(e){let{paths:t,state:i}=e,r=i.workspace;if(r.isolation==="current")return null;if(!r.finish||!r.change_branch||!r.target_branch)throw new Error("Native isolated workspace finish is not persisted");if(r.change_branch===r.target_branch)throw new Error("Native change and target branches must be different for workspace finish");let n=F(t.projectRoot);if(!n.primaryWorktreeRoot||n.currentBranch!==r.change_branch)throw new Error(`Native workspace finish requires branch ${r.change_branch} in the current registered worktree`);Sk(t.projectRoot);let a=[Ct(t.projectRoot,nc(t))];e.archiveDir&&a.push(Ct(t.projectRoot,oe(t,i.name)),Ct(t.projectRoot,e.archiveDir));let o=Ks(t.projectRoot).filter(l=>!rh(l,a));if(o.length>0)throw new Error(`Native workspace finish is blocked until change-owned implementation and artifacts are committed; remaining paths: ${o.slice(0,20).join(", ")}${o.length>20?", ...":""}`);let s=r.isolation==="branch"?t.projectRoot:Ek(n.primaryWorktreeRoot,r.target_branch);if(r.finish==="merge"&&r.isolation==="worktree"){if(!s)throw new Error(`Native merge finish requires a registered worktree on target branch ${r.target_branch}`);if(!ea(s))throw new Error(`Native merge target worktree is not clean: ${s}`)}let c=r.finish==="push"||r.finish==="pull-request"?vf(t.projectRoot,r.change_branch):null;return r.finish==="pull-request"&&(Pk("gh",["--version"]),xk(t.projectRoot,e.pullRequestFinish)),{finish:r.finish,changeRoot:t.projectRoot,primaryRoot:n.primaryWorktreeRoot,changeBranch:r.change_branch,targetBranch:r.target_branch,targetRoot:s,remote:c,isolation:r.isolation,pullRequestFinish:e.pullRequestFinish??null}}async function Rk(e){try{return await Nk.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Ck(e){return{action:e.finish,status:e.finish==="keep"?"kept":"completed",commit:null,remote:e.remote,pushed:!1,pullRequestUrl:null,pullRequest:null,merged:!1,targetRoot:e.targetRoot,cleanup:{performed:!1,reason:null},message:null,recoveryArgs:null}}async function ah(e){let t=Ck(e.plan),i=null;try{let r=[Ct(e.paths.projectRoot,oe(e.paths,e.name)),Ct(e.paths.projectRoot,e.archiveDir),...e.state.spec_changes.map(l=>Ct(e.paths.projectRoot,pa(e.paths,l.capability))),Ct(e.paths.projectRoot,nc(e.paths))],n=Ks(e.plan.changeRoot).filter(l=>!rh(l,r));if(n.length>0)throw new Error(`Native Archive produced or encountered paths outside the authorized finish scope: ${n.slice(0,20).join(", ")}${n.length>20?", ...":""}`);let a=[],o=new Set;for(let l of r){let u=Me.resolve(e.paths.projectRoot,...l.split("/"));if(bk(e.plan.changeRoot,l).length>0&&a.push(l),await Rk(u))for(let d of kk(e.plan.changeRoot,l))o.add(d)}if(a.length>0&&I(e.plan.changeRoot,["add","-u","--",...a]),o.size>0&&I(e.plan.changeRoot,["add","--",...o]),I(e.plan.changeRoot,["diff","--cached","--name-only","-z"])&&I(e.plan.changeRoot,["commit","-m",`chore(native): archive ${e.name}`]),t.commit=I(e.plan.changeRoot,["rev-parse","HEAD"]),!ea(e.plan.changeRoot))throw new Error("Native archive commit left unexpected working-tree changes");if(e.plan.finish==="keep")return t;if(e.plan.finish==="push"||e.plan.finish==="pull-request"){I(e.plan.changeRoot,["push","--set-upstream",e.plan.remote,e.plan.changeBranch]),t.pushed=!0,e.plan.finish==="pull-request"&&(t.pullRequest=th({projectRoot:e.plan.changeRoot,changeName:e.name,transactionId:e.transactionId,remote:e.plan.remote,baseBranch:e.plan.targetBranch,headBranch:e.plan.changeBranch,headSha:t.commit,config:e.plan.pullRequestFinish}),t.pullRequestUrl=t.pullRequest.pullRequest.url);let l=ih(e.plan.changeRoot,process.cwd());return e.plan.isolation==="worktree"&&!l?(I(e.plan.primaryRoot,["worktree","remove",e.plan.changeRoot]),t.cleanup={performed:!0,reason:null}):e.plan.isolation==="worktree"&&(t.cleanup={performed:!1,reason:"invocation-working-directory-is-the-change-worktree"}),t}let c=e.plan.targetRoot??e.plan.changeRoot;return e.plan.isolation==="branch"&&(I(c,["switch",e.plan.targetBranch]),i=c),I(c,["merge","--no-ff","--no-edit",e.plan.changeBranch]),t.merged=!0,t.targetRoot=c,t.cleanup={performed:!1,reason:"post-merge-validation-required-before-cleanup"},t}catch(r){if(r instanceof q&&r.pullRequest&&(t.pullRequestUrl=r.pullRequest.url),i!==null){let n;try{I(i,["merge","--abort"])}catch{}try{F(i).currentBranch===e.plan.targetBranch&&I(i,["switch",e.plan.changeBranch]),n=F(i).currentBranch===e.plan.changeBranch}catch{n=!1}n||(t.targetRoot=i)}throw t.status="blocked",t.message=r.message,t.recoveryArgs=e.plan.finish==="pull-request"?["comet","native","archive",e.name,"--confirmed"]:e.plan.finish==="merge"&&t.targetRoot?["git","-C",t.targetRoot,"status","--short"]:["git","-C",e.plan.changeRoot,"status","--short"],new mr(t)}}import gr from"path";import{realpathSync as uS}from"fs";var Ak=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 oh=1024*1024;var ch="scoped-text-safety",_k=1,Tk=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128});var Ik="comet.native.checker-policy.v1";var GI=ee(Ik,{policy:ch,version:_k,limits:Tk,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"});var jk=["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"],UI=new Set(jk);var Hk=oh,dj=3*Hk;var lh={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:[]},Bk=de("comet-native-runtime:v3:scope-reopen"),Bj=[{skillVersion:"3",skillHash:de("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:de("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:de("comet-native-runtime:v1")}];var dh=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],w$=new Set(dh),zk=new Set([...dh,"minimum_runtime_version","revision"]),y$=new Set([...zk,"operation"]),N$=512*1024,Jk=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),b$=new Set([...Jk,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]);var P$={maxAcceptanceCriteria:Ui.maxCriteria};var _$={maxSpecs:64,maxFileBytes:br,maxTotalBytes:4*1024*1024};import{execFile as tS}from"node:child_process";import{promisify as iS}from"node:util";var q$={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024};var sO=512*1024;var vr=class extends Error{recovery;constructor(t,i){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=i}};var _O=64*1024;var TO=3600*1e3;var IO=iS(tS);var ga=class extends Error{details;constructor(t){let i=t.length===0?"Native verification receipt binding is invalid":`Native verification receipt binding is invalid (${t.length} receipt(s)): ${t.map(r=>`${r.ref}${r.acceptanceId?`[${r.acceptanceId}]`:""} -> ${r.mismatches.join("; ")}`).join(" | ")}`;super(i),this.name="NativeVerificationReceiptBindingError",this.details=t}};var g0={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};var R0=16*1024*1024,C0=256*1024,A0=16*1024;var $0=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});var SH=16*1024*1024,wa=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"},ya=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 Na=class extends Error{constructor(i,r,n){super(i,n);this.preparation=r;this.name="NativeWorkspacePreparationError"}preparation};var ph=["--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."],wc=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:ph,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]
|
|
201
|
+
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]
|
|
202
202
|
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 gc(e,t){return`${e}:
|
|
203
203
|
${t.map(i=>` ${i}`).join(`
|
|
204
|
-
`)}`}function
|
|
204
|
+
`)}`}function sS(e){let t=e.filter(r=>r!=="--help");if(t.length===0)return"";let i=t.slice(0,2).join(" ");return wc[i]||t.length>1&&wc[t[0]]?.subcommands?i:t[0]}function cS(e=[]){let t=sS(e),i=wc[t];if(!i)throw new Error(`Unknown Native help topic: ${t}`);let r=[`Usage: ${i.usage}`,"",i.purpose];i.subcommands&&r.push("",gc("Commands",i.subcommands));let n=t===""?i.options:[...i.options??[],...ph];return n&&n.length>0&&r.push("",gc("Options",n)),r.push("",`Output:
|
|
205
205
|
${i.output}`),i.examples&&r.push("",gc("Examples",i.examples)),t===""&&r.push("","Run `comet native <command> --help` for command-specific details."),{topic:t,usage:`${r.join(`
|
|
206
206
|
`)}
|
|
207
|
-
`}}var
|
|
208
|
-
`}}function yh(e,t){if(t instanceof O)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof wa)return{command:e,exitCode:73,data:{capability:t.capability,expectedHash:t.expectedHash,actualHash:t.actualHash,canonicalPath:t.canonicalPath},error:{code:"conflict",message:t.message}};if(t instanceof ya)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof
|
|
209
|
-
`}:e.error?{exitCode:e.exitCode,stderr:e.error.message}:{exitCode:e.exitCode,stdout:e.text}}async function bh(e,t){let i=vh(e,"change name"),r=
|
|
207
|
+
`}}var lS=cS().usage;var GH=10*1024*1024,O=class extends Error{};function wr(e,t){let i=e.flatMap((r,n)=>r===t?[n]:[]);if(i.length>1)throw new O(`${t} may only be provided once`);return i.length===0?!1:(e.splice(i[0],1),!0)}function ri(e,t){let i=e.flatMap((a,o)=>a===t?[o]:[]);if(i.length>1)throw new O(`${t} may only be provided once`);if(i.length===0)return;let r=i[0],n=e[r+1];if(n===void 0||n.startsWith("--"))throw new O(`${t} requires a value`);return e.splice(r,2),n}function Nc(e){if(e.length>0)throw new O(`Unexpected argument: ${e[0]}`)}function vh(e,t){let i=e.shift();if(!i||i.startsWith("--"))throw new O(`${t} is required`);return i}function yc(e,t){let i=gr.normalize(mh(e)),r=gr.normalize(mh(t));return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function mh(e){let t=gr.resolve(e);try{return uS.native(t)}catch{return t}}function dS(e){let t=gr.resolve(e),i=F(process.cwd());if(!i.isSecondaryWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null)return t;let r=F(t);return!r.isGitWorktree||r.currentWorktreeRoot===null||r.primaryWorktreeRoot===null||!yc(i.primaryWorktreeRoot,r.primaryWorktreeRoot)||yc(i.currentWorktreeRoot,r.currentWorktreeRoot)?t:yc(process.cwd(),i.currentWorktreeRoot)?gr.resolve(process.cwd()):i.currentWorktreeRoot}async function gh(e){return e?dS(e):Tn(process.cwd())}async function wh(e){let t=await Pd({startPath:e,allowMissingConfig:!1});return{config:t.config,paths:t.paths}}function ni(e,t,i){return{command:e,exitCode:0,data:t,text:i??JSON.stringify(t,null,2)+`
|
|
208
|
+
`}}function yh(e,t){if(t instanceof O)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof wa)return{command:e,exitCode:73,data:{capability:t.capability,expectedHash:t.expectedHash,actualHash:t.actualHash,canonicalPath:t.canonicalPath},error:{code:"conflict",message:t.message}};if(t instanceof ya)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof Xn)return{command:e,exitCode:73,data:{change:t.change,expectedRevision:t.expectedRevision,actualRevision:t.actualRevision,outcome:"revision-conflict"},error:{code:"conflict",message:t.message}};if(t instanceof tr)return{command:e,exitCode:73,data:{requestedIsolation:t.requestedIsolation,activeChanges:t.activeChanges,requiredAction:"create-native-worktree"},error:{code:"workspace-isolation-required",message:t.message}};if(t instanceof Na)return{command:e,exitCode:73,data:{preparation:t.preparation},error:{code:"workspace-preparation-incomplete",message:t.message}};if(t instanceof Qn)return{command:e,exitCode:65,data:{change:t.change,complete:!1,omittedCount:t.omittedCount,omittedByReason:t.omittedByReason,samplePaths:t.samplePaths,sampleTruncated:t.sampleTruncated,effectiveLimits:t.effectiveLimits,policyHash:t.policyHash,configPath:".comet/config.yaml",supportedFixes:["increase native.snapshot.max_files, native.snapshot.max_total_bytes, or native.snapshot.max_duration_ms","add an explicit native.snapshot.exclude pattern for data outside implementation scope"],requiredAction:"resolve-native-baseline"},error:{code:"baseline-incomplete",message:t.message}};if(t instanceof ga)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof vr)return{command:e,exitCode:65,data:t.recovery,error:{code:"implementation-scope-stale",message:t.message}};if(t instanceof Error){let i=t.code;if(i&&new Set(["EACCES","EPERM","EIO","EMFILE","ENFILE","ENOSPC","EROFS"]).has(i))return{command:e,exitCode:70,error:{code:"internal",message:t.message}};let r=/\b(lock|transaction|conflict|occupied|incomplete|recovery)\b/iu.test(t.message);return{command:e,exitCode:r?73:65,error:{code:r?"conflict":"invalid-data",message:t.message}}}return{command:e,exitCode:70,error:{code:"internal",message:String(t)}}}function Nh(e,t){return t?{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,...e.data===void 0?{}:{data:e.data},...e.error===void 0?{}:{error:e.error}})+`
|
|
209
|
+
`}:e.error?{exitCode:e.exitCode,stderr:e.error.message}:{exitCode:e.exitCode,stdout:e.text}}async function bh(e,t){let i=vh(e,"change name"),r=wr(e,"--dry-run"),n=ri(e,"--expect-preflight"),a=wr(e,"--confirmed"),o=ri(e,"--finish"),s=ri(e,"--serial-first");if(s!==void 0&&!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(s))throw new O("--serial-first must be one Native change name");let c=o;if(c!==void 0&&c!=="merge"&&c!=="push"&&c!=="pull-request"&&c!=="keep")throw new O("--finish must be merge, push, pull-request, or keep");let l=await wh(t),u=await ur(l.paths,i),f=u?await Yt(l.paths,{kind:"archive",change:i}):null,d=u?!1:await Df(l.paths,i);if(u||d){if(n)throw new O("Portable Native Archive does not use preflight hashes");if(r&&a)throw new O("--confirmed is only valid when executing Archive");if(r&&s)throw new O("--serial-first is only valid when executing Archive");if(!r&&c)throw new O("--finish is only valid with --dry-run");Nc(e);let v=u&&!r&&f?.kind!=="archive"?await Yf({paths:l.paths,name:i}):null,h=v?.state??(u?await Fe(l.paths,i):null);if(v?.action==="reverify"||v?.action==="await-user")return ni(r?"archive --dry-run":"archive",{archived:!1,state:v.state,recovery:v,continuation:hr(v.state)},`${v.message}
|
|
210
210
|
`);if(r){if(!h)return ni("archive --dry-run",{change:i,ready:!0,archiveRecovery:!0,continuation:{disposition:"continue",reason:"Resume the interrupted Native Archive transaction.",commandArgs:["comet","native","archive",i,"--confirmed"],inputOptions:[],runnerAction:null}},`Native Archive recovery is ready for ${i}
|
|
211
|
-
`);if(c)h=await Af({paths:l.paths,name:i,finish:c});else if(h.workspace.isolation!=="current"&&h.workspace.finish===null)throw new O("Native branch and worktree isolation require --finish with --dry-run");let w=await lc({paths:l.paths,name:i}),k=
|
|
212
|
-
`)}if(l.config.native.archive_confirmation==="required"&&!a)throw new O("archive requires --confirmed when native.archive_confirmation is required");if(h&&h.workspace.isolation!=="current"&&h.workspace.finish===null)throw new O("Native branch and worktree isolation require a persisted --finish preview");let m=h?await vc({paths:l.paths,state:h,pullRequestFinish:l.config.native.finish?.pull_request}):null,g;try{g=await Lf({paths:l.paths,name:i,...s?{serialFirstChange:s}:{}})}catch(w){if(!(w instanceof dr)||!h)throw w;let k=await lc({paths:l.paths,name:i}),S=w.peers.length>0?["comet","native","archive",i,"--confirmed","--serial-first",i]:["comet","native","archive",i,"--confirmed"];return{command:"archive",exitCode:73,data:{...k,workspaceFinish:h.workspace.finish,workspaceFinishResult:null,continuation:{disposition:"await-user",reason:w.message,commandArgs:S,inputOptions:w.peers.length>0?["serial-first-change"]:[],runnerAction:null}},error:{code:"conflict",message:w.message}}}h=g.state,!m&&h.workspace.isolation!=="current"&&(m=await vc({paths:l.paths,state:h,archiveDir:g.archiveDir,pullRequestFinish:l.config.native.finish?.pull_request}));let N=null;if(m)try{N=await ah({paths:l.paths,state:g.state,name:i,archiveDir:g.archiveDir,transactionId:g.transactionId,plan:m})}catch(w){if(!(w instanceof
|
|
213
|
-
`)}if(s)throw new O("--serial-first is only valid for portable Native changes");if(!r&&c)throw new O("--finish is only valid with --dry-run");if(Nc(e),r)return{command:"archive --dry-run",exitCode:65,data:{change:i,migrationRequired:!0,repairCommand:`comet native doctor ${i} --repair`},error:{code:"invalid-data",message:`Native active change ${i} must migrate before Archive preview`}};let p=await Gf({paths:l.paths,name:i});return ni("archive",{migration:{from:"legacy",to:p.schema,completed:!0},state:p,continuation:
|
|
214
|
-
`)}function
|
|
215
|
-
`}}async function kh(e,t,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{
|
|
211
|
+
`);if(c)h=await Af({paths:l.paths,name:i,finish:c});else if(h.workspace.isolation!=="current"&&h.workspace.finish===null)throw new O("Native branch and worktree isolation require --finish with --dry-run");let w=await lc({paths:l.paths,name:i}),k=hr(h),S=w.capabilityPeers.length>0?{...k,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["choose-first-archive"],runnerAction:{...k.runnerAction,kind:"none"}}:k;return ni("archive --dry-run",{...w,workspaceFinish:h.workspace.finish,continuation:S},`Native Archive preview: ${w.ready?"ready":"blocked"}
|
|
212
|
+
`)}if(l.config.native.archive_confirmation==="required"&&!a)throw new O("archive requires --confirmed when native.archive_confirmation is required");if(h&&h.workspace.isolation!=="current"&&h.workspace.finish===null)throw new O("Native branch and worktree isolation require a persisted --finish preview");let m=h?await vc({paths:l.paths,state:h,pullRequestFinish:l.config.native.finish?.pull_request}):null,g;try{g=await Lf({paths:l.paths,name:i,...s?{serialFirstChange:s}:{}})}catch(w){if(!(w instanceof dr)||!h)throw w;let k=await lc({paths:l.paths,name:i}),S=w.peers.length>0?["comet","native","archive",i,"--confirmed","--serial-first",i]:["comet","native","archive",i,"--confirmed"];return{command:"archive",exitCode:73,data:{...k,workspaceFinish:h.workspace.finish,workspaceFinishResult:null,continuation:{disposition:"await-user",reason:w.message,commandArgs:S,inputOptions:w.peers.length>0?["serial-first-change"]:[],runnerAction:null}},error:{code:"conflict",message:w.message}}}h=g.state,!m&&h.workspace.isolation!=="current"&&(m=await vc({paths:l.paths,state:h,archiveDir:g.archiveDir,pullRequestFinish:l.config.native.finish?.pull_request}));let N=null;if(m)try{N=await ah({paths:l.paths,state:g.state,name:i,archiveDir:g.archiveDir,transactionId:g.transactionId,plan:m})}catch(w){if(!(w instanceof mr))throw w;return{command:"archive",exitCode:73,data:{...g,workspaceFinish:g.state.workspace.finish,workspaceFinishResult:w.result,continuation:{disposition:"blocked",reason:w.message,commandArgs:w.result.recoveryArgs,inputOptions:[],runnerAction:null}},error:{code:"conflict",message:w.message}}}return ni("archive",{...g,workspaceFinish:g.state.workspace.finish,workspaceFinishResult:N,continuation:hr(g.state)},`Archived Native change ${i} to ${g.archiveDir}
|
|
213
|
+
`)}if(s)throw new O("--serial-first is only valid for portable Native changes");if(!r&&c)throw new O("--finish is only valid with --dry-run");if(Nc(e),r)return{command:"archive --dry-run",exitCode:65,data:{change:i,migrationRequired:!0,repairCommand:`comet native doctor ${i} --repair`},error:{code:"invalid-data",message:`Native active change ${i} must migrate before Archive preview`}};let p=await Gf({paths:l.paths,name:i});return ni("archive",{migration:{from:"legacy",to:p.schema,completed:!0},state:p,continuation:hr(p)},`Migrated Native change ${i}; follow the returned portable continuation before Archive
|
|
214
|
+
`)}function fS(e){return{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,...e.data===void 0?{}:{data:e.data},...e.error===void 0?{}:{error:e.error}})+`
|
|
215
|
+
`}}async function kh(e,t,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{wr(n,"--json"),s=ri(n,"--project-root");let u=[...n,...a],f=await gh(s);c=await t(u,f)}catch(u){c=yh(e,u)}let l=o?fS(c):Nh(c,!1);return l.stdout&&process.stdout.write(l.stdout),l.stderr&&process.stderr.write(l.stderr+(l.stderr.endsWith(`
|
|
216
216
|
`)?"":`
|
|
217
217
|
`)),l.exitCode}process.exitCode=await kh("archive",bh);
|